Class: OpenC3::TargetModel

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

Overview

Manages the target in Redis. It stores the target itself under the __openc3_targets key under the target name field. All the command packets in the target are stored under the __openc3cmd__ key and the telemetry under the __openc3tlm__ key. Any new limits sets are merged into the __limits_sets key as fields. Any new limits groups are created under __limits_groups with field name. These Redis key/fields are all removed when the undeploy method is called.

Constant Summary collapse

PRIMARY_KEY =
'openc3_targets'
VALID_TYPES =
%i(CMD TLM)
ERB_EXTENSIONS =
%w(.txt .rb .py .json .yaml .yml)
ITEM_MAP_CACHE_TIMEOUT =
10.0
PACKET_CACHE_TIMEOUT =
10.0
MAX_COLUMN_HEADER_LENGTH =

QuestDB column header limit for item/param names

127
@@item_map_cache =
{}
@@packet_cache =
{}
@@packet_cache_mutex =
Mutex.new
@@sync_packet_count_data =
{}
@@sync_packet_count_time =
nil
@@sync_packet_count_delay_seconds =

Sync packet counts every second

1.0
@@stale_packet_keys_warned =

Track stale keys already warned about

Set.new

Instance Attribute Summary collapse

Attributes inherited from Model

#name, #plugin, #scope, #updated_at

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Model

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

Constructor Details

#initialize(name:, folder_name: nil, requires: [], ignored_parameters: [], ignored_items: [], limits_groups: [], stored_limits_mode: 'PROCESS', cmd_tlm_files: [], id: nil, updated_at: nil, plugin: nil, cmd_buffer_depth: 5, cmd_log_cycle_time: 600, cmd_log_cycle_size: 50_000_000, cmd_log_retain_time: nil, tlm_buffer_depth: 60, tlm_log_cycle_time: 600, tlm_log_cycle_size: 50_000_000, tlm_log_retain_time: nil, cmd_decom_retain_time: nil, tlm_decom_retain_time: nil, decom_flush_period: 5.0, cleanup_poll_time: 3600, needs_dependencies: false, target_microservices: {}, disable_erb: nil, shard: 0, db_shard: 0, scope:) ⇒ TargetModel

Make sure to update target_model.py if you add additional parameters



453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/openc3/models/target_model.rb', line 453

def initialize(
  name:,
  folder_name: nil,
  requires: [],
  ignored_parameters: [],
  ignored_items: [],
  limits_groups: [],
  stored_limits_mode: 'PROCESS',
  cmd_tlm_files: [],
  id: nil,
  updated_at: nil,
  plugin: nil,
  cmd_buffer_depth: 5,
  cmd_log_cycle_time: 600,
  cmd_log_cycle_size: 50_000_000,
  cmd_log_retain_time: nil,
  tlm_buffer_depth: 60,
  tlm_log_cycle_time: 600,
  tlm_log_cycle_size: 50_000_000,
  tlm_log_retain_time: nil,
  cmd_decom_retain_time: nil,
  tlm_decom_retain_time: nil,
  decom_flush_period: 5.0,
  cleanup_poll_time: 3600,
  needs_dependencies: false,
  target_microservices: {},
  disable_erb: nil,
  shard: 0,
  db_shard: 0,
  scope:
)
  super("#{scope}__#{PRIMARY_KEY}", name: name, plugin: plugin, updated_at: updated_at, scope: scope)
  @folder_name = folder_name
  @requires = requires
  @ignored_parameters = ignored_parameters
  @ignored_items = ignored_items
  @limits_groups = limits_groups
  @stored_limits_mode = stored_limits_mode.to_s.upcase
  @stored_limits_mode = 'PROCESS' unless %w(PROCESS LOG DISABLE).include?(@stored_limits_mode)
  @cmd_tlm_files = cmd_tlm_files
  @id = id
  @cmd_buffer_depth = cmd_buffer_depth
  @cmd_log_cycle_time = cmd_log_cycle_time
  @cmd_log_cycle_size = cmd_log_cycle_size
  @cmd_log_retain_time = cmd_log_retain_time
  @tlm_buffer_depth = tlm_buffer_depth
  @tlm_log_cycle_time = tlm_log_cycle_time
  @tlm_log_cycle_size = tlm_log_cycle_size
  @tlm_log_retain_time = tlm_log_retain_time
  @cmd_decom_retain_time = cmd_decom_retain_time
  @tlm_decom_retain_time = tlm_decom_retain_time
  @decom_flush_period = decom_flush_period
  @cleanup_poll_time = cleanup_poll_time
  @needs_dependencies = needs_dependencies
  @target_microservices = target_microservices
  @disable_erb = disable_erb
  @shard = shard.to_i # to_i to handle nil
  @db_shard = db_shard.to_i # to_i to handle nil
  @bucket = Bucket.getClient()
  @children = []
end

Instance Attribute Details

#childrenObject

Returns the value of attribute children.



85
86
87
# File 'lib/openc3/models/target_model.rb', line 85

def children
  @children
end

#cleanup_poll_timeObject

Returns the value of attribute cleanup_poll_time.



82
83
84
# File 'lib/openc3/models/target_model.rb', line 82

def cleanup_poll_time
  @cleanup_poll_time
end

#cmd_buffer_depthObject

Returns the value of attribute cmd_buffer_depth.



71
72
73
# File 'lib/openc3/models/target_model.rb', line 71

def cmd_buffer_depth
  @cmd_buffer_depth
end

#cmd_decom_retain_timeObject

Returns the value of attribute cmd_decom_retain_time.



79
80
81
# File 'lib/openc3/models/target_model.rb', line 79

def cmd_decom_retain_time
  @cmd_decom_retain_time
end

#cmd_log_cycle_sizeObject

Returns the value of attribute cmd_log_cycle_size.



73
74
75
# File 'lib/openc3/models/target_model.rb', line 73

def cmd_log_cycle_size
  @cmd_log_cycle_size
end

#cmd_log_cycle_timeObject

Returns the value of attribute cmd_log_cycle_time.



72
73
74
# File 'lib/openc3/models/target_model.rb', line 72

def cmd_log_cycle_time
  @cmd_log_cycle_time
end

#cmd_log_retain_timeObject

Returns the value of attribute cmd_log_retain_time.



74
75
76
# File 'lib/openc3/models/target_model.rb', line 74

def cmd_log_retain_time
  @cmd_log_retain_time
end

#cmd_tlm_filesObject

Returns the value of attribute cmd_tlm_files.



69
70
71
# File 'lib/openc3/models/target_model.rb', line 69

def cmd_tlm_files
  @cmd_tlm_files
end

#db_shardObject

Returns the value of attribute db_shard.



88
89
90
# File 'lib/openc3/models/target_model.rb', line 88

def db_shard
  @db_shard
end

#decom_flush_periodObject

Returns the value of attribute decom_flush_period.



81
82
83
# File 'lib/openc3/models/target_model.rb', line 81

def decom_flush_period
  @decom_flush_period
end

#disable_erbObject

Returns the value of attribute disable_erb.



86
87
88
# File 'lib/openc3/models/target_model.rb', line 86

def disable_erb
  @disable_erb
end

#folder_nameObject

Returns the value of attribute folder_name.



63
64
65
# File 'lib/openc3/models/target_model.rb', line 63

def folder_name
  @folder_name
end

#idObject

Returns the value of attribute id.



70
71
72
# File 'lib/openc3/models/target_model.rb', line 70

def id
  @id
end

#ignored_itemsObject

Returns the value of attribute ignored_items.



66
67
68
# File 'lib/openc3/models/target_model.rb', line 66

def ignored_items
  @ignored_items
end

#ignored_parametersObject

Returns the value of attribute ignored_parameters.



65
66
67
# File 'lib/openc3/models/target_model.rb', line 65

def ignored_parameters
  @ignored_parameters
end

#limits_groupsObject

Returns the value of attribute limits_groups.



67
68
69
# File 'lib/openc3/models/target_model.rb', line 67

def limits_groups
  @limits_groups
end

#needs_dependenciesObject

Returns the value of attribute needs_dependencies.



83
84
85
# File 'lib/openc3/models/target_model.rb', line 83

def needs_dependencies
  @needs_dependencies
end

#requiresObject

Returns the value of attribute requires.



64
65
66
# File 'lib/openc3/models/target_model.rb', line 64

def requires
  @requires
end

#shardObject

Returns the value of attribute shard.



87
88
89
# File 'lib/openc3/models/target_model.rb', line 87

def shard
  @shard
end

#stored_limits_modeObject

Returns the value of attribute stored_limits_mode.



68
69
70
# File 'lib/openc3/models/target_model.rb', line 68

def stored_limits_mode
  @stored_limits_mode
end

#target_microservicesObject

Returns the value of attribute target_microservices.



84
85
86
# File 'lib/openc3/models/target_model.rb', line 84

def target_microservices
  @target_microservices
end

#tlm_buffer_depthObject

Returns the value of attribute tlm_buffer_depth.



75
76
77
# File 'lib/openc3/models/target_model.rb', line 75

def tlm_buffer_depth
  @tlm_buffer_depth
end

#tlm_decom_retain_timeObject

Returns the value of attribute tlm_decom_retain_time.



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

def tlm_decom_retain_time
  @tlm_decom_retain_time
end

#tlm_log_cycle_sizeObject

Returns the value of attribute tlm_log_cycle_size.



77
78
79
# File 'lib/openc3/models/target_model.rb', line 77

def tlm_log_cycle_size
  @tlm_log_cycle_size
end

#tlm_log_cycle_timeObject

Returns the value of attribute tlm_log_cycle_time.



76
77
78
# File 'lib/openc3/models/target_model.rb', line 76

def tlm_log_cycle_time
  @tlm_log_cycle_time
end

#tlm_log_retain_timeObject

Returns the value of attribute tlm_log_retain_time.



78
79
80
# File 'lib/openc3/models/target_model.rb', line 78

def tlm_log_retain_time
  @tlm_log_retain_time
end

Class Method Details

.add_to_target_allitems_list(target_name, item_name, scope:) ⇒ Object



393
394
395
396
# File 'lib/openc3/models/target_model.rb', line 393

def self.add_to_target_allitems_list(target_name, item_name, scope:)
  score = 0 # https://redis.io/docs/latest/develop/data-types/sorted-sets/#lexicographical-scores
  store_for_target(target_name, scope: scope).zadd("#{scope}__openc3tlm__#{target_name}__allitems", score, item_name)
end

.all(scope:) ⇒ Object



100
101
102
# File 'lib/openc3/models/target_model.rb', line 100

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

.all_item_names(target_name, type: :TLM, scope:) ⇒ Array<String>

Returns All the item names for every packet in a target.

Returns:

  • (Array<String>)

    All the item names for every packet in a target



377
378
379
380
381
# File 'lib/openc3/models/target_model.rb', line 377

def self.all_item_names(target_name, type: :TLM, scope:)
  items = store_for_target(target_name, scope: scope).zrange("#{scope}__openc3tlm__#{target_name}__allitems", 0, -1)
  items = rebuild_target_allitems_list(target_name, type: type, scope: scope) if items.empty?
  items
end

.all_modified(scope:) ⇒ Object

All targets with indication of modified targets



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/openc3/models/target_model.rb', line 105

def self.all_modified(scope:)
  targets = self.all(scope: scope)
  targets.each { |_target_name, target| target['modified'] = false }

  if ENV['OPENC3_LOCAL_MODE']
    modified_targets = OpenC3::LocalMode.modified_targets(scope: scope)
    modified_targets.each do |target_name|
      targets[target_name]['modified'] = true if targets[target_name]
    end
  else
    modified_targets = Bucket.getClient().list_files(bucket: ENV['OPENC3_CONFIG_BUCKET'], path: "DEFAULT/targets_modified/", only_directories: true)
    modified_targets.each do |target_name|
      # A target could have been deleted without removing the modified files
      # Thus we have to check for the existence of the target_name key
      if targets.has_key?(target_name)
        targets[target_name]['modified'] = true
      end
    end
  end
  # Sort (which turns hash to array) and return hash
  # This enables a consistent listing of the targets
  targets.sort.to_h
end

.all_packet_name_descriptions(target_name, type: :TLM, scope:) ⇒ Array<Hash>

Returns All packet hashes under the target_name.

Returns:

  • (Array<Hash>)

    All packet hashes under the target_name



331
332
333
# File 'lib/openc3/models/target_model.rb', line 331

def self.all_packet_name_descriptions(target_name, type: :TLM, scope:)
  self.packets(target_name, type: type, scope: scope).map! { |hash| hash.slice("packet_name", "description") }
end

.build_item_to_packet_map(target_name, scope:) ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/openc3/models/target_model.rb', line 425

def self.build_item_to_packet_map(target_name, scope:)
  item_map = {}
  packets = packets(target_name, scope: scope)
  packets.each do |packet|
    items = packet['items']
    items.each do |item|
      item_name = item['name']
      item_map[item_name] ||= []
      item_map[item_name] << packet['packet_name']
    end
  end
  return item_map
end

.clear_packet_cacheObject



311
312
313
314
315
# File 'lib/openc3/models/target_model.rb', line 311

def self.clear_packet_cache
  @@packet_cache_mutex.synchronize do
    @@packet_cache.clear
  end
end

.delete_modified(target_name, scope:, files: nil) ⇒ Object

files: optional list of specific modified files to delete, each a name relative to scope ("TARGET/sub/path", matching modified_files output). When given, only those files are removed (used by plugin upgrade to drop some modified files while keeping others); when nil, every modified file for the target is removed (the original behavior).



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/openc3/models/target_model.rb', line 213

def self.delete_modified(target_name, scope:, files: nil)
  if files && !files.empty?
    files.each do |name|
      # TargetFile.destroy handles both local mode and the bucket.
      OpenC3::TargetFile.destroy(scope, name)
    end
    return
  end
  if ENV['OPENC3_LOCAL_MODE']
    OpenC3::LocalMode.delete_modified(target_name, scope: scope)
  end
  bucket = Bucket.getClient()
  # Delete the remote files as well
  resp = bucket.list_objects(
    bucket: ENV['OPENC3_CONFIG_BUCKET'],
    # The trailing slash is important!
    prefix: "#{scope}/targets_modified/#{target_name}/",
  )
  resp.each do |item|
    bucket.delete_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: item.key)
  end
end

.destroy_script_versions(plugin_instance_name, scope:) ⇒ Object

Uninstall-only: remove a plugin's entire Version History repo. Called from the CLI uninstall path with the plugin instance name; upgrade reuses the repo and must never call this. No-op in Core builds (or whenever OPENC3_VERSION_HISTORY_DIR is unset) since VersionStore is absent or disabled. Best-effort: a failure here must not abort the uninstall.



173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/openc3/models/target_model.rb', line 173

def self.destroy_script_versions(plugin_instance_name, scope:)
  name, _version = plugin_name_version(plugin_instance_name)
  return unless name
  begin
    require 'openc3-enterprise/utilities/version_store'
  rescue LoadError
    return
  end
  ::VersionStore.destroy_repo(scope: scope, plugin: name)
rescue => e
  Logger.warn("destroy_script_versions failed for #{scope}/#{plugin_instance_name}: #{e.message}")
end

.download(target_name, scope:) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/openc3/models/target_model.rb', line 236

def self.download(target_name, scope:)
  # Validate target_name to not allow directory traversal
  if target_name.include?('..') || target_name.include?('/') || target_name.include?('\\')
    raise ArgumentError, "Invalid target_name: #{target_name.inspect}"
  end
  temp_dir = Dir.mktmpdir
  begin
    zip_filename = OpenC3.sanitize_path(File.join(temp_dir, "#{target_name}.zip"))
    Zip.continue_on_exists_proc = true
    zip = Zip::File.open(zip_filename, create: true)

    if ENV['OPENC3_LOCAL_MODE']
      OpenC3::LocalMode.zip_target(target_name, zip, scope: scope)
    else
      bucket = Bucket.getClient()
      # The trailing slash is important!
      prefix = "#{scope}/targets_modified/#{target_name}/"
      resp = bucket.list_objects(
        bucket: ENV['OPENC3_CONFIG_BUCKET'],
        prefix: prefix,
      )
      resp.each do |item|
        # item.key looks like DEFAULT/targets_modified/INST/screens/blah.txt
        base_path = item.key.sub(prefix, '') # remove prefix
        local_path = File.join(temp_dir, base_path)
        # Ensure dir structure exists, get_object fails if not
        FileUtils.mkdir_p(File.dirname(local_path))
        bucket.get_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: item.key, path: local_path)
        zip.add(base_path, local_path)
      end
    end
    zip.close

    result = OpenStruct.new
    result.filename = File.basename(zip_filename)
    result.contents = File.read(zip_filename, mode: 'rb')
  ensure
    FileUtils.remove_entry_secure(temp_dir, true)
  end

  return result
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



92
93
94
# File 'lib/openc3/models/target_model.rb', line 92

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

.get_all_command_counts(target_name, scope:) ⇒ Object



1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
# File 'lib/openc3/models/target_model.rb', line 1553

def self.get_all_command_counts(target_name, scope:)
  result = {}
  get_all = store_for_target(target_name, scope: scope).hgetall("#{scope}__COMMANDCNTS__{#{target_name}}")
  if Hash === get_all
    get_all.each do |key, value|
      result[key] = value.to_i
    end
  else
    return result
  end
end

.get_all_telemetry_counts(target_name, scope:) ⇒ Object



1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
# File 'lib/openc3/models/target_model.rb', line 1397

def self.get_all_telemetry_counts(target_name, scope:)
  result = {}
  get_all = store_for_target(target_name, scope: scope).hgetall("#{scope}__TELEMETRYCNTS__{#{target_name}}")
  if Hash === get_all
    get_all.each do |key, value|
      result[key] = value.to_i
    end
  else
    return result
  end
end

.get_command_count(target_name, packet_name, scope:) ⇒ Object



1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
# File 'lib/openc3/models/target_model.rb', line 1565

def self.get_command_count(target_name, packet_name, scope:)
  value = store_for_target(target_name, scope: scope).hget("#{scope}__COMMANDCNTS__{#{target_name}}", packet_name)
  if String === value
    return value.to_i
  elsif value.nil?
    return 0 # Return 0 if the key doesn't exist
  else
    return value
  end
end

.get_command_counts(target_packets, scope:) ⇒ Object



1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
# File 'lib/openc3/models/target_model.rb', line 1576

def self.get_command_counts(target_packets, scope:)
  # Group by db_shard, preserving original index
  db_shard_groups = {} # db_shard => [{index:, target_name:, packet_name:}]
  target_packets.each_with_index do |(target_name, packet_name), idx|
    target_name = target_name.upcase
    packet_name = packet_name.upcase
    db_shard = Store.db_shard_for_target(target_name, scope: scope)
    db_shard_groups[db_shard] ||= []
    db_shard_groups[db_shard] << { index: idx, target_name: target_name, packet_name: packet_name }
  end

  counts = Array.new(target_packets.length, 0)
  db_shard_groups.each do |db_shard, entries|
    store = Store.instance(db_shard: db_shard)
    result = store.redis_pool.pipelined do
      entries.each do |entry|
        store.hget("#{scope}__COMMANDCNTS__{#{entry[:target_name]}}", entry[:packet_name])
      end
    end
    entries.each_with_index do |entry, i|
      counts[entry[:index]] = result[i] ? result[i].to_i : 0
    end
  end
  return counts
end

.get_item_to_packet_map(target_name, scope:) ⇒ Object



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/openc3/models/target_model.rb', line 408

def self.get_item_to_packet_map(target_name, scope:)
  cache_time, item_map = @@item_map_cache[target_name]
  return item_map if item_map and (Time.now - cache_time) < ITEM_MAP_CACHE_TIMEOUT
  item_map_key = "#{scope}__#{target_name}__item_to_packet_map"
  target_name = target_name.upcase
  store = store_for_target(target_name, scope: scope)
  json_data = store.get(item_map_key)
  if json_data
    item_map = JSON.parse(json_data, allow_nan: true, create_additions: true)
  else
    item_map = build_item_to_packet_map(target_name, scope: scope)
    store.set(item_map_key, JSON.generate(item_map, allow_nan: true))
  end
  @@item_map_cache[target_name] = [Time.now, item_map]
  return item_map
end

.get_telemetry_count(target_name, packet_name, scope:) ⇒ Object



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
# File 'lib/openc3/models/target_model.rb', line 1409

def self.get_telemetry_count(target_name, packet_name, scope:)
  value = store_for_target(target_name, scope: scope).hget("#{scope}__TELEMETRYCNTS__{#{target_name}}", packet_name)
  if String === value
    return value.to_i
  elsif value.nil?
    return 0 # Return 0 if the key doesn't exist
  else
    return value
  end
end

.get_telemetry_counts(target_packets, scope:) ⇒ Object



1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
# File 'lib/openc3/models/target_model.rb', line 1420

def self.get_telemetry_counts(target_packets, scope:)
  # Group by db_shard, preserving original index
  db_shard_groups = {} # db_shard => [{index:, target_name:, packet_name:}]
  target_packets.each_with_index do |(target_name, packet_name), idx|
    target_name = target_name.upcase
    packet_name = packet_name.upcase
    db_shard = Store.db_shard_for_target(target_name, scope: scope)
    db_shard_groups[db_shard] ||= []
    db_shard_groups[db_shard] << { index: idx, target_name: target_name, packet_name: packet_name }
  end

  counts = Array.new(target_packets.length, 0)
  db_shard_groups.each do |db_shard, entries|
    store = Store.instance(db_shard: db_shard)
    result = store.redis_pool.pipelined do
      entries.each do |entry|
        store.hget("#{scope}__TELEMETRYCNTS__{#{entry[:target_name]}}", entry[:packet_name])
      end
    end
    entries.each_with_index do |entry, i|
      counts[entry[:index]] = result[i] ? result[i].to_i : 0
    end
  end
  return counts
end

.handle_config(parser, keyword, parameters, plugin: nil, needs_dependencies: false, scope:) ⇒ Object

Called by the PluginModel to allow this class to validate it's top-level keyword: "TARGET"



440
441
442
443
444
445
446
447
448
449
450
# File 'lib/openc3/models/target_model.rb', line 440

def self.handle_config(parser, keyword, parameters, plugin: nil, needs_dependencies: false, scope:)
  case keyword
  when 'TARGET'
    usage = "#{keyword} <TARGET FOLDER NAME> <TARGET NAME>"
    parser.verify_num_parameters(2, 2, usage)
    parser.verify_parameter_naming(2) # Target name is the 2nd parameter
    return self.new(name: parameters[1].to_s.upcase, folder_name: parameters[0].to_s.upcase, plugin: plugin,  needs_dependencies: needs_dependencies, scope: scope)
  else
    raise ConfigParser::Error.new(parser, "Unknown keyword and parameters for Target: #{keyword} #{parameters.join(" ")}")
  end
end

.increment_command_count(target_name, packet_name, count, scope:) ⇒ Object



1544
1545
1546
1547
1548
1549
1550
1551
# File 'lib/openc3/models/target_model.rb', line 1544

def self.increment_command_count(target_name, packet_name, count, scope:)
  result = store_for_target(target_name, scope: scope).hincrby("#{scope}__COMMANDCNTS__{#{target_name}}", packet_name, count)
  if String === result
    return result.to_i
  else
    return result
  end
end

.increment_telemetry_count(target_name, packet_name, count, scope:) ⇒ Object



1388
1389
1390
1391
1392
1393
1394
1395
# File 'lib/openc3/models/target_model.rb', line 1388

def self.increment_telemetry_count(target_name, packet_name, count, scope:)
  result = store_for_target(target_name, scope: scope).hincrby("#{scope}__TELEMETRYCNTS__{#{target_name}}", packet_name, count)
  if String === result
    return result.to_i
  else
    return result
  end
end

.init_tlm_packet_counts(tlm_target_names, scope:) ⇒ Object



1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'lib/openc3/models/target_model.rb', line 1450

def self.init_tlm_packet_counts(tlm_target_names, scope:)
  @@sync_packet_count_time = Time.now
  @@stale_packet_keys_warned = Set.new

  # Get all the packet counts with the global counters
  tlm_target_names.each do |target_name|
    get_all_telemetry_counts(target_name, scope: scope).each do |packet_name, count|
      begin
        update_packet = System.telemetry.packet(target_name, packet_name)
        update_packet.received_count = count.to_i
      rescue RuntimeError
        key = "#{target_name} #{packet_name}"
        unless @@stale_packet_keys_warned.include?(key)
          @@stale_packet_keys_warned.add(key)
          Logger.warn("Stale tlmcnt Redis key detected for unknown packet #{key} - ignoring")
        end
      end
    end
  end
  get_all_telemetry_counts('UNKNOWN', scope: scope).each do |packet_name, count|
    begin
      update_packet = System.telemetry.packet('UNKNOWN', packet_name)
      update_packet.received_count = count.to_i
    rescue RuntimeError
      key = "UNKNOWN #{packet_name}"
      unless @@stale_packet_keys_warned.include?(key)
        @@stale_packet_keys_warned.add(key)
        Logger.warn("Stale tlmcnt Redis key detected for unknown packet #{key} - ignoring")
      end
    end
  end
end

.limits_groups(scope:) ⇒ Hash{String => Array<Array<String, String, String>>}

Returns:



399
400
401
402
403
404
405
406
# File 'lib/openc3/models/target_model.rb', line 399

def self.limits_groups(scope:)
  groups = Store.hgetall("#{scope}__limits_groups")
  if groups
    groups.map { |group, items| [group, JSON.parse(items, allow_nan: true, create_additions: true)] }.to_h
  else
    {}
  end
end

.modified_files(target_name, scope:) ⇒ Object

Given target's modified file list



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/openc3/models/target_model.rb', line 187

def self.modified_files(target_name, scope:)
  modified = []

  if ENV['OPENC3_LOCAL_MODE']
    modified = OpenC3::LocalMode.modified_files(target_name, scope: scope)
  else
    resp = Bucket.getClient().list_objects(
      bucket: ENV['OPENC3_CONFIG_BUCKET'],
      # The trailing slash is important!
      prefix: "#{scope}/targets_modified/#{target_name}/",
    )
    resp.each do |item|
      # Results look like DEFAULT/targets_modified/INST/procedures/new.rb
      # so split on '/' and ignore the first two values
      modified << item.key.split('/')[2..-1].join('/')
    end
  end
  # Sort to enable a consistent listing of the modified files
  modified.sort
end

.names(scope:) ⇒ Object



96
97
98
# File 'lib/openc3/models/target_model.rb', line 96

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

.packet(target_name, packet_name, type: :TLM, scope:) ⇒ Hash

Returns Packet hash or raises an exception.

Returns:

  • (Hash)

    Packet hash or raises an exception



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/openc3/models/target_model.rb', line 285

def self.packet(target_name, packet_name, type: :TLM, scope:)
  raise "Unknown type #{type} for #{target_name} #{packet_name}" unless VALID_TYPES.include?(type)

  # Check cache first
  cache_key = "#{scope}__#{type}__#{target_name}__#{packet_name}"
  @@packet_cache_mutex.synchronize do
    cached = @@packet_cache[cache_key]
    if cached && (Time.now - cached[:time]) < PACKET_CACHE_TIMEOUT
      return cached[:packet]
    end
  end

  # Assume it exists and just try to get it to avoid an extra call to Store.exist?
  json = store_for_target(target_name, scope: scope).hget("#{scope}__openc3#{type.to_s.downcase}__#{target_name}", packet_name)
  raise "Packet definition '#{target_name} #{packet_name}' does not exist" if json.nil?

  packet = JSON.parse(json, allow_nan: true, create_additions: true)

  # Store in cache
  @@packet_cache_mutex.synchronize do
    @@packet_cache[cache_key] = { packet: packet, time: Time.now }
  end

  packet
end

.packet_item(target_name, packet_name, item_name, type: :TLM, scope:) ⇒ Hash

Returns Item hash or raises an exception.

Returns:

  • (Hash)

    Item hash or raises an exception



353
354
355
356
357
358
# File 'lib/openc3/models/target_model.rb', line 353

def self.packet_item(target_name, packet_name, item_name, type: :TLM, scope:)
  packet = packet(target_name, packet_name, type: type, scope: scope)
  item = packet['items'].find { |item| item['name'] == item_name.to_s }
  raise "Item '#{packet['target_name']} #{packet['packet_name']} #{item_name}' does not exist (TargetModel)" unless item
  item
end

.packet_items(target_name, packet_name, items, type: :TLM, scope:) ⇒ Array<Hash>

Returns Item hash array or raises an exception.

Returns:

  • (Array<Hash>)

    Item hash array or raises an exception



361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/openc3/models/target_model.rb', line 361

def self.packet_items(target_name, packet_name, items, type: :TLM, scope:)
  packet = packet(target_name, packet_name, type: type, scope: scope)
  found = packet['items'].find_all { |item| items.map(&:to_s).include?(item['name']) }
  if found.length != items.length # we didn't find them all
    found_items = found.collect { |item| item['name'] }
    not_found = []
    (items - found_items).each do |item|
      not_found << "'#{target_name} #{packet_name} #{item}'"
    end
    # 'does not exist' not grammatically correct but we use it in every other exception
    raise "Item(s) #{not_found.join(', ')} does not exist"
  end
  found
end

.packets(target_name, type: :TLM, scope:) ⇒ Array<Hash>

Returns All packet hashes under the target_name.

Returns:

  • (Array<Hash>)

    All packet hashes under the target_name



318
319
320
321
322
323
324
325
326
327
328
# File 'lib/openc3/models/target_model.rb', line 318

def self.packets(target_name, type: :TLM, scope:)
  raise "Unknown type #{type} for #{target_name}" unless VALID_TYPES.include?(type)
  raise "Target '#{target_name}' does not exist for scope: #{scope} (TargetModel)" unless get(name: target_name, scope: scope)

  result = []
  packets = store_for_target(target_name, scope: scope).hgetall("#{scope}__openc3#{type.to_s.downcase}__#{target_name}")
  packets.sort.each do |_packet_name, packet_json|
    result << JSON.parse(packet_json, allow_nan: true, create_additions: true)
  end
  result
end

.plugin_base_name(target_name, scope:) ⇒ Object

Version-stripped plugin base name that owns this target, e.g. "openc3-cosmos-demo" from instance "openc3-cosmos-demo-7.2.0.gem__0". Used as the per-plugin Version History repo key: stable across upgrades (only the version segment changes), so history survives version bumps. Returns nil when the target has no owning plugin (e.g. a hand-created target); callers fall back to a no-plugin bucket.



160
161
162
163
164
165
166
# File 'lib/openc3/models/target_model.rb', line 160

def self.plugin_base_name(target_name, scope:)
  model = get(name: target_name, scope: scope)
  name, _version = plugin_name_version(model && model['plugin'])
  name
rescue
  nil
end

.plugin_name_version(plugin_instance) ⇒ Object

Splits a plugin instance name ("openc3-cosmos-demo-7.2.0.gem__0") into [base_name, version] (["openc3-cosmos-demo", "7.2.0"]), or nil when the name doesn't carry a version segment. Drops the "__N" install-instance suffix and the ".gem" extension first.



133
134
135
136
137
138
139
# File 'lib/openc3/models/target_model.rb', line 133

def self.plugin_name_version(plugin_instance)
  return nil if plugin_instance.nil? || plugin_instance.empty?
  gem = plugin_instance.split('__')[0].sub(/\.gem\z/, '')
  parts = gem.split('-')
  return nil if parts.length < 2
  [parts[0..-2].join('-'), parts[-1]]
end

.plugin_version_label(target_name, scope:) ⇒ Object

"name version" of the plugin that installed this target (e.g. "openc3-cosmos-demo 7.2.0"), derived from the plugin instance name ("openc3-cosmos-demo-7.2.0.gem__0"), or nil if unavailable. Used to annotate the Version History baseline with the file's origin.



145
146
147
148
149
150
151
152
# File 'lib/openc3/models/target_model.rb', line 145

def self.plugin_version_label(target_name, scope:)
  model = get(name: target_name, scope: scope)
  name, version = plugin_name_version(model && model['plugin'])
  return nil unless name
  "#{name} #{version}"
rescue
  nil
end

.rebuild_target_allitems_list(target_name, type: :TLM, scope:) ⇒ Object



383
384
385
386
387
388
389
390
391
# File 'lib/openc3/models/target_model.rb', line 383

def self.rebuild_target_allitems_list(target_name, type: :TLM, scope:)
  packets = packets(target_name, type: type, scope: scope)
  packets.each do |packet|
    packet['items'].each do |item|
      TargetModel.add_to_target_allitems_list(target_name, item['name'], scope: scope)
    end
  end
  store_for_target(target_name, scope: scope).zrange("#{scope}__openc3tlm__#{target_name}__allitems", 0, -1) # return the new sorted set to let redis do the sorting
end

.set_packet(target_name, packet_name, packet, type: :TLM, scope:) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/openc3/models/target_model.rb', line 335

def self.set_packet(target_name, packet_name, packet, type: :TLM, scope:)
  raise "Unknown type #{type} for #{target_name} #{packet_name}" unless VALID_TYPES.include?(type)

  # Invalidate cache entry
  cache_key = "#{scope}__#{type}__#{target_name}__#{packet_name}"
  @@packet_cache_mutex.synchronize do
    @@packet_cache.delete(cache_key)
  end

  begin
    store_for_target(target_name, scope: scope).hset("#{scope}__openc3#{type.to_s.downcase}__#{target_name}", packet_name, JSON.generate(packet.as_json, allow_nan: true))
  rescue JSON::GeneratorError => e
    Logger.error("Invalid text present in #{target_name} #{packet_name} #{type.to_s.downcase} packet")
    raise e
  end
end

.store_for_target(target_name, scope:) ⇒ Object

Get a Store instance routed to the correct db_shard for a target



280
281
282
# File 'lib/openc3/models/target_model.rb', line 280

def self.store_for_target(target_name, scope:)
  Store.instance(db_shard: Store.db_shard_for_target(target_name, scope: scope))
end

.sync_packet_count_delay_seconds=(value) ⇒ Object



1446
1447
1448
# File 'lib/openc3/models/target_model.rb', line 1446

def self.sync_packet_count_delay_seconds=(value)
  @@sync_packet_count_delay_seconds = value
end

.sync_tlm_packet_counts(packet, tlm_target_names, scope:) ⇒ Object



1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
# File 'lib/openc3/models/target_model.rb', line 1483

def self.sync_tlm_packet_counts(packet, tlm_target_names, scope:)
  if @@sync_packet_count_delay_seconds <= 0
    # Perfect but slow method
    packet.received_count = increment_telemetry_count(packet.target_name, packet.packet_name, 1, scope: scope)
  else
    # Eventually consistent method
    # Only sync every period (default 1 second) to avoid hammering Redis
    # This is a trade off between speed and accuracy
    # The packet count is eventually consistent
    @@sync_packet_count_data[packet.target_name] ||= {}
    @@sync_packet_count_data[packet.target_name][packet.packet_name] ||= 0
    @@sync_packet_count_data[packet.target_name][packet.packet_name] += 1

    # Ensures counters change between syncs
    update_packet = System.telemetry.packet(packet.target_name, packet.packet_name)
    update_packet.received_count += 1
    packet.received_count = update_packet.received_count

    # Check if we need to sync the packet counts
    if @@sync_packet_count_time.nil? or (Time.now - @@sync_packet_count_time) > @@sync_packet_count_delay_seconds
      @@sync_packet_count_time = Time.now

      # Increment global counters for packets received
      @@sync_packet_count_data.each do |target_name, packet_data|
        packet_data.each do |packet_name, count|
          increment_telemetry_count(target_name, packet_name, count, scope: scope)
        end
      end
      @@sync_packet_count_data = {}

      # Get all the packet counts with the global counters
      tlm_target_names.each do |target_name|
        get_all_telemetry_counts(target_name, scope: scope).each do |packet_name, count|
          begin
            update_packet = System.telemetry.packet(target_name, packet_name)
            update_packet.received_count = count.to_i
          rescue RuntimeError
            key = "#{target_name} #{packet_name}"
            unless @@stale_packet_keys_warned.include?(key)
              @@stale_packet_keys_warned.add(key)
              Logger.warn("Stale tlmcnt Redis key detected for unknown packet #{key} - ignoring")
            end
          end
        end
      end
      get_all_telemetry_counts('UNKNOWN', scope: scope).each do |packet_name, count|
        begin
          update_packet = System.telemetry.packet('UNKNOWN', packet_name)
          update_packet.received_count = count.to_i
        rescue RuntimeError
          key = "UNKNOWN #{packet_name}"
          unless @@stale_packet_keys_warned.include?(key)
            @@stale_packet_keys_warned.add(key)
            Logger.warn("Stale tlmcnt Redis key detected for unknown packet #{key} - ignoring")
          end
        end
      end
    end
  end
end

Instance Method Details

#add_topics_to_microservice(microservice_name, topics) ⇒ Object



1106
1107
1108
1109
1110
1111
1112
# File 'lib/openc3/models/target_model.rb', line 1106

def add_topics_to_microservice(microservice_name, topics)
  model = MicroserviceModel.get_model(name: microservice_name, scope: @scope)
  model.topics.concat(topics)
  model.topics.uniq!
  model.ignore_changes = true # Don't restart the microservice right now
  model.update
end

#apply_upgrade_version(name, new_data, ctx) ⇒ Object

See deploy/upgrade_context. Reads the modified shadow directly (not TargetFile.body, which would fall back to the just-overwritten pristine copy), commits it, removes it, then commits the incoming plugin content. Best-effort: a versioning failure must not abort the plugin upgrade.



762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/openc3/models/target_model.rb', line 762

def apply_upgrade_version(name, new_data, ctx)
  modified_key = "#{@scope}/targets_modified/#{name}"
  resp = @bucket.get_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: modified_key)
  return unless resp && resp.body
  old_body = resp.body.read
  # Nothing actually changed — the modification already matches the plugin.
  # Leave the (identical) shadow in place and create no version churn.
  return if old_body.b == new_data.b
  old_body = old_body.force_encoding('UTF-8') unless File.extname(name) == '.bin'
  # Preserve the pre-upgrade (user-modified) content as a version.
  # Idempotent: a no-op when it already matches the latest version.
  ::VersionStore.commit(scope: @scope, name: name, text: old_body)
  # Drop the modified shadow so the plugin file (already written to
  # targets/) becomes the live content.
  OpenC3::TargetFile.destroy(@scope, name)
  # Commit the incoming plugin content as a plugin-upgrade version,
  # attributed to the installing user.
  ::VersionStore.commit(scope: @scope, name: name, text: new_data,
    username: ctx[:username], source: 'plugin-upgrade', plugin: ctx[:plugin])
rescue => e
  Logger.warn("Version History upgrade capture failed for #{@scope}/#{name}: #{e.message}")
end

#as_json(*_a) ⇒ Object



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/openc3/models/target_model.rb', line 515

def as_json(*_a)
  {
    'name' => @name,
    'folder_name' => @folder_name,
    'requires' => @requires,
    'ignored_parameters' => @ignored_parameters,
    'ignored_items' => @ignored_items,
    'limits_groups' => @limits_groups,
    'stored_limits_mode' => @stored_limits_mode,
    'cmd_tlm_files' => @cmd_tlm_files,
    'id' => @id,
    'updated_at' => @updated_at,
    'plugin' => @plugin,
    'cmd_buffer_depth' => @cmd_buffer_depth,
    'cmd_log_cycle_time' => @cmd_log_cycle_time,
    'cmd_log_cycle_size' => @cmd_log_cycle_size,
    'cmd_log_retain_time' => @cmd_log_retain_time,
    'tlm_buffer_depth' => @tlm_buffer_depth,
    'tlm_log_cycle_time' => @tlm_log_cycle_time,
    'tlm_log_cycle_size' => @tlm_log_cycle_size,
    'tlm_log_retain_time' => @tlm_log_retain_time,
    'cmd_decom_retain_time' => @cmd_decom_retain_time,
    'tlm_decom_retain_time' => @tlm_decom_retain_time,
    'decom_flush_period' => @decom_flush_period,
    'cleanup_poll_time' => @cleanup_poll_time,
    'needs_dependencies' => @needs_dependencies,
    'target_microservices' => @target_microservices.as_json(),
    'disable_erb' => @disable_erb,
    'shard' => @shard,
    'db_shard' => @db_shard,
  }
end

#build_target_archive(temp_dir, target_folder) ⇒ Object



908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
# File 'lib/openc3/models/target_model.rb', line 908

def build_target_archive(temp_dir, target_folder)
  target_files = []
  Find.find(target_folder) { |file| target_files << file }
  target_files.sort!
  @id = OpenC3.hash_files(target_files, nil, 'SHA256').hexdigest
  File.open(File.join(target_folder, 'target_id.txt'), 'wb') { |file| file.write(@id) }
  key = "#{@scope}/targets/#{@name}/target_id.txt"
  @bucket.put_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: key, body: @id)

  # Create target archive zip file
  prefix = File.dirname(target_folder) + '/'
  output_file = File.join(temp_dir, @name + '_' + @id + '.zip')
  Zip.continue_on_exists_proc = true
  Zip::File.open(output_file, create: true) do |zipfile|
    target_files.each do |target_file|
      zip_file_path = target_file.delete_prefix(prefix)
      if File.directory?(target_file)
        zipfile.mkdir(zip_file_path)
      else
        zipfile.add(zip_file_path, target_file)
      end
    end
  end

  # Write Target Archive to bucket
  File.open(output_file, 'rb') do |file|
    bucket_key = key = "#{@scope}/target_archives/#{@name}/#{@name}_current.zip"
    @bucket.put_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: bucket_key, body: file)
  end
  File.open(output_file, 'rb') do |file|
    bucket_key = key = "#{@scope}/target_archives/#{@name}/#{@name}_#{@id}.zip"
    @bucket.put_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: bucket_key, body: file)
  end
end

#check_column_header_lengths(system) ⇒ Object



796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
# File 'lib/openc3/models/target_model.rb', line 796

def check_column_header_lengths(system)
  too_long = []
  [system.packet_config.telemetry, system.packet_config.commands].each do |packets_by_target|
    packets_by_target.each do |target_name, packets|
      packets.each do |packet_name, packet|
        packet.sorted_items.each do |item|
          if item.name.length > MAX_COLUMN_HEADER_LENGTH
            too_long << "#{target_name} #{packet_name} #{item.name} (#{item.name.length})"
          end
        end
      end
    end
  end
  unless too_long.empty?
    raise "Item / parameter names must be #{MAX_COLUMN_HEADER_LENGTH} characters or less (QuestDB column header limit). The following are too long:\n  #{too_long.join("\n  ")}"
  end
end

#collect_modified_diff(name, new_data, collector) ⇒ Object

Dry-run companion to apply_upgrade_version: append name to collector when a modified copy exists and differs (by bytes) from the rendered plugin content. Read-only.



788
789
790
791
792
793
794
# File 'lib/openc3/models/target_model.rb', line 788

def collect_modified_diff(name, new_data, collector)
  resp = @bucket.get_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: "#{@scope}/targets_modified/#{name}")
  return unless resp && resp.body
  collector << name if resp.body.read.b != new_data.b
rescue => e
  Logger.warn("Modified diff check failed for #{@scope}/#{name}: #{e.message}")
end

#deploy(gem_path, variables, validate_only: false, upgrade_context: nil) ⇒ Object

upgrade_context (plugin upgrades only) drives two modes, both keyed by the deployed file name "TARGET/sub/path" (matches modified_files output):

{ diff_collector: [] } ??? dry run (with validate_only): append the names
of modified files whose live content differs from the rendered plugin
content. Read-only; used to warn before an upgrade.
{ username:, plugin: "name version", version_files: [<name>...] } ??? for
each listed file with a modified copy: record the modified copy in
Version History, drop the shadow so the plugin content becomes current,
then commit the incoming content as a plugin-upgrade version.

nil (the default and Core builds without VersionStore) = no-op.



667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/openc3/models/target_model.rb', line 667

def deploy(gem_path, variables, validate_only: false, upgrade_context: nil)
  variables["target_name"] = @name
  start_path = "/targets/#{@folder_name}/"
  temp_dir = Dir.mktmpdir
  found = false
  diff_collector = upgrade_context && upgrade_context[:diff_collector]
  versioning = !validate_only && upgrade_context && upgrade_context[:version_files] && version_store_available?
  begin
    target_path = gem_path + start_path + "**/*"
    Dir.glob(target_path) do |filename|
      next if filename == '.' or filename == '..' or File.directory?(filename)

      path = filename.split(gem_path)[-1]
      target_folder_path = path.split(start_path)[-1]
      key = "#{@scope}/targets/#{@name}/#{target_folder_path}"

      # Load target files
      @filename = filename # For render
      data = File.read(filename, mode: "rb")
      erb_disabled = check_disable_erb(filename)
      begin
        unless erb_disabled
          OpenC3.set_working_dir(File.dirname(filename)) do
            if ERB_EXTENSIONS.include?(File.extname(filename).downcase) and File.basename(filename)[0] != '_'
              data = ERB.new(data.force_encoding("UTF-8").comment_erb(), trim_mode: "-").result(binding.set_variables(variables))
            end
          end
        end
      rescue => e
        # ERB error parsing a screen is just a logger error because life can go on
        # With cmd/tlm or scripts this is a serious error and we raise
        if (filename.include?('/screens/'))
          Logger.error("ERB error parsing #{key} due to #{e.message}")
        else
          raise "ERB error parsing #{key} due to #{e.message}"
        end
      end
      local_path = File.join(temp_dir, @name, target_folder_path)
      FileUtils.mkdir_p(File.dirname(local_path))
      File.open(local_path, 'wb') { |file| file.write(data) }
      found = true
      @bucket.put_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: key, body: data) unless validate_only

      # Plugin upgrade: either collect this file into the diff (dry run) or
      # take it from the plugin while preserving the modified copy in
      # Version History. Both skip files with no modified copy.
      name = "#{@name}/#{target_folder_path}"
      if diff_collector
        collect_modified_diff(name, data, diff_collector)
      elsif versioning && upgrade_context[:version_files].include?(name)
        apply_upgrade_version(name, data, upgrade_context)
      end
    end
    raise "No target files found at #{target_path}" unless found

    target_folder = File.join(temp_dir, @name)
    # Build a System for just this target
    system = System.new([@name], temp_dir)
    check_column_header_lengths(system)
    if variables["xtce_output"]
      puts "Converting target #{@name} to .xtce files in #{variables["xtce_output"]}/#{@name}"
      if variables['time_association_name'].to_s.empty?
        puts "    No packet time item given, so no TimeAssociation will be written."
      else
        puts "    Using mnemonic '#{variables['time_association_name']}' as the packet time item."
      end
      system.packet_config.to_xtce(variables["xtce_output"], variables['time_association_name'])
    end
    unless validate_only
      build_target_archive(temp_dir, target_folder)
      system = update_store(system)
      deploy_microservices(gem_path, variables, system)
      ConfigTopic.write({ kind: 'created', type: 'target', name: @name, plugin: @plugin }, scope: @scope)
    end
  ensure
    FileUtils.remove_entry_secure(temp_dir, true)
  end
end

#deploy_cleanup_microservice(gem_path, variables, instance = nil, parent = nil) ⇒ Object



1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
# File 'lib/openc3/models/target_model.rb', line 1228

def deploy_cleanup_microservice(gem_path, variables, instance = nil, parent = nil)
  microservice_name = "#{@scope}__CLEANUP#{instance}__#{@name}"
  microservice = MicroserviceModel.new(
    name: microservice_name,
    cmd: ["ruby", "cleanup_microservice.rb", microservice_name],
    work_dir: '/openc3/lib/openc3/microservices',
    plugin: @plugin,
    parent: parent,
    shard: @shard,
    db_shard: @db_shard,
    scope: @scope
  )
  microservice.create
  microservice.deploy(gem_path, variables)
  @children << microservice_name if parent
  Logger.info "Configured microservice #{microservice_name}"
end

#deploy_commmandlog_microservice(gem_path, variables, topics, instance = nil, parent = nil) ⇒ Object



1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
# File 'lib/openc3/models/target_model.rb', line 1114

def deploy_commmandlog_microservice(gem_path, variables, topics, instance = nil, parent = nil)
  microservice_name = "#{@scope}__COMMANDLOG#{instance}__#{@name}"
  microservice = MicroserviceModel.new(
    name: microservice_name,
    folder_name: @folder_name,
    cmd: ["ruby", "log_microservice.rb", microservice_name],
    work_dir: '/openc3/lib/openc3/microservices',
    options: [
      ["RAW_OR_DECOM", "RAW"],
      ["CMD_OR_TLM", "CMD"],
      ["CYCLE_TIME", @cmd_log_cycle_time],
      ["CYCLE_SIZE", @cmd_log_cycle_size],
      ["BUFFER_DEPTH", @cmd_buffer_depth]
    ],
    topics: topics,
    plugin: @plugin,
    parent: parent,
    needs_dependencies: @needs_dependencies,
    shard: @shard,
    db_shard: @db_shard,
    scope: @scope
  )
  microservice.create
  microservice.deploy(gem_path, variables)
  @children << microservice_name if parent
  Logger.info "Configured microservice #{microservice_name}"
end

#deploy_decom_microservice(target, gem_path, variables, topics, instance = nil, parent = nil) ⇒ Object



1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
# File 'lib/openc3/models/target_model.rb', line 1170

def deploy_decom_microservice(target, gem_path, variables, topics, instance = nil, parent = nil)
  microservice_name = "#{@scope}__DECOM#{instance}__#{@name}"
  # Assume Ruby initially
  filename = 'decom_microservice.rb'
  work_dir = '/openc3/lib/openc3/microservices'
  language_cmd = target.language
  if target.language == 'python'
    filename = 'decom_microservice.py'
    work_dir.sub!('openc3/lib', 'openc3/python')
    parent = nil
    # Use venv Python to ensure editable packages are found
    language_cmd = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
  end
  microservice = MicroserviceModel.new(
    name: microservice_name,
    folder_name: @folder_name,
    cmd: [language_cmd, filename, microservice_name],
    work_dir: work_dir,
    topics: topics,
    target_names: [@name],
    plugin: @plugin,
    parent: parent,
    needs_dependencies: @needs_dependencies,
    shard: @shard,
    db_shard: @db_shard,
    scope: @scope
  )
  microservice.create
  microservice.deploy(gem_path, variables)
  @children << microservice_name if parent
  Logger.info "Configured microservice #{microservice_name}"
end

#deploy_microservices(gem_path, variables, system) ⇒ Object



1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
# File 'lib/openc3/models/target_model.rb', line 1310

def deploy_microservices(gem_path, variables, system)
  command_topic_list = []
  decom_command_topic_list = []
  packet_topic_list = []
  decom_topic_list = []
  begin
    system.commands.packets(@name).each do |packet_name, _packet|
      command_topic_list << "#{@scope}__COMMAND__{#{@name}}__#{packet_name}"
      decom_command_topic_list << "#{@scope}__DECOMCMD__{#{@name}}__#{packet_name}"
    end
  rescue
    # No command packets for this target
  end
  begin
    system.telemetry.packets(@name).each do |packet_name, _packet|
      packet_topic_list << "#{@scope}__TELEMETRY__{#{@name}}__#{packet_name}"
      decom_topic_list  << "#{@scope}__DECOM__{#{@name}}__#{packet_name}"
    end
  rescue
    # No telemetry packets for this target
  end

  @parent = nil
  %w(DECOM COMMANDLOG PACKETLOG CLEANUP).each do |type|
    unless @target_microservices[type]
      @parent = "#{@scope}__MULTI__#{@name}"
      break
    end
  end

  unless command_topic_list.empty?
    # CommandLog Microservice
    deploy_target_microservices('COMMANDLOG', command_topic_list, "#{@scope}__COMMAND__{#{@name}}") do |topics, instance, parent|
      deploy_commmandlog_microservice(gem_path, variables, topics, instance, parent)
    end
  end

  unless packet_topic_list.empty?
    # PacketLog Microservice
    deploy_target_microservices('PACKETLOG', packet_topic_list, "#{@scope}__TELEMETRY__{#{@name}}") do |topics, instance, parent|
      deploy_packetlog_microservice(gem_path, variables, topics, instance, parent)
    end
  end

  # Decommutation Microservice - also handles build_cmd / inject_tlm /
  # get_tlm_buffer via the DECOMINTERFACE topic, so deploy whenever the
  # target has commands or telemetry, not just telemetry.
  if packet_topic_list.any?
    deploy_target_microservices('DECOM', packet_topic_list, "#{@scope}__TELEMETRY__{#{@name}}") do |topics, instance, parent|
      deploy_decom_microservice(system.targets[@name], gem_path, variables, topics, instance, parent)
    end
  elsif command_topic_list.any?
    # Cmd-only target: deploy DECOM with no tlm topics so build_cmd works.
    # DecomMicroservice subscribes to DECOMINTERFACE in its initializer.
    deploy_decom_microservice(system.targets[@name], gem_path, variables, [], nil, @parent)
  end

  # TSDB Microservice - subscribes to both decommutated telemetry and commands
  tsdb_topic_list = decom_topic_list + decom_command_topic_list
  if !tsdb_topic_list.empty? and ENV['OPENC3_TSDB_HOSTNAME'] and ENV['OPENC3_TSDB_QUERY_PORT'] and ENV['OPENC3_TSDB_INGEST_PORT'] and ENV['OPENC3_TSDB_USERNAME'] and ENV['OPENC3_TSDB_PASSWORD']
    deploy_target_microservices('TSDB', tsdb_topic_list, "#{@scope}__DECOM") do |topics, instance, parent|
      deploy_tsdb_microservice(gem_path, variables, topics, instance, parent)
    end
  end

  if @cmd_log_retain_time or @tlm_log_retain_time
    # Cleanup Microservice
    deploy_target_microservices('CLEANUP', nil, nil) do |_, instance, parent|
      deploy_cleanup_microservice(gem_path, variables, instance, parent)
    end
  end

  if @parent
    # Multi Microservice to parent other target microservices
    deploy_multi_microservice(gem_path, variables)
  end
end

#deploy_multi_microservice(gem_path, variables, instance = nil) ⇒ Object



1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
# File 'lib/openc3/models/target_model.rb', line 1246

def deploy_multi_microservice(gem_path, variables, instance = nil)
  if @children.length > 0
    microservice_name = "#{@scope}__MULTI#{instance}__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      cmd: ["ruby", "multi_microservice.rb", *@children],
      work_dir: '/openc3/lib/openc3/microservices',
      plugin: @plugin,
      needs_dependencies: @needs_dependencies,
      shard: @shard,
      db_shard: @db_shard,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"
  end
end

#deploy_packetlog_microservice(gem_path, variables, topics, instance = nil, parent = nil) ⇒ Object



1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File 'lib/openc3/models/target_model.rb', line 1142

def deploy_packetlog_microservice(gem_path, variables, topics, instance = nil, parent = nil)
  microservice_name = "#{@scope}__PACKETLOG#{instance}__#{@name}"
  microservice = MicroserviceModel.new(
    name: microservice_name,
    folder_name: @folder_name,
    cmd: ["ruby", "log_microservice.rb", microservice_name],
    work_dir: '/openc3/lib/openc3/microservices',
    options: [
      ["RAW_OR_DECOM", "RAW"],
      ["CMD_OR_TLM", "TLM"],
      ["CYCLE_TIME", @tlm_log_cycle_time],
      ["CYCLE_SIZE", @tlm_log_cycle_size],
      ["BUFFER_DEPTH", @tlm_buffer_depth]
    ],
    topics: topics,
    plugin: @plugin,
    parent: parent,
    needs_dependencies: @needs_dependencies,
    shard: @shard,
    db_shard: @db_shard,
    scope: @scope
  )
  microservice.create
  microservice.deploy(gem_path, variables)
  @children << microservice_name if parent
  Logger.info "Configured microservice #{microservice_name}"
end

#deploy_target_microservices(type, base_topic_list, topic_prefix) ⇒ Object



1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
# File 'lib/openc3/models/target_model.rb', line 1265

def deploy_target_microservices(type, base_topic_list, topic_prefix)
  target_microservices = @target_microservices[type]
  if target_microservices
    # These are stand alone microservice(s) ... not part of MULTI
    if base_topic_list
      # Only create the microservice if there are topics
      # This prevents creation of DECOM with no TLM Packets (for example)
      deploy_count = 0
      all_topics = base_topic_list.dup

      # Figure out if there are individual packets assigned to this microservice
      target_microservices.sort! {|a, b| a.length <=> b.length}
      target_microservices.each_with_index do |packet_names, _index|
        topics = []
        packet_names.each do |packet_name|
          topics << "#{topic_prefix}__#{packet_name}"
        end
        topics = all_topics.dup if topics.length <= 0
        if topics.length > 0
          instance = nil
          instance = deploy_count unless deploy_count == 0
          yield topics, instance, nil
          deploy_count += 1
          topics.each do |topic|
            all_topics.delete(topic)
          end
        end
      end
      # If there are any topics (packets) left over that haven't been
      # explicitly handled above, spawn another microservice
      if all_topics.length > 0
        instance = nil
        instance = deploy_count unless deploy_count == 0
        yield all_topics, instance, nil
      end
    else
      # Do not spawn the microservice
      yield nil, nil, nil
    end
  else
    # Not a stand alone microservice ... part of MULTI
    yield base_topic_list, nil, @parent if not base_topic_list or base_topic_list.length > 0
  end
end

#deploy_tsdb_microservice(gem_path, variables, topics, instance = nil, parent = nil) ⇒ Object



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
# File 'lib/openc3/models/target_model.rb', line 1203

def deploy_tsdb_microservice(gem_path, variables, topics, instance = nil, parent = nil)
  microservice_name = "#{@scope}__TSDB#{instance}__#{@name}"
  options = []
  options << ["CMD_DECOM_RETAIN_TIME", @cmd_decom_retain_time] if @cmd_decom_retain_time
  options << ["TLM_DECOM_RETAIN_TIME", @tlm_decom_retain_time] if @tlm_decom_retain_time
  options << ["DECOM_FLUSH_PERIOD", @decom_flush_period] if @decom_flush_period
  microservice = MicroserviceModel.new(
    name: microservice_name,
    folder_name: @folder_name,
    cmd: [ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python', "tsdb_microservice.py", microservice_name],
    work_dir: "/openc3/python/openc3/microservices",
    options: options,
    topics: topics,
    plugin: @plugin,
    parent: nil,
    needs_dependencies: @needs_dependencies,
    shard: @shard,
    db_shard: @db_shard,
    scope: @scope
  )
  microservice.create
  microservice.deploy(gem_path, variables)
  Logger.info "Configured microservice #{microservice_name}"
end

#dynamic_update(packets, cmd_or_tlm = :TELEMETRY, filename = "dynamic_tlm.txt") ⇒ Object

NOTE: If you call dynamic_update multiple times you should specify a different filename parameter or the last one will be overwritten



1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'lib/openc3/models/target_model.rb', line 1040

def dynamic_update(packets, cmd_or_tlm = :TELEMETRY, filename = "dynamic_tlm.txt")
  # Build hash of targets/packets
  packet_hash = {}
  packets.each do |packet|
    target_name = packet.target_name.upcase
    packet_hash[target_name] ||= {}
    packet_name = packet.packet_name.upcase
    packet_hash[target_name][packet_name] = packet
  end

  # Update Redis
  if cmd_or_tlm == :TELEMETRY
    update_store_telemetry(packet_hash, clear_old: false)
    update_store_item_map()
  else
    update_store_commands(packet_hash, clear_old: false)
  end

  # Build dynamic file for cmd_tlm
  configs = {}
  packets.each do |packet|
    target_name = packet.target_name.upcase
    configs[target_name] ||= ""
    config = configs[target_name]
    config << packet.to_config(cmd_or_tlm)
    config << "\n"
  end
  configs.each do |target_name, config|
    bucket_key = "#{@scope}/targets_modified/#{target_name}/cmd_tlm/#{filename}"
    client = Bucket.getClient()
    client.put_object(
      # Use targets_modified to save modifications
      # This keeps the original target clean (read-only)
      bucket: ENV['OPENC3_CONFIG_BUCKET'],
      key: bucket_key,
      body: config
    )
  end

  # Inform microservices of new topics
  # Need to tell loggers to log, and decom to decom
  # We do this for no downtime
  raw_topics = []
  decom_topics = []
  packets.each do |packet|
    if cmd_or_tlm == :TELEMETRY
      raw_topics << "#{@scope}__TELEMETRY__{#{@name}}__#{packet.packet_name.upcase}"
      decom_topics << "#{@scope}__DECOM__{#{@name}}__#{packet.packet_name.upcase}"
    else
      raw_topics << "#{@scope}__COMMAND__{#{@name}}__#{packet.packet_name.upcase}"
      decom_topics << "#{@scope}__DECOMCMD__{#{@name}}__#{packet.packet_name.upcase}"
    end
  end
  if cmd_or_tlm == :TELEMETRY
    Topic.write_topic("MICROSERVICE__#{@scope}__PACKETLOG__#{@name}", {'command' => 'ADD_TOPICS', 'topics' => raw_topics.as_json.to_json}, db_shard: @db_shard)
    add_topics_to_microservice("#{@scope}__PACKETLOG__#{@name}", raw_topics)
    Topic.write_topic("MICROSERVICE__#{@scope}__DECOM__#{@name}", {'command' => 'ADD_TOPICS', 'topics' => raw_topics.as_json.to_json}, db_shard: @db_shard)
    add_topics_to_microservice("#{@scope}__DECOM__#{@name}", raw_topics)
  else
    Topic.write_topic("MICROSERVICE__#{@scope}__COMMANDLOG__#{@name}", {'command' => 'ADD_TOPICS', 'topics' => raw_topics.as_json.to_json}, db_shard: @db_shard)
    add_topics_to_microservice("#{@scope}__COMMANDLOG__#{@name}", raw_topics)
  end
  Topic.write_topic("MICROSERVICE__#{@scope}__TSDB__#{@name}", {'command' => 'ADD_TOPICS', 'topics' => decom_topics.as_json.to_json}, db_shard: @db_shard)
  add_topics_to_microservice("#{@scope}__TSDB__#{@name}", decom_topics)
end

#handle_config(parser, keyword, parameters) ⇒ Object

Handles Target specific configuration keywords



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/openc3/models/target_model.rb', line 549

def handle_config(parser, keyword, parameters)
  case keyword
  when 'CMD_BUFFER_DEPTH'
    parser.verify_num_parameters(1, 1, "#{keyword} <Number of commands to buffer to ensure logged in order>")
    @cmd_buffer_depth = parameters[0].to_i
  when 'CMD_LOG_CYCLE_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum time between files in seconds>")
    @cmd_log_cycle_time = parameters[0].to_i
  when 'CMD_LOG_CYCLE_SIZE'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum file size in bytes>")
    @cmd_log_cycle_size = parameters[0].to_i
  when 'CMD_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for raw cmd log files in seconds - nil = Forever>")
    @cmd_log_retain_time = ConfigParser.handle_nil(parameters[0])
    @cmd_log_retain_time = @cmd_log_retain_time.to_i if @cmd_log_retain_time
  when 'CMD_DECOM_LOG_CYCLE_TIME', 'CMD_DECOM_LOG_CYCLE_SIZE', 'CMD_DECOM_LOG_RETAIN_TIME'
    # DEPRECATED keywords - do nothing
  when 'TLM_BUFFER_DEPTH'
    parser.verify_num_parameters(1, 1, "#{keyword} <Number of telemetry packets to buffer to ensure logged in order>")
    @tlm_buffer_depth = parameters[0].to_i
  when 'TLM_LOG_CYCLE_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum time between files in seconds>")
    @tlm_log_cycle_time = parameters[0].to_i
  when 'TLM_LOG_CYCLE_SIZE'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum file size in bytes>")
    @tlm_log_cycle_size = parameters[0].to_i
  when 'TLM_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for raw tlm log files in seconds - nil = Forever>")
    @tlm_log_retain_time = ConfigParser.handle_nil(parameters[0])
    @tlm_log_retain_time = @tlm_log_retain_time.to_i if @tlm_log_retain_time
  when 'TLM_DECOM_LOG_CYCLE_TIME', 'TLM_DECOM_LOG_CYCLE_SIZE', 'TLM_DECOM_LOG_RETAIN_TIME'
    # DEPRECATED keywords - do nothing
  when 'CMD_DECOM_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time with unit (e.g., 30d, 1y) - nil = Forever>")
    @cmd_decom_retain_time = ConfigParser.handle_nil(parameters[0])
    if @cmd_decom_retain_time and !@cmd_decom_retain_time.match?(/^\d+[hdwMy]$/)
      raise ConfigParser::Error.new(parser, "CMD_DECOM_RETAIN_TIME must be a number followed by h, d, w, M, or y (e.g., 24h, 7d, 1y)")
    end
  when 'TLM_DECOM_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time with unit (e.g., 30d, 1y) - nil = Forever>")
    @tlm_decom_retain_time = ConfigParser.handle_nil(parameters[0])
    if @tlm_decom_retain_time and !@tlm_decom_retain_time.match?(/^\d+[hdwMy]$/)
      raise ConfigParser::Error.new(parser, "TLM_DECOM_RETAIN_TIME must be a number followed by h, d, w, M, or y (e.g., 24h, 7d, 1y)")
    end
  when 'DECOM_FLUSH_PERIOD'
    parser.verify_num_parameters(1, 1, "#{keyword} <Flush period in seconds>")
    @decom_flush_period = Float(parameters[0])
  when 'REDUCED_MINUTE_LOG_RETAIN_TIME', 'REDUCED_HOUR_LOG_RETAIN_TIME', 'REDUCED_DAY_LOG_RETAIN_TIME', 'REDUCED_LOG_RETAIN_TIME'
    # DEPRECATED
  when 'REDUCER_DISABLE', 'REDUCER_DISABLED', 'REDUCER_MAX_CPU_UTILIZATION', 'REDUCED_MAX_CPU_UTILIZATION'
    # DEPRECATED
  when 'LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for all raw log files in seconds - nil = Forever>")
    log_retain_time = ConfigParser.handle_nil(parameters[0])
    if log_retain_time
      @cmd_log_retain_time = log_retain_time.to_i
      @tlm_log_retain_time = log_retain_time.to_i
    end
  when 'CLEANUP_POLL_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Cleanup polling period in seconds>")
    @cleanup_poll_time = parameters[0].to_i
  when 'TARGET_MICROSERVICE'
    parser.verify_num_parameters(1, 1, "#{keyword} <Type: DECOM COMMANDLOG PACKETLOG CLEANUP>")
    type = parameters[0].to_s.upcase
    unless %w(DECOM COMMANDLOG PACKETLOG CLEANUP).include?(type)
      raise "Unknown TARGET_MICROSERVICE #{type}"
    end
    @target_microservices[type] ||= []
    @target_microservices[type] << []
    @current_target_microservice = type
  when 'PACKET'
    if @current_target_microservice
      parser.verify_num_parameters(1, 1, "#{keyword} <Packet Name>")
      if @current_target_microservice == 'CLEANUP'
        raise ConfigParser::Error.new(parser, "PACKET cannot be used with target microservice #{@current_target_microservice}")
      end
      @target_microservices[@current_target_microservice][-1] << parameters[0].to_s.upcase
    else
      raise ConfigParser::Error.new(parser, "PACKET cannot be used without a TARGET_MICROSERVICE")
    end
  when 'DISABLE_ERB'
    # 0 to unlimited parameters
    @disable_erb ||= []
    if parameters
      @disable_erb.concat(parameters)
    end
  when 'SHARD'
    parser.verify_num_parameters(1, 1, "#{keyword} <Shard Number Starting from 0>")
    @shard = Integer(parameters[0])

  when 'DB_SHARD'
    parser.verify_num_parameters(1, 1, "#{keyword} <Shard Number Starting from 0>")
    @db_shard = Integer(parameters[0])

  when 'STORED_LIMITS_MODE'
    parser.verify_num_parameters(1, 1, "#{keyword} <PROCESS, LOG, or DISABLE>")
    mode = parameters[0].to_s.upcase
    unless %w(PROCESS LOG DISABLE).include?(mode)
      raise ConfigParser::Error.new(parser, "STORED_LIMITS_MODE must be one of PROCESS, LOG, or DISABLE")
    end
    @stored_limits_mode = mode

  else
    raise ConfigParser::Error.new(parser, "Unknown keyword and parameters for Target: #{keyword} #{parameters.join(" ")}")
  end
  return nil
end

#render(template_name, options = {}) ⇒ Object

Called by the ERB template to render a partial



877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/openc3/models/target_model.rb', line 877

def render(template_name, options = {})
  raise "Partial name '#{template_name}' must begin with an underscore." if File.basename(template_name)[0] != '_'

  b = binding
  b.local_variable_set(:target_name, @name)
  if options[:locals]
    options[:locals].each { |key, value| b.local_variable_set(key, value) }
  end

  # Assume the file is there. If not we raise a pretty obvious error
  if File.expand_path(template_name) == template_name # absolute path
    path = template_name
  else # relative to the current @filename
    path = File.join(File.dirname(@filename), template_name)
  end

  data = File.read(path, mode: "rb")
  erb_disabled = check_disable_erb(path)
  begin
    if erb_disabled
      return data
    else
      OpenC3.set_working_dir(File.dirname(path)) do
        return ERB.new(data.force_encoding("UTF-8").comment_erb(), trim_mode: "-").result(b)
      end
    end
  rescue => e
    raise "ERB error parsing: #{path}: #{e.formatted}"
  end
end

#undeployObject



814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
# File 'lib/openc3/models/target_model.rb', line 814

def undeploy
  prefix = "#{@scope}/targets/#{@name}/"
  objects = @bucket.list_objects(bucket: ENV['OPENC3_CONFIG_BUCKET'], prefix: prefix)
  keys = objects.map(&:key)
  if keys.length > 0
    # Batch delete in chunks of 1000 (S3 limit)
    keys.each_slice(1000) do |key_batch|
      @bucket.delete_objects(bucket: ENV['OPENC3_CONFIG_BUCKET'], keys: key_batch)
    end
  end

  self.class.get_model(name: @name, scope: @scope).limits_groups.each do |group|
    Store.hdel("#{@scope}__limits_groups", group)
  end
  self.class.packets(@name, type: :CMD, scope: @scope).each do |packet|
    Topic.del("#{@scope}__COMMAND__{#{@name}}__#{packet['packet_name']}", db_shard: @db_shard)
    Topic.del("#{@scope}__DECOMCMD__{#{@name}}__#{packet['packet_name']}", db_shard: @db_shard)
  end
  self.class.packets(@name, scope: @scope).each do |packet|
    Topic.del("#{@scope}__TELEMETRY__{#{@name}}__#{packet['packet_name']}", db_shard: @db_shard)
    Topic.del("#{@scope}__DECOM__{#{@name}}__#{packet['packet_name']}", db_shard: @db_shard)
    CvtModel.del(target_name: @name, packet_name: packet['packet_name'], scope: @scope)
  end
  LimitsEventTopic.delete(@name, scope: @scope)
  db_shard_store = Store.instance(db_shard: @db_shard)
  db_shard_store.del("#{@scope}__openc3tlm__#{@name}")
  db_shard_store.del("#{@scope}__openc3cmd__#{@name}")
  db_shard_store.del("#{@scope}__TELEMETRYCNTS__{#{@name}}")
  db_shard_store.del("#{@scope}__COMMANDCNTS__{#{@name}}")

  # Note: these match the names of the services in deploy_microservices
  %w(MULTI DECOM COMMANDLOG PACKETLOG CLEANUP).each do |type|
    target_microservices = @target_microservices[type]
    if target_microservices
      max_instances = target_microservices.length + 1
    else
      max_instances = 1
    end
    max_instances.times do |index|
      instance = nil
      instance = index unless index == 0
      model = MicroserviceModel.get_model(name: "#{@scope}__#{type}#{instance}__#{@name}", scope: @scope)
      model.destroy if model
    end
  end
  # Delete item_map
  item_map_key = "#{@scope}__#{@name}__item_to_packet_map"
  db_shard_store.del(item_map_key)
  @@item_map_cache[@name] = nil

  topic = { kind: 'deleted', type: 'target', name: @name }
  # The UNKNOWN target doesn't have an associated plugin
  topic[:plugin] = @plugin if @plugin
  ConfigTopic.write(topic, scope: @scope)
rescue Exception => e
  Logger.error("Error undeploying target model #{@name} in scope #{@scope} due to #{e}")
end

#update_store(system, clear_old: true) ⇒ Object



1028
1029
1030
1031
1032
1033
1034
1035
1036
# File 'lib/openc3/models/target_model.rb', line 1028

def update_store(system, clear_old: true)
  update_target_model(system)
  update_store_telemetry(system.telemetry.all, clear_old: clear_old)
  update_store_commands(system.commands.all, clear_old: clear_old)
  update_store_limits_groups(system)
  update_store_limits_sets(system)
  update_store_item_map()
  return system
end

#update_store_commands(packet_hash, clear_old: true) ⇒ Object



981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
# File 'lib/openc3/models/target_model.rb', line 981

def update_store_commands(packet_hash, clear_old: true)
  db_shard_store = Store.instance(db_shard: @db_shard)
  packet_hash.each do |target_name, packets|
    if clear_old
      db_shard_store.del("#{@scope}__openc3cmd__#{target_name}")
      db_shard_store.del("#{@scope}__COMMANDCNTS__{#{target_name}}")
    end
    packets.each do |packet_name, packet|
      Logger.debug "Configuring cmd packet: #{target_name} #{packet_name}"
      begin
        db_shard_store.hset("#{@scope}__openc3cmd__#{target_name}", packet_name, JSON.generate(packet.as_json, allow_nan: true))
      rescue JSON::GeneratorError => e
        Logger.error("Invalid text present in #{target_name} #{packet_name} cmd packet")
        raise e
      end
    end
  end
end

#update_store_item_mapObject



1020
1021
1022
1023
1024
1025
1026
# File 'lib/openc3/models/target_model.rb', line 1020

def update_store_item_map
  # Create item_map
  item_map_key = "#{@scope}__#{@name}__item_to_packet_map"
  item_map = self.class.build_item_to_packet_map(@name, scope: @scope)
  Store.instance(db_shard: @db_shard).set(item_map_key, JSON.generate(item_map, allow_nan: true))
  @@item_map_cache[@name] = [Time.now, item_map]
end

#update_store_limits_groups(system) ⇒ Object



1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
# File 'lib/openc3/models/target_model.rb', line 1000

def update_store_limits_groups(system)
  system.limits.groups.each do |group, items|
    begin
      Store.hset("#{@scope}__limits_groups", group, JSON.generate(items, allow_nan: true))
    rescue JSON::GeneratorError => e
      Logger.error("Invalid text present in #{group} limits group")
      raise e
    end
  end
end

#update_store_limits_sets(system) ⇒ Object



1011
1012
1013
1014
1015
1016
1017
1018
# File 'lib/openc3/models/target_model.rb', line 1011

def update_store_limits_sets(system)
  sets = Store.hgetall("#{@scope}__limits_sets")
  sets ||= {}
  system.limits.sets.each do |set|
    sets[set.to_s] = "false" unless sets.key?(set.to_s)
  end
  Store.hmset("#{@scope}__limits_sets", *sets)
end

#update_store_telemetry(packet_hash, clear_old: true) ⇒ Object



955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
# File 'lib/openc3/models/target_model.rb', line 955

def update_store_telemetry(packet_hash, clear_old: true)
  db_shard_store = Store.instance(db_shard: @db_shard)
  packet_hash.each do |target_name, packets|
    if clear_old
      db_shard_store.del("#{@scope}__openc3tlm__#{target_name}")
      db_shard_store.del("#{@scope}__openc3tlm__#{target_name}__allitems")
      db_shard_store.del("#{@scope}__TELEMETRYCNTS__{#{target_name}}")
    end
    packets.each do |packet_name, packet|
      Logger.debug "Configuring tlm packet: #{target_name} #{packet_name}"
      begin
        db_shard_store.hset("#{@scope}__openc3tlm__#{target_name}", packet_name, JSON.generate(packet.as_json, allow_nan: true))
      rescue JSON::GeneratorError => e
        Logger.error("Invalid text present in #{target_name} #{packet_name} tlm packet")
        raise e
      end
      json_hash = {}
      packet.sorted_items.each do |item|
        json_hash[item.name] = nil
        TargetModel.add_to_target_allitems_list(target_name, item.name, scope: @scope)
      end
      CvtModel.set(json_hash, target_name: packet.target_name, packet_name: packet.packet_name, scope: @scope)
    end
  end
end

#update_target_model(system) ⇒ Object



943
944
945
946
947
948
949
950
951
952
953
# File 'lib/openc3/models/target_model.rb', line 943

def update_target_model(system)
  target = system.targets[@name]

  # Add in the information from the target and update
  @requires = target.requires
  @ignored_parameters = target.ignored_parameters
  @ignored_items = target.ignored_items
  @cmd_tlm_files = target.cmd_tlm_files
  @limits_groups = system.limits.groups.keys
  update()
end

#version_store_available?Boolean

Version History is an Enterprise feature. The plugin deploy runs in the cmd-tlm-api process, which (unlike script-runner-api) doesn't otherwise require the store, so lazily load it on demand. Returns false in Core builds where the Enterprise gem isn't present.

Returns:

  • (Boolean)


750
751
752
753
754
755
756
# File 'lib/openc3/models/target_model.rb', line 750

def version_store_available?
  return true if defined?(::VersionStore)
  require 'openc3-enterprise/utilities/version_store'
  defined?(::VersionStore) ? true : false
rescue LoadError
  false
end