openc3 7.5.1 → 7.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +0 -0
  3. data/bin/openc3cli +82 -5
  4. data/data/config/_params.yaml +3 -0
  5. data/data/config/command_modifiers.yaml +5 -3
  6. data/data/config/default_plugins.yaml +1 -0
  7. data/data/config/interface_modifiers.yaml +17 -1
  8. data/data/config/item_modifiers.yaml +24 -1
  9. data/data/config/microservice.yaml +15 -1
  10. data/data/config/parameter_modifiers.yaml +4 -4
  11. data/data/config/plugins.yaml +511 -3
  12. data/data/config/settings.yaml +17 -0
  13. data/data/config/target.yaml +53 -0
  14. data/data/config/telemetry.yaml +58 -2
  15. data/data/config/widgets.yaml +30 -0
  16. data/lib/openc3/accessors/accessor.rb +14 -2
  17. data/lib/openc3/accessors/binary_accessor.rb +25 -5
  18. data/lib/openc3/api/CLAUDE.md +1 -0
  19. data/lib/openc3/api/api.rb +1 -0
  20. data/lib/openc3/api/cmd_api.rb +9 -1
  21. data/lib/openc3/api/interface_api.rb +7 -2
  22. data/lib/openc3/api/limits_api.rb +93 -41
  23. data/lib/openc3/api/router_api.rb +7 -2
  24. data/lib/openc3/api/settings_api.rb +4 -1
  25. data/lib/openc3/api/shared_resource_api.rb +107 -0
  26. data/lib/openc3/api/tlm_api.rb +10 -0
  27. data/lib/openc3/interfaces/http_client_interface.rb +84 -27
  28. data/lib/openc3/interfaces/protocols/preidentified_protocol.rb +6 -2
  29. data/lib/openc3/interfaces/tcpip_server_interface.rb +205 -125
  30. data/lib/openc3/io/json_api.rb +2 -10
  31. data/lib/openc3/io/json_api_object.rb +2 -10
  32. data/lib/openc3/logs/packet_log_writer.rb +8 -3
  33. data/lib/openc3/microservices/decom_common.rb +4 -1
  34. data/lib/openc3/microservices/decom_microservice.rb +52 -6
  35. data/lib/openc3/microservices/interface_decom_common.rb +13 -0
  36. data/lib/openc3/microservices/interface_microservice.rb +50 -11
  37. data/lib/openc3/microservices/limits_group_microservice.rb +513 -0
  38. data/lib/openc3/microservices/log_microservice.rb +22 -8
  39. data/lib/openc3/microservices/microservice.rb +8 -2
  40. data/lib/openc3/microservices/multi_microservice.rb +76 -22
  41. data/lib/openc3/microservices/queue_microservice.rb +29 -24
  42. data/lib/openc3/migrations/20260704000000_default_bridge.rb +1 -2
  43. data/lib/openc3/migrations/20261103000001_limits_group_backfill.rb +193 -0
  44. data/lib/openc3/models/bridge_model.rb +3 -3
  45. data/lib/openc3/models/cvt_model.rb +3 -1
  46. data/lib/openc3/models/host_interface_microservice_model.rb +4 -4
  47. data/lib/openc3/models/interface_model.rb +27 -7
  48. data/lib/openc3/models/microservice_group.rb +167 -0
  49. data/lib/openc3/models/microservice_model.rb +88 -2
  50. data/lib/openc3/models/panel_model.rb +109 -0
  51. data/lib/openc3/models/plugin_model.rb +1006 -26
  52. data/lib/openc3/models/plugin_store_model.rb +6 -1
  53. data/lib/openc3/models/protected_storage_model.rb +64 -0
  54. data/lib/openc3/models/queue_model.rb +19 -10
  55. data/lib/openc3/models/scope_model.rb +80 -3
  56. data/lib/openc3/models/setting_model.rb +2 -2
  57. data/lib/openc3/models/shared_resource_model.rb +381 -0
  58. data/lib/openc3/models/target_model.rb +324 -68
  59. data/lib/openc3/operators/microservice_operator.rb +76 -9
  60. data/lib/openc3/operators/operator.rb +29 -0
  61. data/lib/openc3/packets/commands.rb +16 -16
  62. data/lib/openc3/packets/limits.rb +2 -0
  63. data/lib/openc3/packets/packet.rb +75 -4
  64. data/lib/openc3/packets/packet_config.rb +152 -13
  65. data/lib/openc3/packets/packet_item.rb +35 -14
  66. data/lib/openc3/packets/packet_item_limits.rb +67 -6
  67. data/lib/openc3/packets/parsers/limits_parser.rb +69 -2
  68. data/lib/openc3/packets/parsers/packet_item_parser.rb +6 -0
  69. data/lib/openc3/packets/parsers/packet_parser.rb +45 -0
  70. data/lib/openc3/packets/parsers/state_parser.rb +1 -1
  71. data/lib/openc3/script/CLAUDE.md +1 -0
  72. data/lib/openc3/script/api_shared.rb +17 -9
  73. data/lib/openc3/script/calendar.rb +18 -6
  74. data/lib/openc3/script/commands.rb +11 -9
  75. data/lib/openc3/script/critical_cmd.rb +22 -2
  76. data/lib/openc3/script/metadata.rb +30 -4
  77. data/lib/openc3/script/plugins.rb +8 -0
  78. data/lib/openc3/script/script.rb +8 -24
  79. data/lib/openc3/script/web_socket_api.rb +23 -17
  80. data/lib/openc3/system/system.rb +9 -3
  81. data/lib/openc3/top_level.rb +17 -0
  82. data/lib/openc3/topics/command_topic.rb +7 -1
  83. data/lib/openc3/topics/decom_interface_topic.rb +9 -3
  84. data/lib/openc3/topics/discovery_topic.rb +84 -0
  85. data/lib/openc3/topics/limits_event_topic.rb +236 -17
  86. data/lib/openc3/topics/telemetry_decom_topic.rb +12 -3
  87. data/lib/openc3/topics/topic.rb +2 -1
  88. data/lib/openc3/utilities/authentication.rb +67 -16
  89. data/lib/openc3/utilities/cli_generator.rb +117 -25
  90. data/lib/openc3/utilities/client_ip_header_filter.rb +38 -0
  91. data/lib/openc3/utilities/config_overlay.rb +24 -1
  92. data/lib/openc3/utilities/cosmos_rails_formatter.rb +18 -10
  93. data/lib/openc3/utilities/hardware_discovery.rb +279 -0
  94. data/lib/openc3/utilities/limits_rollup.rb +81 -0
  95. data/lib/openc3/utilities/local_mode.rb +48 -5
  96. data/lib/openc3/utilities/questdb_client.rb +130 -22
  97. data/lib/openc3/utilities/reingest_job.rb +12 -3
  98. data/lib/openc3/utilities/running_script.rb +206 -49
  99. data/lib/openc3/utilities/script.rb +24 -12
  100. data/lib/openc3/utilities/script_env.rb +164 -0
  101. data/lib/openc3/utilities/script_message_signing.rb +133 -0
  102. data/lib/openc3/utilities/store_autoload.rb +32 -1
  103. data/lib/openc3/utilities/store_queued.rb +5 -1
  104. data/lib/openc3/version.rb +6 -6
  105. data/templates/command_validator/command_validator.py +9 -9
  106. data/templates/{tool_react/pnpm-workspace.yaml → panel/.prettierrc.cjs} +7 -5
  107. data/templates/panel/Rakefile +24 -0
  108. data/templates/panel/package.json +17 -0
  109. data/templates/{tool_angular → panel}/pnpm-workspace.yaml +5 -0
  110. data/templates/panel/src/Panel.js +52 -0
  111. data/templates/panel/src/Panel.vue +60 -0
  112. data/templates/panel/src/panelSdk.js +24 -0
  113. data/templates/panel/vite-Panel.config.js +43 -0
  114. data/templates/tool_vue/package.json +3 -3
  115. data/templates/widget/package.json +2 -2
  116. metadata +24 -56
  117. data/templates/tool_angular/.editorconfig +0 -16
  118. data/templates/tool_angular/.gitignore +0 -44
  119. data/templates/tool_angular/.vscode/extensions.json +0 -4
  120. data/templates/tool_angular/.vscode/launch.json +0 -20
  121. data/templates/tool_angular/.vscode/tasks.json +0 -42
  122. data/templates/tool_angular/angular.json +0 -111
  123. data/templates/tool_angular/extra-webpack.config.js +0 -8
  124. data/templates/tool_angular/package.json +0 -48
  125. data/templates/tool_angular/src/app/app-routing.module.ts +0 -15
  126. data/templates/tool_angular/src/app/app.component.html +0 -22
  127. data/templates/tool_angular/src/app/app.component.scss +0 -18
  128. data/templates/tool_angular/src/app/app.component.spec.ts +0 -29
  129. data/templates/tool_angular/src/app/app.component.ts +0 -52
  130. data/templates/tool_angular/src/app/app.module.ts +0 -30
  131. data/templates/tool_angular/src/app/custom-overlay-container.ts +0 -17
  132. data/templates/tool_angular/src/app/empty-route/empty-route.component.ts +0 -7
  133. data/templates/tool_angular/src/app/openc3-api.d.ts +0 -1
  134. data/templates/tool_angular/src/assets/.gitkeep +0 -0
  135. data/templates/tool_angular/src/environments/environment.prod.ts +0 -3
  136. data/templates/tool_angular/src/environments/environment.ts +0 -16
  137. data/templates/tool_angular/src/favicon.ico +0 -0
  138. data/templates/tool_angular/src/index.html +0 -13
  139. data/templates/tool_angular/src/main.single-spa.ts +0 -40
  140. data/templates/tool_angular/src/single-spa/asset-url.ts +0 -12
  141. data/templates/tool_angular/src/single-spa/single-spa-props.ts +0 -8
  142. data/templates/tool_angular/src/styles.scss +0 -1
  143. data/templates/tool_angular/tsconfig.app.json +0 -13
  144. data/templates/tool_angular/tsconfig.json +0 -33
  145. data/templates/tool_angular/tsconfig.spec.json +0 -14
  146. data/templates/tool_react/.eslintrc +0 -7
  147. data/templates/tool_react/.gitignore +0 -71
  148. data/templates/tool_react/.prettierignore +0 -8
  149. data/templates/tool_react/babel.config.json +0 -29
  150. data/templates/tool_react/jest.config.js +0 -12
  151. data/templates/tool_react/package.json +0 -51
  152. data/templates/tool_react/src/openc3-tool_name.js +0 -24
  153. data/templates/tool_react/src/root.component.js +0 -88
  154. data/templates/tool_react/src/root.component.test.js +0 -9
  155. data/templates/tool_react/webpack.config.js +0 -27
  156. data/templates/tool_svelte/.gitignore +0 -71
  157. data/templates/tool_svelte/.prettierignore +0 -8
  158. data/templates/tool_svelte/.prettierrc.js +0 -5
  159. data/templates/tool_svelte/babel.config.js +0 -12
  160. data/templates/tool_svelte/build/smui.css +0 -1
  161. data/templates/tool_svelte/jest.config.js +0 -9
  162. data/templates/tool_svelte/package.json +0 -49
  163. data/templates/tool_svelte/pnpm-workspace.yaml +0 -20
  164. data/templates/tool_svelte/rollup.config.js +0 -74
  165. data/templates/tool_svelte/src/App.svelte +0 -42
  166. data/templates/tool_svelte/src/App.test.js +0 -9
  167. data/templates/tool_svelte/src/theme/_smui-theme.scss +0 -25
  168. data/templates/tool_svelte/src/tool_name.js +0 -17
  169. data/templates/widget/LICENSE.md +0 -20
@@ -19,6 +19,14 @@ require 'openc3/system/system'
19
19
 
20
20
  module OpenC3
21
21
  module InterfaceDecomCommon
22
+ # Names of the length items owned by the variable sized items in item_names
23
+ def variable_length_item_names(packet, item_names)
24
+ item_names.filter_map do |name|
25
+ item = packet.items[name.to_s.upcase]
26
+ item.variable_bit_size['length_item_name'].upcase if item&.variable_bit_size
27
+ end
28
+ end
29
+
22
30
  def handle_inject_tlm(inject_tlm_json)
23
31
  inject_tlm_hash = JSON.parse(inject_tlm_json, allow_nan: true, create_additions: true)
24
32
  target_name = inject_tlm_hash['target_name']
@@ -27,7 +35,12 @@ module OpenC3
27
35
  type = inject_tlm_hash['type'].to_s.intern
28
36
  packet = System.telemetry.packet(target_name, packet_name)
29
37
  if item_hash
38
+ length_item_names = variable_length_item_names(packet, item_hash.keys)
30
39
  item_hash.each do |name, value|
40
+ # Writing the variable sized item sets its length item, and writing the
41
+ # length item first would make the item's current size disagree with the buffer
42
+ next if length_item_names.include?(name.to_s.upcase)
43
+
31
44
  packet.write(name.to_s, value, type)
32
45
  end
33
46
  end
@@ -197,6 +197,28 @@ module OpenC3
197
197
  # Note: intentional fall through below this point
198
198
  critical_model = CriticalCmdModel.get_model(name: msg_hash['release_critical'], scope: @scope)
199
199
  if critical_model
200
+ # Claim the release so the command is sent at most once. Refuses a
201
+ # duplicate release message and one whose approval was undone.
202
+ # Nothing reads the ack for a release so log why it was refused.
203
+ begin
204
+ claimed = critical_model.claim_release
205
+ rescue => e
206
+ message = "Critical command '#{msg_hash['release_critical']}' not released: #{e.message}"
207
+ @logger.error("#{@interface.name}: #{message}", scope: @scope)
208
+ next message
209
+ end
210
+ unless claimed
211
+ if critical_model.released
212
+ # A duplicate release message, the command was already sent
213
+ message = "Critical command '#{msg_hash['release_critical']}' not released: already released"
214
+ @logger.warn("#{@interface.name}: #{message}", scope: @scope)
215
+ else
216
+ # An approved command that won't be sent, e.g. its approval was undone
217
+ message = "Critical command '#{msg_hash['release_critical']}' not released: #{critical_model.status}"
218
+ @logger.error("#{@interface.name}: #{message}", scope: @scope)
219
+ end
220
+ next message
221
+ end
200
222
  msg_hash = critical_model.cmd_hash
201
223
  release_critical = true
202
224
  else
@@ -284,18 +306,15 @@ module OpenC3
284
306
  # An unidentified buffer is sent as UNKNOWN on behalf of the target it was sent to
285
307
  enabled_target_name = command.target_name
286
308
  enabled_target_name = target_name if enabled_target_name == 'UNKNOWN' and target_name
287
- if @interface.cmd_target_enabled[enabled_target_name]
288
- orig_command = System.commands.packet(command.target_name, command.packet_name)
289
- orig_command.received_count = TargetModel.increment_command_count(command.target_name, command.packet_name, 1, scope: @scope)
290
- command.received_count = orig_command.received_count
291
- command.received_time = Time.now
292
- else
309
+ unless @interface.cmd_target_enabled[enabled_target_name]
293
310
  next "Target #{command.target_name} is disabled" if release_critical
311
+
294
312
  next nil # Don't ack disabled targets
295
313
  end
296
- rescue RangeError => e
297
- # Command parameter out of range is a user error, not a bug,
298
- # so only log the message and not the full stack trace
314
+ rescue RangeError, ArgumentError => e
315
+ # A command parameter that is out of range, can't be written, or
316
+ # is required but not given is a user error, not a bug, so only
317
+ # log the message and not the full stack trace
299
318
  @logger.error "#{@interface.name}: #{e.message}"
300
319
  next e.message
301
320
  rescue => e
@@ -305,6 +324,14 @@ module OpenC3
305
324
  end
306
325
 
307
326
  command.extra ||= {}
327
+ if msg_hash['extra']
328
+ # Caller metadata lives under its own key so it can't collide with keys
329
+ # COSMOS sets (cmd_string, username, approver, ...) or that the packet's
330
+ # accessor sets during build_cmd (e.g. HttpAccessor's HTTP_PATH,
331
+ # HTTP_METHOD, HTTP_HEADERS, HTTP_QUERIES which HttpClientInterface
332
+ # uses to build the outgoing request)
333
+ command.extra['metadata'] = JSON.parse(msg_hash['extra'], allow_nan: true, create_additions: true)
334
+ end
308
335
  command.extra['cmd_string'] = msg_hash['cmd_string']
309
336
  command.extra['username'] = msg_hash['username']
310
337
  command.extra['interface_name'] = @interface.name
@@ -324,9 +351,13 @@ module OpenC3
324
351
  # Check for Critical Command
325
352
  if @critical_commanding and @critical_commanding != 'OFF' and not release_critical
326
353
  restricted = command.restricted
327
- if hazardous or restricted or (@critical_commanding == 'ALL' and manual)
354
+ # Command Sender treats any command as hazardous when range checks are
355
+ # ignored or parameter conversions are disabled, so require approval
356
+ # for those manual commands too. Scripts that send this way aren't held.
357
+ mode_hazardous = manual && (!range_check || raw)
358
+ if hazardous or mode_hazardous or restricted or (@critical_commanding == 'ALL' and manual)
328
359
  cmd_type = 'NORMAL'
329
- if hazardous
360
+ if hazardous or mode_hazardous
330
361
  cmd_type = 'HAZARDOUS'
331
362
  elsif restricted
332
363
  cmd_type = 'RESTRICTED'
@@ -338,6 +369,14 @@ module OpenC3
338
369
  end
339
370
  end
340
371
 
372
+ # Count the command only once it's going to the interface. A command
373
+ # returned for hazardous confirmation or held for critical approval
374
+ # isn't counted until it's resent or released.
375
+ orig_command = System.commands.packet(command.target_name, command.packet_name)
376
+ orig_command.received_count = TargetModel.increment_command_count(command.target_name, command.packet_name, 1, scope: @scope)
377
+ command.received_count = orig_command.received_count
378
+ command.received_time = Time.now
379
+
341
380
  validate = ConfigParser.handle_true_false(msg_hash['validate'], default: true)
342
381
  begin
343
382
  if @interface.connected?
@@ -0,0 +1,513 @@
1
+ # encoding: ascii-8bit
2
+
3
+ # Copyright 2026 OpenC3, Inc.
4
+ # All Rights Reserved.
5
+ #
6
+ # This program is distributed in the hope that it will be useful,
7
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9
+ # See LICENSE.md for more details.
10
+
11
+ # This file may also be used under the terms of a commercial license
12
+ # if purchased from OpenC3, Inc.
13
+
14
+ require 'openc3/microservices/microservice'
15
+ require 'openc3/models/target_model'
16
+ require 'openc3/topics/config_topic'
17
+ require 'openc3/topics/limits_event_topic'
18
+ require 'openc3/topics/telemetry_decom_topic'
19
+ require 'openc3/utilities/limits_rollup'
20
+ require 'openc3/utilities/sleeper'
21
+
22
+ module OpenC3
23
+ # Rolls up the limits state of every limits group in the scope into the
24
+ # <TARGET> LIMITS_GROUP packet of the target which defines the group. Watches
25
+ # limits events, recomputes the groups an event affects, and publishes a
26
+ # target's packet only when one of its groups' values changes. Each read of
27
+ # the events topic (up to 1000 events) is published once, so a burst of
28
+ # events costs a few publishes rather than one per event.
29
+ #
30
+ # Group and item definitions only change when a target is installed or
31
+ # removed, which writes a target event to the scope's config topic. Those
32
+ # events trigger a reload, as does an error in the event loop in case events
33
+ # were missed.
34
+ #
35
+ # Runs as a thread in the scope's SCOPEMULTI microservice since groups can
36
+ # contain items of any target. Group definitions, current limits states and
37
+ # limits settings all live on db_shard 0 while write_packet writes each packet
38
+ # to its target's db_shard.
39
+ class LimitsGroupMicroservice < Microservice
40
+ READ_TIMEOUT_MS = 1000
41
+ # Longest wait between retries after an error
42
+ MAX_RETRY_SECONDS = 30
43
+
44
+ def initialize(*args)
45
+ super(*args)
46
+ # Groups are keyed by TARGET__GROUP (LimitsEventTopic.limits_group_key)
47
+ @groups = {} # group => [[TGT, PKT, ITEM], ...]
48
+ @order = [] # groups with children before their parents
49
+ @item_groups = {} # 'TGT__PKT__ITEM' => groups which directly contain the item
50
+ @parents = {} # child group => parent groups
51
+ @definitions = {} # target => { packet => { item => limits enabled in the definition } }
52
+ @current_limits = {} # 'TGT__PKT__ITEM' => limits state
53
+ @settings = {} # 'TGT__PKT__ITEM' => { 'enabled' => ... }
54
+ @disabled_groups = Set.new # groups disabled themselves (see LimitsEventTopic.limits_group_settings)
55
+ @values = {} # group => [state, enabled] as last computed (see LimitsRollup.rollup)
56
+ @published = {} # target => its groups' @values as last published
57
+ @packets = {} # target => [group names, its LIMITS_GROUP packet]
58
+ @settings_changed = false # settings must be reread before the next publish
59
+ @changed_groups = Set.new # groups whose members changed since the last flush
60
+ @warned = Set.new
61
+ # Targets changed since an error, or nil when no recovery is pending
62
+ @recovery_targets = nil
63
+ @retry_sleeper = Sleeper.new
64
+ @event_count = 0 # limits events which changed a group's inputs
65
+ @processing_seconds = 0.0 # time spent computing and publishing for them
66
+ @limits_events_topic = "#{@scope}__openc3_limits_events"
67
+ @config_topic = "#{@scope}#{ConfigTopic::PRIMARY_KEY}"
68
+ @metric.set(name: 'limits_group_publish_total', value: @count, type: 'counter')
69
+ set_event_metrics(0.0)
70
+ end
71
+
72
+ def run
73
+ # Start reading events from now. Anything missed while we were down is
74
+ # covered by recomputing every group from current_limits in reload.
75
+ # Both topics are on db_shard 0 so one read covers them.
76
+ topics = [@limits_events_topic, @config_topic]
77
+ Topic.update_topic_offsets(topics)
78
+ # Last limits event read, used to detect events trimmed before they were read.
79
+ # Reading starts at or after this point so it can only cause an extra reload.
80
+ @limits_event_offset = Topic.get_last_offset(@limits_events_topic)
81
+ reload()
82
+ publish(force: true)
83
+ failures = 0
84
+ until @cancel_thread
85
+ changed_targets = Set.new
86
+ recovering = false
87
+ begin
88
+ # Events may have been missed after an error so recompute everything
89
+ # from the store. Retried before every read, even when no events
90
+ # arrive, until it succeeds.
91
+ if @recovery_targets
92
+ recovering = true
93
+ reload(changed_targets: @recovery_targets.to_a)
94
+ publish()
95
+ @recovery_targets = nil
96
+ recovering = false
97
+ end
98
+
99
+ limits_events_checked = false
100
+ events = 0
101
+ seconds = 0.0
102
+ Topic.read_topics(topics, nil, READ_TIMEOUT_MS) do |topic, msg_id, msg_hash, _redis|
103
+ break if @cancel_thread
104
+
105
+ if topic == @config_topic
106
+ # Installing or removing a target writes its packet definitions and
107
+ # limits groups before the event so they're ready to reread
108
+ changed_targets << msg_hash['name'] if msg_hash['type'] == 'target'
109
+ else
110
+ # Any gap is before the first event in a read so only check once per read
111
+ unless limits_events_checked
112
+ reload_if_events_trimmed()
113
+ limits_events_checked = true
114
+ end
115
+ @limits_event_offset = msg_id
116
+ update_topic_lag(topic, msg_id, metric_name: 'limits_group_topic_delta_seconds', help: 'Delta time between limits event written to stream and limits group start')
117
+ start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
118
+ events += 1 if handle_event(JSON.parse(msg_hash['event'], allow_nan: true, create_additions: true))
119
+ seconds += Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
120
+ end
121
+ end
122
+ break if @cancel_thread
123
+
124
+ # A plugin can install several targets at once so reload once per read
125
+ reload(changed_targets: changed_targets.to_a) unless changed_targets.empty?
126
+ # Publish once for everything this read changed
127
+ if events > 0 or !changed_targets.empty?
128
+ start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
129
+ flush()
130
+ seconds += Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
131
+ end
132
+ record_events(events, seconds) if events > 0
133
+ failures = 0
134
+ rescue => e
135
+ @error = e
136
+ @logger.error("Limits group microservice #{recovering ? 'reload ' : ''}error: #{e.formatted}")
137
+ # Keep the targets changed so far so the recovery rereads their definitions
138
+ @recovery_targets = (@recovery_targets || Set.new).merge(changed_targets)
139
+ failures += 1
140
+ break if @retry_sleeper.sleep([2**(failures - 1), MAX_RETRY_SECONDS].min)
141
+ end
142
+ end
143
+ end
144
+
145
+ def shutdown
146
+ @retry_sleeper.cancel
147
+ super()
148
+ end
149
+
150
+ # Reread the group definitions, limits states and settings and recompute
151
+ # every group. Item definitions are cached per packet and only reread for
152
+ # packets not yet cached and those of the changed targets.
153
+ #
154
+ # @param changed_targets [Array<String>] Targets installed or removed since the last reload
155
+ def reload(changed_targets: [])
156
+ changed_targets.each do |target_name|
157
+ # Reinstalling can move the target to another db_shard and the publish
158
+ # below writes to it, so don't use the db_shard cached before
159
+ Store.clear_db_shard_for_target(target_name, scope: @scope)
160
+ @definitions.delete(target_name)
161
+ # Installing a target clears its LIMITS_GROUP CVT so publish it again
162
+ # even if its groups' values didn't change
163
+ @published.delete(target_name)
164
+ end
165
+ @groups = TargetModel.limits_groups(scope: @scope)
166
+ build_indexes()
167
+ @current_limits = Store.hgetall("#{@scope}__current_limits")
168
+ load_settings()
169
+ @settings_changed = false
170
+ load_definitions()
171
+ @values = {}
172
+ @changed_groups.clear
173
+ compute(@order)
174
+ end
175
+
176
+ # The limits events stream only keeps ~1000 entries so a flood of
177
+ # LIMITS_CHANGE events (e.g. a target's first packets) can trim events
178
+ # before a busy microservice reads them. current_limits and the settings
179
+ # are always current so recompute every group from them.
180
+ def reload_if_events_trimmed
181
+ return unless LimitsEventTopic.events_trimmed?(@limits_event_offset, scope: @scope)
182
+
183
+ @logger.warn("#{@name}: Limits events were trimmed before they could be read, reloading limits groups")
184
+ reload()
185
+ publish()
186
+ end
187
+
188
+ # Handles one event and publishes right away. The run loop instead handles
189
+ # every event in a read with handle_event and then calls flush once.
190
+ #
191
+ # @param event [Hash] A limits event from the limits events topic
192
+ def process_event(event)
193
+ start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
194
+ return unless handle_event(event)
195
+
196
+ flush()
197
+ record_events(1, Process.clock_gettime(Process::CLOCK_MONOTONIC) - start)
198
+ end
199
+
200
+ # Records the groups an event affects. flush recomputes them once for every
201
+ # event in a read since a large group can take a while to compute.
202
+ #
203
+ # @param event [Hash] A limits event from the limits events topic
204
+ # @return [Boolean] Whether the event affects any group
205
+ def handle_event(event)
206
+ case event['type']
207
+ when 'LIMITS_CHANGE', 'LIMITS_ENABLE_STATE'
208
+ key = "#{event['target_name']}__#{event['packet_name']}__#{event['item_name']}"
209
+ groups = @item_groups[key]
210
+ return false unless groups
211
+
212
+ # Read the stored state rather than trusting the event: events for stored
213
+ # packets with suppress_stored don't update current_limits
214
+ @current_limits[key] = Store.hget("#{@scope}__current_limits", key)
215
+ settings = Store.hget("#{@scope}__current_limits_settings", key)
216
+ @settings[key] = settings ? JSON.parse(settings, allow_nan: true, create_additions: true) : nil
217
+ @changed_groups.merge(groups)
218
+ true
219
+ when 'LIMITS_GROUP_ENABLE_STATE', 'LIMITS_SETTINGS'
220
+ # These can change the enabled flag of many items and groups so reread
221
+ # them all, once per read in flush
222
+ @settings_changed = true
223
+ true
224
+ else
225
+ false
226
+ end
227
+ end
228
+
229
+ # Recomputes the groups events changed (all of them if the settings changed)
230
+ # and publishes every target whose groups changed since its last publish
231
+ def flush
232
+ if @settings_changed
233
+ load_settings()
234
+ compute(@order)
235
+ @settings_changed = false
236
+ elsif !@changed_groups.empty?
237
+ compute(with_ancestors(@changed_groups.to_a))
238
+ end
239
+ @changed_groups.clear
240
+ publish()
241
+ end
242
+
243
+ # Publish the LIMITS_GROUP packet of each target whose groups' values changed
244
+ # since its last publish
245
+ #
246
+ # @param force [Boolean] Publish every target's packet even if nothing changed
247
+ def publish(force: false)
248
+ by_target = {}
249
+ @values.each do |key, value|
250
+ target_name, group_name = LimitsEventTopic.split_limits_group_key(key)
251
+ # Groups stored before groups were owned by a target have no packet to publish
252
+ next unless target_name
253
+
254
+ (by_target[target_name] ||= {})[group_name] = value
255
+ end
256
+ # A target whose groups are all gone has no packet any more
257
+ @published.select! { |target_name, _values| by_target.key?(target_name) }
258
+ @packets.select! { |target_name, _packet| by_target.key?(target_name) }
259
+
260
+ by_target.each do |target_name, values|
261
+ next if !force and values == @published[target_name]
262
+
263
+ publish_target(target_name, values)
264
+ @published[target_name] = values
265
+ end
266
+ end
267
+
268
+ attr_reader :values
269
+
270
+ private
271
+
272
+ # @param events [Integer] Events which affected a group
273
+ # @param seconds [Float] Time spent computing and publishing them
274
+ def record_events(events, seconds)
275
+ @event_count += events
276
+ @processing_seconds += seconds
277
+ set_event_metrics(seconds)
278
+ end
279
+
280
+ # The duration gauge is the last read's processing time. The totals let
281
+ # a benchmark compute the average per event over any period from two samples.
282
+ def set_event_metrics(duration)
283
+ @metric.set(name: 'limits_group_duration_seconds', value: duration, type: 'gauge', unit: 'seconds', help: 'Time to roll up and publish the last read of limits events')
284
+ @metric.set(name: 'limits_group_event_total', value: @event_count, type: 'counter', help: 'Limits events which affected a limits group')
285
+ @metric.set(name: 'limits_group_processing_seconds_total', value: @processing_seconds, type: 'counter', unit: 'seconds', help: 'Time spent rolling up and publishing limits events')
286
+ end
287
+
288
+ def publish_target(target_name, values)
289
+ # Building the packet means defining two items per group so only rebuild
290
+ # it when the target's groups change. Every item is written below.
291
+ groups, packet = @packets[target_name]
292
+ unless groups == values.keys
293
+ packet = PacketConfig.generate_limits_group_packet(target_name, values.keys)
294
+ @packets[target_name] = [values.keys, packet]
295
+ end
296
+ values.each do |group, (state, enabled)|
297
+ item = packet.get_item(group)
298
+ # A group whose enabled members have no state yet reports GREEN with no
299
+ # limits state so limits aware widgets show it uncolored, as does a DISABLED group
300
+ packet.write_item(item, PacketConfig::LIMITS_GROUP_STATES[state || 'GREEN'], :RAW)
301
+ item.limits.state = (state and state != LimitsRollup::DISABLED) ? state.to_sym : nil
302
+ enabled_item = packet.get_item("#{group}#{PacketConfig::LIMITS_GROUP_ENABLED_SUFFIX}")
303
+ packet.write_item(enabled_item, PacketConfig::LIMITS_GROUP_ENABLED_STATES[enabled], :RAW)
304
+ end
305
+ packet.received_time = Time.now.sys
306
+ # Count it like an interface does so the packet counts show it and it survives restarts
307
+ packet.received_count = TargetModel.increment_telemetry_count(target_name, PacketConfig::LIMITS_GROUP_PACKET, 1, scope: @scope)
308
+ packet.stored = false
309
+ # write_packet updates the DECOM topic and the CVT but (unlike inject_tlm)
310
+ # doesn't check limits so the rollup never raises limits events of its own
311
+ TelemetryDecomTopic.write_packet(packet, scope: @scope)
312
+ @count += 1
313
+ @metric.set(name: 'limits_group_publish_total', value: @count, type: 'counter')
314
+ end
315
+
316
+ def build_indexes
317
+ @item_groups = {}
318
+ @parents = {}
319
+ @groups.each do |group, members|
320
+ members.each do |target_name, packet_name, item_name|
321
+ if child_group?(packet_name)
322
+ (@parents[LimitsEventTopic.limits_group_key(target_name, item_name)] ||= []) << group
323
+ else
324
+ (@item_groups["#{target_name}__#{packet_name}__#{item_name}"] ||= []) << group
325
+ end
326
+ end
327
+ end
328
+
329
+ # Order the groups so children are computed before their parents. Install
330
+ # rejects cycles but if one is stored anyway skip the edge that closes it.
331
+ @order = []
332
+ done = Set.new
333
+ visiting = Set.new
334
+ visit = lambda do |group|
335
+ return if done.include?(group)
336
+
337
+ if visiting.include?(group)
338
+ warn_once("cycle #{group}", "LIMITS_GROUP #{display(group)} contains itself. Ignoring the nested group that closes the loop.")
339
+ return
340
+ end
341
+ visiting << group
342
+ @groups[group].each do |target_name, packet_name, item_name|
343
+ next unless child_group?(packet_name)
344
+
345
+ child = LimitsEventTopic.limits_group_key(target_name, item_name)
346
+ visit.call(child) if @groups[child]
347
+ end
348
+ visiting.delete(group)
349
+ done << group
350
+ @order << group
351
+ end
352
+ @groups.keys.sort.each { |group| visit.call(group) }
353
+ end
354
+
355
+ def load_settings
356
+ @settings = {}
357
+ Store.hgetall("#{@scope}__current_limits_settings").each do |key, json|
358
+ @settings[key] = JSON.parse(json, allow_nan: true, create_additions: true)
359
+ end
360
+ @disabled_groups = LimitsEventTopic.limits_group_settings(scope: @scope)
361
+ .select { |_group, settings| settings['enabled'] == false }.keys.to_set
362
+ end
363
+
364
+ # Item definitions supply the limits enabled flag when no setting is stored
365
+ # and tell us which members are unknown or have no limits. Only the enabled
366
+ # flags are kept, per packet, so each packet definition is parsed once until
367
+ # its target is installed or removed again.
368
+ def load_definitions
369
+ packets = Set.new
370
+ @groups.each_value do |members|
371
+ members.each do |target_name, packet_name, _item_name|
372
+ packets << [target_name, packet_name] unless child_group?(packet_name)
373
+ end
374
+ end
375
+ # Drop packets no group references any more
376
+ @definitions.each do |target_name, target_packets|
377
+ target_packets.select! { |packet_name, _items| packets.include?([target_name, packet_name]) }
378
+ end
379
+ @definitions.reject! { |_target_name, target_packets| target_packets.empty? }
380
+
381
+ db_shards = {}
382
+ packets.each do |target_name, packet_name|
383
+ next if @definitions.dig(target_name, packet_name)
384
+
385
+ # Read the store rather than TargetModel.packet, and the target's
386
+ # db_shard rather than Store.db_shard_for_target, since both caches can
387
+ # hold what they saw before the target was just installed
388
+ db_shard = (db_shards[target_name] ||= target_db_shard(target_name))
389
+ next unless db_shard # Unknown target so all its members are ignored
390
+
391
+ json = Store.instance(db_shard: db_shard).hget("#{@scope}__openc3tlm__#{target_name}", packet_name)
392
+ next unless json # Unknown packet so all its members are ignored
393
+
394
+ items = {}
395
+ JSON.parse(json, allow_nan: true, create_additions: true)['items'].each do |item|
396
+ items[item['name']] = item['limits']['enabled'] ? true : false if limits?(item)
397
+ end
398
+ (@definitions[target_name] ||= {})[packet_name] = items
399
+ end
400
+ end
401
+
402
+ # Only items with limits or state colors can be enabled. Ruby stores enabled
403
+ # false for a disabled item but the Python APIs remove the key, so look at
404
+ # the limits values and states too.
405
+ #
406
+ # @param item [Hash] Item definition
407
+ # @return [Boolean] Whether the item has limits or state colors
408
+ def limits?(item)
409
+ limits = item['limits'] || {}
410
+ return true if limits.key?('enabled')
411
+ # Limits values are stored by limits set name, e.g. DEFAULT
412
+ return true if limits.any? { |_name, value| value.is_a?(Hash) }
413
+
414
+ (item['states'] || {}).any? { |_name, state| state.is_a?(Hash) and state['color'] }
415
+ end
416
+
417
+ # @return [Integer, nil] the target's db_shard or nil if it isn't installed
418
+ def target_db_shard(target_name)
419
+ json = Store.hget("#{@scope}__openc3_targets", target_name)
420
+ json ? JSON.parse(json, allow_nan: true, create_additions: true)['db_shard'].to_i : nil
421
+ end
422
+
423
+ # @return [Array<String>] the groups plus every group above them
424
+ def with_ancestors(groups)
425
+ result = Set.new
426
+ pending = groups.dup
427
+ until pending.empty?
428
+ group = pending.pop
429
+ next if result.include?(group)
430
+
431
+ result << group
432
+ pending.concat(@parents[group] || [])
433
+ end
434
+ @order.select { |group| result.include?(group) }
435
+ end
436
+
437
+ # @param groups [Array<String>] groups to compute, children before parents
438
+ def compute(groups)
439
+ groups.each do |group|
440
+ # A group disabled itself (disable_limits_group with cascade false) is
441
+ # DISABLED whatever its members are, and its parents ignore it
442
+ if @disabled_groups.include?(group)
443
+ @values[group] = [LimitsRollup::DISABLED, LimitsRollup::ENABLED_FALSE]
444
+ next
445
+ end
446
+
447
+ members = []
448
+ @groups[group].each do |target_name, packet_name, item_name|
449
+ if child_group?(packet_name)
450
+ # A child which isn't defined (yet) is ignored like an unknown item
451
+ child = @values[LimitsEventTopic.limits_group_key(target_name, item_name)]
452
+ unless child
453
+ warn_once("#{group} child #{target_name} #{item_name}",
454
+ "LIMITS_GROUP #{display(group)} member #{target_name} #{PacketConfig::LIMITS_GROUP_PACKET} #{item_name} is not a defined limits group. Ignoring it until it is.")
455
+ next
456
+ end
457
+
458
+ # A child's state already ignores its disabled members. A child which is
459
+ # entirely disabled is ignored like a disabled item and a partly enabled
460
+ # child makes this group partly enabled.
461
+ members << child
462
+ else
463
+ member = item_member(target_name, packet_name, item_name, group)
464
+ members << member if member
465
+ end
466
+ end
467
+ @values[group] = LimitsRollup.rollup(members)
468
+ end
469
+ end
470
+
471
+ # @return [Array(String|nil, Boolean), nil] [limits state, enabled] or nil if the item is unknown
472
+ def item_member(target_name, packet_name, item_name, group)
473
+ definition = @definitions.dig(target_name, packet_name)
474
+ unless definition and definition.key?(item_name)
475
+ warn_once("#{group} #{target_name} #{packet_name} #{item_name}",
476
+ "LIMITS_GROUP #{display(group)} member #{target_name} #{packet_name} #{item_name} does not exist or has no limits. Ignoring it.")
477
+ return nil
478
+ end
479
+
480
+ key = "#{target_name}__#{packet_name}__#{item_name}"
481
+ settings = @settings[key]
482
+ if settings and settings.key?('enabled')
483
+ enabled = settings['enabled']
484
+ else
485
+ enabled = definition[item_name]
486
+ end
487
+ [@current_limits[key], enabled ? true : false]
488
+ end
489
+
490
+ # Nested groups are the members <TARGET> LIMITS_GROUP <GROUP>
491
+ def child_group?(packet_name)
492
+ packet_name == PacketConfig::LIMITS_GROUP_PACKET
493
+ end
494
+
495
+ # @return [String] TARGET GROUP for log messages
496
+ def display(group)
497
+ LimitsEventTopic.split_limits_group_key(group).compact.join(' ')
498
+ end
499
+
500
+ def warn_once(key, message)
501
+ return if @warned.include?(key)
502
+
503
+ @warned << key
504
+ @logger.warn(message)
505
+ end
506
+ end
507
+ end
508
+
509
+ if __FILE__ == $0
510
+ OpenC3::LimitsGroupMicroservice.run
511
+ OpenC3::ThreadManager.instance.shutdown
512
+ OpenC3::ThreadManager.instance.join
513
+ end