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
@@ -31,13 +31,16 @@ require 'openc3/models/router_model'
31
31
  require 'openc3/models/script_engine_model'
32
32
  require 'openc3/models/tool_model'
33
33
  require 'openc3/models/widget_model'
34
+ require 'openc3/models/panel_model'
34
35
  require 'openc3/models/microservice_model'
36
+ require 'openc3/models/microservice_group'
35
37
  require 'openc3/api/api'
36
38
  require 'openc3/utilities/pypi_url'
37
39
  require 'tmpdir'
38
40
  require 'tempfile'
39
41
  require 'fileutils'
40
42
  require 'open3'
43
+ require 'securerandom'
41
44
 
42
45
  module OpenC3
43
46
  class EmptyGemFileError < StandardError; end
@@ -51,12 +54,48 @@ module OpenC3
51
54
  PRIMARY_KEY = 'openc3_plugins'
52
55
  # Reserved VARIABLE names. See local_mode.rb: update_local_plugin()
53
56
  RESERVED_VARIABLE_NAMES = ['target_name', 'microservice_name', 'scope']
57
+ # Variable defined by VARIABLE_BRIDGE holding the selected bridge
58
+ BRIDGE_VARIABLE_NAME = 'bridge_name'
59
+ # ${name} in a VARIABLE_DISCOVERY parameter is replaced by the value of variable name
60
+ DISCOVERY_REFERENCE = /\$\{(\w+)\}/
61
+ # Input types of VARIABLE_TYPE in the plugin dialog
62
+ VARIABLE_TYPES = ['TEXT', 'BOOLEAN', 'INTEGER', 'NUMBER', 'PASSWORD', 'JSON', 'SECRET', 'TARGET_NAME']
63
+ # Type of a variable defined by VARIABLE_FILE, whose value is an uploaded file
64
+ FILE_VARIABLE_TYPE = 'FILE'
65
+ # Bucket folder (under the scope) of the files uploaded for VARIABLE_FILE
66
+ UPLOADS_PATH = 'plugin_uploads'
67
+ # The value of a VARIABLE_FILE variable: the upload's id and file name
68
+ UPLOAD_VALUE = %r{\A(\h{8}-\h{4}-\h{4}-\h{4}-\h{12})/([^/\\]+)\z}
69
+ # A file extension a VARIABLE_FILE accepts, e.g. .csv or .tar.gz
70
+ FILE_EXTENSION = /\A\.\w[\w.-]*\z/
71
+ # Keywords that run a script in the plugin before or after it is installed
72
+ INSTALL_SCRIPT_KEYWORDS = ['PRE_INSTALL_SCRIPT', 'POST_INSTALL_SCRIPT']
73
+ # Seconds an install script can run before the install fails
74
+ INSTALL_SCRIPT_TIMEOUT_S = 600
75
+ # Seconds the plugin dialog's validation can run before it's reported as
76
+ # not finishing (it can run PRE_INSTALL_SCRIPTs)
77
+ VALIDATE_TIMEOUT_S = 120
78
+ # Seconds to wait for a preview of plugin.txt (under the frontend's 60s request timeout)
79
+ PREVIEW_TIMEOUT_S = 30
54
80
  PLUGIN_TXT = 'plugin.txt'
81
+ # Seconds modified_diff waits for its child process. Kept under the
82
+ # frontend's 60s request timeout so the user sees this error, not a
83
+ # generic timeout.
84
+ MODIFIED_DIFF_TIMEOUT = 50
85
+ # Most bytes of the modifieddiff child's output read back into an error
86
+ MODIFIED_DIFF_OUTPUT_LIMIT = 2048
55
87
 
56
88
  attr_accessor :variables
57
89
  attr_accessor :plugin_txt_lines
90
+ attr_accessor :plugin_text
58
91
  attr_accessor :minimum_cosmos_version
59
92
  attr_accessor :needs_dependencies
93
+ # The plugin's requirements.txt as installed, which bridges send to the host
94
+ # (openc3-cosmos-app) to provision bridged interfaces
95
+ attr_accessor :python_requirements
96
+ # The plugin's pyproject.toml as installed, sent to the host like
97
+ # python_requirements
98
+ attr_accessor :python_pyproject
60
99
  attr_accessor :store_plugin_id
61
100
  attr_accessor :store_version_id
62
101
  attr_accessor :title
@@ -129,20 +168,75 @@ module OpenC3
129
168
  # Phase 1 Gather Variables
130
169
  variables = {}
131
170
  current_variable_name = nil
171
+ plugin_text_blocks = []
172
+ plugin_text_lines = nil # Non-nil while inside PLUGIN_TEXT_START / PLUGIN_TEXT_END
173
+ variable_text_lines = nil # Non-nil while inside VARIABLE_TEXT_START / VARIABLE_TEXT_END
174
+ # Yield non-keyword lines so blank lines and markdown headers (# lines) are captured in PLUGIN_TEXT
132
175
  parser.parse_file(plugin_txt_path,
133
- false,
176
+ true,
134
177
  true,
135
178
  false) do |keyword, params|
179
+ if plugin_text_lines
180
+ if keyword == 'PLUGIN_TEXT_END'
181
+ parser.set_preserve_lines(false)
182
+ plugin_text_blocks << plugin_text_lines
183
+ plugin_text_lines = nil
184
+ else
185
+ plugin_text_lines << parser.line
186
+ end
187
+ next
188
+ end
189
+ if variable_text_lines
190
+ if keyword == 'VARIABLE_TEXT_END'
191
+ parser.set_preserve_lines(false)
192
+ # Shown below the PLUGIN_TEXT when the VARIABLE_STATE is selected
193
+ option = variables[current_variable_name]['options'][-1]
194
+ option['markdown'] = [option['markdown'], unindent_lines(variable_text_lines)].compact.join("\n\n")
195
+ variable_text_lines = nil
196
+ else
197
+ variable_text_lines << parser.line
198
+ end
199
+ next
200
+ end
201
+
136
202
  case keyword
137
- when 'VARIABLE'
138
- usage = "#{keyword} <Variable Name> <Default Value>"
139
- parser.verify_num_parameters(2, nil, usage)
140
- variable_name = params[0]
141
- if RESERVED_VARIABLE_NAMES.include?(variable_name)
142
- raise "VARIABLE name '#{variable_name}' is reserved"
203
+ when 'PLUGIN_TEXT_START'
204
+ parser.verify_num_parameters(0, 0, keyword)
205
+ # Preserve the raw lines (no stripping, quote or continuation processing) until PLUGIN_TEXT_END
206
+ parser.set_preserve_lines(true)
207
+ plugin_text_lines = []
208
+ when 'PLUGIN_TEXT_END'
209
+ raise "PLUGIN_TEXT_END must follow a PLUGIN_TEXT_START"
210
+ when 'VARIABLE_TEXT_START'
211
+ parser.verify_num_parameters(0, 0, keyword)
212
+ unless current_variable_name and variables[current_variable_name]['options']
213
+ raise "VARIABLE_TEXT_START must follow a VARIABLE_STATE definition"
214
+ end
215
+ parser.set_preserve_lines(true)
216
+ variable_text_lines = []
217
+ when 'VARIABLE_TEXT_END'
218
+ raise "VARIABLE_TEXT_END must follow a VARIABLE_TEXT_START"
219
+ when 'VARIABLE', 'VARIABLE_BRIDGE'
220
+ if keyword == 'VARIABLE'
221
+ usage = "#{keyword} <Variable Name> <Default Value>"
222
+ parser.verify_num_parameters(2, nil, usage)
223
+ variable_name = params[0]
224
+ if RESERVED_VARIABLE_NAMES.include?(variable_name)
225
+ raise "VARIABLE name '#{variable_name}' is reserved"
226
+ end
227
+ value = params[1..-1].join(" ")
228
+ else
229
+ usage = "#{keyword} <Default Bridge Name (optional)>"
230
+ parser.verify_num_parameters(0, 1, usage)
231
+ variable_name = BRIDGE_VARIABLE_NAME
232
+ value = (params[0] || 'DEFAULT').upcase
233
+ end
234
+ if variables[variable_name] and (keyword == 'VARIABLE_BRIDGE' or variables[variable_name]['bridge'])
235
+ raise "VARIABLE '#{BRIDGE_VARIABLE_NAME}' is defined by VARIABLE_BRIDGE and cannot be redefined"
143
236
  end
144
- value = params[1..-1].join(" ")
145
237
  variables[variable_name] = { 'value' => value }
238
+ # Selected from the available bridges in the plugin dialog
239
+ variables[variable_name]['bridge'] = true if keyword == 'VARIABLE_BRIDGE'
146
240
  current_variable_name = variable_name
147
241
  if existing_variables && existing_variables.key?(variable_name)
148
242
  existing = existing_variables[variable_name]
@@ -153,6 +247,35 @@ module OpenC3
153
247
  variables[variable_name]['value'] = existing
154
248
  end
155
249
  end
250
+ when 'VARIABLE_FILE'
251
+ usage = "#{keyword} <Variable Name> <Destination Path> <File Extensions (optional)> ..."
252
+ parser.verify_num_parameters(2, nil, usage)
253
+ variable_name = params[0]
254
+ if RESERVED_VARIABLE_NAMES.include?(variable_name) or variable_name == BRIDGE_VARIABLE_NAME
255
+ raise "VARIABLE name '#{variable_name}' is reserved"
256
+ end
257
+ file_path = params[1]
258
+ unless safe_relative_path?(file_path)
259
+ raise "VARIABLE_FILE destination '#{file_path}' must be a path inside the plugin"
260
+ end
261
+ # The value is the uploaded file (blank until one is uploaded),
262
+ # which phase 2 copies to file_path in the plugin
263
+ variables[variable_name] = { 'value' => '', 'type' => FILE_VARIABLE_TYPE, 'file_path' => file_path }
264
+ # The file extensions the upload must have, if any (with a leading
265
+ # dot and lowercase, so .CSV, CSV and csv are all .csv)
266
+ extensions = params[2..].map do |extension|
267
+ extension = extension.strip.downcase
268
+ extension = ".#{extension}" unless extension.start_with?('.')
269
+ raise "VARIABLE_FILE extension '#{extension}' is not a valid file extension" unless extension.match?(FILE_EXTENSION)
270
+ extension
271
+ end.uniq
272
+ variables[variable_name]['extensions'] = extensions unless extensions.empty?
273
+ current_variable_name = variable_name
274
+ if existing_variables && existing_variables.key?(variable_name)
275
+ existing = existing_variables[variable_name]
276
+ existing = existing['value'] if existing.is_a?(Hash)
277
+ variables[variable_name]['value'] = existing.to_s if existing.to_s.match?(UPLOAD_VALUE)
278
+ end
156
279
  when 'VARIABLE_DESCRIPTION'
157
280
  usage = "#{keyword} <Description>"
158
281
  parser.verify_num_parameters(1, 1, usage)
@@ -160,6 +283,80 @@ module OpenC3
160
283
  raise "VARIABLE_DESCRIPTION must follow a VARIABLE definition"
161
284
  end
162
285
  variables[current_variable_name]['description'] = params[0]
286
+ when 'VARIABLE_LABEL'
287
+ usage = "#{keyword} <Label>"
288
+ parser.verify_num_parameters(1, 1, usage)
289
+ unless current_variable_name
290
+ raise "VARIABLE_LABEL must follow a VARIABLE definition"
291
+ end
292
+ # Shown in the plugin dialog instead of the variable name
293
+ variables[current_variable_name]['label'] = params[0]
294
+ when 'VARIABLE_TYPE'
295
+ usage = "#{keyword} <#{VARIABLE_TYPES.join(' | ')}>"
296
+ parser.verify_num_parameters(1, 1, usage)
297
+ unless current_variable_name
298
+ raise "VARIABLE_TYPE must follow a VARIABLE definition"
299
+ end
300
+ type = params[0].upcase
301
+ if variables[current_variable_name]['type'] == FILE_VARIABLE_TYPE
302
+ raise "VARIABLE_TYPE cannot be used with a VARIABLE_FILE"
303
+ end
304
+ unless VARIABLE_TYPES.include?(type)
305
+ raise "VARIABLE_TYPE must be one of #{VARIABLE_TYPES.join(', ')} but got '#{params[0]}'"
306
+ end
307
+ variables[current_variable_name]['type'] = type
308
+ when 'VARIABLE_GROUP'
309
+ usage = "#{keyword} <Group Name>"
310
+ parser.verify_num_parameters(1, 1, usage)
311
+ unless current_variable_name
312
+ raise "VARIABLE_GROUP must follow a VARIABLE definition"
313
+ end
314
+ # Shown in a titled section of the plugin dialog
315
+ variables[current_variable_name]['group'] = params[0]
316
+ when 'VARIABLE_REQUIRED'
317
+ parser.verify_num_parameters(0, 0, keyword)
318
+ unless current_variable_name
319
+ raise "VARIABLE_REQUIRED must follow a VARIABLE definition"
320
+ end
321
+ # The plugin dialog won't install while it is shown and blank
322
+ variables[current_variable_name]['required'] = true
323
+ when 'VARIABLE_PATTERN'
324
+ usage = "#{keyword} <Regular Expression> <Error Message (optional)>"
325
+ parser.verify_num_parameters(1, 2, usage)
326
+ unless current_variable_name
327
+ raise "VARIABLE_PATTERN must follow a VARIABLE definition"
328
+ end
329
+ begin
330
+ Regexp.new(params[0])
331
+ rescue RegexpError => e
332
+ raise "VARIABLE_PATTERN '#{params[0]}' is not a valid regular expression: #{e.message}"
333
+ end
334
+ # Matched against the whole value of a non-blank variable in the plugin dialog
335
+ variables[current_variable_name]['pattern'] = params[0]
336
+ variables[current_variable_name]['pattern_message'] = params[1] if params[1]
337
+ when 'VARIABLE_HIDDEN'
338
+ parser.verify_num_parameters(0, 0, keyword)
339
+ unless current_variable_name
340
+ raise "VARIABLE_HIDDEN must follow a VARIABLE definition"
341
+ end
342
+ # Never shown in the plugin dialog. Its value comes from VARIABLE_STATE_SET or
343
+ # VARIABLE_DISCOVERY_SET for use in ERB and VARIABLE_DISCOVERY parameters.
344
+ variables[current_variable_name]['hidden'] = true
345
+ when 'VARIABLE_ADVANCED'
346
+ parser.verify_num_parameters(0, 0, keyword)
347
+ unless current_variable_name
348
+ raise "VARIABLE_ADVANCED must follow a VARIABLE definition"
349
+ end
350
+ # Shown in a collapsed section of the plugin dialog
351
+ variables[current_variable_name]['advanced'] = true
352
+ when 'VARIABLE_MULTIPLE'
353
+ parser.verify_num_parameters(0, 0, keyword)
354
+ unless current_variable_name
355
+ raise "VARIABLE_MULTIPLE must follow a VARIABLE definition"
356
+ end
357
+ # Any number of its VARIABLE_STATEs can be selected, and ERB gets
358
+ # their values as an Array. Checked once the variable is complete.
359
+ variables[current_variable_name]['multiple'] = true
163
360
  when 'VARIABLE_STATE'
164
361
  usage = "#{keyword} <Display Text> <Value>"
165
362
  parser.verify_num_parameters(1, 2, usage)
@@ -169,12 +366,159 @@ module OpenC3
169
366
  variables[current_variable_name]['options'] ||= []
170
367
  option = { 'value' => params[1] || params[0], 'text' => params[0] }
171
368
  variables[current_variable_name]['options'] << option
369
+ when 'VARIABLE_DISCOVERY'
370
+ usage = "#{keyword} <Discovery Class Filename or Module> <Discovery Parameters (optional)> ..."
371
+ parser.verify_num_parameters(1, nil, usage)
372
+ unless current_variable_name
373
+ raise "VARIABLE_DISCOVERY must follow a VARIABLE definition"
374
+ end
375
+ # Either a filename (openc3/discovery/hid_discovery.py) or a module (openc3.discovery.hid_discovery)
376
+ unless params[0].end_with?('.py') or params[0] =~ /\A[A-Za-z_]\w*(\.[A-Za-z_]\w*)*\z/
377
+ raise "VARIABLE_DISCOVERY requires a Python discovery class filename (.py) or module name but got '#{params[0]}'"
378
+ end
379
+ # A variable can have multiple discoveries whose results are combined.
380
+ # Each is the discovery class followed by the parameters passed to it.
381
+ variables[current_variable_name]['discovery'] ||= []
382
+ variables[current_variable_name]['discovery'] << { 'discovery' => params }
383
+ when 'VARIABLE_DISCOVERY_SET'
384
+ usage = "#{keyword} <Variable Name> <Value>"
385
+ parser.verify_num_parameters(2, nil, usage)
386
+ discoveries = variables[current_variable_name]['discovery'] if current_variable_name
387
+ unless discoveries
388
+ raise "#{keyword} must follow a VARIABLE_DISCOVERY definition"
389
+ end
390
+ # Applied when the user selects a value found by this discovery
391
+ discoveries[-1]['set'] ||= {}
392
+ discoveries[-1]['set'][params[0]] = params[1..-1].join(" ")
393
+ when 'VARIABLE_STATE_SHOW'
394
+ usage = "#{keyword} <Variable Name> <Variable Name (optional)> ..."
395
+ parser.verify_num_parameters(1, nil, usage)
396
+ options = variables[current_variable_name]['options'] if current_variable_name
397
+ unless options
398
+ raise "#{keyword} must follow a VARIABLE_STATE definition"
399
+ end
400
+ options[-1]['show'] ||= []
401
+ options[-1]['show'].concat(params)
402
+ options[-1]['show'].uniq!
403
+ when 'VARIABLE_STATE_DESCRIPTION', 'VARIABLE_STATE_ICON'
404
+ usage = keyword == 'VARIABLE_STATE_ICON' ? "#{keyword} <Icon Name>" : "#{keyword} <Description>"
405
+ parser.verify_num_parameters(1, 1, usage)
406
+ options = variables[current_variable_name]['options'] if current_variable_name
407
+ unless options
408
+ raise "#{keyword} must follow a VARIABLE_STATE definition"
409
+ end
410
+ if keyword == 'VARIABLE_STATE_ICON'
411
+ # Material Design Icons like mdi-cloud, or another icon set's prefix:name
412
+ unless params[0] =~ /\A[\w:-]+\z/
413
+ raise "VARIABLE_STATE_ICON '#{params[0]}' is not a valid icon name like mdi-cloud"
414
+ end
415
+ options[-1]['icon'] = params[0]
416
+ else
417
+ # Shown below the state's text in the plugin dialog dropdown
418
+ options[-1]['description'] = params[0]
419
+ end
420
+ when 'VARIABLE_STATE_REQUIRED'
421
+ usage = "#{keyword} <Variable Name> <Variable Name (optional)> ..."
422
+ parser.verify_num_parameters(1, nil, usage)
423
+ options = variables[current_variable_name]['options'] if current_variable_name
424
+ unless options
425
+ raise "#{keyword} must follow a VARIABLE_STATE definition"
426
+ end
427
+ # Required in the plugin dialog while the state is selected
428
+ options[-1]['required'] ||= []
429
+ options[-1]['required'].concat(params)
430
+ options[-1]['required'].uniq!
431
+ when 'VARIABLE_STATE_SET'
432
+ usage = "#{keyword} <Variable Name> <Value>"
433
+ parser.verify_num_parameters(2, nil, usage)
434
+ options = variables[current_variable_name]['options'] if current_variable_name
435
+ unless options
436
+ raise "#{keyword} must follow a VARIABLE_STATE definition"
437
+ end
438
+ options[-1]['set'] ||= {}
439
+ options[-1]['set'][params[0]] = params[1..-1].join(" ")
172
440
  end
173
441
  end
174
442
 
443
+ raise "PLUGIN_TEXT_START without a matching PLUGIN_TEXT_END" if plugin_text_lines
444
+ raise "VARIABLE_TEXT_START without a matching VARIABLE_TEXT_END" if variable_text_lines
445
+ plugin_markdown = plugin_text_blocks.empty? ? nil : plugin_text_blocks.map { |lines| unindent_lines(lines) }.join("\n\n")
446
+
447
+ # Variables can be defined after the VARIABLE_STATE_SHOW / SET and VARIABLE_DISCOVERY_SET
448
+ # that reference them so validate the references once all variables are known
449
+ variables.each do |variable_name, variable|
450
+ references = []
451
+ Array(variable['options']).each do |option|
452
+ (Array(option['show']) + Array(option['required']) + Array(option['set']&.keys)).each do |target_name|
453
+ references << [target_name, "state '#{option['text']}'"]
454
+ end
455
+ end
456
+ Array(variable['discovery']).each do |discovery|
457
+ source = "discovery '#{discovery['discovery'].join(' ')}'"
458
+ Array(discovery['set']&.keys).each do |target_name|
459
+ references << [target_name, source]
460
+ end
461
+ # Discovery parameters can use the value of another variable as ${name}
462
+ discovery['discovery'][1..].each do |param|
463
+ param.scan(DISCOVERY_REFERENCE).flatten.each do |target_name|
464
+ references << [target_name, source]
465
+ end
466
+ end
467
+ end
468
+ references.each do |target_name, source|
469
+ if target_name == variable_name
470
+ raise "VARIABLE '#{variable_name}' #{source} cannot reference itself"
471
+ end
472
+ unless variables.key?(target_name)
473
+ raise "VARIABLE '#{variable_name}' #{source} references undefined VARIABLE '#{target_name}'"
474
+ end
475
+ if variables[target_name]['multiple'] and source.start_with?('discovery') and discovery_reference?(variable, target_name)
476
+ raise "VARIABLE '#{variable_name}' #{source} cannot use VARIABLE_MULTIPLE variable '#{target_name}' as a parameter"
477
+ end
478
+ end
479
+ end
480
+
481
+ variables.each do |variable_name, variable|
482
+ existing = (existing_variables and existing_variables.key?(variable_name))
483
+ unless variable['multiple']
484
+ # No longer VARIABLE_MULTIPLE since the existing install
485
+ variable['value'] = variable['value'].join(',') if variable['value'].is_a?(Array)
486
+ next
487
+ end
488
+ # The plugin.txt default must be states, but an existing install's
489
+ # values that an upgrade removed from the states are dropped
490
+ validate_multiple(variable_name, variable, check_default: !existing)
491
+ variable['value'] = multiple_values(variable['value']) & variable['options'].map { |option| option['value'] }
492
+ end
493
+
494
+ # Apply the VARIABLE_STATE_SET values of each initially selected state (in file order so
495
+ # a set can select the state of a later variable). Values from an existing install win,
496
+ # except for hidden variables which always follow the state (they can't be edited).
497
+ variables.each do |_variable_name, variable|
498
+ selected_options(variable).each do |selected|
499
+ Hash(selected['set']).each do |target_name, value|
500
+ next if existing_variables and existing_variables.key?(target_name) and not variables[target_name]['hidden']
501
+ target = variables[target_name]
502
+ target['value'] = target['multiple'] ? multiple_values(value) & target['options'].map { |option| option['value'] } : value
503
+ end
504
+ end
505
+ end
506
+
507
+ # A new install's TARGET_NAME variables default to a target name that
508
+ # isn't taken, so installing a plugin again doesn't collide with the
509
+ # targets of the first install. Existing installs keep their names.
510
+ taken = nil
511
+ variables.each do |variable_name, variable|
512
+ next unless variable['type'] == 'TARGET_NAME'
513
+ next if existing_variables and existing_variables.key?(variable_name)
514
+ taken ||= Set.new(TargetModel.names(scope: scope))
515
+ variable['value'] = available_target_name(variable['value'], taken)
516
+ taken << variable['value'].upcase
517
+ end
518
+
175
519
  store_plugin_id = Integer(store_plugin_id) if store_plugin_id
176
520
  store_version_id = Integer(store_version_id) if store_version_id
177
- model = PluginModel.new(name: gem_name, variables: variables, plugin_txt_lines: plugin_txt_lines, store_plugin_id: store_plugin_id, store_version_id: store_version_id, minimum_cosmos_version: minimum_cosmos_version, scope: scope)
521
+ model = PluginModel.new(name: gem_name, variables: variables, plugin_txt_lines: plugin_txt_lines, plugin_text: plugin_markdown, store_plugin_id: store_plugin_id, store_version_id: store_version_id, minimum_cosmos_version: minimum_cosmos_version, scope: scope)
178
522
  result = model.as_json()
179
523
  result['existing_plugin_txt_lines'] = existing_plugin_txt_lines if existing_plugin_txt_lines and not process_existing and existing_plugin_txt_lines != result['plugin_txt_lines']
180
524
  return result
@@ -184,9 +528,40 @@ module OpenC3
184
528
  end
185
529
  end
186
530
 
531
+ # Extract simple key-value pairs for ERB substitution
532
+ # Variables can be either new format (hash with 'value' key) or old format (string)
533
+ def self.erb_variables(plugin_hash, scope:)
534
+ erb_variables = {}
535
+ (plugin_hash['variables'] || {}).each do |name, var|
536
+ erb_variables[name] = var.is_a?(Hash) ? var['value'] : var
537
+ # A VARIABLE_MULTIPLE is the Array of the selected state values
538
+ erb_variables[name] = multiple_values(var['value']) if var.is_a?(Hash) and var['multiple']
539
+ # A VARIABLE_FILE is the path its file is copied to in the plugin, or
540
+ # blank without a file
541
+ if var.is_a?(Hash) and var['type'] == FILE_VARIABLE_TYPE
542
+ erb_variables[name] = var['value'].to_s.match?(UPLOAD_VALUE) ? var['file_path'] : ''
543
+ end
544
+ end
545
+ erb_variables['scope'] = scope
546
+ erb_variables
547
+ end
548
+
549
+ # Renders ERB in a plugin's Python dependency file (requirements.txt or
550
+ # pyproject.toml) in place using the plugin variables. The ERB filename is
551
+ # set so templates can locate files next to it with File.dirname(__FILE__).
552
+ def self.render_python_dependency_erb(path, erb_variables)
553
+ data = File.read(path).force_encoding("UTF-8")
554
+ return unless data.include?('<%')
555
+ erb = ERB.new(data.comment_erb(), trim_mode: "-")
556
+ erb.filename = path
557
+ File.write(path, erb.result(binding.set_variables(erb_variables)))
558
+ end
559
+
187
560
  # Called by the PluginsController to create the plugin
188
561
  # Because this uses ERB it must be run in a separate process from the API to
189
- # prevent corruption and single require problems in the current process
562
+ # prevent corruption and single require problems in the current process.
563
+ # This also applies to validate_only and diff_only: both still render ERB
564
+ # and load the plugin's classes. Use modified_diff from the API.
190
565
  # diff_only: dry run that renders the plugin's target files and returns the
191
566
  # list of modified files ("TARGET/path") whose live content differs from
192
567
  # what this plugin would deploy — used to warn before an upgrade which user
@@ -238,6 +613,10 @@ module OpenC3
238
613
  end
239
614
  end
240
615
 
616
+ # Files uploaded for VARIABLE_FILE go where the plugin expects them
617
+ # before anything reads the plugin's files
618
+ copy_uploads(plugin_hash, gem_path, scope: scope)
619
+
241
620
  plugin_model.minimum_cosmos_version = pkg.spec.metadata['openc3_cosmos_minimum_version']
242
621
 
243
622
  # Process OpenC3 Store metadata
@@ -275,10 +654,22 @@ module OpenC3
275
654
  # Handle python dependencies (pyproject.toml or requirements.txt)
276
655
  pyproject_path = File.join(gem_path, 'pyproject.toml')
277
656
  requirements_path = File.join(gem_path, 'requirements.txt')
657
+ # Dependency files may use ERB so plugin variables can select dependencies
658
+ [pyproject_path, requirements_path].each do |path|
659
+ render_python_dependency_erb(path, self.erb_variables(plugin_hash, scope: scope)) if File.exist?(path)
660
+ end
661
+
662
+ # Stored as rendered (installs of one gem can render them differently)
663
+ # for bridges to provision the host
664
+ if File.exist?(requirements_path) || File.exist?(pyproject_path)
665
+ plugin_model.python_requirements = File.read(requirements_path) if File.exist?(requirements_path)
666
+ plugin_model.python_pyproject = File.read(pyproject_path) if File.exist?(pyproject_path)
667
+ plugin_model.update unless dry_run
668
+ end
278
669
 
279
670
  if File.exist?(pyproject_path) || File.exist?(requirements_path)
280
671
  pypi_url = resolve_pypi_url(scope: scope)
281
- # Skipped for any dry run: diff_only runs inline in an HTTP request, so
672
+ # Skipped for any dry run: diff_only runs during an HTTP request, so
282
673
  # a slow or unreachable PyPI would time it out, and it must not mutate
283
674
  # the plugin venv.
284
675
  unless dry_run
@@ -342,6 +733,28 @@ module OpenC3
342
733
  plugin_model.update unless dry_run
343
734
  end
344
735
 
736
+ # Run the PRE_INSTALL_SCRIPTs now that the plugin's files and Python
737
+ # packages are in place, before anything is installed from them (they
738
+ # can generate files, e.g. target definitions). Validation runs them
739
+ # too, with OPENC3_PLUGIN_DRY_RUN set, since what they generate may be
740
+ # needed. The upgrade diff (diff_only) doesn't: it runs in an HTTP
741
+ # request, which must not run plugin code or wait on a slow script, so
742
+ # generated files aren't in the diff. POST_INSTALL_SCRIPTs run after
743
+ # everything is installed, and not in dry runs.
744
+ erb_variables = self.erb_variables(plugin_hash, scope: scope)
745
+ scripts = Tempfile.create(PLUGIN_TXT) do |scripts_tf|
746
+ scripts_tf.write(plugin_hash['plugin_txt_lines'].join("\n"))
747
+ scripts_tf.close
748
+ install_scripts(scripts_tf.path, erb_variables)
749
+ end
750
+ script_options = { gem_path: gem_path, plugin_name: plugin_model.name, erb_variables: erb_variables, dry_run: dry_run, scope: scope }
751
+ gem_lib_dirs = -> { Dir.glob("#{gem_path}/**/lib").select { |dir| File.directory?(dir) } }
752
+ unless diff_only
753
+ scripts['PRE_INSTALL_SCRIPT'].each do |script, args|
754
+ run_install_script('PRE_INSTALL_SCRIPT', script, args, load_dirs: gem_lib_dirs.call, **script_options)
755
+ end
756
+ end
757
+
345
758
  # Temporarily add all lib folders from the gem to the end of the load path
346
759
  load_dirs = []
347
760
  begin
@@ -358,24 +771,29 @@ module OpenC3
358
771
  tf.write(file_data)
359
772
  tf.close
360
773
  plugin_txt_path = tf.path
361
- variables = plugin_hash['variables']
362
- variables ||= {}
363
- # Extract simple key-value pairs for ERB substitution
364
- # Variables can be either new format (hash with 'value' key) or old format (string)
365
- erb_variables = {}
366
- variables.each do |name, var|
367
- erb_variables[name] = var.is_a?(Hash) ? var['value'] : var
368
- end
369
- erb_variables['scope'] = scope
370
774
  if File.exist?(plugin_txt_path)
371
775
  parser = OpenC3::ConfigParser.new("https://openc3.com")
372
776
 
373
777
  current_model = nil
778
+ text_end = nil # The END keyword while inside a PLUGIN_TEXT or VARIABLE_TEXT block
374
779
  parser.parse_file(plugin_txt_path, false, true, true, erb_variables) do |keyword, params|
780
+ # PLUGIN_TEXT and VARIABLE_TEXT were captured in phase 1 so skip them
781
+ if text_end
782
+ if keyword == text_end
783
+ parser.set_preserve_lines(false)
784
+ text_end = nil
785
+ end
786
+ next
787
+ end
375
788
  case keyword
376
- when 'VARIABLE', 'VARIABLE_DESCRIPTION', 'VARIABLE_STATE', 'NEEDS_DEPENDENCIES'
789
+ when 'PLUGIN_TEXT_START', 'VARIABLE_TEXT_START'
790
+ parser.set_preserve_lines(true)
791
+ text_end = keyword.sub('_START', '_END')
792
+ when 'VARIABLE', 'VARIABLE_DESCRIPTION', 'VARIABLE_LABEL', 'VARIABLE_TYPE', 'VARIABLE_GROUP', 'VARIABLE_REQUIRED', 'VARIABLE_PATTERN', 'VARIABLE_HIDDEN', 'VARIABLE_ADVANCED', 'VARIABLE_MULTIPLE', 'VARIABLE_STATE', 'VARIABLE_STATE_SHOW', 'VARIABLE_STATE_SET', 'VARIABLE_STATE_REQUIRED', 'VARIABLE_STATE_DESCRIPTION', 'VARIABLE_STATE_ICON', 'VARIABLE_DISCOVERY', 'VARIABLE_DISCOVERY_SET', 'VARIABLE_BRIDGE', 'VARIABLE_FILE', 'NEEDS_DEPENDENCIES'
377
793
  # Ignore during phase 2
378
- when 'TARGET', 'INTERFACE', 'ROUTER', 'MICROSERVICE', 'TOOL', 'WIDGET', 'SCRIPT_ENGINE'
794
+ when 'PRE_INSTALL_SCRIPT', 'POST_INSTALL_SCRIPT'
795
+ # Run before and after the install
796
+ when 'TARGET', 'INTERFACE', 'ROUTER', 'MICROSERVICE', 'TOOL', 'WIDGET', 'PANEL', 'SCRIPT_ENGINE'
379
797
  begin
380
798
  if current_model
381
799
  current_model.create unless dry_run
@@ -411,6 +829,11 @@ module OpenC3
411
829
  current_model = nil
412
830
  end
413
831
  end
832
+ unless dry_run
833
+ scripts['POST_INSTALL_SCRIPT'].each do |script, args|
834
+ run_install_script('POST_INSTALL_SCRIPT', script, args, load_dirs: load_dirs, **script_options)
835
+ end
836
+ end
414
837
  ensure
415
838
  load_dirs.each do |load_dir|
416
839
  $LOAD_PATH.delete(load_dir)
@@ -432,16 +855,331 @@ module OpenC3
432
855
  # Returns a list of "TARGET/path" names whose live (modified) content
433
856
  # differs from the rendered plugin content. Read-only; no side effects.
434
857
  # Errors propagate so callers can tell a failed check from an empty diff.
435
- def self.modified_diff(plugin_hash, scope:)
436
- install_phase2(plugin_hash, scope: scope, diff_only: true)
858
+ #
859
+ # Like an install, this runs install_phase2 in a separate process
860
+ # (`openc3cli modifieddiff`) to prevent corruption and single require
861
+ # problems in the API process: install_phase2 renders ERB, adds the gem's
862
+ # lib folders to $LOAD_PATH and loads the plugin's classes. The child runs
863
+ # in its own process group so it can be cleaned up as a whole, and the
864
+ # result is read back from a file.
865
+ def self.modified_diff(plugin_hash, scope:, timeout: MODIFIED_DIFF_TIMEOUT)
866
+ temp_dir = Dir.mktmpdir
867
+ begin
868
+ plugin_hash_path = File.join(temp_dir, 'plugin_hash.json')
869
+ result_path = File.join(temp_dir, 'result.json')
870
+ output_path = File.join(temp_dir, 'output.txt')
871
+ # The child's temp files (extracted gem, rendered files) go under
872
+ # temp_dir too. A child killed on timeout can't run its own cleanup,
873
+ # so removing temp_dir below is what cleans them up.
874
+ child_tmp_dir = File.join(temp_dir, 'tmp')
875
+ FileUtils.mkdir_p(child_tmp_dir)
876
+ File.write(plugin_hash_path, JSON.generate(plugin_hash, allow_nan: true))
877
+ cmd = modified_diff_command(scope, plugin_hash_path, result_path)
878
+ pid = Process.spawn({ 'TMPDIR' => child_tmp_dir }, *cmd, in: File::NULL, [:out, :err] => [output_path, 'w'], pgroup: true)
879
+ status = wait_for_child(pid, timeout)
880
+ raise "Timed out after #{timeout} seconds checking modified files against the plugin" unless status
881
+
882
+ result = nil
883
+ if File.exist?(result_path)
884
+ result = JSON.parse(File.read(result_path), allow_nan: true) rescue nil
885
+ end
886
+ if status.success? and result.is_a?(Hash) and result['files'].is_a?(Array)
887
+ return result['files'].map(&:to_s)
888
+ end
889
+
890
+ message = result['error'] if result.is_a?(Hash) and result['error']
891
+ unless message
892
+ output = output_tail(output_path).strip
893
+ message = "Modified file check failed (exit status #{status.exitstatus.inspect})"
894
+ message += ": #{output.lines.last(5).join.strip}" unless output.empty?
895
+ end
896
+ raise message.to_s
897
+ ensure
898
+ FileUtils.remove_entry_secure(temp_dir, true)
899
+ end
900
+ end
901
+
902
+ # Command run by modified_diff. A separate method so specs can substitute
903
+ # a stand-in for openc3cli, which only exists inside the containers.
904
+ def self.modified_diff_command(scope, plugin_hash_path, result_path)
905
+ ['ruby', '/openc3/bin/openc3cli', 'modifieddiff', scope, plugin_hash_path, result_path]
906
+ end
907
+
908
+ # Returns at most the last max_bytes of the file at path, or '' if it
909
+ # doesn't exist, so a huge child log isn't read into the API process.
910
+ def self.output_tail(path, max_bytes = MODIFIED_DIFF_OUTPUT_LIMIT)
911
+ return '' unless File.exist?(path)
912
+
913
+ File.open(path, 'rb') do |file|
914
+ file.seek([file.size - max_bytes, 0].max)
915
+ # The seek can land inside a multibyte character
916
+ return file.read.to_s.force_encoding(Encoding::UTF_8).scrub('')
917
+ end
918
+ end
919
+ private_class_method :output_tail
920
+
921
+ # Waits up to timeout seconds for pid. Returns its Process::Status, or nil
922
+ # if it didn't finish in time. Either way it then kills pid's whole process
923
+ # group, so nothing the plugin started outlives the check. (A process group
924
+ # id isn't reused while the group has members, so this is safe after pid
925
+ # has exited.)
926
+ def self.wait_for_child(pid, timeout)
927
+ status = nil
928
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
929
+ while Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
930
+ _, status = Process.wait2(pid, Process::WNOHANG)
931
+ break if status
932
+
933
+ sleep(0.1)
934
+ end
935
+ begin
936
+ Process.kill('KILL', -pid)
937
+ rescue Errno::ESRCH, Errno::EPERM
938
+ # Group already empty
939
+ end
940
+ Process.wait(pid) rescue nil unless status
941
+ return status
942
+ end
943
+ private_class_method :wait_for_child
944
+
945
+ # Validate a plugin as the plugin dialog would install it (its variables
946
+ # and possibly edited plugin.txt lines) with a dry run install of its gem.
947
+ # Runs in a separate process like an install, since the dry run loads the
948
+ # plugin's code and renders its ERB. Returns { 'valid' => true } or
949
+ # { 'valid' => false, 'error' => message }.
950
+ def self.validate(plugin_hash, scope:)
951
+ plugin_hash = plugin_hash.slice('name', 'variables', 'plugin_txt_lines')
952
+ result, output = run_plugin_cli(['validate', '--plugin-hash'], plugin_hash, 'valid', VALIDATE_TIMEOUT_S, scope: scope)
953
+ return { 'valid' => false, 'error' => "Validation did not finish within #{VALIDATE_TIMEOUT_S} seconds" } if result == :timeout
954
+ result || { 'valid' => false, 'error' => "Validation failed: #{output.lines.last(5).join.strip}" }
955
+ end
956
+
957
+ # Run openc3cli with a plugin hash for work that loads the plugin's code or
958
+ # renders its ERB, which must not run in the API process. The child gets
959
+ # its own process group so a timeout also stops anything it started.
960
+ # Returns [result, output]: result is the last JSON object it printed whose
961
+ # first key is result_key (after anything the plugin's code printed), nil
962
+ # if there's none, or :timeout.
963
+ def self.run_plugin_cli(args, plugin_hash, result_key, timeout_s, scope:)
964
+ output = +''
965
+ Tempfile.create(['plugin_hash', '.json']) do |file|
966
+ file.write(JSON.generate(plugin_hash, allow_nan: true))
967
+ file.close
968
+ command = ['ruby', '/openc3/bin/openc3cli', *args, file.path, scope]
969
+ Open3.popen2e(*command, pgroup: true) do |stdin, out, wait_thread|
970
+ stdin.close
971
+ reader = Thread.new do
972
+ output << out.read.to_s
973
+ rescue IOError
974
+ end
975
+ unless wait_thread.join(timeout_s)
976
+ Process.kill('KILL', -wait_thread.pid) rescue nil
977
+ wait_thread.join
978
+ reader.join(1)
979
+ return [:timeout, output]
980
+ end
981
+ reader.join
982
+ end
983
+ end
984
+ prefix = "{\"#{result_key}\""
985
+ result = output.lines.reverse.lazy.filter_map do |line|
986
+ JSON.parse(line) if line.start_with?(prefix)
987
+ rescue JSON::ParserError
988
+ nil
989
+ end.first
990
+ [result, output]
991
+ end
992
+
993
+ # The message of an error from validating a plugin, with where it is in
994
+ # the plugin for a configuration error
995
+ def self.validation_error(error)
996
+ message = error.message.to_s
997
+ return message unless error.is_a?(ConfigParser::Error) and error.filename
998
+ filename = error.filename.to_s
999
+ # plugin.txt is processed from a temporary file, and the plugin's other
1000
+ # files from where its gem was extracted
1001
+ if File.basename(filename).start_with?(PLUGIN_TXT)
1002
+ filename = PLUGIN_TXT
1003
+ elsif (match = filename.match(%r{/gem/(.+)\z}))
1004
+ filename = match[1]
1005
+ end
1006
+ location = error.line_number ? "#{filename}:#{error.line_number}" : filename
1007
+ details = ["#{location}: #{message}"]
1008
+ details << " #{error.line.strip}" if error.line and not error.line.strip.empty?
1009
+ details << "Usage: #{error.usage}" if error.usage and not error.usage.empty?
1010
+ details.join("\n")
1011
+ end
1012
+
1013
+ # The plugin.txt lines that install the plugin with ERB rendered using the
1014
+ # plugin_hash variables, without the variable definitions and text blocks.
1015
+ # The ERB is arbitrary Ruby, so it's rendered in a separate process
1016
+ # (render_preview through openc3cli) like validate and install.
1017
+ # Returns { 'plugin_txt' => text } or { 'error' => message }.
1018
+ def self.preview(plugin_hash, scope:)
1019
+ plugin_hash = plugin_hash.slice('variables', 'plugin_txt_lines')
1020
+ result, output = run_plugin_cli(['validate', '--preview'], plugin_hash, 'preview', PREVIEW_TIMEOUT_S, scope: scope)
1021
+ return { 'error' => "Preview did not finish within #{PREVIEW_TIMEOUT_S} seconds" } if result == :timeout
1022
+ return result['preview'] if result
1023
+ { 'error' => "Preview failed: #{output.lines.last(5).join.strip}" }
1024
+ end
1025
+
1026
+ # Render the preview in this process. Only for openc3cli: see preview.
1027
+ def self.render_preview(plugin_hash, scope:)
1028
+ erb_variables = self.erb_variables(plugin_hash, scope: scope)
1029
+ text = Array(plugin_hash['plugin_txt_lines']).join("\n")
1030
+ begin
1031
+ output = ERB.new(text.comment_erb(), trim_mode: "-").result(binding.set_variables(erb_variables))
1032
+ rescue Exception => e # SyntaxError and NameError are common ERB mistakes
1033
+ line = e.backtrace_locations&.find { |location| location.path == '(erb)' }&.lineno
1034
+ line ||= e.message[/\(erb\):(\d+)/, 1]
1035
+ return { 'error' => "ERB error#{" at line #{line}" if line}: #{e.message.lines.first&.strip}" }
1036
+ end
1037
+ lines = []
1038
+ text_end = nil
1039
+ output.each_line(chomp: true) do |line|
1040
+ keyword = line.strip.split(/\s+/, 2)[0]
1041
+ if text_end
1042
+ text_end = nil if keyword == text_end
1043
+ next
1044
+ end
1045
+ if keyword.nil?
1046
+ lines << '' unless lines.empty? or lines[-1].empty?
1047
+ elsif keyword == 'PLUGIN_TEXT_START' or keyword == 'VARIABLE_TEXT_START'
1048
+ text_end = keyword.sub('_START', '_END')
1049
+ elsif not keyword.start_with?('VARIABLE', '#')
1050
+ lines << line
1051
+ end
1052
+ end
1053
+ lines.pop while lines[-1] == ''
1054
+ { 'plugin_txt' => lines.join("\n") }
1055
+ end
1056
+
1057
+ # Discovery classes can be given as a filename or module name, so compare
1058
+ # them as module names, e.g. openc3.discovery.serial_discovery
1059
+ def self.discovery_class_key(name)
1060
+ name.to_s.delete_suffix('.py').tr('/', '.')
1061
+ end
1062
+
1063
+ # Version of the discovery_matchers format, shared with the OpenC3 Store
1064
+ DISCOVERY_MATCHERS_FORMAT = 1
1065
+
1066
+ # The hardware a plugin can be installed for, from the VARIABLE_DISCOVERY of
1067
+ # its variables (as parsed by install_phase1). Hardware discovery on the
1068
+ # host scans for devices once and checks them against the matchers of every
1069
+ # plugin in the OpenC3 Store, which computes them when a plugin is uploaded.
1070
+ #
1071
+ # Each matcher is a discovery class and its parameters (which must find the
1072
+ # device), the variable the found value goes into, other variables to set
1073
+ # when installing for it, and an optional title. Discovery parameters that
1074
+ # use other variables (${name}) give one matcher for each state that sets
1075
+ # them, e.g. one per integration of the Home Assistant plugin. A discovery
1076
+ # without parameters finds any device of its kind, so it isn't a matcher.
1077
+ def self.discovery_matchers(variables)
1078
+ matchers = []
1079
+ variables.each do |variable_name, variable|
1080
+ Array(variable['discovery']).each do |entry|
1081
+ discovery_class = discovery_class_key(entry['discovery'][0])
1082
+ params = entry['discovery'][1..]
1083
+ discovery_set = entry['set'] || {}
1084
+ references = params.flat_map { |param| param.scan(DISCOVERY_REFERENCE).flatten }.uniq
1085
+
1086
+ # Fill in the parameters for each state that sets the variables they use
1087
+ states = discovery_states(variables, variable_name, references)
1088
+ if states.empty?
1089
+ # Nothing sets them, so they keep their default values
1090
+ states = [[nil, nil, references.to_h { |name| [name, variables[name]['value']] }]]
1091
+ end
1092
+ states.each do |control_name, option, values|
1093
+ expanded = params.map { |param| param.gsub(DISCOVERY_REFERENCE) { values[$1].to_s } }.join(' ').split
1094
+ next if expanded.empty?
1095
+ set = {}
1096
+ set[control_name] = option['value'] if control_name
1097
+ set.merge!(discovery_set)
1098
+ matcher = { 'class' => discovery_class, 'params' => expanded, 'variable' => variable_name, 'set' => set }
1099
+ title = option ? option['text'] : discovery_set_title(variables, discovery_set)
1100
+ matcher['title'] = title if title
1101
+ matchers << matcher unless matchers.include?(matcher)
1102
+ end
1103
+ end
1104
+ end
1105
+ { 'format' => DISCOVERY_MATCHERS_FORMAT, 'matchers' => matchers }
1106
+ end
1107
+
1108
+ # The states that set any of references and show variable_name, as
1109
+ # [variable name, state, reference values]. References a state doesn't set
1110
+ # keep their default values.
1111
+ def self.discovery_states(variables, variable_name, references)
1112
+ return [] if references.empty?
1113
+ states = []
1114
+ variables.each do |control_name, control|
1115
+ options = Array(control['options'])
1116
+ # States that use VARIABLE_STATE_SHOW only show the variable if they list it
1117
+ shown_by_states = options.any? { |option| Array(option['show']).include?(variable_name) }
1118
+ options.each do |option|
1119
+ set = option['set'] || {}
1120
+ next unless references.any? { |name| set.key?(name) }
1121
+ next if shown_by_states and !Array(option['show']).include?(variable_name)
1122
+ values = references.to_h { |name| [name, set.fetch(name) { variables[name]['value'] }] }
1123
+ states << [control_name, option, values]
1124
+ end
1125
+ end
1126
+ states
1127
+ end
1128
+
1129
+ # The text of a state selected by a VARIABLE_DISCOVERY_SET, e.g. the model of
1130
+ # controller a USB product ID identifies
1131
+ def self.discovery_set_title(variables, discovery_set)
1132
+ discovery_set.each do |name, value|
1133
+ option = Array(variables.dig(name, 'options')).find { |state| state['value'] == value }
1134
+ return option['text'] if option
1135
+ end
1136
+ nil
1137
+ end
1138
+
1139
+ # The value an installed plugin selected for a VARIABLE_DISCOVERY variable
1140
+ # "claims" that device (e.g. a serial port or controller serial number) so
1141
+ # discovery stops offering it to other plugins. Claims are per bridge, as
1142
+ # each bridge is a different host, and per discovery class (not its
1143
+ # parameters) so e.g. a HID serial number claimed through one product ID is
1144
+ # claimed for every HID discovery. Uninstalling the plugin releases its claims.
1145
+ #
1146
+ # @param exclude_plugin [String] Plugin being upgraded or edited, which must
1147
+ # still be offered the devices it already holds
1148
+ # @return [Hash] Claimed value => name of the plugin holding it
1149
+ def self.discovery_claims(bridge_name, discovery_class, exclude_plugin: nil, scope:)
1150
+ bridge_name = bridge_name.to_s.upcase
1151
+ key = discovery_class_key(discovery_class)
1152
+ claims = {}
1153
+ all(scope: scope).each do |plugin_name, plugin|
1154
+ next if plugin_name == exclude_plugin
1155
+ variables = (plugin['variables'] || {}).values.select { |variable| variable.is_a?(Hash) }
1156
+ bridge = variables.find { |variable| variable['bridge'] }
1157
+ next unless (bridge ? bridge['value'] : 'DEFAULT').to_s.upcase == bridge_name
1158
+ variables.each do |variable|
1159
+ next unless variable['discovery'].is_a?(Array)
1160
+ next unless variable['discovery'].any? { |entry| discovery_class_key(Array(entry['discovery'])[0]) == key }
1161
+ claims[variable['value'].to_s] ||= plugin_name
1162
+ end
1163
+ end
1164
+ claims
1165
+ end
1166
+
1167
+ # Remove the common leading whitespace so PLUGIN_TEXT can be indented in plugin.txt
1168
+ # without turning the markdown into code blocks
1169
+ def self.unindent_lines(lines)
1170
+ indent = lines.reject { |line| line.strip.empty? }.map { |line| line[/\A[ \t]*/].length }.min || 0
1171
+ lines.map { |line| line[indent..] || '' }.join("\n").strip
437
1172
  end
438
1173
 
439
1174
  def initialize(
440
1175
  name:,
441
1176
  variables: {},
442
1177
  plugin_txt_lines: [],
1178
+ plugin_text: nil,
443
1179
  minimum_cosmos_version: nil,
444
1180
  needs_dependencies: false,
1181
+ python_requirements: nil,
1182
+ python_pyproject: nil,
445
1183
  store_plugin_id: nil,
446
1184
  store_version_id: nil,
447
1185
  title: nil,
@@ -457,8 +1195,11 @@ module OpenC3
457
1195
  super("#{scope}__#{PRIMARY_KEY}", name: name, updated_at: updated_at, scope: scope)
458
1196
  @variables = variables
459
1197
  @plugin_txt_lines = plugin_txt_lines
1198
+ @plugin_text = plugin_text
460
1199
  @minimum_cosmos_version = minimum_cosmos_version
461
1200
  @needs_dependencies = ConfigParser.handle_true_false(needs_dependencies)
1201
+ @python_requirements = python_requirements
1202
+ @python_pyproject = python_pyproject
462
1203
  @store_plugin_id = store_plugin_id
463
1204
  @store_version_id = store_version_id
464
1205
  @title = title
@@ -485,8 +1226,11 @@ module OpenC3
485
1226
  'name' => @name,
486
1227
  'variables' => @variables,
487
1228
  'plugin_txt_lines' => @plugin_txt_lines,
1229
+ 'plugin_text' => @plugin_text,
488
1230
  'minimum_cosmos_version' => @minimum_cosmos_version,
489
1231
  'needs_dependencies' => @needs_dependencies,
1232
+ 'python_requirements' => @python_requirements,
1233
+ 'python_pyproject' => @python_pyproject,
490
1234
  'store_plugin_id' => @store_plugin_id,
491
1235
  'store_version_id' => @store_version_id,
492
1236
  'title' => @title,
@@ -505,6 +1249,10 @@ module OpenC3
505
1249
  errors = []
506
1250
  microservice_count = 0
507
1251
  microservices = MicroserviceModel.find_all_by_plugin(plugin: @name, scope: @scope)
1252
+ # A microservice group's Python parent takes the plugin of its Python decom
1253
+ # children for their venv, but it also runs the members of other plugins.
1254
+ # Update it once this plugin's members are gone instead of removing it.
1255
+ group_parents, microservices = microservices.partition { |name, _model| MicroserviceGroup.parent?(name) }
508
1256
  microservices.each do |_name, model_instance|
509
1257
  begin
510
1258
  model_instance.destroy
@@ -517,7 +1265,7 @@ module OpenC3
517
1265
  sleep 15 if microservice_count > 0 # Cycle time 5s times 2 plus 5s wait for soft stop and then hard stop
518
1266
  # Remove all the other models now that the processes have stopped
519
1267
  # Save TargetModel for last as it has the most to cleanup
520
- [InterfaceModel, RouterModel, ToolModel, WidgetModel, TargetModel, ScriptEngineModel].each do |model|
1268
+ [InterfaceModel, RouterModel, ToolModel, WidgetModel, PanelModel, TargetModel, ScriptEngineModel].each do |model|
521
1269
  model.find_all_by_plugin(plugin: @name, scope: @scope).each do |_name, model_instance|
522
1270
  begin
523
1271
  model_instance.destroy
@@ -526,6 +1274,14 @@ module OpenC3
526
1274
  end
527
1275
  end
528
1276
  end
1277
+ # TargetModel#undeploy already did this unless it failed first
1278
+ group_parents.each do |name, _model|
1279
+ begin
1280
+ MicroserviceGroup.update(name.split('__')[2], scope: @scope)
1281
+ rescue => e
1282
+ errors << e
1283
+ end
1284
+ end
529
1285
  # Cleanup Redis stuff that might have been left by microservices
530
1286
  microservices.each do |_name, model_instance|
531
1287
  begin
@@ -560,7 +1316,7 @@ module OpenC3
560
1316
  ensure
561
1317
  # Double check everything is gone
562
1318
  found = []
563
- [MicroserviceModel, InterfaceModel, RouterModel, ToolModel, WidgetModel, TargetModel, ScriptEngineModel].each do |model|
1319
+ [MicroserviceModel, InterfaceModel, RouterModel, ToolModel, WidgetModel, PanelModel, TargetModel, ScriptEngineModel].each do |model|
564
1320
  model.find_all_by_plugin(plugin: @name, scope: @scope).each do |_name, model_instance|
565
1321
  found << model_instance
566
1322
  end
@@ -665,6 +1421,10 @@ module OpenC3
665
1421
  return true
666
1422
  end
667
1423
 
1424
+ # Use the dependency files as rendered at install, since they may use ERB
1425
+ File.write(pyproject_path, @python_pyproject) if File.exist?(pyproject_path) && @python_pyproject
1426
+ File.write(requirements_path, @python_requirements) if File.exist?(requirements_path) && @python_requirements
1427
+
668
1428
  pypi_url = self.class.resolve_pypi_url(scope: scope)
669
1429
  pypi_args = self.class.build_pypi_args(pypi_url)
670
1430
 
@@ -699,5 +1459,225 @@ module OpenC3
699
1459
  rescue => e
700
1460
  Logger.warn("Could not remove gem #{gem_filename}: #{e.message}", scope: scope)
701
1461
  end
1462
+
1463
+ # name if no target in taken uses it, otherwise the first of name_2,
1464
+ # name_3, ... that is free. A numbered name counts on from its number.
1465
+ def self.available_target_name(name, taken)
1466
+ name = name.to_s.strip.upcase
1467
+ return name if name.empty? or !taken.include?(name)
1468
+ base, number = name.match(/\A(.+?)(?:_(\d+))?\z/).captures
1469
+ number = number ? number.to_i + 1 : 2
1470
+ number += 1 while taken.include?("#{base}_#{number}")
1471
+ "#{base}_#{number}"
1472
+ end
1473
+
1474
+ # Whether path is relative and stays inside the folder it is relative to
1475
+ def self.safe_relative_path?(path)
1476
+ path = path.to_s
1477
+ return false if path.empty? or path.start_with?('/', '\\') or path.match?(/\A[A-Za-z]:/)
1478
+ parts = path.split(%r{[/\\]})
1479
+ !parts.include?('..') and !parts.reject { |part| part.empty? or part == '.' }.empty?
1480
+ end
1481
+
1482
+ # The values of a VARIABLE_MULTIPLE variable as an Array. The value is an
1483
+ # Array once parsed, but the plugin.txt default, VARIABLE_STATE_SET,
1484
+ # VARIABLE_DISCOVERY_SET and the values of an install from before the
1485
+ # variable was VARIABLE_MULTIPLE give them as a comma separated String.
1486
+ def self.multiple_values(value)
1487
+ values = value.is_a?(Array) ? value.map(&:to_s) : value.to_s.split(',')
1488
+ values.map(&:strip).reject(&:empty?).uniq
1489
+ end
1490
+
1491
+ # The selected VARIABLE_STATEs of a variable: the one matching its value,
1492
+ # or each one a VARIABLE_MULTIPLE has selected
1493
+ def self.selected_options(variable)
1494
+ options = Array(variable['options'])
1495
+ if variable['multiple']
1496
+ values = multiple_values(variable['value'])
1497
+ options.select { |option| values.include?(option['value']) }
1498
+ else
1499
+ selected = options.find { |option| option['value'] == variable['value'] }
1500
+ selected ? [selected] : []
1501
+ end
1502
+ end
1503
+
1504
+ # Whether a variable's VARIABLE_DISCOVERY parameters use ${target_name}
1505
+ def self.discovery_reference?(variable, target_name)
1506
+ Array(variable['discovery']).any? do |discovery|
1507
+ discovery['discovery'][1..].any? { |param| param.scan(DISCOVERY_REFERENCE).flatten.include?(target_name) }
1508
+ end
1509
+ end
1510
+
1511
+ # A VARIABLE_MULTIPLE selects any of its VARIABLE_STATEs, so it can't take
1512
+ # other kinds of values, and two of its states setting the same variable
1513
+ # would conflict when both are selected
1514
+ def self.validate_multiple(variable_name, variable, check_default: true)
1515
+ prefix = "VARIABLE_MULTIPLE '#{variable_name}'"
1516
+ raise "#{prefix} requires VARIABLE_STATEs to select from" if Array(variable['options']).empty?
1517
+ raise "#{prefix} cannot be a VARIABLE_FILE" if variable['type'] == FILE_VARIABLE_TYPE
1518
+ raise "#{prefix} cannot be a VARIABLE_BRIDGE" if variable['bridge']
1519
+ raise "#{prefix} cannot use VARIABLE_TYPE" if variable['type']
1520
+ raise "#{prefix} cannot use VARIABLE_PATTERN" if variable['pattern']
1521
+ raise "#{prefix} cannot use VARIABLE_DISCOVERY" if variable['discovery']
1522
+ state_values = variable['options'].map { |option| option['value'] }
1523
+ multiple_values(variable['value']).each do |value|
1524
+ if check_default and !state_values.include?(value)
1525
+ raise "#{prefix} default '#{value}' is not one of its VARIABLE_STATE values: #{state_values.join(', ')}"
1526
+ end
1527
+ end
1528
+ setters = {}
1529
+ variable['options'].each do |option|
1530
+ Hash(option['set']).each_key do |target_name|
1531
+ if setters[target_name]
1532
+ raise "#{prefix} states '#{setters[target_name]}' and '#{option['text']}' both set VARIABLE '#{target_name}' with VARIABLE_STATE_SET, which conflict when both are selected"
1533
+ end
1534
+ setters[target_name] = option['text']
1535
+ end
1536
+ end
1537
+ end
1538
+
1539
+ # The bucket key of an uploaded VARIABLE_FILE value, or nil if it isn't one
1540
+ def self.upload_key(value, scope:)
1541
+ match = value.to_s.match(UPLOAD_VALUE)
1542
+ return nil unless match
1543
+ "#{scope}/#{UPLOADS_PATH}/#{match[1]}/#{match[2]}"
1544
+ end
1545
+
1546
+ # Whether an uploaded VARIABLE_FILE value's file name has one of the
1547
+ # extensions (any extension if there are none)
1548
+ def self.upload_extension_allowed?(value, extensions)
1549
+ return true if extensions.nil? or extensions.empty?
1550
+ filename = value.to_s.match(UPLOAD_VALUE)&.[](2).to_s.downcase
1551
+ extensions.any? { |extension| filename.end_with?(extension) and filename.length > extension.length }
1552
+ end
1553
+
1554
+ # Store a file uploaded for a VARIABLE_FILE in the config bucket. Returns
1555
+ # the variable value that refers to it.
1556
+ def self.store_upload(file_path, filename, scope:)
1557
+ filename = File.basename(filename.to_s.tr('\\', '/'))
1558
+ if filename.empty? or filename == '.' or filename == '..'
1559
+ raise "Invalid upload filename '#{filename}'"
1560
+ end
1561
+ value = "#{SecureRandom.uuid}/#{filename}"
1562
+ File.open(file_path, 'rb') do |file|
1563
+ Bucket.getClient().put_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: upload_key(value, scope: scope), body: file)
1564
+ end
1565
+ value
1566
+ end
1567
+
1568
+ # Copy the files uploaded for the VARIABLE_FILE variables into the
1569
+ # extracted plugin at their destinations
1570
+ def self.copy_uploads(plugin_hash, gem_path, scope:)
1571
+ (plugin_hash['variables'] || {}).each do |name, variable|
1572
+ next unless variable.is_a?(Hash) and variable['type'] == FILE_VARIABLE_TYPE
1573
+ key = upload_key(variable['value'], scope: scope)
1574
+ next unless key
1575
+ unless upload_extension_allowed?(variable['value'], variable['extensions'])
1576
+ raise "The file uploaded for VARIABLE_FILE #{name} must be a #{variable['extensions'].join(', ')} file. Upload it again."
1577
+ end
1578
+ unless safe_relative_path?(variable['file_path'])
1579
+ raise "VARIABLE_FILE #{name} destination '#{variable['file_path']}' must be a path inside the plugin"
1580
+ end
1581
+ destination = File.join(gem_path, variable['file_path'])
1582
+ FileUtils.mkdir_p(File.dirname(destination))
1583
+ Bucket.getClient().get_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: key, path: destination)
1584
+ unless File.exist?(destination)
1585
+ raise "The file uploaded for VARIABLE_FILE #{name} is missing. Upload it again."
1586
+ end
1587
+ Logger.info("Copied the file uploaded for #{name} to #{variable['file_path']}", scope: scope)
1588
+ end
1589
+ end
1590
+
1591
+ # Delete the files uploaded for an uninstalled plugin's VARIABLE_FILE
1592
+ # variables, unless another installed plugin uses them
1593
+ def self.cleanup_uploads(variables, scope:)
1594
+ keys = Array(variables&.values).filter_map do |variable|
1595
+ upload_key(variable['value'], scope: scope) if variable.is_a?(Hash) and variable['type'] == FILE_VARIABLE_TYPE
1596
+ end
1597
+ return if keys.empty?
1598
+ in_use = all(scope: scope).values.flat_map do |plugin|
1599
+ Array(plugin['variables']&.values).filter_map do |variable|
1600
+ upload_key(variable['value'], scope: scope) if variable.is_a?(Hash) and variable['type'] == FILE_VARIABLE_TYPE
1601
+ end
1602
+ end
1603
+ (keys - in_use).each do |key|
1604
+ Bucket.getClient().delete_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: key)
1605
+ end
1606
+ rescue => e
1607
+ Logger.warn("Could not remove uploaded plugin files: #{e.message}", scope: scope)
1608
+ end
1609
+
1610
+ # The PRE_INSTALL_SCRIPT and POST_INSTALL_SCRIPT lines of a plugin.txt, in
1611
+ # order, as { 'PRE_INSTALL_SCRIPT' => [[path, args]], ... }
1612
+ def self.install_scripts(plugin_txt_path, erb_variables)
1613
+ scripts = INSTALL_SCRIPT_KEYWORDS.to_h { |keyword| [keyword, []] }
1614
+ parser = OpenC3::ConfigParser.new("https://openc3.com")
1615
+ text_end = nil
1616
+ parser.parse_file(plugin_txt_path, false, true, true, erb_variables) do |keyword, params|
1617
+ if text_end
1618
+ if keyword == text_end
1619
+ parser.set_preserve_lines(false)
1620
+ text_end = nil
1621
+ end
1622
+ next
1623
+ end
1624
+ if keyword == 'PLUGIN_TEXT_START' or keyword == 'VARIABLE_TEXT_START'
1625
+ parser.set_preserve_lines(true)
1626
+ text_end = keyword.sub('_START', '_END')
1627
+ elsif INSTALL_SCRIPT_KEYWORDS.include?(keyword)
1628
+ parser.verify_num_parameters(1, nil, "#{keyword} <Script Path> <Arguments (optional)>")
1629
+ unless safe_relative_path?(params[0])
1630
+ raise "#{keyword} '#{params[0]}' must be a path inside the plugin"
1631
+ end
1632
+ unless ['.rb', '.py'].include?(File.extname(params[0]).downcase)
1633
+ raise "#{keyword} '#{params[0]}' must be a Ruby (.rb) or Python (.py) script"
1634
+ end
1635
+ scripts[keyword] << [params[0], params[1..]]
1636
+ end
1637
+ end
1638
+ scripts
1639
+ end
1640
+
1641
+ # Run a PRE_INSTALL_SCRIPT or POST_INSTALL_SCRIPT from the extracted plugin
1642
+ # in gem_path. Its output goes to the install log, and a failure (non-zero
1643
+ # exit or running too long) fails the install.
1644
+ def self.run_install_script(keyword, script, args, gem_path:, load_dirs:, plugin_name:, erb_variables:, dry_run:, scope:)
1645
+ path = File.join(gem_path, script)
1646
+ raise "#{keyword} '#{script}' was not found in the plugin" unless File.file?(path)
1647
+ environment = {
1648
+ 'OPENC3_SCOPE' => scope,
1649
+ 'OPENC3_PLUGIN_NAME' => plugin_name,
1650
+ 'OPENC3_PLUGIN_PATH' => gem_path,
1651
+ 'OPENC3_PLUGIN_VARIABLES' => JSON.generate(erb_variables),
1652
+ 'OPENC3_PLUGIN_DRY_RUN' => dry_run ? 'true' : 'false',
1653
+ }
1654
+ if File.extname(path).downcase == '.py'
1655
+ command = [ENV.fetch('OPENC3_PYTHON_BIN', '/openc3/python/.venv/bin/python'), path, *args]
1656
+ environment['PYTHONPATH'] = (load_dirs + [ENV.fetch('PYTHONPATH', nil)]).compact.reject(&:empty?).join(':')
1657
+ venv_dir = PythonVenv.plugin_venv_path(scope: scope, plugin_name: plugin_name)
1658
+ PythonVenv.configure_environment(environment, venv_dir) if venv_dir
1659
+ else
1660
+ command = ['ruby', path, *args]
1661
+ environment['RUBYLIB'] = (load_dirs + [ENV.fetch('RUBYLIB', nil)]).compact.reject(&:empty?).join(':')
1662
+ end
1663
+ Logger.info("Running #{keyword} #{([script] + args).join(' ')}", scope: scope)
1664
+ status = nil
1665
+ Open3.popen2e(environment, *command, chdir: gem_path) do |stdin, output, wait_thread|
1666
+ stdin.close
1667
+ reader = Thread.new do
1668
+ output.each_line { |line| Logger.info("#{keyword} #{script}: #{line.chomp}", scope: scope) }
1669
+ rescue IOError
1670
+ end
1671
+ unless wait_thread.join(INSTALL_SCRIPT_TIMEOUT_S)
1672
+ Process.kill('KILL', wait_thread.pid) rescue nil
1673
+ wait_thread.join
1674
+ reader.join(1)
1675
+ raise "#{keyword} '#{script}' did not finish within #{INSTALL_SCRIPT_TIMEOUT_S} seconds"
1676
+ end
1677
+ reader.join
1678
+ status = wait_thread.value
1679
+ end
1680
+ raise "#{keyword} '#{script}' failed with exit status #{status.exitstatus}" unless status.success?
1681
+ end
702
1682
  end
703
1683
  end