Class: OpenC3::QueueModel

Inherits:
Model show all
Defined in:
lib/openc3/models/queue_model.rb

Constant Summary collapse

PRIMARY_KEY =
'openc3__queue'.freeze
@@class_mutex =
Mutex.new

Instance Attribute Summary collapse

Attributes inherited from Model

#plugin, #scope, #updated_at

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Model

#check_disable_erb, #destroyed?, #diff, filter, find_all_by_plugin, from_json, get_all_models, get_model, handle_config, set, store, store_queued, #update

Constructor Details

#initialize(name:, scope:, state: 'HOLD', updated_at: nil) ⇒ QueueModel

Returns a new instance of QueueModel.



82
83
84
85
86
87
88
89
90
# File 'lib/openc3/models/queue_model.rb', line 82

def initialize(name:, scope:, state: 'HOLD', updated_at: nil)
  super("#{scope}__#{PRIMARY_KEY}", name: name, updated_at: updated_at, scope: scope)
  @microservice_name = "#{scope}__QUEUE__#{name}"
  if %w(HOLD RELEASE DISABLE).include?(state)
    @state = state
  else
    @state = 'HOLD'
  end
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



80
81
82
# File 'lib/openc3/models/queue_model.rb', line 80

def name
  @name
end

#stateObject

Returns the value of attribute state.



80
81
82
# File 'lib/openc3/models/queue_model.rb', line 80

def state
  @state
end

Class Method Details

.all(scope:) ⇒ Object



38
39
40
# File 'lib/openc3/models/queue_model.rb', line 38

def self.all(scope:)
  super("#{scope}__#{PRIMARY_KEY}")
end

.build_command_data(username:, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: nil, timeout: nil) ⇒ Object

Build the hash that gets serialized into Redis. Always uses symbol keys so downstream code in this class can access values consistently. cmd_params is JSON-encoded as a string so binary data survives the round-trip via as_json.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/openc3/models/queue_model.rb', line 64

def self.build_command_data(username:, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: nil, timeout: nil)
  command_data = { username: username, timestamp: Time.now.to_nsec_from_epoch }
  if target_name && cmd_name
    command_data[:target_name] = target_name
    command_data[:cmd_name] = cmd_name
    command_data[:cmd_params] = JSON.generate(cmd_params.as_json, allow_nan: true) if cmd_params
  elsif command
    command_data[:value] = command
  else
    raise QueueError, "Must provide either command string or target_name/cmd_name parameters"
  end
  command_data[:validate] = validate unless validate.nil?
  command_data[:timeout] = timeout unless timeout.nil?
  command_data
end

.get(name:, scope:) ⇒ Object

NOTE: The following three class methods are used by the ModelController and are reimplemented to enable various Model class methods to work



30
31
32
# File 'lib/openc3/models/queue_model.rb', line 30

def self.get(name:, scope:)
  super("#{scope}__#{PRIMARY_KEY}", name: name)
end

.names(scope:) ⇒ Object



34
35
36
# File 'lib/openc3/models/queue_model.rb', line 34

def self.names(scope:)
  super("#{scope}__#{PRIMARY_KEY}")
end

.queue_command(name, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: true, timeout: nil, username:, scope:) ⇒ Object

END NOTE

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/openc3/models/queue_model.rb', line 43

def self.queue_command(name, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: true, timeout: nil, username:, scope:)
  model = get_model(name: name, scope: scope)
  raise QueueError, "Queue '#{name}' not found in scope '#{scope}'" unless model

  if model.state == 'DISABLE'
    error_msg = command || "#{target_name} #{cmd_name}"
    raise QueueError, "Queue '#{name}' is disabled. Command '#{error_msg}' not queued."
  end

  result = Store.zrevrange("#{scope}:#{name}", 0, 0, with_scores: true)
  id = result.empty? ? 1.0 : result[0][1].to_f + 1

  command_data = build_command_data(username: username, command: command, target_name: target_name,
                                    cmd_name: cmd_name, cmd_params: cmd_params, validate: validate, timeout: timeout)
  Store.zadd("#{scope}:#{name}", id, command_data.to_json)
  model.notify(kind: 'command')
end

Instance Method Details

#as_json(*a) ⇒ Hash

Returns generated from the QueueModel.

Returns:

  • (Hash)

    generated from the QueueModel



103
104
105
106
107
108
109
110
# File 'lib/openc3/models/queue_model.rb', line 103

def as_json(*a)
  return {
    'name' => @name,
    'scope' => @scope,
    'state' => @state,
    'updated_at' => @updated_at
  }
end

#create(update: false, force: false, queued: false) ⇒ Object



92
93
94
95
96
97
98
99
100
# File 'lib/openc3/models/queue_model.rb', line 92

def create(update: false, force: false, queued: false)
  super(update: update, force: force, queued: queued)
  if update
    notify(kind: 'updated')
  else
    deploy()
    notify(kind: 'created')
  end
end

#create_microservice(topics:) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/openc3/models/queue_model.rb', line 196

def create_microservice(topics:)
  # queue Microservice
  microservice = MicroserviceModel.new(
    name: @microservice_name,
    folder_name: nil,
    cmd: ['ruby', 'queue_microservice.rb', @microservice_name],
    work_dir: '/openc3/lib/openc3/microservices',
    options: [
      ["QUEUE_STATE", @state],
    ],
    topics: topics,
    target_names: [],
    plugin: nil,
    scope: @scope
  )
  microservice.create
end

#deployObject



214
215
216
217
218
219
# File 'lib/openc3/models/queue_model.rb', line 214

def deploy
  topics = ["#{@scope}__#{QueueTopic::PRIMARY_KEY}"]
  if MicroserviceModel.get_model(name: @microservice_name, scope: @scope).nil?
    create_microservice(topics: topics)
  end
end

#destroyObject

Delete the model from the Store



240
241
242
243
244
# File 'lib/openc3/models/queue_model.rb', line 240

def destroy
  undeploy()
  Store.zremrangebyrank("#{@scope}:#{@name}", 0, -1)
  super()
end

#insert_command(id: nil, username:, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: nil, timeout: nil) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/openc3/models/queue_model.rb', line 121

def insert_command(id: nil, username:, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: nil, timeout: nil)
  if @state == 'DISABLE'
    command_name = command || "#{target_name} #{cmd_name}"
    raise QueueError, "Queue '#{@name}' is disabled. Command '#{command_name}' not queued."
  end

  unless id
    result = Store.zrevrange("#{@scope}:#{@name}", 0, 0, with_scores: true)
    id = result.empty? ? 1.0 : result[0][1].to_f + 1
  end

  command_data = self.class.build_command_data(username: username, command: command, target_name: target_name,
                                               cmd_name: cmd_name, cmd_params: cmd_params, validate: validate, timeout: timeout)
  Store.zadd("#{@scope}:#{@name}", id, command_data.to_json)
  notify(kind: 'command')
end

#listObject



188
189
190
191
192
193
194
# File 'lib/openc3/models/queue_model.rb', line 188

def list
  return Store.zrange("#{@scope}:#{@name}", 0, -1, with_scores: true).map do |item|
    result = JSON.parse(item[0])
    result['id'] = item[1].to_f
    result
  end
end

#notify(kind:) ⇒ Object

Returns [] update the redis stream / queue topic that something has changed.

Returns:

  • update the redis stream / queue topic that something has changed



113
114
115
116
117
118
119
# File 'lib/openc3/models/queue_model.rb', line 113

def notify(kind:)
  notification = {
    'kind' => kind,
    'data' => JSON.generate(as_json, allow_nan: true),
  }
  QueueTopic.write_notification(notification, scope: @scope)
end

#remove_command(id = nil) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/openc3/models/queue_model.rb', line 155

def remove_command(id = nil)
  if @state == 'DISABLE'
    raise QueueError, "Queue '#{@name}' is disabled. Command not removed."
  end

  if id
    # Remove specific id
    result = Store.zrangebyscore("#{@scope}:#{@name}", id, id)
    if result.empty?
      return nil
    else
      Store.zremrangebyscore("#{@scope}:#{@name}", id, id)
      command_data = JSON.parse(result[0])
      command_data['id'] = id.to_f
      notify(kind: 'command')
      return command_data
    end
  else
    # Remove first element (lowest score)
    result = Store.zrange("#{@scope}:#{@name}", 0, 0, with_scores: true)
    if result.empty?
      return nil
    else
      score = result[0][1]
      Store.zremrangebyscore("#{@scope}:#{@name}", score, score)
      command_data = JSON.parse(result[0][0], allow_nan: true)
      command_data['id'] = score.to_f
      notify(kind: 'command')
      return command_data
    end
  end
end

#undeployObject



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/openc3/models/queue_model.rb', line 221

def undeploy
  model = MicroserviceModel.get_model(name: @microservice_name, scope: @scope)
  if model
    # Let the frontend know that the microservice is shutting down
    # Custom event which matches the 'deployed' event in QueueMicroservice
    notification = {
      'kind' => 'undeployed',
      # name and updated_at fields are required for Event formatting
      'data' => JSON.generate({
        'name' => @microservice_name,
        'updated_at' => Time.now.to_nsec_from_epoch,
      }),
    }
    QueueTopic.write_notification(notification, scope: @scope)
    model.destroy
  end
end

#update_command(id:, username:, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: nil, timeout: nil) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/openc3/models/queue_model.rb', line 138

def update_command(id:, username:, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: nil, timeout: nil)
  if @state == 'DISABLE'
    raise QueueError, "Queue '#{@name}' is disabled. Command at id #{id} not updated."
  end

  existing = Store.zrangebyscore("#{@scope}:#{@name}", id, id)
  if existing.empty?
    raise QueueError, "No command found at id #{id} in queue '#{@name}'"
  end

  Store.zremrangebyscore("#{@scope}:#{@name}", id, id)
  command_data = self.class.build_command_data(username: username, command: command, target_name: target_name,
                                               cmd_name: cmd_name, cmd_params: cmd_params, validate: validate, timeout: timeout)
  Store.zadd("#{@scope}:#{@name}", id, command_data.to_json)
  notify(kind: 'command')
end