cosmos 5.0.2 → 5.0.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (93) hide show
  1. checksums.yaml +4 -4
  2. data/bin/cosmos +183 -42
  3. data/data/config/microservice.yaml +47 -35
  4. data/data/config/plugins.yaml +10 -147
  5. data/data/config/target.yaml +70 -0
  6. data/data/config/tool.yaml +37 -31
  7. data/ext/cosmos/ext/cosmos_io/cosmos_io.c +14 -14
  8. data/ext/cosmos/ext/packet/packet.c +3 -3
  9. data/ext/cosmos/ext/structure/structure.c +31 -31
  10. data/lib/cosmos/api/api.rb +1 -25
  11. data/lib/cosmos/api/cmd_api.rb +17 -6
  12. data/lib/cosmos/api/config_api.rb +10 -4
  13. data/lib/cosmos/api/limits_api.rb +1 -1
  14. data/lib/cosmos/api/settings_api.rb +19 -7
  15. data/lib/cosmos/api/target_api.rb +2 -2
  16. data/lib/cosmos/api/tlm_api.rb +65 -41
  17. data/lib/cosmos/config/config_parser.rb +19 -22
  18. data/lib/cosmos/config/meta_config_parser.rb +1 -1
  19. data/lib/cosmos/conversions/generic_conversion.rb +2 -2
  20. data/lib/cosmos/conversions/polynomial_conversion.rb +5 -8
  21. data/lib/cosmos/conversions/segmented_polynomial_conversion.rb +26 -9
  22. data/lib/cosmos/io/json_drb.rb +5 -1
  23. data/lib/cosmos/logs/log_writer.rb +78 -29
  24. data/lib/cosmos/microservices/cleanup_microservice.rb +28 -29
  25. data/lib/cosmos/microservices/decom_microservice.rb +1 -1
  26. data/lib/cosmos/microservices/interface_microservice.rb +0 -16
  27. data/lib/cosmos/microservices/microservice.rb +3 -3
  28. data/lib/cosmos/microservices/reducer_microservice.rb +12 -10
  29. data/lib/cosmos/models/cvt_model.rb +6 -6
  30. data/lib/cosmos/models/gem_model.rb +9 -3
  31. data/lib/cosmos/models/info_model.rb +1 -1
  32. data/lib/cosmos/models/interface_model.rb +16 -7
  33. data/lib/cosmos/models/interface_status_model.rb +1 -1
  34. data/lib/cosmos/models/metadata_model.rb +69 -219
  35. data/lib/cosmos/models/metric_model.rb +2 -2
  36. data/lib/cosmos/models/microservice_model.rb +7 -4
  37. data/lib/cosmos/models/microservice_status_model.rb +1 -1
  38. data/lib/cosmos/models/model.rb +23 -16
  39. data/lib/cosmos/models/note_model.rb +122 -0
  40. data/lib/cosmos/models/ping_model.rb +2 -1
  41. data/lib/cosmos/models/plugin_model.rb +108 -48
  42. data/lib/cosmos/models/process_status_model.rb +1 -1
  43. data/lib/cosmos/models/scope_model.rb +10 -25
  44. data/lib/cosmos/models/settings_model.rb +55 -0
  45. data/lib/cosmos/models/sorted_model.rb +167 -0
  46. data/lib/cosmos/models/target_model.rb +143 -27
  47. data/lib/cosmos/models/tool_config_model.rb +38 -0
  48. data/lib/cosmos/models/tool_model.rb +9 -9
  49. data/lib/cosmos/models/widget_model.rb +11 -11
  50. data/lib/cosmos/operators/microservice_operator.rb +2 -1
  51. data/lib/cosmos/packets/packet.rb +24 -1
  52. data/lib/cosmos/packets/packet_config.rb +2 -2
  53. data/lib/cosmos/packets/packet_item.rb +57 -0
  54. data/lib/cosmos/packets/packet_item_limits.rb +14 -2
  55. data/lib/cosmos/packets/parsers/packet_item_parser.rb +1 -1
  56. data/lib/cosmos/packets/parsers/packet_parser.rb +1 -1
  57. data/lib/cosmos/packets/parsers/xtce_parser.rb +1 -1
  58. data/lib/cosmos/packets/structure.rb +30 -33
  59. data/lib/cosmos/packets/structure_item.rb +10 -1
  60. data/lib/cosmos/script/api_shared.rb +30 -25
  61. data/lib/cosmos/script/calendar.rb +37 -15
  62. data/lib/cosmos/script/commands.rb +5 -7
  63. data/lib/cosmos/script/script.rb +19 -39
  64. data/lib/cosmos/script/storage.rb +92 -105
  65. data/lib/cosmos/system/system.rb +2 -1
  66. data/lib/cosmos/tools/table_manager/table_config.rb +16 -1
  67. data/lib/cosmos/tools/table_manager/table_item.rb +1 -1
  68. data/lib/cosmos/tools/table_manager/table_manager_core.rb +213 -309
  69. data/lib/cosmos/top_level.rb +5 -1
  70. data/lib/cosmos/topics/autonomic_topic.rb +2 -2
  71. data/lib/cosmos/topics/calendar_topic.rb +1 -1
  72. data/lib/cosmos/topics/command_decom_topic.rb +35 -1
  73. data/lib/cosmos/topics/command_topic.rb +6 -4
  74. data/lib/cosmos/topics/config_topic.rb +68 -0
  75. data/lib/cosmos/topics/interface_topic.rb +8 -8
  76. data/lib/cosmos/topics/limits_event_topic.rb +5 -3
  77. data/lib/cosmos/topics/notifications_topic.rb +1 -1
  78. data/lib/cosmos/topics/router_topic.rb +9 -9
  79. data/lib/cosmos/topics/telemetry_decom_topic.rb +5 -1
  80. data/lib/cosmos/topics/telemetry_topic.rb +1 -1
  81. data/lib/cosmos/topics/timeline_topic.rb +1 -1
  82. data/lib/cosmos/topics/topic.rb +23 -8
  83. data/lib/cosmos/utilities/logger.rb +4 -3
  84. data/lib/cosmos/utilities/metric.rb +32 -26
  85. data/lib/cosmos/utilities/s3.rb +61 -0
  86. data/lib/cosmos/utilities/s3_file_cache.rb +12 -6
  87. data/lib/cosmos/utilities/store.rb +1 -0
  88. data/lib/cosmos/utilities/store_autoload.rb +25 -134
  89. data/lib/cosmos/version.rb +5 -4
  90. data/templates/plugin-template/plugin.gemspec +0 -2
  91. metadata +12 -10
  92. data/bin/xtce_converter +0 -92
  93. data/lib/cosmos/models/narrative_model.rb +0 -280
@@ -83,11 +83,6 @@ module Cosmos
83
83
  @interface.write_raw(msg_hash['raw'])
84
84
  next 'SUCCESS'
85
85
  end
86
- if msg_hash['inject_tlm']
87
- Logger.info "#{@interface.name}: Inject telemetry" if msg_hash['log']
88
- @tlm.inject_tlm(msg_hash)
89
- next 'SUCCESS'
90
- end
91
86
  if msg_hash.key?('log_raw')
92
87
  if msg_hash['log_raw'] == 'true'
93
88
  Logger.info "#{@interface.name}: Enable raw logging"
@@ -143,7 +138,6 @@ module Cosmos
143
138
  hazardous, hazardous_description = System.commands.cmd_pkt_hazardous?(command)
144
139
  # Return back the error, description, and the formatted command
145
140
  # This allows the error handler to simply re-send the command
146
- # TODO: Should we set target_name, cmd_name, and cmd_params instead?
147
141
  next "HazardousError\n#{hazardous_description}\n#{System.commands.format(command)}" if hazardous
148
142
  end
149
143
 
@@ -413,16 +407,6 @@ module Cosmos
413
407
  TelemetryTopic.write_packet(packet, scope: @scope)
414
408
  end
415
409
 
416
- def inject_tlm(hash)
417
- packet = System.telemetry.packet(hash['target_name'], hash['packet_name']).clone
418
- if hash['item_hash']
419
- JSON.parse(hash['item_hash']).each do |item, value|
420
- packet.write(item.to_s, value, hash['type'].to_sym)
421
- end
422
- end
423
- handle_packet(packet)
424
- end
425
-
426
410
  def handle_connection_failed(connect_error)
427
411
  @error = connect_error
428
412
  Logger.error "#{@interface.name}: Connection Failed: #{connect_error.formatted(false, false)}"
@@ -40,7 +40,7 @@ module Cosmos
40
40
  attr_accessor :scope
41
41
 
42
42
  def self.run
43
- microservice = self.new(ARGV[0])
43
+ microservice = self.new(ENV['COSMOS_MICROSERVICE_NAME'])
44
44
  begin
45
45
  MicroserviceStatusModel.set(microservice.as_json, scope: microservice.scope)
46
46
  microservice.state = 'RUNNING'
@@ -52,7 +52,7 @@ module Cosmos
52
52
  else
53
53
  microservice.error = err
54
54
  microservice.state = 'DIED_ERROR'
55
- Logger.fatal("Microservice #{ARGV[0]} dying from exception\n#{err.formatted}")
55
+ Logger.fatal("Microservice #{ENV['COSMOS_MICROSERVICE_NAME']} dying from exception\n#{err.formatted}")
56
56
  end
57
57
  ensure
58
58
  MicroserviceStatusModel.set(microservice.as_json, scope: microservice.scope)
@@ -75,7 +75,7 @@ module Cosmos
75
75
 
76
76
  @name = name
77
77
  split_name = name.split("__")
78
- raise "Microservice names should be scope, type, and then name" if split_name.length != 3
78
+ raise "Name #{name} doesn't match convention of SCOPE__TYPE__NAME" if split_name.length != 3
79
79
 
80
80
  @scope = split_name[0]
81
81
  $cosmos_scope = @scope
@@ -96,9 +96,8 @@ module Cosmos
96
96
  ReducerModel
97
97
  .all_files(type: :DECOM, target: @target_name, scope: @scope)
98
98
  .each do |file|
99
- if process_file(file, 'minute', MINUTE_ENTRY_SECS, MINUTE_FILE_SECS)
100
- ReducerModel.rm_file(file)
101
- end
99
+ process_file(file, 'minute', MINUTE_ENTRY_SECS, MINUTE_FILE_SECS)
100
+ ReducerModel.rm_file(file)
102
101
  end
103
102
  end
104
103
  end
@@ -108,9 +107,8 @@ module Cosmos
108
107
  ReducerModel
109
108
  .all_files(type: :MINUTE, target: @target_name, scope: @scope)
110
109
  .each do |file|
111
- if process_file(file, 'hour', HOUR_ENTRY_SECS, HOUR_FILE_SECS)
112
- ReducerModel.rm_file(file)
113
- end
110
+ process_file(file, 'hour', HOUR_ENTRY_SECS, HOUR_FILE_SECS)
111
+ ReducerModel.rm_file(file)
114
112
  end
115
113
  end
116
114
  end
@@ -120,9 +118,8 @@ module Cosmos
120
118
  ReducerModel
121
119
  .all_files(type: :HOUR, target: @target_name, scope: @scope)
122
120
  .each do |file|
123
- if process_file(file, 'day', DAY_ENTRY_SECS, DAY_FILE_SECS)
124
- ReducerModel.rm_file(file)
125
- end
121
+ process_file(file, 'day', DAY_ENTRY_SECS, DAY_FILE_SECS)
122
+ ReducerModel.rm_file(file)
126
123
  end
127
124
  end
128
125
  end
@@ -250,7 +247,12 @@ module Cosmos
250
247
  )
251
248
  true
252
249
  rescue => e
253
- Logger.error("Reducer Error #{e}\n#{e.backtrace}")
250
+ if file.local_path and File.exist?(file.local_path)
251
+ Logger.error("Reducer Error: #{filename}:#{File.size(file.local_path)} bytes: \n#{e.formatted}")
252
+ else
253
+ Logger.error("Reducer Error: #{filename}:(Not Retrieved): \n#{e.formatted}")
254
+ end
255
+ false
254
256
  end
255
257
 
256
258
  def reduce(type, data_keys, reduced)
@@ -40,12 +40,12 @@ module Cosmos
40
40
 
41
41
  # Delete the current value table for a target
42
42
  def self.del(target_name:, packet_name:, scope:)
43
- Store.hdel("#{scope}__tlm__#{target_name}", packet_name)
43
+ EphemeralStore.hdel("#{scope}__tlm__#{target_name}", packet_name)
44
44
  end
45
45
 
46
46
  # Set the current value table for a target, packet
47
47
  def self.set(hash, target_name:, packet_name:, scope:)
48
- Store.hset("#{scope}__tlm__#{target_name}", packet_name, JSON.generate(hash.as_json))
48
+ EphemeralStore.hset("#{scope}__tlm__#{target_name}", packet_name, JSON.generate(hash.as_json))
49
49
  end
50
50
 
51
51
  # Set an item in the current value table
@@ -62,9 +62,9 @@ module Cosmos
62
62
  else
63
63
  raise "Unknown type '#{type}' for #{target_name} #{packet_name} #{item_name}"
64
64
  end
65
- hash = JSON.parse(Store.hget("#{scope}__tlm__#{target_name}", packet_name))
65
+ hash = JSON.parse(EphemeralStore.hget("#{scope}__tlm__#{target_name}", packet_name))
66
66
  hash[field] = value
67
- Store.hset("#{scope}__tlm__#{target_name}", packet_name, JSON.generate(hash.as_json))
67
+ EphemeralStore.hset("#{scope}__tlm__#{target_name}", packet_name, JSON.generate(hash.as_json))
68
68
  end
69
69
 
70
70
  # Get an item from the current value table
@@ -86,7 +86,7 @@ module Cosmos
86
86
  else
87
87
  raise "Unknown type '#{type}' for #{target_name} #{packet_name} #{item_name}"
88
88
  end
89
- hash = JSON.parse(Store.hget("#{scope}__tlm__#{target_name}", packet_name))
89
+ hash = JSON.parse(EphemeralStore.hget("#{scope}__tlm__#{target_name}", packet_name))
90
90
  hash.values_at(*types).each do |result|
91
91
  return result if result
92
92
  end
@@ -106,7 +106,7 @@ module Cosmos
106
106
 
107
107
  lookups.each do |target_packet_key, target_name, packet_name, packet_values|
108
108
  unless packet_lookup[target_packet_key]
109
- packet = Store.hget("#{scope}__tlm__#{target_name}", packet_name)
109
+ packet = EphemeralStore.hget("#{scope}__tlm__#{target_name}", packet_name)
110
110
  raise "Packet '#{target_name} #{packet_name}' does not exist" unless packet
111
111
  packet_lookup[target_packet_key] = JSON.parse(packet)
112
112
  end
@@ -73,7 +73,7 @@ module Cosmos
73
73
  return nil
74
74
  end
75
75
 
76
- def self.install(name_or_path)
76
+ def self.install(name_or_path, scope:)
77
77
  temp_dir = Dir.mktmpdir
78
78
  begin
79
79
  if File.exist?(name_or_path)
@@ -81,10 +81,16 @@ module Cosmos
81
81
  else
82
82
  gem_file_path = get(temp_dir, name_or_path)
83
83
  end
84
- rubygems_url = get_setting('rubygems_url')
84
+ begin
85
+ rubygems_url = get_setting('rubygems_url', scope: scope)
86
+ rescue
87
+ # If Redis isn't running try the ENV, then simply rubygems.org
88
+ rubygems_url = ENV['RUBYGEMS_URL']
89
+ rubygems_url ||= 'https://rubygems.org'
90
+ end
85
91
  Gem.sources = [rubygems_url] if rubygems_url
86
92
  Gem.done_installing_hooks.clear
87
- Gem.install(gem_file_path, {:build_args => '--no-document'})
93
+ Gem.install(gem_file_path, "> 0.pre", :build_args => ['--no-document'], :prerelease => true)
88
94
  rescue => err
89
95
  message = "Gem file #{gem_file_path} error installing to /gems\n#{err.formatted}"
90
96
  Logger.error message
@@ -24,7 +24,7 @@ module Cosmos
24
24
 
25
25
  # @return Hash information and statistics about the redis server
26
26
  def self.get()
27
- return Store.info()
27
+ return [Store.info(), EphemeralStore.info]
28
28
  end
29
29
 
30
30
  end
@@ -237,7 +237,7 @@ module Cosmos
237
237
  end
238
238
 
239
239
  # Creates a MicroserviceModel to deploy the Interface/Router
240
- def deploy(gem_path, variables)
240
+ def deploy(gem_path, variables, validate_only: false)
241
241
  type = self.class._get_type
242
242
  microservice_name = "#{@scope}__#{type}__#{@name}"
243
243
  microservice = MicroserviceModel.new(
@@ -249,9 +249,12 @@ module Cosmos
249
249
  needs_dependencies: @needs_dependencies,
250
250
  scope: @scope
251
251
  )
252
- microservice.create
253
- microservice.deploy(gem_path, variables)
254
- Logger.info "Configured #{type.downcase} microservice #{microservice_name}"
252
+ unless validate_only
253
+ microservice.create
254
+ microservice.deploy(gem_path, variables)
255
+ ConfigTopic.write({ kind: 'created', type: type.downcase, name: @name, plugin: @plugin }, scope: @scope)
256
+ Logger.info "Configured #{type.downcase} microservice #{microservice_name}"
257
+ end
255
258
  microservice
256
259
  end
257
260
 
@@ -259,9 +262,15 @@ module Cosmos
259
262
  # should should trigger the operator to kill the microservice that in turn
260
263
  # will destroy the InterfaceStatusModel when a stop is called.
261
264
  def undeploy
262
- model = MicroserviceModel.get_model(name: "#{@scope}__#{self.class._get_type}__#{@name}", scope: @scope)
263
- model.destroy if model
264
- if self.class._get_type == 'INTERFACE'
265
+ type = self.class._get_type
266
+ name = "#{@scope}__#{type}__#{@name}"
267
+ model = MicroserviceModel.get_model(name: name, scope: @scope)
268
+ if model
269
+ model.destroy
270
+ ConfigTopic.write({ kind: 'deleted', type: type.downcase, name: @name, plugin: @plugin }, scope: @scope)
271
+ end
272
+
273
+ if type == 'INTERFACE'
265
274
  status_model = InterfaceStatusModel.get_model(name: @name, scope: @scope)
266
275
  else
267
276
  status_model = RouterStatusModel.get_model(name: @name, scope: @scope)
@@ -23,7 +23,7 @@ module Cosmos
23
23
  # Stores the status about an interface. This class also implements logic
24
24
  # to handle status for a router since the functionality is identical
25
25
  # (only difference is the Redis key used).
26
- class InterfaceStatusModel < Model
26
+ class InterfaceStatusModel < EphemeralModel
27
27
  INTERFACES_PRIMARY_KEY = 'cosmos_interface_status'
28
28
  ROUTERS_PRIMARY_KEY = 'cosmos_router_status'
29
29
 
@@ -19,271 +19,121 @@
19
19
 
20
20
  # https://www.rubydoc.info/gems/redis/Redis/Commands/SortedSets
21
21
 
22
- require 'cosmos/topics/calendar_topic'
22
+ require 'cosmos/models/sorted_model'
23
23
 
24
24
  module Cosmos
25
-
26
- class MetadataError < StandardError; end
27
-
28
- class MetadataInputError < MetadataError; end
29
-
30
- class MetadataOverlapError < MetadataError; end
31
-
32
- class MetadataModel < Model
33
-
34
- CHRONICLE_TYPE = 'metadata'.freeze
35
- CURRENT_VALUE = '__current.metadata.value'.freeze
25
+ class MetadataModel < SortedModel
26
+ METADATA_TYPE = 'metadata'.freeze
36
27
  PRIMARY_KEY = '__METADATA'.freeze
37
28
 
38
29
  def self.pk(scope)
39
- return "#{scope}#{PRIMARY_KEY}"
40
- end
41
-
42
- # @return [String|nil] String of the saved json or nil if score not found under current value
43
- def self.get_current_value(target:, scope:)
44
- json = Store.hget("#{scope}#{CURRENT_VALUE}", target)
45
- return nil unless json
46
- return self.from_json(JSON.parse(json), scope: scope)
47
- end
48
-
49
- # @return [Array|nil] Array up to 100 of this model or empty array
50
- def self.get(start:, stop:, scope:, limit: 100)
51
- if start > stop
52
- raise MetadataInputError.new "start: #{start} must be before stop: #{stop}"
53
- end
54
- pk = self.pk(scope)
55
- array = Store.zrangebyscore(pk, start, stop, :limit => [0, limit])
56
- ret_array = Array.new
57
- array.each do |value|
58
- ret_array << JSON.parse(value)
59
- end
60
- return ret_array
61
- end
62
-
63
- # @return [Array<Hash>] Array up to the limit of the models (as Hash objects) stored under the primary key
64
- def self.all(scope:, limit: 100)
65
- pk = self.pk(scope)
66
- array = Store.zrange(pk, 0, -1, :limit => [0, limit])
67
- ret_array = Array.new
68
- array.each do |value|
69
- ret_array << JSON.parse(value)
70
- end
71
- return ret_array
72
- end
73
-
74
- # @return [Integer] count of the members stored under the primary key
75
- def self.count(scope:)
76
- return Store.zcard(self.pk(scope))
77
- end
78
-
79
- # @return [String|nil] String of the saved json or nil if score not found under primary_key
80
- def self.score(score:, scope:)
81
- pk = self.pk(scope)
82
- array = Store.zrangebyscore(pk, score, score, :limit => [0, 1])
83
- array.each do |value|
84
- return JSON.parse(value)
85
- end
86
- return nil
87
- end
88
-
89
- # Remove member from a sorted set based on the score.
90
- # @return [Integer] count of the members removed
91
- def self.destroy(scope:, score:)
92
- pk = self.pk(scope)
93
- Store.zremrangebyscore(pk, score, score)
94
- end
95
-
96
- # Remove members from min to max of the sorted set.
97
- # @return [Integer] count of the members removed
98
- def self.range_destroy(scope:, min:, max:)
99
- pk = self.pk(scope)
100
- Store.zremrangebyscore(pk, min, max)
30
+ "#{scope}#{PRIMARY_KEY}"
101
31
  end
102
32
 
103
- # @return [MetadataModel] Model generated from the passed JSON
104
- def self.from_json(json, scope:)
105
- json = JSON.parse(json) if String === json
106
- raise "json data is nil" if json.nil?
33
+ attr_reader :color, :metadata, :constraints, :type
107
34
 
108
- json.transform_keys!(&:to_sym)
109
- self.new(**json, scope: scope)
110
- end
111
-
112
- attr_reader :target, :start, :color, :metadata, :type
113
-
114
- # @param [String] target - should be the target but can be anything
115
- # @param [Integer] start - time metadata is active in seconds from Epoch
35
+ # @param [Integer] start - Time metadata is active in seconds from Epoch
116
36
  # @param [String] color - The event color
117
- # @param [String] metadata - Key value pair object to link to name
37
+ # @param [Hash] metadata - Hash of metadata values
38
+ # @param [Hash] constraints - Constraints to apply to the metadata
118
39
  # @param [String] scope - Cosmos scope to track event to
119
40
  def initialize(
120
- target:,
41
+ scope:,
121
42
  start:,
122
43
  color: nil,
123
44
  metadata:,
124
- scope:,
125
- type: CHRONICLE_TYPE,
45
+ constraints: nil,
46
+ type: METADATA_TYPE,
126
47
  updated_at: 0
127
48
  )
128
- super(MetadataModel.pk(scope), name: start.to_s, scope: scope)
129
- set_input(start: start, color: color, metadata: metadata)
130
- @target = target
131
- @type = type
132
- @updated_at = updated_at
49
+ super(start: start, scope: scope, updated_at: updated_at)
50
+ @start = start
51
+ @color = color
52
+ @metadata = metadata
53
+ @constraints = constraints if constraints
54
+ @type = type # For the as_json, from_json round trip
133
55
  end
134
56
 
135
- # validate color
136
- def validate_color(color)
137
- if color.nil?
138
- color = '#%06x' % (rand * 0xffffff)
139
- end
140
- valid_color = color =~ /(#*)([0-9,a-f,A-f]{6})/
141
- if valid_color.nil?
142
- raise MetadataInputError.new "invalid color, must be in hex format, e.g. #FF0000"
143
- end
144
-
145
- color = "##{color}" unless color.start_with?('#')
146
- return color
57
+ # Validates the instance variables: @start, @color, @metadata
58
+ def validate(update: false)
59
+ validate_start(update: update)
60
+ validate_color()
61
+ validate_metadata()
62
+ validate_constraints() if @constraints
147
63
  end
148
64
 
149
- # validate the input to the rules we have created for timelines.
150
- # - An entry's start MUST be valid.
151
- # - An entry's start MUST NOT be in the future.
152
- # - An entry's metadata MUST a hash/object.
153
- def validate_input(start:, color:, metadata:)
154
- if start.is_a?(Integer) == false
155
- raise MetadataInputError.new "failed validation input must be integer: #{start}"
65
+ def validate_color()
66
+ if @color.nil?
67
+ @color = '#%06x' % (rand * 0xffffff)
156
68
  end
157
- now = Time.now.strftime('%s%3N').to_i
158
- if start > now
159
- raise MetadataInputError.new "start can not be in the future: #{start} > #{now}"
160
- end
161
- validate_color(color)
162
- if metadata.is_a?(Hash) == false
163
- raise MetadataInputError.new "Metadata must be a hash/object: #{metadata}"
69
+ unless @color =~ /(#*)([0-9,a-f,A-f]{6})/
70
+ raise SortedInputError.new "invalid color, must be in hex format, e.g. #FF0000"
164
71
  end
72
+ @color = "##{@color}" unless @color.start_with?('#')
165
73
  end
166
74
 
167
- # Set the values of the instance, @start, @stop, @metadata...
168
- def set_input(start:, color:, metadata:)
169
- if start.is_a?(Integer) == false
170
- raise MetadataInputError.new "start input must be integer: #{start}"
75
+ def validate_metadata()
76
+ unless @metadata.is_a?(Hash)
77
+ raise SortedInputError.new "Metadata must be a hash/object: #{@metadata}"
171
78
  end
172
- @start = start
173
- @color = color
174
- @metadata = metadata
79
+ # Convert keys to strings. This isn't quite as efficient as symbols
80
+ # but we store as JSON which is all strings and it makes comparisons easier.
81
+ @metadata = @metadata.transform_keys(&:to_s)
175
82
  end
176
83
 
177
- # validate_time will be called on create and update this will validate
178
- # that no other chronicle event or metadata had been saved for that time.
179
- # One event or metadata per second to ensure data can be updated.
180
- #
181
- # @param [Integer] ignore_score - should be nil unless you want to ignore
182
- # a time when doing an update
183
- def validate_time(ignore_score: nil)
184
- array = Store.zrangebyscore(@primary_key, @start, @start, :limit => [0, 1])
185
- array.each do |value|
186
- entry = JSON.parse(value)
187
- if ignore_score == entry['start']
188
- next
189
- else
190
- return entry
84
+ def validate_constraints()
85
+ unless @constraints.is_a?(Hash)
86
+ raise SortedInputError.new "Constraints must be a hash/object: #{@constraints}"
87
+ end
88
+ # Convert keys to strings. This isn't quite as efficient as symbols
89
+ # but we store as JSON which is all strings and it makes comparisons easier.
90
+ @constraints = @constraints.transform_keys(&:to_s)
91
+ unless (@constraints.keys - @metadata.keys).empty?
92
+ raise SortedInputError.new "Constraints keys must be subset of metadata: #{@constraints.keys} subset #{@metadata.keys}"
93
+ end
94
+ @constraints.each do |key, constraint|
95
+ unless constraint.include?(@metadata[key])
96
+ raise SortedInputError.new "Constraint violation! key:#{key} value:#{@metadata[key]} constraint:#{constraint}"
191
97
  end
192
98
  end
193
- return nil
194
99
  end
195
100
 
196
- # Update the Redis hash at primary_key and set the score equal to the start Epoch time
197
- # the member is set to the JSON generated via calling as_json
198
- def create
199
- validate_input(start: @start, color: @color, metadata: @metadata)
200
- collision = validate_time()
201
- unless collision.nil?
202
- raise MetadataOverlapError.new "no chronicle can overlap, collision: #{collision}"
203
- end
204
-
101
+ # Update the Redis hash at primary_key based on the initial passed start
102
+ # The member is set to the JSON generated via calling as_json
103
+ def create(update: false)
104
+ validate(update: update)
205
105
  @updated_at = Time.now.to_nsec_from_epoch
106
+ MetadataModel.destroy(scope: @scope, start: update) if update
206
107
  Store.zadd(@primary_key, @start, JSON.generate(as_json()))
207
- update_current_value()
208
- notify(kind: 'created')
209
- end
210
-
211
- # Update the Redis hash at primary_key and remove the current activity at the current score
212
- # and update the score to the new score equal to the start Epoch time this uses a multi
213
- # to execute both the remove and create. The member via the JSON generated via calling as_json
214
- def update(start:, color:, metadata:)
215
- validate_input(start: start, color: color, metadata: metadata)
216
- old_start = @start
217
- @updated_at = Time.now.to_nsec_from_epoch
218
- set_input(start: start, color: color, metadata: metadata)
219
- # copy of create
220
- collision = validate_time(ignore_score: old_start)
221
- unless collision.nil?
222
- raise MetadataOverlapError.new "failed to update #{old_start}, no chronicles can overlap, collision: #{collision}"
223
- end
224
-
225
- Store.multi do |multi|
226
- multi.zremrangebyscore(@primary_key, old_start, old_start)
227
- multi.zadd(@primary_key, @start, JSON.generate(as_json()))
228
- end
229
- update_current_value(old_start: old_start)
230
- notify(kind: 'updated', extra: old_start)
231
- return @start
232
- end
233
-
234
- # Update the Redis hash at primary_key and check if this metadata instance
235
- # is newer than the current instance stored in the hash. If the hash does
236
- # NOT contain an instance or this metadata instance is newer it will update
237
- # the current hash.
238
- def update_current_value(old_start: nil)
239
- update = true
240
- json = Store.hget("#{@scope}#{CURRENT_VALUE}", @target)
241
- unless json.nil?
242
- model = MetadataModel.from_json(JSON.parse(json), scope: @scope)
243
- update = model.start <= @start || model.start == old_start
244
- end
245
108
  if update
246
- return Store.hset("#{@scope}#{CURRENT_VALUE}", @target, JSON.generate(as_json()))
109
+ notify(kind: 'updated')
110
+ else
111
+ notify(kind: 'created')
247
112
  end
248
113
  end
249
114
 
250
- # destroy the activity from the redis database
251
- def destroy
252
- Store.zremrangebyscore(@primary_key, @start, @start)
253
- notify(kind: 'deleted')
254
- end
255
-
256
- # @return [] update the redis stream / timeline topic that something has changed
257
- def notify(kind:, extra: nil)
258
- notification = {
259
- 'data' => JSON.generate(as_json()),
260
- 'kind' => kind,
261
- 'type' => 'calendar',
262
- }
263
- notification['extra'] = extra unless extra.nil?
264
- begin
265
- CalendarTopic.write_entry(notification, scope: @scope)
266
- rescue StandardError => e
267
- raise MetadataError.new "Failed to write to stream: #{notification}, #{e}"
268
- end
115
+ # Update the model. All arguments are optional, only those set will be updated.
116
+ def update(start: nil, color: nil, metadata: nil, constraints: nil)
117
+ orig_start = @start
118
+ @start = start if start
119
+ @color = color if color
120
+ @metadata = metadata if metadata
121
+ @constraints = constraints if constraints
122
+ create(update: orig_start)
269
123
  end
270
124
 
271
125
  # @return [Hash] generated from the MetadataModel
272
126
  def as_json
273
- return {
274
- 'target' => @target,
127
+ {
275
128
  'scope' => @scope,
276
- 'updated_at' => @updated_at,
277
129
  'start' => @start,
278
130
  'color' => @color,
279
131
  'metadata' => @metadata,
280
- 'type' => CHRONICLE_TYPE,
132
+ 'constraints' => @constraints,
133
+ 'type' => METADATA_TYPE,
134
+ 'updated_at' => @updated_at,
281
135
  }
282
136
  end
283
-
284
- # @return [String] string view of metadata
285
- def to_s
286
- return "<MetadataModel t: #{@target}, s: #{@start}, c: #{@color}, m: #{@metadata}>"
287
- end
137
+ alias to_s as_json
288
138
  end
289
139
  end
@@ -20,7 +20,7 @@
20
20
  require 'cosmos/models/model'
21
21
 
22
22
  module Cosmos
23
- class MetricModel < Model
23
+ class MetricModel < EphemeralModel
24
24
  PRIMARY_KEY = '__cosmos__metric'.freeze
25
25
 
26
26
  # NOTE: The following three class methods are used by the ModelController
@@ -38,7 +38,7 @@ module Cosmos
38
38
  end
39
39
 
40
40
  def self.destroy(scope:, name:)
41
- Store.hdel("#{scope}#{PRIMARY_KEY}", name)
41
+ EphemeralStore.hdel("#{scope}#{PRIMARY_KEY}", name)
42
42
  end
43
43
 
44
44
  def initialize(name:, scope:, metric_name:, label_list:)
@@ -171,11 +171,10 @@ module Cosmos
171
171
  return nil
172
172
  end
173
173
 
174
- def deploy(gem_path, variables)
174
+ def deploy(gem_path, variables, validate_only: false)
175
175
  return unless @folder_name
176
176
 
177
177
  variables["microservice_name"] = @name
178
- rubys3_client = Aws::S3::Client.new
179
178
  start_path = "/microservices/#{@folder_name}/"
180
179
  Dir.glob(gem_path + start_path + "**/*") do |filename|
181
180
  next if filename == '.' or filename == '..' or File.directory?(filename)
@@ -186,9 +185,12 @@ module Cosmos
186
185
  # Load microservice files
187
186
  data = File.read(filename, mode: "rb")
188
187
  Cosmos.set_working_dir(File.dirname(filename)) do
189
- data = ERB.new(data).result(binding.set_variables(variables)) if data.is_printable?
188
+ data = ERB.new(data, trim_mode: "-").result(binding.set_variables(variables)) if data.is_printable?
189
+ end
190
+ unless validate_only
191
+ Aws::S3::Client.new.put_object(bucket: 'config', key: key, body: data)
192
+ ConfigTopic.write({ kind: 'created', type: 'microservice', name: @name, plugin: @plugin }, scope: @scope)
190
193
  end
191
- rubys3_client.put_object(bucket: 'config', key: key, body: data)
192
194
  end
193
195
  end
194
196
 
@@ -198,6 +200,7 @@ module Cosmos
198
200
  rubys3_client.list_objects(bucket: 'config', prefix: prefix).contents.each do |object|
199
201
  rubys3_client.delete_object(bucket: 'config', key: object.key)
200
202
  end
203
+ ConfigTopic.write({ kind: 'deleted', type: 'microservice', name: @name, plugin: @plugin }, scope: @scope)
201
204
  end
202
205
  end
203
206
  end
@@ -20,7 +20,7 @@
20
20
  require 'cosmos/models/model'
21
21
 
22
22
  module Cosmos
23
- class MicroserviceStatusModel < Model
23
+ class MicroserviceStatusModel < EphemeralModel
24
24
  PRIMARY_KEY = 'cosmos_microservice_status'
25
25
 
26
26
  attr_accessor :state