Class: Cosmos::TargetModel

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

Overview

Manages the target in Redis. It stores the target itself under the <SCOPE>__cosmos_targets key under the target name field. All the command packets in the target are stored under the <SCOPE>__cosmoscmd__<TARGET NAME> key and the telemetry under the <SCOPE>__cosmostlm__<TARGET NAME> key. Any new limits sets are merged into the <SCOPE>__limits_sets key as fields. Any new limits groups are created under <SCOPE>__limits_groups with field name. These Redis key/fields are all removed when the undeploy method is called.

Constant Summary collapse

PRIMARY_KEY =
'cosmos_targets'
VALID_TYPES =
%i(CMD TLM)

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

#create, #destroy, filter, find_all_by_plugin, from_json, get_all_models, get_model, set, #update

Constructor Details

#initialize(name:, folder_name: nil, requires: [], ignored_parameters: [], ignored_items: [], limits_groups: [], cmd_tlm_files: [], cmd_unique_id_mode: false, tlm_unique_id_mode: false, id: nil, updated_at: nil, plugin: nil, cmd_log_cycle_time: 600, cmd_log_cycle_size: 50_000_000, cmd_log_retain_time: nil, cmd_decom_log_cycle_time: 600, cmd_decom_log_cycle_size: 50_000_000, cmd_decom_log_retain_time: nil, tlm_log_cycle_time: 600, tlm_log_cycle_size: 50_000_000, tlm_log_retain_time: nil, tlm_decom_log_cycle_time: 600, tlm_decom_log_cycle_size: 50_000_000, tlm_decom_log_retain_time: nil, reduced_minute_log_retain_time: nil, reduced_hour_log_retain_time: nil, reduced_day_log_retain_time: nil, cleanup_poll_time: 900, needs_dependencies: false, scope:) ⇒ TargetModel

Returns a new instance of TargetModel.



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/cosmos/models/target_model.rb', line 171

def initialize(
  name:,
  folder_name: nil,
  requires: [],
  ignored_parameters: [],
  ignored_items: [],
  limits_groups: [],
  cmd_tlm_files: [],
  cmd_unique_id_mode: false,
  tlm_unique_id_mode: false,
  id: nil,
  updated_at: nil,
  plugin: nil,
  cmd_log_cycle_time: 600,
  cmd_log_cycle_size: 50_000_000,
  cmd_log_retain_time: nil,
  cmd_decom_log_cycle_time: 600,
  cmd_decom_log_cycle_size: 50_000_000,
  cmd_decom_log_retain_time: nil,
  tlm_log_cycle_time: 600,
  tlm_log_cycle_size: 50_000_000,
  tlm_log_retain_time: nil,
  tlm_decom_log_cycle_time: 600,
  tlm_decom_log_cycle_size: 50_000_000,
  tlm_decom_log_retain_time: nil,
  reduced_minute_log_retain_time: nil,
  reduced_hour_log_retain_time: nil,
  reduced_day_log_retain_time: nil,
  cleanup_poll_time: 900,
  needs_dependencies: false,
  scope:
)
  super("#{scope}__#{PRIMARY_KEY}", name: name, plugin: plugin, updated_at: updated_at,
    cmd_log_cycle_time: cmd_log_cycle_time, cmd_log_cycle_size: cmd_log_cycle_size,
    cmd_log_retain_time: cmd_log_retain_time,
    cmd_decom_log_cycle_time: cmd_decom_log_cycle_time, cmd_decom_log_cycle_size: cmd_decom_log_cycle_size,
    cmd_decom_log_retain_time: cmd_decom_log_retain_time,
    tlm_log_cycle_time: tlm_log_cycle_time, tlm_log_cycle_size: tlm_log_cycle_size,
    tlm_log_retain_time: tlm_log_retain_time,
    tlm_decom_log_cycle_time: tlm_decom_log_cycle_time, tlm_decom_log_cycle_size: tlm_decom_log_cycle_size,
    tlm_decom_log_retain_time: tlm_decom_log_retain_time, 
    reduced_minute_log_retain_time: reduced_minute_log_retain_time,
    reduced_hour_log_retain_time: reduced_hour_log_retain_time, reduced_day_log_retain_time: reduced_day_log_retain_time,
    cleanup_poll_time: cleanup_poll_time, needs_dependencies: needs_dependencies,
    scope: scope)
  @folder_name = folder_name
  @requires = requires
  @ignored_parameters = ignored_parameters
  @ignored_items = ignored_items
  @limits_groups = limits_groups
  @cmd_tlm_files = cmd_tlm_files
  @cmd_unique_id_mode = cmd_unique_id_mode
  @tlm_unique_id_mode = tlm_unique_id_mode
  @id = id
  @cmd_log_cycle_time = cmd_log_cycle_time
  @cmd_log_cycle_size = cmd_log_cycle_size
  @cmd_log_retain_time = cmd_log_retain_time
  @cmd_decom_log_cycle_time = cmd_decom_log_cycle_time
  @cmd_decom_log_cycle_size = cmd_decom_log_cycle_size
  @cmd_decom_log_retain_time = cmd_decom_log_retain_time
  @tlm_log_cycle_time = tlm_log_cycle_time
  @tlm_log_cycle_size = tlm_log_cycle_size
  @tlm_log_retain_time = tlm_log_retain_time
  @tlm_decom_log_cycle_time = tlm_decom_log_cycle_time
  @tlm_decom_log_cycle_size = tlm_decom_log_cycle_size
  @tlm_decom_log_retain_time = tlm_decom_log_retain_time
  @reduced_minute_log_retain_time = reduced_minute_log_retain_time
  @reduced_hour_log_retain_time = reduced_hour_log_retain_time
  @reduced_day_log_retain_time = reduced_day_log_retain_time
  @cleanup_poll_time = cleanup_poll_time
  @needs_dependencies = needs_dependencies
end

Instance Attribute Details

#cleanup_poll_timeObject

Returns the value of attribute cleanup_poll_time.



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

def cleanup_poll_time
  @cleanup_poll_time
end

#cmd_decom_log_cycle_sizeObject

Returns the value of attribute cmd_decom_log_cycle_size.



56
57
58
# File 'lib/cosmos/models/target_model.rb', line 56

def cmd_decom_log_cycle_size
  @cmd_decom_log_cycle_size
end

#cmd_decom_log_cycle_timeObject

Returns the value of attribute cmd_decom_log_cycle_time.



55
56
57
# File 'lib/cosmos/models/target_model.rb', line 55

def cmd_decom_log_cycle_time
  @cmd_decom_log_cycle_time
end

#cmd_decom_log_retain_timeObject

Returns the value of attribute cmd_decom_log_retain_time.



57
58
59
# File 'lib/cosmos/models/target_model.rb', line 57

def cmd_decom_log_retain_time
  @cmd_decom_log_retain_time
end

#cmd_log_cycle_sizeObject

Returns the value of attribute cmd_log_cycle_size.



53
54
55
# File 'lib/cosmos/models/target_model.rb', line 53

def cmd_log_cycle_size
  @cmd_log_cycle_size
end

#cmd_log_cycle_timeObject

Returns the value of attribute cmd_log_cycle_time.



52
53
54
# File 'lib/cosmos/models/target_model.rb', line 52

def cmd_log_cycle_time
  @cmd_log_cycle_time
end

#cmd_log_retain_timeObject

Returns the value of attribute cmd_log_retain_time.



54
55
56
# File 'lib/cosmos/models/target_model.rb', line 54

def cmd_log_retain_time
  @cmd_log_retain_time
end

#cmd_tlm_filesObject

Returns the value of attribute cmd_tlm_files.



48
49
50
# File 'lib/cosmos/models/target_model.rb', line 48

def cmd_tlm_files
  @cmd_tlm_files
end

#cmd_unique_id_modeObject

Returns the value of attribute cmd_unique_id_mode.



49
50
51
# File 'lib/cosmos/models/target_model.rb', line 49

def cmd_unique_id_mode
  @cmd_unique_id_mode
end

#folder_nameObject

Returns the value of attribute folder_name.



43
44
45
# File 'lib/cosmos/models/target_model.rb', line 43

def folder_name
  @folder_name
end

#idObject

Returns the value of attribute id.



51
52
53
# File 'lib/cosmos/models/target_model.rb', line 51

def id
  @id
end

#ignored_itemsObject

Returns the value of attribute ignored_items.



46
47
48
# File 'lib/cosmos/models/target_model.rb', line 46

def ignored_items
  @ignored_items
end

#ignored_parametersObject

Returns the value of attribute ignored_parameters.



45
46
47
# File 'lib/cosmos/models/target_model.rb', line 45

def ignored_parameters
  @ignored_parameters
end

#limits_groupsObject

Returns the value of attribute limits_groups.



47
48
49
# File 'lib/cosmos/models/target_model.rb', line 47

def limits_groups
  @limits_groups
end

#needs_dependenciesObject

Returns the value of attribute needs_dependencies.



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

def needs_dependencies
  @needs_dependencies
end

#reduced_day_log_retain_timeObject

Returns the value of attribute reduced_day_log_retain_time.



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

def reduced_day_log_retain_time
  @reduced_day_log_retain_time
end

#reduced_hour_log_retain_timeObject

Returns the value of attribute reduced_hour_log_retain_time.



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

def reduced_hour_log_retain_time
  @reduced_hour_log_retain_time
end

#reduced_minute_log_retain_timeObject

Returns the value of attribute reduced_minute_log_retain_time.



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

def reduced_minute_log_retain_time
  @reduced_minute_log_retain_time
end

#requiresObject

Returns the value of attribute requires.



44
45
46
# File 'lib/cosmos/models/target_model.rb', line 44

def requires
  @requires
end

#tlm_decom_log_cycle_sizeObject

Returns the value of attribute tlm_decom_log_cycle_size.



62
63
64
# File 'lib/cosmos/models/target_model.rb', line 62

def tlm_decom_log_cycle_size
  @tlm_decom_log_cycle_size
end

#tlm_decom_log_cycle_timeObject

Returns the value of attribute tlm_decom_log_cycle_time.



61
62
63
# File 'lib/cosmos/models/target_model.rb', line 61

def tlm_decom_log_cycle_time
  @tlm_decom_log_cycle_time
end

#tlm_decom_log_retain_timeObject

Returns the value of attribute tlm_decom_log_retain_time.



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

def tlm_decom_log_retain_time
  @tlm_decom_log_retain_time
end

#tlm_log_cycle_sizeObject

Returns the value of attribute tlm_log_cycle_size.



59
60
61
# File 'lib/cosmos/models/target_model.rb', line 59

def tlm_log_cycle_size
  @tlm_log_cycle_size
end

#tlm_log_cycle_timeObject

Returns the value of attribute tlm_log_cycle_time.



58
59
60
# File 'lib/cosmos/models/target_model.rb', line 58

def tlm_log_cycle_time
  @tlm_log_cycle_time
end

#tlm_log_retain_timeObject

Returns the value of attribute tlm_log_retain_time.



60
61
62
# File 'lib/cosmos/models/target_model.rb', line 60

def tlm_log_retain_time
  @tlm_log_retain_time
end

#tlm_unique_id_modeObject

Returns the value of attribute tlm_unique_id_mode.



50
51
52
# File 'lib/cosmos/models/target_model.rb', line 50

def tlm_unique_id_mode
  @tlm_unique_id_mode
end

Class Method Details

.all(scope:) ⇒ Object



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

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

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

Returns Hash>] All packet hashes under the target_name.

Returns:

  • (Array)

    Hash>] All packet hashes under the target_name



109
110
111
# File 'lib/cosmos/models/target_model.rb', line 109

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

.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



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

def self.get(name:, scope:)
  super("#{scope}__#{PRIMARY_KEY}", name: name)
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”



159
160
161
162
163
164
165
166
167
168
169
# File 'lib/cosmos/models/target_model.rb', line 159

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, scope: scope)
  else
    raise ConfigParser::Error.new(parser, "Unknown keyword and parameters for Target: #{keyword} #{parameters.join(" ")}")
  end
end

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

Returns:



149
150
151
152
153
154
155
156
# File 'lib/cosmos/models/target_model.rb', line 149

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

.names(scope:) ⇒ Object



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

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



85
86
87
88
89
90
91
92
93
# File 'lib/cosmos/models/target_model.rb', line 85

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

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

  JSON.parse(json)
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



125
126
127
128
129
130
# File 'lib/cosmos/models/target_model.rb', line 125

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" 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



133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/cosmos/models/target_model.rb', line 133

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 gramatically 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

Returns Hash>] All packet hashes under the target_name.

Returns:

  • (Array)

    Hash>] All packet hashes under the target_name



96
97
98
99
100
101
102
103
104
105
106
# File 'lib/cosmos/models/target_model.rb', line 96

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" unless get(name: target_name, scope: scope)

  result = []
  packets = Store.hgetall("#{scope}__cosmos#{type.to_s.downcase}__#{target_name}")
  packets.sort.each do |packet_name, packet_json|
    result << JSON.parse(packet_json)
  end
  result
end

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



113
114
115
116
117
118
119
120
121
122
# File 'lib/cosmos/models/target_model.rb', line 113

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)

  begin
    Store.hset("#{scope}__cosmostlm__#{target_name}", packet_name, JSON.generate(packet.as_json))
  rescue JSON::GeneratorError => err
    Logger.error("Invalid text present in #{target_name} #{packet_name} #{type.to_s.downcase} packet")
    raise err
  end
end

Instance Method Details

#as_configObject



278
279
280
# File 'lib/cosmos/models/target_model.rb', line 278

def as_config
  "TARGET #{@folder_name} #{@name}\n"
end

#as_jsonObject



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
# File 'lib/cosmos/models/target_model.rb', line 244

def as_json
  {
    'name' => @name,
    'folder_name' => @folder_name,
    'requires' => @requires,
    'ignored_parameters' => @ignored_parameters,
    'ignored_items' => @ignored_items,
    'limits_groups' => @limits_groups,
    'cmd_tlm_files' => @cmd_tlm_files,
    'cmd_unique_id_mode' => cmd_unique_id_mode,
    'tlm_unique_id_mode' => @tlm_unique_id_mode,
    'id' => @id,
    'updated_at' => @updated_at,
    'plugin' => @plugin,
    'cmd_log_cycle_time' => @cmd_log_cycle_time,
    'cmd_log_cycle_size' => @cmd_log_cycle_size,
    'cmd_log_retain_time' => @cmd_log_retain_time,
    'cmd_decom_log_cycle_time' => @cmd_decom_log_cycle_time,
    'cmd_decom_log_cycle_size' => @cmd_decom_log_cycle_size,
    'cmd_decom_log_retain_time' => @cmd_decom_log_retain_time,
    'tlm_log_cycle_time' => @tlm_log_cycle_time,
    'tlm_log_cycle_size' => @tlm_log_cycle_size,
    'tlm_log_retain_time' => @tlm_log_retain_time,
    'tlm_decom_log_cycle_time' => @tlm_decom_log_cycle_time,
    'tlm_decom_log_cycle_size' => @tlm_decom_log_cycle_size,
    'tlm_decom_log_retain_time' => @tlm_decom_log_retain_time,
    'reduced_minute_log_retain_time' => @reduced_minute_log_retain_time,
    'reduced_hour_log_retain_time' => @reduced_hour_log_retain_time,
    'reduced_day_log_retain_time' => @reduced_day_log_retain_time,        
    'cleanup_poll_time' => @cleanup_poll_time,
    'needs_dependencies' => @needs_dependencies,
  }
end

#build_target_archive(rubys3_client, temp_dir, target_folder) ⇒ Object



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
# File 'lib/cosmos/models/target_model.rb', line 465

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

  # Create target archive zip file
  prefix = File.dirname(target_folder) + '/'
  output_file = File.join(temp_dir, @name + '_' + hash + '.zip')
  Zip.continue_on_exists_proc = true
  Zip::File.open(output_file, Zip::File::CREATE) 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 S3 Bucket
  File.open(output_file, 'rb') do |file|
    s3_key = key = "#{@scope}/target_archives/#{@name}/#{@name}_current.zip"
    rubys3_client.put_object(bucket: 'config', key: s3_key, body: file)
  end
  File.open(output_file, 'rb') do |file|
    s3_key = key = "#{@scope}/target_archives/#{@name}/#{@name}_#{hash}.zip"
    rubys3_client.put_object(bucket: 'config', key: s3_key, body: file)
  end
end

#deploy(gem_path, variables) ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/cosmos/models/target_model.rb', line 363

def deploy(gem_path, variables)
  rubys3_client = Aws::S3::Client.new
  variables["target_name"] = @name
  start_path = "/targets/#{@folder_name}/"
  temp_dir = Dir.mktmpdir
  found = false
  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")
      begin
        Cosmos.set_working_dir(File.dirname(filename)) do
          data = ERB.new(data).result(binding.set_variables(variables)) if data.is_printable? and File.basename(filename)[0] != '_'
        end
      rescue => error
        raise "ERB error parsing: #{filename}: #{error.formatted}"
      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
      rubys3_client.put_object(bucket: 'config', key: key, body: data)
    end
    raise "No target files found at #{target_path}" unless found

    target_folder = File.join(temp_dir, @name)
    build_target_archive(rubys3_client, temp_dir, target_folder)
    system = update_store(temp_dir)
    deploy_microservices(gem_path, variables, system)
  ensure
    FileUtils.remove_entry(temp_dir) if temp_dir and File.exist?(temp_dir)
  end
end

#deploy_microservices(gem_path, variables, system) ⇒ Object



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
656
657
658
659
660
661
662
663
664
665
666
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
# File 'lib/cosmos/models/target_model.rb', line 566

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
  # It's ok to call initialize_streams with an empty array
  Store.initialize_streams(command_topic_list)
  Store.initialize_streams(decom_command_topic_list)
  Store.initialize_streams(packet_topic_list)
  Store.initialize_streams(decom_topic_list)

  unless command_topic_list.empty?
    # CommandLog Microservice
    microservice_name = "#{@scope}__COMMANDLOG__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      folder_name: @folder_name,
      cmd: ["ruby", "log_microservice.rb", microservice_name],
      work_dir: '/cosmos/lib/cosmos/microservices',
      options: [
        ["RAW_OR_DECOM", "RAW"],
        ["CMD_OR_TLM", "CMD"],
        ["CYCLE_TIME", @cmd_log_cycle_time],
        ["CYCLE_SIZE", @cmd_log_cycle_size]
      ],
      topics: command_topic_list,
      target_names: [@name],
      plugin: plugin,
      needs_dependencies: @needs_dependencies,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"

    # DecomCmdLog Microservice
    microservice_name = "#{@scope}__DECOMCMDLOG__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      folder_name: @folder_name,
      cmd: ["ruby", "log_microservice.rb", microservice_name],
      work_dir: '/cosmos/lib/cosmos/microservices',
      options: [
        ["RAW_OR_DECOM", "DECOM"],
        ["CMD_OR_TLM", "CMD"],
        ["CYCLE_TIME", @cmd_decom_log_cycle_time],
        ["CYCLE_SIZE", @cmd_decom_log_cycle_size]
      ],
      topics: decom_command_topic_list,
      target_names: [@name],
      plugin: plugin,
      needs_dependencies: @needs_dependencies,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"
  end

  unless packet_topic_list.empty?
    # PacketLog Microservice
    microservice_name = "#{@scope}__PACKETLOG__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      folder_name: @folder_name,
      cmd: ["ruby", "log_microservice.rb", microservice_name],
      work_dir: '/cosmos/lib/cosmos/microservices',
      options: [
        ["RAW_OR_DECOM", "RAW"],
        ["CMD_OR_TLM", "TLM"],
        ["CYCLE_TIME", @tlm_log_cycle_time],
        ["CYCLE_SIZE", @tlm_log_cycle_size]
      ],
      topics: packet_topic_list,
      target_names: [@name],
      plugin: plugin,
      needs_dependencies: @needs_dependencies,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"

    # DecomLog Microservice
    microservice_name = "#{@scope}__DECOMLOG__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      folder_name: @folder_name,
      cmd: ["ruby", "log_microservice.rb", microservice_name],
      work_dir: '/cosmos/lib/cosmos/microservices',
      options: [
        ["RAW_OR_DECOM", "DECOM"],
        ["CMD_OR_TLM", "TLM"],
        ["CYCLE_TIME", @tlm_decom_log_cycle_time],
        ["CYCLE_SIZE", @tlm_decom_log_cycle_size]
      ],
      topics: decom_topic_list,
      target_names: [@name],
      plugin: plugin,
      needs_dependencies: @needs_dependencies,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"

    # Decommutation Microservice
    microservice_name = "#{@scope}__DECOM__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      folder_name: @folder_name,
      cmd: ["ruby", "decom_microservice.rb", microservice_name],
      work_dir: '/cosmos/lib/cosmos/microservices',
      topics: packet_topic_list,
      target_names: [@name],
      plugin: plugin,
      needs_dependencies: @needs_dependencies,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"

    # Reducer Microservice
    microservice_name = "#{@scope}__REDUCER__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      folder_name: @folder_name,
      cmd: ["ruby", "reducer_microservice.rb", microservice_name],
      work_dir: '/cosmos/lib/cosmos/microservices',
      topics: decom_topic_list,
      plugin: plugin,
      needs_dependencies: @needs_dependencies,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"
  end

  if @cmd_log_retain_time or @cmd_decom_log_retain_time or @tlm_log_retain_time or @tlm_decom_log_retain_time or
     @reduced_minute_log_retain_time or @reduced_hour_log_retain_time or @reduced_day_log_retain_time
    # Cleanup Microservice
    microservice_name = "#{@scope}__CLEANUP__#{@name}"
    microservice = MicroserviceModel.new(
      name: microservice_name,
      cmd: ["ruby", "cleanup_microservice.rb", microservice_name],
      work_dir: '/cosmos/lib/cosmos/microservices',
      plugin: plugin,
      scope: @scope
    )
    microservice.create
    microservice.deploy(gem_path, variables)
    Logger.info "Configured microservice #{microservice_name}"
  end
end

#handle_config(parser, keyword, parameters) ⇒ Object

Handles Target specific configuration keywords



283
284
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/cosmos/models/target_model.rb', line 283

def handle_config(parser, keyword, parameters)
  case keyword
  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 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'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum time between files in seconds>")
    @cmd_decom_log_cycle_time = parameters[0].to_i
  when 'CMD_DECOM_LOG_CYCLE_SIZE'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum file size in bytes>")
    @cmd_decom_log_cycle_size = parameters[0].to_i
  when 'CMD_DECOM_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for cmd decom log files in seconds - nil = Forever>")
    @cmd_decom_log_retain_time = ConfigParser.handle_nil(parameters[0])
    @cmd_decom_log_retain_time = @cmd_decom_log_retain_time.to_i if @cmd_decom_log_retain_time        
  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 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'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum time between files in seconds>")
    @tlm_decom_log_cycle_time = parameters[0].to_i
  when 'TLM_DECOM_LOG_CYCLE_SIZE'
    parser.verify_num_parameters(1, 1, "#{keyword} <Maximum file size in bytes>")
    @tlm_decom_log_cycle_size = parameters[0].to_i
  when 'TLM_DECOM_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for tlm decom log files in seconds - nil = Forever>")
    @tlm_decom_log_retain_time = ConfigParser.handle_nil(parameters[0])
    @tlm_decom_log_retain_time = @tlm_decom_log_retain_time.to_i if @tlm_decom_log_retain_time
  when 'REDUCED_MINUTE_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for reduced minute log files in seconds - nil = Forever>")
    @reduced_minute_log_retain_time = ConfigParser.handle_nil(parameters[0])
    @reduced_minute_log_retain_time = @reduced_minute_log_retain_time.to_i if @reduced_minute_log_retain_time
  when 'REDUCED_HOUR_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for reduced hour log files in seconds - nil = Forever>")
    @reduced_hour_log_retain_time = ConfigParser.handle_nil(parameters[0])
    @reduced_hour_log_retain_time = @reduced_hour_log_retain_time.to_i if @reduced_hour_log_retain_time
  when 'REDUCED_DAY_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for reduced day log files in seconds - nil = Forever>")
    @reduced_day_log_retain_time = ConfigParser.handle_nil(parameters[0])
    @reduced_day_log_retain_time = @reduced_day_log_retain_time.to_i if @reduced_day_log_retain_time                
  when 'LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for all 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
      @cmd_decom_log_retain_time = log_retain_time.to_i   
      @tlm_log_retain_time = log_retain_time.to_i
      @tlm_decom_log_retain_time = log_retain_time.to_i
    end     
  when 'REDUCED_LOG_RETAIN_TIME'
    parser.verify_num_parameters(1, 1, "#{keyword} <Retention time for all reduced log files in seconds - nil = Forever>")
    reduced_log_retain_time = ConfigParser.handle_nil(parameters[0])
    if reduced_log_retain_time 
      @reduced_minute_log_retain_time = reduced_log_retain_time.to_i
      @reduced_hour_log_retain_time = reduced_log_retain_time.to_i   
      @reduced_day_log_retain_time = reduced_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
  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



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/cosmos/models/target_model.rb', line 440

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

  begin
    Cosmos.set_working_dir(File.dirname(path)) do
      return ERB.new(File.read(path)).result(b)
    end
  rescue => error
    raise "ERB error parsing: #{path}: #{error.formatted}"
  end
end

#undeployObject



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/cosmos/models/target_model.rb', line 405

def undeploy
  rubys3_client = Aws::S3::Client.new
  prefix = "#{@scope}/targets/#{@name}/"
  rubys3_client.list_objects(bucket: 'config', prefix: prefix).contents.each do |object|
    rubys3_client.delete_object(bucket: 'config', key: object.key)
  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|
    Store.del("#{@scope}__COMMAND__{#{@name}}__#{packet['packet_name']}")
    Store.del("#{@scope}__DECOMCMD__{#{@name}}__#{packet['packet_name']}")
  end
  self.class.packets(@name, scope: @scope).each do |packet|
    Store.del("#{@scope}__TELEMETRY__{#{@name}}__#{packet['packet_name']}")
    Store.del("#{@scope}__DECOM__{#{@name}}__#{packet['packet_name']}")
    CvtModel.del(target_name: @name, packet_name: packet['packet_name'], scope: @scope)
    LimitsEventTopic.delete(@name, packet['packet_name'], scope: @scope)
  end
  Store.del("#{@scope}__cosmostlm__#{@name}")
  Store.del("#{@scope}__cosmoscmd__#{@name}")

  # Note: these match the names of the services in deploy_microservices
  %w(DECOM COMMANDLOG DECOMCMDLOG PACKETLOG DECOMLOG REDUCER CLEANUP).each do |type|
    model = MicroserviceModel.get_model(name: "#{@scope}__#{type}__#{@name}", scope: @scope)
    model.destroy if model
  end
end

#update_store(temp_dir) ⇒ Object



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/cosmos/models/target_model.rb', line 500

def update_store(temp_dir)
  # Build a System for just this target
  system = System.new([@name], temp_dir)
  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
  @cmd_unique_id_mode = target.cmd_unique_id_mode
  @tlm_unique_id_mode = target.tlm_unique_id_mode
  @id = target.id
  @limits_groups = system.limits.groups.keys
  update()

  # Store Packet Definitions
  system.telemetry.all.each do |target_name, packets|
    Store.del("#{@scope}__cosmostlm__#{target_name}")
    packets.each do |packet_name, packet|
      Logger.info "Configuring tlm packet: #{target_name} #{packet_name}"
      begin
        Store.hset("#{@scope}__cosmostlm__#{target_name}", packet_name, JSON.generate(packet.as_json))
      rescue JSON::GeneratorError => err
        Logger.error("Invalid text present in #{target_name} #{packet_name} tlm packet")
        raise err
      end
      json_hash = Hash.new
      packet.sorted_items.each do |item|
        json_hash[item.name] = nil
      end
      CvtModel.set(json_hash, target_name: packet.target_name, packet_name: packet.packet_name, scope: @scope)
    end
  end
  system.commands.all.each do |target_name, packets|
    Store.del("#{@scope}__cosmoscmd__#{target_name}")
    packets.each do |packet_name, packet|
      Logger.info "Configuring cmd packet: #{target_name} #{packet_name}"
      begin
        Store.hset("#{@scope}__cosmoscmd__#{target_name}", packet_name, JSON.generate(packet.as_json))
      rescue JSON::GeneratorError => err
        Logger.error("Invalid text present in #{target_name} #{packet_name} cmd packet")
        raise err
      end
    end
  end
  # Store Limits Groups
  system.limits.groups.each do |group, items|
    begin
      Store.hset("#{@scope}__limits_groups", group, JSON.generate(items))
    rescue JSON::GeneratorError => err
      Logger.error("Invalid text present in #{group} limits group")
      raise err
    end
  end
  # Merge in Limits Sets
  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)

  return system
end