Class: Script
- Inherits:
-
OpenC3::TargetFile
- Object
- OpenC3::TargetFile
- Script
- Defined in:
- lib/openc3/utilities/script.rb
Constant Summary collapse
- LIFECYCLE_STATES =
Script lifecycle states and the transitions allowed from each state
%w(development review approved)
- LIFECYCLE_TRANSITIONS =
{ 'development' => %w(review approved), 'review' => %w(development approved), 'approved' => %w(review development), }
Constants inherited from OpenC3::TargetFile
OpenC3::TargetFile::TEMP_FOLDER
Class Method Summary collapse
- .all(scope, target = nil) ⇒ Object
- .create(params) ⇒ Object
- .delete_temp(scope) ⇒ Object
- .destroy(scope, name) ⇒ Object
- .detect_language(text, filename = nil) ⇒ Object
- .get_breakpoints(scope, name) ⇒ Object
- .instrumented(filename, text) ⇒ Object
- .lifecycle(scope, name) ⇒ Object
- .lifecycle_enabled? ⇒ Boolean
- .lock(scope, name, username) ⇒ Object
- .locked?(scope, name) ⇒ Boolean
- .mnemonics(filename, text) ⇒ Object
- .process_suite(name, contents, new_process: true, username: nil, scope:, python_venv: nil) ⇒ Object
- .run(scope, name, suite_runner = nil, disconnect = false, environment = nil, user_full_name = nil, username = nil, line_no = nil, end_line_no = nil, python_venv = nil) ⇒ Object
-
.set_lifecycle(scope, name, state, username, comment, current: nil) ⇒ Object
current: the caller-known current state; pass it to avoid a redundant git read when the controller has already fetched it for transition validation.
- .syntax(filename, text) ⇒ Object
- .temp_file?(name) ⇒ Boolean
- .unlock(scope, name) ⇒ Object
Methods inherited from OpenC3::TargetFile
body, remote_target_files, strip_modified
Class Method Details
.all(scope, target = nil) ⇒ Object
37 38 39 |
# File 'lib/openc3/utilities/script.rb', line 37 def self.all(scope, target = nil) super(scope, nil, target: target) # No path matchers end |
.create(params) ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
# File 'lib/openc3/utilities/script.rb', line 212 def self.create(params) existing = body(params[:scope], params[:name]) # Commit if there is no existing or something has changed if existing.nil? or existing != params[:text] super(params[:scope], params[:name], params[:text]) end breakpoints = params[:breakpoints] if breakpoints if breakpoints.empty? OpenC3::Store.hdel("#{params[:scope]}__script-breakpoints", params[:name]) else OpenC3::Store.hset("#{params[:scope]}__script-breakpoints", params[:name], breakpoints.as_json().to_json(allow_nan: true)) end end end |
.delete_temp(scope) ⇒ Object
229 230 231 232 233 234 |
# File 'lib/openc3/utilities/script.rb', line 229 def self.delete_temp(scope) files = super(scope) files.each do |name| OpenC3::Store.hdel("#{scope}__script-breakpoints", "#{TEMP_FOLDER}/#{File.basename(name)}") end end |
.destroy(scope, name) ⇒ Object
236 237 238 239 |
# File 'lib/openc3/utilities/script.rb', line 236 def self.destroy(scope, name) super(scope, name) OpenC3::Store.hdel("#{scope}__script-breakpoints", name) end |
.detect_language(text, filename = nil) ⇒ Object
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
# File 'lib/openc3/utilities/script.rb', line 327 def self.detect_language(text, filename = nil) if filename extension = File.extname(filename) if extension == '.rb' return 'ruby' elsif extension == '.py' return 'python' elsif extension.length > 0 return 'other' end end return 'ruby' if text =~ /^\s*(require|load|puts) / return 'python' if text =~ /^\s*(import|from) / return 'ruby' if text =~ /^\s*end\s*$/ return 'python' if text =~ /^\s*(if|def|while|else|elif|class).*:\s*$/ return 'ruby' # otherwise guess Ruby end |
.get_breakpoints(scope, name) ⇒ Object
55 56 57 58 59 |
# File 'lib/openc3/utilities/script.rb', line 55 def self.get_breakpoints(scope, name) breakpoints = OpenC3::Store.hget("#{scope}__script-breakpoints", strip_modified(name)) return JSON.parse(breakpoints, allow_nan: true, create_additions: true) if breakpoints [] end |
.instrumented(filename, text) ⇒ Object
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
# File 'lib/openc3/utilities/script.rb', line 260 def self.instrumented(filename, text) language = detect_language(text, filename) if language == 'ruby' return { 'title' => 'Instrumented Script', 'description' => RunningScript.instrument_script( text, filename, true, ).split("\n").as_json().to_json(allow_nan: true), } elsif language == 'python' start = Time.now temp = Tempfile.new(%w[instrument .py]) temp.write(text) temp.close runner_path = File.join(RAILS_ROOT, 'scripts', 'run_instrument.py') process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python' process = ChildProcess.build(process_name, runner_path.to_s, temp.path) process.cwd = File.join(RAILS_ROOT, 'scripts') stdout = Tempfile.new("child-stdout") stdout.sync = true stderr = Tempfile.new("child-stderr") stderr.sync = true process.io.stdout = stdout process.io.stderr = stderr process.start process.wait stdout.rewind stdout_results = stdout.read stdout.close stdout.unlink stderr.rewind stderr_results = stderr.read stderr.close stderr.unlink success = process.exit_code == 0 puts "Processed Instrumenting #{filename} in #{Time.now - start} seconds" # Make sure we're getting the last line which should be the suite puts "Stdout Results:#{stdout_results}:" puts "Stderr Results:#{stderr_results}:" # stdout_results = stdout_results.split("\n")[-1] if stdout_results if success return { 'title' => 'Instrumented Script', 'description' => stdout_results.to_s.split("\n").as_json().to_json(allow_nan: true), } else return { 'title' => 'Error Instrumenting Script', 'description' => (stdout_results.to_s + stderr_results.to_s).split("\n").as_json().to_json(allow_nan: true), } end else return { 'title' => 'Instrumenting Not Supported', 'description' => ['Only Ruby and Python Support Viewing Instrumentation'].as_json.to_json, } end end |
.lifecycle(scope, name) ⇒ Object
69 70 71 72 73 |
# File 'lib/openc3/utilities/script.rb', line 69 def self.lifecycle(scope, name) return { 'state' => 'development', 'history' => [] } if temp_file?(name) return { 'state' => 'development', 'history' => [] } unless lifecycle_enabled? ::VersionStore.lifecycle(scope: scope, name: strip_modified(name)) end |
.lifecycle_enabled? ⇒ Boolean
65 66 67 |
# File 'lib/openc3/utilities/script.rb', line 65 def self.lifecycle_enabled? defined?(::VersionStore) && ::VersionStore.enabled? end |
.lock(scope, name, username) ⇒ Object
41 42 43 |
# File 'lib/openc3/utilities/script.rb', line 41 def self.lock(scope, name, username) OpenC3::Store.hset("#{scope}__script-locks", strip_modified(name), username) end |
.locked?(scope, name) ⇒ Boolean
49 50 51 52 53 |
# File 'lib/openc3/utilities/script.rb', line 49 def self.locked?(scope, name) locked_by = OpenC3::Store.hget("#{scope}__script-locks", strip_modified(name)) locked_by ||= false locked_by end |
.mnemonics(filename, text) ⇒ Object
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
# File 'lib/openc3/utilities/script.rb', line 346 def self.mnemonics(filename, text) # Ruby and Python are currently handled in-browser # Script Engine Possibly extension = File.extname(filename).to_s.downcase script_engine_model = OpenC3::ScriptEngineModel.get_model(name: extension, scope: 'DEFAULT') if script_engine_model script_engine = script_engine_model.filename if File.extname(script_engine).to_s.downcase == '.py' process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python' runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.py') else process_name = 'ruby' runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.rb') end tf = nil begin tf = Tempfile.new((['mnemonics', extension])) tf.write(text) tf.close() results, status = Open3.capture2e("#{process_name} \"#{runner_path}\" mnemonic_check \"#{tf.path}\"") lines = [] if results and results.length > 0 results.each_line do |line| lines << line end return( { 'title' => 'Mnemonics Check Failed', 'description' => lines.as_json().to_json(allow_nan: true) } ) else return( { 'title' => 'Mnemonics Check Successful', 'description' => ["Mnemonics OK"].as_json().to_json(allow_nan: true), } ) end ensure tf.unlink if tf end else raise "Unsupported script file type: #{extension}" end end |
.process_suite(name, contents, new_process: true, username: nil, scope:, python_venv: nil) ⇒ Object
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/openc3/utilities/script.rb', line 86 def self.process_suite(name, contents, new_process: true, username: nil, scope:, python_venv: nil) python = false python = true if File.extname(name) == '.py' start = Time.now if python temp = Tempfile.new(%w[suite .py]) else temp = Tempfile.new(%w[suite .rb]) end # Remove any carriage returns which ruby doesn't like temp.write(contents.gsub(/\r/, ' ')) temp.close # We open a new process so as to not pollute the API with require success = true if new_process or python if python runner_path = File.join(RAILS_ROOT, 'scripts', 'run_suite_analysis.py') process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python' process = ChildProcess.build(process_name, runner_path.to_s, scope, temp.path) else runner_path = File.join(RAILS_ROOT, 'scripts', 'run_suite_analysis.rb') process = ChildProcess.build('ruby', runner_path.to_s, scope, temp.path) end process.cwd = File.join(RAILS_ROOT, 'scripts') # Check for offline access token model = nil model = OpenC3::OfflineAccessModel.get_model(name: username, scope: scope) if username and username != '' # Set proper secrets for running script process.environment['SECRET_KEY_BASE'] = nil process.environment['OPENC3_REDIS_USERNAME'] = ENV['OPENC3_SR_REDIS_USERNAME'] || 'OPENC3_SR_REDIS_USERNAME not set' process.environment['OPENC3_REDIS_PASSWORD'] = ENV['OPENC3_SR_REDIS_PASSWORD'] || 'OPENC3_SR_REDIS_PASSWORD not set' process.environment['OPENC3_BUCKET_USERNAME'] = ENV['OPENC3_SR_BUCKET_USERNAME'] || 'OPENC3_SR_BUCKET_USERNAME not set' process.environment['OPENC3_BUCKET_PASSWORD'] = ENV['OPENC3_SR_BUCKET_PASSWORD'] || 'OPENC3_SR_BUCKET_PASSWORD not set' process.environment['OPENC3_SR_REDIS_USERNAME'] = nil process.environment['OPENC3_SR_REDIS_PASSWORD'] = nil process.environment['OPENC3_SR_BUCKET_USERNAME'] = nil process.environment['OPENC3_SR_BUCKET_PASSWORD'] = nil process.environment['OPENC3_API_CLIENT'] = ENV['OPENC3_API_CLIENT'] || 'api' if model and model.offline_access_token auth = OpenC3::OpenC3KeycloakAuthentication.new(ENV['OPENC3_KEYCLOAK_URL']) valid_token = auth.get_token_from_refresh_token(model.offline_access_token) if valid_token process.environment['OPENC3_API_TOKEN'] = model.offline_access_token else model.offline_access_token = nil model.update raise "offline_access token invalid for script" end else process.environment['OPENC3_API_USER'] = ENV['OPENC3_API_USER'] || nil if ENV['OPENC3_SERVICE_PASSWORD'] process.environment['OPENC3_API_PASSWORD'] = ENV['OPENC3_SERVICE_PASSWORD'] else # The viewer user doesn't have an offline access token (because they can't run scripts) # but they still want to be able to view suite files # Since processing a suite file requires running it they won't get the Suite chrome # so return nothing here and allow Script Runner to simply view the suite file return '', '', false end end process.environment['GEM_HOME'] = ENV['GEM_HOME'] || '/gems' process.environment['PYTHONUSERBASE'] = ENV['PYTHONUSERBASE'] || OpenC3::PythonVenv::DEFAULT_PYTHONUSERBASE # Preserve PYTHONPATH to ensure Python can find both UV venv and user packages process.environment['PYTHONPATH'] = ENV['PYTHONPATH'] || '.' # Suite analysis executes Python in a separate process before the script # itself is started. Give that process the same plugin venv visibility as # RunningScript so imports used while defining a suite can be resolved. if python OpenC3::PythonVenv.configure_for_script( process.environment, name: name, scope: scope, python_venv: python_venv ) end # Spawned process should not be controlled by same Bundler constraints as spawning process ENV.each do |key, _value| if key =~ /^BUNDLE/ process.environment[key] = nil end end process.environment['RUBYOPT'] = nil # Removes loading bundler setup process.environment['OPENC3_SCOPE'] = scope stdout = Tempfile.new("child-stdout") stdout.sync = true stderr = Tempfile.new("child-stderr") stderr.sync = true process.io.stdout = stdout process.io.stderr = stderr process.start begin process.poll_for_exit(10) # wait for max 10s rescue ChildProcess::TimeoutError process.stop stderr_results = "Suite analysis timed out - possible infinite loop in script\n" success = false end stdout.rewind stdout_results = stdout.read stdout.close stdout.unlink stderr.rewind stderr_results ||= "" stderr_results += stderr.read stderr.close stderr.unlink success = process.exit_code == 0 if success else require temp.path stdout_results = OpenC3::SuiteRunner.build_suites.as_json().to_json(allow_nan: true) end temp.delete puts "Processed #{name} in #{Time.now - start} seconds" # Make sure we're getting the last line which should be the suite puts "Stdout Results:#{stdout_results}:" puts "Stderr Results:#{stderr_results}:" stdout_results = stdout_results.split("\n")[-1] if stdout_results return stdout_results, stderr_results, success end |
.run(scope, name, suite_runner = nil, disconnect = false, environment = nil, user_full_name = nil, username = nil, line_no = nil, end_line_no = nil, python_venv = nil) ⇒ Object
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# File 'lib/openc3/utilities/script.rb', line 241 def self.run( scope, name, suite_runner = nil, disconnect = false, environment = nil, user_full_name = nil, username = nil, line_no = nil, end_line_no = nil, python_venv = nil ) # Verify the script exists before spawning a run. Without this check a run # is started and the missing file only surfaces as a runtime error inside # the spawned process. Returning nil lets the caller return a 404. return nil unless Script.body(scope, name) RunningScript.spawn(scope, name, suite_runner, disconnect, environment, user_full_name, username, line_no, end_line_no, python_venv) end |
.set_lifecycle(scope, name, state, username, comment, current: nil) ⇒ Object
current: the caller-known current state; pass it to avoid a redundant git read when the controller has already fetched it for transition validation.
77 78 79 80 81 82 83 84 |
# File 'lib/openc3/utilities/script.rb', line 77 def self.set_lifecycle(scope, name, state, username, comment, current: nil) raise "Cannot set lifecycle on temporary files" if temp_file?(name) raise "Script lifecycle requires the version history store" unless lifecycle_enabled? name = strip_modified(name) current ||= lifecycle(scope, name)['state'] ::VersionStore.set_lifecycle(scope: scope, name: name, from: current, to: state, username: username, comment: comment) end |
.syntax(filename, text) ⇒ Object
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 |
# File 'lib/openc3/utilities/script.rb', line 391 def self.syntax(filename, text) if text.nil? return( { 'title' => 'Syntax Check Failed', 'description' => 'no text passed' } ) end language = detect_language(text, filename) if language == 'ruby' check_process = IO.popen('ruby -c -rubygems 2>&1', 'r+') check_process.write("require 'openc3'; require 'openc3/script'; " + text) check_process.close_write results = check_process.readlines check_process.close if results if results.any?(/Syntax OK/) return( { 'title' => 'Syntax Check Successful', 'description' => results.as_json().to_json(allow_nan: true), } ) else # Results is an array of strings like this: ":2: syntax error ..." # Normally the procedure comes before the first colon but since we # are writing to the process this is blank so we throw it away results.map! { |result| result.split(':')[1..-1].join(':') } return( { 'title' => 'Syntax Check Failed', 'description' => results.as_json().to_json(allow_nan: true) } ) end else return( { 'title' => 'Syntax Check Exception', 'description' => 'Ruby syntax check unexpectedly returned nil', } ) end elsif language == 'python' # Python tf = nil begin tf = Tempfile.new((['syntax', '.py'])) tf.write(text) tf.close() process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python' results, status = Open3.capture2e("#{process_name} -m py_compile #{tf.path}") lines = [] success = status.respond_to?(:success?) ? status.success? : status == 0 if !success || (results and results.length > 0) results.each_line do |line| lines << line end lines << "Syntax Error" if lines.empty? return( { 'title' => 'Syntax Check Failed', 'description' => lines.as_json().to_json(allow_nan: true) } ) else return( { 'title' => 'Syntax Check Successful', 'description' => ["Syntax OK"].as_json().to_json(allow_nan: true), } ) end ensure tf.unlink if tf end else # Script Engine Possibly extension = File.extname(filename).to_s.downcase script_engine_model = OpenC3::ScriptEngineModel.get_model(name: extension, scope: 'DEFAULT') if script_engine_model script_engine = script_engine_model.filename if File.extname(script_engine).to_s.downcase == '.py' process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python' runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.py') else process_name = 'ruby' runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.rb') end tf = nil begin tf = Tempfile.new((['syntax', extension])) tf.write(text) tf.close() results, status = Open3.capture2e("#{process_name} \"#{runner_path}\" syntax_check \"#{tf.path}\"") lines = [] if results and results.length > 0 results.each_line do |line| lines << line end return( { 'title' => 'Syntax Check Failed', 'description' => lines.as_json().to_json(allow_nan: true) } ) else return( { 'title' => 'Syntax Check Successful', 'description' => ["Syntax OK"].as_json().to_json(allow_nan: true), } ) end ensure tf.unlink if tf end else raise "Unsupported script file type: #{extension}" end end end |
.temp_file?(name) ⇒ Boolean
61 62 63 |
# File 'lib/openc3/utilities/script.rb', line 61 def self.temp_file?(name) strip_modified(name).start_with?("#{TEMP_FOLDER}/") end |