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
@@ -25,15 +25,18 @@ require 'openc3/io/stderr'
25
25
  require 'childprocess'
26
26
  require 'openc3/script/suite_runner'
27
27
  require 'openc3/utilities/script'
28
+ require 'openc3/utilities/script_message_signing'
28
29
  require 'openc3/utilities/store'
29
30
  require 'openc3/utilities/store_queued'
30
31
  require 'openc3/utilities/bucket_require'
31
32
  require 'openc3/utilities/python_venv'
33
+ require 'openc3/utilities/script_env'
32
34
  require 'openc3/models/offline_access_model'
33
35
  require 'openc3/models/environment_model'
34
36
  require 'openc3/models/script_engine_model'
35
37
  require 'openc3/models/script_status_model'
36
38
  require 'fileutils'
39
+ require 'prism'
37
40
 
38
41
  if not defined? RAILS_ROOT
39
42
  if ENV['RAILS_ROOT']
@@ -100,6 +103,9 @@ module OpenC3
100
103
  prompt_for_critical_cmd metadata_input open_file_dialog open_files_dialog open_bucket_dialog]
101
104
  SCRIPT_METHODS.each do |method|
102
105
  define_method(method) do |*args, **kwargs|
106
+ if method == :metadata_input
107
+ OpenC3.deprecation_warning("`metadata_input` is deprecated. Please use the user input methods followed by `inject_tlm` instead.", uplevel: 1)
108
+ end
103
109
  while true
104
110
  if RunningScript.instance
105
111
  RunningScript.instance.scriptrunner_puts("#{method}(#{args.join(', ')})")
@@ -179,7 +185,7 @@ module OpenC3
179
185
  else
180
186
  # Retrieve file
181
187
  text = ::Script.body(RunningScript.instance.scope, procedure_name)
182
- raise "Unable to retrieve: #{procedure_name}" unless text
188
+ raise RunningScript::InvalidStartLineError, "Unable to retrieve: #{procedure_name}" unless text
183
189
  running_script_anycable_publish("running-script-channel:#{RunningScript.instance.id}", { type: :file, filename: procedure_name, text: text.to_utf8, breakpoints: breakpoints })
184
190
 
185
191
  # Cache instrumentation into RAM
@@ -192,28 +198,33 @@ module OpenC3
192
198
  end
193
199
  RunningScript.instrumented_cache[path] = [instrumented_script, text]
194
200
  else
195
- if line_no > 1 or not end_line_no.nil?
201
+ # != rather than > so line 0 or below reaches the range check instead of
202
+ # running the whole file with a negative line offset
203
+ if line_no != 1 or not end_line_no.nil?
196
204
  text_lines = text.lines
197
205
 
198
206
  # Instrument only the specified lines
207
+ requested_end_line_no = end_line_no # nil means goto / run from line
199
208
  if end_line_no.nil?
200
209
  end_line_no = text_lines.length
201
210
  end
202
211
 
203
212
  if line_no < 1 or line_no > text_lines.length
204
- raise "Invalid start line number: #{line_no} for #{procedure_name}"
213
+ raise RunningScript::InvalidStartLineError, "Invalid start line number: #{line_no} for #{procedure_name}"
205
214
  end
206
215
 
207
216
  if end_line_no < 1 or end_line_no > text_lines.length
208
- raise "Invalid end line number: #{end_line_no} for #{procedure_name}"
217
+ raise RunningScript::InvalidStartLineError, "Invalid end line number: #{end_line_no} for #{procedure_name}"
209
218
  end
210
219
 
211
220
  if line_no > end_line_no
212
- raise "Start line number #{line_no} is greater than end line number #{end_line_no} for #{procedure_name}"
221
+ raise RunningScript::InvalidStartLineError, "Start line number #{line_no} is greater than end line number #{end_line_no} for #{procedure_name}"
213
222
  end
214
223
 
215
224
  if not use_script_engine
216
- text = text_lines[(line_no - 1)...end_line_no].join
225
+ partial_text = text_lines[(line_no - 1)...end_line_no].join
226
+ RunningScript.validate_partial_script(text, partial_text, procedure_name, line_no, requested_end_line_no)
227
+ text = partial_text
217
228
  end
218
229
  end
219
230
 
@@ -364,6 +375,31 @@ module OpenC3
364
375
  end
365
376
 
366
377
  class RunningScript
378
+ # In-memory HMAC key for signing/verifying control channel messages.
379
+ # Set by run_script.rb from stdin; never written to env or disk.
380
+ class << self
381
+ attr_accessor :signing_key
382
+ end
383
+
384
+ # Raised when Goto, Run From Line, or Execute Selection would start or end
385
+ # inside a method or block, so the lines can't run on their own
386
+ class InvalidStartLineError < StandardError; end
387
+
388
+ # Goto and Execute Selection run a slice of the file as its own code. A slice
389
+ # that starts inside a method or block leaves a dangling `end`, which used to
390
+ # surface as a confusing SyntaxError. Explain it instead. A whole file that
391
+ # doesn't parse is left to the normal SyntaxError.
392
+ def self.validate_partial_script(text, partial_text, filename, line_no, end_line_no)
393
+ return if Prism.parse(partial_text).success?
394
+ return unless Prism.parse(text).success?
395
+
396
+ if end_line_no
397
+ raise InvalidStartLineError, "Cannot run lines #{line_no}-#{end_line_no} of #{filename}: the selection starts or ends inside a method or block (def, if, do...end). Select complete statements instead and right-click Execute Selection."
398
+ else
399
+ raise InvalidStartLineError, "Cannot start at line #{line_no} of #{filename}: it is inside a method or block (def, if, do...end) that starts above it. Goto can only move to a line outside any method or block. Use Step to move through a method or right-click Execute Selection."
400
+ end
401
+ end
402
+
367
403
  def id
368
404
  return @script_status.id
369
405
  end
@@ -410,6 +446,8 @@ class RunningScript
410
446
  @@file_cache = {}
411
447
  @@output_thread = nil
412
448
  @@pause_on_error = true
449
+ # Guards @execute_while_paused_info, which the debug thread sets and the run thread takes
450
+ @@execute_while_paused_mutex = Mutex.new
413
451
  @@error = nil
414
452
  @@output_sleeper = OpenC3::Sleeper.new
415
453
  @@cancel_output = false
@@ -463,6 +501,13 @@ class RunningScript
463
501
 
464
502
  running_script_id = OpenC3::Store.incr('running-script-id')
465
503
 
504
+ # Per-script key used to sign control-channel messages. Kept in a hash scripts
505
+ # cannot read (never on the script_status record, which they can). It is
506
+ # stored once the script status exists; see prune_signing_keys.
507
+ signing_key = SecureRandom.hex(32)
508
+ signing_keys = OpenC3::ScriptMessageSigning.keys_hash(scope)
509
+ prune_signing_keys(scope)
510
+
466
511
  # COSMOS Core username (Enterprise has the actual name)
467
512
  username ||= 'Anonymous'
468
513
  # COSMOS Core full name (Enterprise has the actual name)
@@ -471,7 +516,10 @@ class RunningScript
471
516
 
472
517
  begin
473
518
  process = ChildProcess.build(process_name, runner_path.to_s, running_script_id.to_s, scope)
519
+ # inherit! only wires stdout/stderr (childprocess 5.1.0), leaving stdin
520
+ # free for the duplex pipe used to deliver secrets
474
521
  process.io.inherit! # Helps with debugging
522
+ process.duplex = true
475
523
  script_cwd = File.join(RAILS_ROOT, 'tmp', "script_#{running_script_id}")
476
524
  FileUtils.mkdir_p(script_cwd)
477
525
  process.cwd = script_cwd
@@ -480,21 +528,18 @@ class RunningScript
480
528
  model = nil
481
529
  model = OpenC3::OfflineAccessModel.get_model(name: username, scope: scope) if username != 'Anonymous'
482
530
 
483
- # Load the global environment variables
484
- status_environment = {}
485
- values = OpenC3::EnvironmentModel.all(scope: scope).values
486
- values.each do |env|
487
- process.environment[env['key']] = env['value']
488
- status_environment[env['key']] = env['value']
489
- end
531
+ # Load the global environment variables. Reserved names (OPENC3_*, LD_*,
532
+ # proxies, etc.) are configured by COSMOS and skipped here. The
533
+ # controllers reject them on create; this also covers entries stored
534
+ # before that check existed.
535
+ status_environment = OpenC3::ScriptEnv.apply_user_entries(
536
+ process.environment, OpenC3::EnvironmentModel.all(scope: scope).values, source: 'global', scope: scope
537
+ )
490
538
  # Load the script specific ENV vars set by the GUI
491
539
  # These can override the previously defined global env vars
492
- if environment
493
- environment.each do |env|
494
- process.environment[env['key']] = env['value']
495
- status_environment[env['key']] = env['value']
496
- end
497
- end
540
+ status_environment.merge!(
541
+ OpenC3::ScriptEnv.apply_user_entries(process.environment, environment, source: 'script', scope: scope)
542
+ )
498
543
 
499
544
  script_status = OpenC3::ScriptStatusModel.new(
500
545
  name: running_script_id.to_s, # Unique id for this script
@@ -519,23 +564,22 @@ class RunningScript
519
564
  scope: scope # Scope of the script
520
565
  )
521
566
  script_status.create()
522
-
523
- # Set proper secrets for running script
524
- process.environment['SECRET_KEY_BASE'] = nil
525
- process.environment['OPENC3_REDIS_USERNAME'] = ENV.fetch('OPENC3_SR_REDIS_USERNAME', nil)
526
- process.environment['OPENC3_REDIS_PASSWORD'] = ENV.fetch('OPENC3_SR_REDIS_PASSWORD', nil)
527
- process.environment['OPENC3_BUCKET_USERNAME'] = ENV.fetch('OPENC3_SR_BUCKET_USERNAME', nil)
528
- process.environment['OPENC3_BUCKET_PASSWORD'] = ENV.fetch('OPENC3_SR_BUCKET_PASSWORD', nil)
529
- process.environment['OPENC3_SR_REDIS_USERNAME'] = nil
530
- process.environment['OPENC3_SR_REDIS_PASSWORD'] = nil
531
- process.environment['OPENC3_SR_BUCKET_USERNAME'] = nil
532
- process.environment['OPENC3_SR_BUCKET_PASSWORD'] = nil
567
+ # Stored after the status so prune_signing_keys never sees a key without
568
+ # a running status
569
+ OpenC3::Store.hset(signing_keys, running_script_id.to_s, signing_key)
570
+
571
+ # Keep secrets out of the child's environment: /proc/<pid>/environ keeps the
572
+ # environment the process started with, even after the child deletes them
573
+ # from ENV. The child gets the ones it needs over stdin below. This also
574
+ # removes ANYCABLE_REDIS_URL, which embeds the all-keys 'openc3' Redis user
575
+ # and would expose every signing key.
576
+ OpenC3::ScriptEnv.scrub_spawn_environment(process.environment)
533
577
  process.environment['OPENC3_API_CLIENT'] = ENV.fetch('OPENC3_API_CLIENT', nil)
534
578
  if model and model.offline_access_token
535
579
  auth = OpenC3::OpenC3KeycloakAuthentication.new(ENV.fetch('OPENC3_KEYCLOAK_URL', nil))
536
580
  valid_token = auth.get_token_from_refresh_token(model.offline_access_token)
537
581
  if valid_token
538
- process.environment['OPENC3_API_TOKEN'] = model.offline_access_token
582
+ auth_secret = { 'token' => model.offline_access_token }
539
583
  else
540
584
  model.offline_access_token = nil
541
585
  model.update
@@ -544,7 +588,7 @@ class RunningScript
544
588
  else
545
589
  process.environment['OPENC3_API_USER'] = ENV.fetch('OPENC3_API_USER', nil)
546
590
  if ENV['OPENC3_SERVICE_PASSWORD']
547
- process.environment['OPENC3_API_PASSWORD'] = ENV.fetch('OPENC3_SERVICE_PASSWORD')
591
+ auth_secret = { 'user' => ENV.fetch('OPENC3_API_USER', nil), 'password' => ENV.fetch('OPENC3_SERVICE_PASSWORD') }
548
592
  else
549
593
  raise "No authentication available for script"
550
594
  end
@@ -576,8 +620,18 @@ class RunningScript
576
620
 
577
621
  process.detach = true
578
622
  process.start
623
+ started = true
624
+ # Secrets go over stdin (not env, which is readable via /proc/<pid>/environ)
625
+ process.io.stdin.puts(JSON.generate({ 'signing_key' => signing_key, 'auth' => auth_secret, 'env' => OpenC3::ScriptEnv.stdin_secrets }))
626
+ process.io.stdin.close
579
627
  running_script_id
580
628
  rescue => e
629
+ begin
630
+ # Don't leave a detached child running without credentials
631
+ process.stop if started && process
632
+ rescue => stop_error
633
+ OpenC3::Logger.error("Failed to stop script process after spawn failure: #{stop_error.message}")
634
+ end
581
635
  begin
582
636
  # Clean up the orphaned script status record so the script
583
637
  # does not remain stuck in 'spawning' state forever.
@@ -587,10 +641,32 @@ class RunningScript
587
641
  rescue => cleanup_error
588
642
  OpenC3::Logger.error("Failed to cleanup after spawn failure: #{cleanup_error.message}")
589
643
  end
644
+ begin
645
+ OpenC3::Store.hdel(signing_keys, running_script_id.to_s)
646
+ rescue => del_error
647
+ OpenC3::Logger.error("Failed to delete signing key after spawn failure: #{del_error.message}")
648
+ end
590
649
  raise e
591
650
  end
592
651
  end
593
652
 
653
+ # Signing keys have no expiry, so a key can never disappear while its script
654
+ # runs. Scripts that end on their own can't delete their key (their Redis user
655
+ # can't access the hash), so remove keys whose script is no longer running.
656
+ # Reads the keys before the running names so a script spawned in between keeps
657
+ # its key: spawn stores the key only after creating the running status.
658
+ def self.prune_signing_keys(scope)
659
+ signing_keys = OpenC3::ScriptMessageSigning.keys_hash(scope)
660
+ ids = OpenC3::Store.hkeys(signing_keys)
661
+ return if ids.empty?
662
+
663
+ stale = ids - OpenC3::ScriptStatusModel.names(scope: scope, type: 'running')
664
+ OpenC3::Store.hdel(signing_keys, *stale) unless stale.empty?
665
+ rescue => e
666
+ # Housekeeping only; never prevent a script from starting
667
+ OpenC3::Logger.error("Failed to prune script signing keys: #{e.message}")
668
+ end
669
+
594
670
  def initialize(script_status)
595
671
  @@instance = self
596
672
  # Flush the replay queue (used by running_script_anycable_publish) quickly so
@@ -604,6 +680,8 @@ class RunningScript
604
680
  @prompt_id = nil
605
681
  @line_offset = 0
606
682
  @output_io = StringIO.new('', 'r+')
683
+ @capturing_output = false
684
+ @executing_selection = false
607
685
  @output_io_mutex = Mutex.new
608
686
  @continue_after_error = true
609
687
  @debug_text = nil
@@ -766,6 +844,7 @@ class RunningScript
766
844
  @script_status.line_no = 0
767
845
  @current_file = nil
768
846
  @execute_while_paused_info = nil
847
+ @executing_selection = false
769
848
  end
770
849
 
771
850
  def unique_filename
@@ -988,6 +1067,9 @@ class RunningScript
988
1067
  # Handle stopping mid-script if necessary
989
1068
  raise OpenC3::StopScript if @stop
990
1069
 
1070
+ # Handle a goto requested while running
1071
+ check_execute_while_paused(pause: false)
1072
+
991
1073
  handle_potential_tab_change(filename)
992
1074
 
993
1075
  # Adjust line number for offset in main script
@@ -1041,9 +1123,14 @@ class RunningScript
1041
1123
  def debug(debug_text)
1042
1124
  handle_output_io()
1043
1125
 
1126
+ # GOTO 32 and Goto(32) call the goto script API, which hands off to
1127
+ # execute_while_paused because debug doesn't run on the run thread
1128
+ goto_text = RunningScript.normalize_debug_goto(debug_text)
1129
+ debug_text = goto_text if goto_text
1130
+
1044
1131
  use_script_engine = false
1045
1132
  extension = File.extname(current_filename()).to_s.downcase
1046
- if @script_engine and extension != ".py"
1133
+ if @script_engine and extension != ".py" and !goto_text
1047
1134
  use_script_engine = true
1048
1135
  end
1049
1136
 
@@ -1109,16 +1196,40 @@ class RunningScript
1109
1196
 
1110
1197
  # bind_variables of nil binds only when filename is the currently running file
1111
1198
  def execute_while_paused(filename, line_no = 1, end_line_no = nil, bind_variables = nil)
1112
- if @script_status.state == 'paused' or @script_status.state == 'error' or @script_status.state == 'breakpoint'
1113
- @execute_while_paused_info = { filename: filename, line_no: line_no, end_line_no: end_line_no, bind_variables: bind_variables }
1199
+ state = @script_status.state
1200
+ if end_line_no.nil? and @executing_selection
1201
+ # A goto inside Execute Selection would end the whole script when it completes
1202
+ scriptrunner_puts("Cannot goto while Execute Selection is running")
1203
+ elsif end_line_no.nil? and state == 'running' and !@use_instrumentation
1204
+ # The goto would wait for the next instrumented line, which may be far away
1205
+ scriptrunner_puts("Cannot goto while instrumentation is disabled")
1206
+ # Goto while running jumps at the start of the next line (see pre_line_instrumentation)
1207
+ elsif ['paused', 'error', 'breakpoint'].include?(state) or (state == 'running' and end_line_no.nil?)
1208
+ @@execute_while_paused_mutex.synchronize do
1209
+ @execute_while_paused_info = { filename: filename, line_no: line_no, end_line_no: end_line_no, bind_variables: bind_variables }
1210
+ end
1114
1211
  else
1115
- scriptrunner_puts("Cannot execute selection or goto unless script is paused, breakpoint, or in error state")
1212
+ scriptrunner_puts("Cannot execute selection unless script is paused, breakpoint, or in error state. Cannot goto unless script is running, paused, breakpoint, or in error state.")
1116
1213
  end
1117
1214
  end
1118
1215
 
1216
+ # The debug prompt accepts goto in any case: GOTO 32, Goto(32), goto "other.rb", 12
1217
+ # Returns the text with goto lowercased so it calls the goto script API, or
1218
+ # nil if the text is not a goto
1219
+ def self.normalize_debug_goto(debug_text)
1220
+ text = debug_text.strip
1221
+ return nil unless /\Agoto(?=[\s(]|\z)/i.match?(text)
1222
+
1223
+ 'goto' + text[4..]
1224
+ end
1225
+
1119
1226
  def scriptrunner_puts(string, color = 'BLACK')
1120
1227
  line_to_write = Time.now.sys.formatted + " (SCRIPTRUNNER): " + string
1121
- $stdout.puts line_to_write
1228
+ # Write to STDOUT rather than $stdout. While a script runs $stdout also
1229
+ # feeds @output_io, so handle_output_io would publish this line a second
1230
+ # time. Log it directly instead so the message log still has it.
1231
+ STDOUT.puts line_to_write
1232
+ message_log.write(line_to_write + "\n") if @capturing_output
1122
1233
  running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :output, line: line_to_write, color: color })
1123
1234
  end
1124
1235
 
@@ -1187,7 +1298,11 @@ class RunningScript
1187
1298
  @go = false
1188
1299
  @prompt_id = prompt['id'] if prompt
1189
1300
  until (@go or @stop)
1190
- check_execute_while_paused()
1301
+ if prompt
1302
+ discard_goto_during_prompt()
1303
+ else
1304
+ check_execute_while_paused()
1305
+ end
1191
1306
  sleep(0.01)
1192
1307
  count += 1
1193
1308
  if count % 100 == 0 # Approximately Every Second
@@ -1220,18 +1335,28 @@ class RunningScript
1220
1335
  raise error if error and !@continue_after_error
1221
1336
  end
1222
1337
 
1223
- def check_execute_while_paused
1224
- if @execute_while_paused_info
1225
- bind_variables = @execute_while_paused_info[:bind_variables]
1338
+ # pause: true (the default) lands a goto paused on its line so the user can inspect
1339
+ # it before Step or Go. pre_line_instrumentation passes false to jump while running.
1340
+ def check_execute_while_paused(pause: true)
1341
+ info = take_execute_while_paused_info()
1342
+ if info
1343
+ bind_variables = info[:bind_variables]
1226
1344
  if bind_variables.nil?
1227
- bind_variables = (@script_status.current_filename == @execute_while_paused_info[:filename])
1345
+ bind_variables = (@script_status.current_filename == info[:filename])
1228
1346
  end
1229
- if @execute_while_paused_info[:end_line_no]
1347
+ if info[:end_line_no]
1230
1348
  # Execute Selection While Paused
1231
1349
  state = @script_status.state
1232
1350
  current_filename = @script_status.current_filename
1233
1351
  line_no = @script_status.line_no
1234
- start(@execute_while_paused_info[:filename], line_no: @execute_while_paused_info[:line_no], end_line_no: @execute_while_paused_info[:end_line_no], bind_variables: bind_variables)
1352
+ # Restore rather than clear because a selection can pause and run another
1353
+ previous_executing_selection = @executing_selection
1354
+ @executing_selection = true
1355
+ begin
1356
+ start(info[:filename], line_no: info[:line_no], end_line_no: info[:end_line_no], bind_variables: bind_variables)
1357
+ ensure
1358
+ @executing_selection = previous_executing_selection
1359
+ end
1235
1360
  # Need to restore state after returning so that the correct line will be shown in ScriptRunner
1236
1361
  @script_status.state = state
1237
1362
  @script_status.current_filename = current_filename
@@ -1239,12 +1364,38 @@ class RunningScript
1239
1364
  @script_status.update(queued: true)
1240
1365
  running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :line, filename: @script_status.current_filename, line_no: @script_status.line_no, state: @script_status.state })
1241
1366
  else
1242
- # Goto While Paused
1243
- start(@execute_while_paused_info[:filename], line_no: @execute_while_paused_info[:line_no], bind_variables: bind_variables, complete: true)
1367
+ # Goto: pause before executing the first line at the new location
1368
+ previous_pause = @pause
1369
+ @pause = true if pause
1370
+ begin
1371
+ start(info[:filename], line_no: info[:line_no], bind_variables: bind_variables, complete: true)
1372
+ rescue InvalidStartLineError => e
1373
+ # Nothing ran, so stay where we are rather than entering the error state
1374
+ @pause = previous_pause
1375
+ scriptrunner_puts(e.message, 'RED')
1376
+ end
1244
1377
  end
1245
1378
  end
1246
- ensure
1247
- @execute_while_paused_info = nil
1379
+ end
1380
+
1381
+ # Return the queued goto or execute selection and clear it in one step. Reading
1382
+ # and clearing separately could drop one the debug thread queues in between.
1383
+ def take_execute_while_paused_info
1384
+ @@execute_while_paused_mutex.synchronize do
1385
+ info = @execute_while_paused_info
1386
+ @execute_while_paused_info = nil
1387
+ info
1388
+ end
1389
+ end
1390
+
1391
+ # A goto accepted while the script was running can still be queued when the
1392
+ # script stops on a prompt. Running it there would leave the prompt open, so
1393
+ # drop it and tell the user.
1394
+ def discard_goto_during_prompt
1395
+ info = take_execute_while_paused_info()
1396
+ return unless info
1397
+
1398
+ scriptrunner_puts("Goto to line #{info[:line_no]} canceled because the script is waiting on a prompt. Answer the prompt and try again.", 'RED')
1248
1399
  end
1249
1400
 
1250
1401
  def mark_running
@@ -1321,7 +1472,11 @@ class RunningScript
1321
1472
  @script_status.update(queued: true)
1322
1473
  thread.join
1323
1474
  end
1324
- running_script_publish("cmd-running-script-channel:#{@script_status.id}", "shutdown")
1475
+ shutdown_msg = "shutdown"
1476
+ if RunningScript.signing_key
1477
+ shutdown_msg = OpenC3::ScriptMessageSigning.sign(RunningScript.signing_key, "shutdown")
1478
+ end
1479
+ running_script_publish("cmd-running-script-channel:#{@script_status.id}", shutdown_msg)
1325
1480
  end
1326
1481
 
1327
1482
  def mark_breakpoint
@@ -1341,6 +1496,7 @@ class RunningScript
1341
1496
  # Capture STDOUT and STDERR
1342
1497
  $stdout.add_stream(@output_io)
1343
1498
  $stderr.add_stream(@output_io)
1499
+ @capturing_output = true
1344
1500
 
1345
1501
  output = "Starting script: #{File.basename(@script_status.filename)}"
1346
1502
  output += " in DISCONNECT mode" if $disconnect
@@ -1401,6 +1557,7 @@ class RunningScript
1401
1557
  # $stderr to the IO constant
1402
1558
  $stdout.remove_stream(@output_io) if $stdout.respond_to? :remove_stream
1403
1559
  $stderr.remove_stream(@output_io) if $stderr.respond_to? :remove_stream
1560
+ @capturing_output = false
1404
1561
 
1405
1562
  # Clear run thread and instance to indicate we are no longer running
1406
1563
  @@instance = saved_instance
@@ -18,6 +18,7 @@
18
18
  require 'tempfile'
19
19
  require 'openc3/utilities/target_file'
20
20
  require 'openc3/utilities/python_venv'
21
+ require 'openc3/utilities/script_env'
21
22
  require 'openc3/utilities/running_script'
22
23
  require 'openc3/script/suite'
23
24
  require 'openc3/script/suite_runner'
@@ -116,22 +117,15 @@ class Script < OpenC3::TargetFile
116
117
  model = nil
117
118
  model = OpenC3::OfflineAccessModel.get_model(name: username, scope: scope) if username and username != ''
118
119
 
119
- # Set proper secrets for running script
120
- process.environment['SECRET_KEY_BASE'] = nil
121
- process.environment['OPENC3_REDIS_USERNAME'] = ENV['OPENC3_SR_REDIS_USERNAME'] || 'OPENC3_SR_REDIS_USERNAME not set'
122
- process.environment['OPENC3_REDIS_PASSWORD'] = ENV['OPENC3_SR_REDIS_PASSWORD'] || 'OPENC3_SR_REDIS_PASSWORD not set'
123
- process.environment['OPENC3_BUCKET_USERNAME'] = ENV['OPENC3_SR_BUCKET_USERNAME'] || 'OPENC3_SR_BUCKET_USERNAME not set'
124
- process.environment['OPENC3_BUCKET_PASSWORD'] = ENV['OPENC3_SR_BUCKET_PASSWORD'] || 'OPENC3_SR_BUCKET_PASSWORD not set'
125
- process.environment['OPENC3_SR_REDIS_USERNAME'] = nil
126
- process.environment['OPENC3_SR_REDIS_PASSWORD'] = nil
127
- process.environment['OPENC3_SR_BUCKET_USERNAME'] = nil
128
- process.environment['OPENC3_SR_BUCKET_PASSWORD'] = nil
120
+ # Keep secrets out of the child's environment (/proc/<pid>/environ keeps it
121
+ # even after the child deletes them from ENV); the ones it needs go over stdin
122
+ OpenC3::ScriptEnv.scrub_spawn_environment(process.environment)
129
123
  process.environment['OPENC3_API_CLIENT'] = ENV['OPENC3_API_CLIENT'] || 'api'
130
124
  if model and model.offline_access_token
131
125
  auth = OpenC3::OpenC3KeycloakAuthentication.new(ENV['OPENC3_KEYCLOAK_URL'])
132
126
  valid_token = auth.get_token_from_refresh_token(model.offline_access_token)
133
127
  if valid_token
134
- process.environment['OPENC3_API_TOKEN'] = model.offline_access_token
128
+ auth_secret = { 'token' => model.offline_access_token }
135
129
  else
136
130
  model.offline_access_token = nil
137
131
  model.update
@@ -140,7 +134,7 @@ class Script < OpenC3::TargetFile
140
134
  else
141
135
  process.environment['OPENC3_API_USER'] = ENV['OPENC3_API_USER'] || nil
142
136
  if ENV['OPENC3_SERVICE_PASSWORD']
143
- process.environment['OPENC3_API_PASSWORD'] = ENV['OPENC3_SERVICE_PASSWORD']
137
+ auth_secret = { 'user' => ENV.fetch('OPENC3_API_USER', nil), 'password' => ENV.fetch('OPENC3_SERVICE_PASSWORD') }
144
138
  else
145
139
  # The viewer user doesn't have an offline access token (because they can't run scripts)
146
140
  # but they still want to be able to view suite files
@@ -178,8 +172,24 @@ class Script < OpenC3::TargetFile
178
172
  stderr.sync = true
179
173
  process.io.stdout = stdout
180
174
  process.io.stderr = stderr
175
+ # Explicit stdout/stderr leave stdin free; duplex gives us a pipe to deliver auth
176
+ process.duplex = true
181
177
  process.start
182
178
  begin
179
+ # Secrets go over stdin (not env, which is readable via /proc/<pid>/environ)
180
+ begin
181
+ process.io.stdin.puts(JSON.generate({ 'auth' => auth_secret, 'env' => OpenC3::ScriptEnv.stdin_secrets }))
182
+ process.io.stdin.close
183
+ rescue StandardError
184
+ process.stop # don't leave a child running without credentials
185
+ [stdout, stderr].each do |f|
186
+ f.close
187
+ f.unlink
188
+ rescue StandardError
189
+ nil
190
+ end
191
+ raise
192
+ end
183
193
  process.poll_for_exit(10) # wait for max 10s
184
194
  rescue ChildProcess::TimeoutError
185
195
  process.stop
@@ -279,6 +289,8 @@ class Script < OpenC3::TargetFile
279
289
  process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
280
290
  process = ChildProcess.build(process_name, runner_path.to_s, temp.path)
281
291
  process.cwd = File.join(RAILS_ROOT, 'scripts')
292
+ # run_instrument.py is pure local AST work and needs no secrets
293
+ OpenC3::ScriptEnv.scrub_spawn_environment(process.environment)
282
294
 
283
295
  stdout = Tempfile.new("child-stdout")
284
296
  stdout.sync = true