Class: RunningScript

Inherits:
Object show all
Defined in:
lib/openc3/utilities/running_script.rb

Constant Summary collapse

SUITE_REGEX =

This REGEX is also found in scripts_controller.rb Matches the following test cases: class MySuite < TestSuite

class MySuite < OpenC3::Suite

class MySuite < Cosmos::TestSuite class MySuite < Suite # comment # class MySuite < Suite # <– doesn’t match commented out

/^(\s*)?class\s+\w+\s+<\s+(Cosmos::|OpenC3::)?(Suite|TestSuite)/
@@instance =
nil
@@message_log =
nil
@@run_thread =
nil
@@breakpoints =
{}
@@line_delay =
0.1
@@max_output_characters =
50000
@@instrumented_cache =
{}
@@file_cache =
{}
@@output_thread =
nil
@@pause_on_error =
true
@@error =
nil
@@output_sleeper =
OpenC3::Sleeper.new
@@cancel_output =
false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script_status) ⇒ RunningScript

Returns a new instance of RunningScript.



537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# File 'lib/openc3/utilities/running_script.rb', line 537

def initialize(script_status)
  @@instance = self
  @script_status = script_status
  @script_status.pid = Process.pid
  @user_input = ''
  @prompt_id = nil
  @line_offset = 0
  @output_io = StringIO.new('', 'r+')
  @output_io_mutex = Mutex.new
  @continue_after_error = true
  @debug_text = nil
  @debug_history = []
  @debug_code_completion = nil
  @output_time = Time.now.sys

  initialize_variables()
  update_running_script_store("init")
  redirect_io() # Redirect $stdout and $stderr
  mark_breakpoints(@script_status.filename)
  disconnect_script() if @script_status.disconnect

  @script_engine = nil
  if @script_status.script_engine
    klass = OpenC3.require_class(@script_status.script_engine)
    @script_engine = klass.new(self)
  end

  # Retrieve file
  @body = ::Script.body(@script_status.scope, @script_status.filename)
  raise "Script not found: #{@script_status.filename}" if @body.nil?
  breakpoints = @@breakpoints[@script_status.filename]&.filter { |_, present| present }&.map { |line_number, _| line_number - 1 } # -1 because frontend lines are 0-indexed
  breakpoints ||= []
  running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :file, filename: @script_status.filename, scope: @script_status.scope, text: @body.to_utf8, breakpoints: breakpoints })
  if not @script_status.script_engine and @body =~ SUITE_REGEX
    # Process the suite file in this context so we can load it
    # TODO: Do we need to worry about success or failure of the suite processing?
    ::Script.process_suite(@script_status.filename, @body, new_process: false, scope: @script_status.scope)
    # Call load_utility to parse the suite and allow for individual methods to be executed
    load_utility(@script_status.filename)
  end
end

Instance Attribute Details

#continue_after_errorObject

Returns the value of attribute continue_after_error.



350
351
352
# File 'lib/openc3/utilities/running_script.rb', line 350

def continue_after_error
  @continue_after_error
end

#exceptionsObject

Returns the value of attribute exceptions.



351
352
353
# File 'lib/openc3/utilities/running_script.rb', line 351

def exceptions
  @exceptions
end

#execute_while_paused_infoObject

Returns the value of attribute execute_while_paused_info.



358
359
360
# File 'lib/openc3/utilities/running_script.rb', line 358

def execute_while_paused_info
  @execute_while_paused_info
end

#prompt_idObject

Returns the value of attribute prompt_id.



355
356
357
# File 'lib/openc3/utilities/running_script.rb', line 355

def prompt_id
  @prompt_id
end

#script_bindingObject

Returns the value of attribute script_binding.



352
353
354
# File 'lib/openc3/utilities/running_script.rb', line 352

def script_binding
  @script_binding
end

#script_engineObject

Returns the value of attribute script_engine.



353
354
355
# File 'lib/openc3/utilities/running_script.rb', line 353

def script_engine
  @script_engine
end

#script_statusObject (readonly)

Returns the value of attribute script_status.



356
357
358
# File 'lib/openc3/utilities/running_script.rb', line 356

def script_status
  @script_status
end

#suite_reportObject (readonly)

Returns the value of attribute suite_report.



357
358
359
# File 'lib/openc3/utilities/running_script.rb', line 357

def suite_report
  @suite_report
end

#use_instrumentationObject

Returns the value of attribute use_instrumentation.



349
350
351
# File 'lib/openc3/utilities/running_script.rb', line 349

def use_instrumentation
  @use_instrumentation
end

#user_inputObject

Returns the value of attribute user_input.



354
355
356
# File 'lib/openc3/utilities/running_script.rb', line 354

def user_input
  @user_input
end

Class Method Details

.breakpointsObject



754
755
756
# File 'lib/openc3/utilities/running_script.rb', line 754

def self.breakpoints
  @@breakpoints
end

.clear_breakpoint(filename, line_number) ⇒ Object



1008
1009
1010
1011
# File 'lib/openc3/utilities/running_script.rb', line 1008

def self.clear_breakpoint(filename, line_number)
  @@breakpoints[filename] ||= {}
  @@breakpoints[filename].delete(line_number) if @@breakpoints[filename][line_number]
end

.clear_breakpoints(filename = nil) ⇒ Object



1013
1014
1015
1016
1017
1018
1019
# File 'lib/openc3/utilities/running_script.rb', line 1013

def self.clear_breakpoints(filename = nil)
  if filename == nil or filename.empty?
    @@breakpoints = {}
  else
    @@breakpoints.delete(filename)
  end
end

.file_cacheObject



766
767
768
# File 'lib/openc3/utilities/running_script.rb', line 766

def self.file_cache
  @@file_cache
end

.file_cache=(value) ⇒ Object



770
771
772
# File 'lib/openc3/utilities/running_script.rb', line 770

def self.file_cache=(value)
  @@file_cache = value
end

.instanceObject



730
731
732
# File 'lib/openc3/utilities/running_script.rb', line 730

def self.instance
  @@instance
end

.instance=(value) ⇒ Object



734
735
736
# File 'lib/openc3/utilities/running_script.rb', line 734

def self.instance=(value)
  @@instance = value
end

.instrument_script(text, filename, mark_private = false, line_offset: 0, cache: true) ⇒ Object

Raises:



813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
# File 'lib/openc3/utilities/running_script.rb', line 813

def self.instrument_script(text, filename, mark_private = false, line_offset: 0, cache: true)
  if cache and filename and !filename.empty?
    @@file_cache[filename] = text.clone
  end

  ruby_lex_utils = RubyLexUtils.new
  instrumented_text = ''

  @cancel_instrumentation = false
  num_lines = text.num_lines.to_f
  num_lines = 1 if num_lines < 1
  instrumented_text =
    instrument_script_implementation(ruby_lex_utils,
                                     text,
                                     num_lines,
                                     filename,
                                     mark_private,
                                     line_offset)

  raise OpenC3::StopScript if @cancel_instrumentation
  instrumented_text
end

.instrument_script_implementation(ruby_lex_utils, text, _num_lines, filename, mark_private = false, line_offset = 0) ⇒ Object



836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
# File 'lib/openc3/utilities/running_script.rb', line 836

def self.instrument_script_implementation(ruby_lex_utils,
                                          text,
                                          _num_lines,
                                          filename,
                                          mark_private = false,
                                          line_offset = 0)
  if mark_private
    instrumented_text = 'private; '
  else
    instrumented_text = ''
  end

  ruby_lex_utils.each_lexed_segment(text) do |segment, instrumentable, inside_begin, line_no|
    return nil if @cancel_instrumentation
    instrumented_line = ''
    if instrumentable
      # Add a newline if it's empty to ensure the instrumented code has
      # the same number of lines as the original script
      if segment.strip.empty?
        instrumented_text << "\n"
        next
      end

      # Create a variable to hold the segment's return value
      instrumented_line << "__return_val = nil; "

      # If not inside a begin block then create one to catch exceptions
      unless inside_begin
        instrumented_line << 'begin; '
      end

      # Add preline instrumentation
      instrumented_line << "RunningScript.instance.script_binding = binding(); "\
        "RunningScript.instance.pre_line_instrumentation('#{filename}', #{line_no + line_offset}); "

      # Add the actual line
      instrumented_line << "__return_val = begin; "
      instrumented_line << segment
      instrumented_line.chomp!

      # Add postline instrumentation
      instrumented_line << " end; RunningScript.instance.post_line_instrumentation('#{filename}', #{line_no + line_offset}); "

      # Complete begin block to catch exceptions
      unless inside_begin
        instrumented_line << "rescue Exception => eval_error; "\
        "retry if RunningScript.instance.exception_instrumentation(eval_error, '#{filename}', #{line_no + line_offset}); end; "
      end

      instrumented_line << " __return_val\n"
    else
      unless segment =~ /^\s*end\s*$/ or segment =~ /^\s*when .*$/
        num_left_brackets = segment.count('{')
        num_right_brackets = segment.count('}')
        num_left_square_brackets = segment.count('[')
        num_right_square_brackets = segment.count(']')

        if (num_right_brackets > num_left_brackets) ||
          (num_right_square_brackets > num_left_square_brackets)
          instrumented_line = segment
        else
          instrumented_line = "RunningScript.instance.pre_line_instrumentation('#{filename}', #{line_no + line_offset}); " + segment
        end
      else
        instrumented_line = segment
      end
    end

    instrumented_text << instrumented_line
  end
  instrumented_text
end

.instrumented_cacheObject



758
759
760
# File 'lib/openc3/utilities/running_script.rb', line 758

def self.instrumented_cache
  @@instrumented_cache
end

.instrumented_cache=(value) ⇒ Object



762
763
764
# File 'lib/openc3/utilities/running_script.rb', line 762

def self.instrumented_cache=(value)
  @@instrumented_cache = value
end

.line_delayObject



738
739
740
# File 'lib/openc3/utilities/running_script.rb', line 738

def self.line_delay
  @@line_delay
end

.line_delay=(value) ⇒ Object



742
743
744
# File 'lib/openc3/utilities/running_script.rb', line 742

def self.line_delay=(value)
  @@line_delay = value
end

.max_output_charactersObject



746
747
748
# File 'lib/openc3/utilities/running_script.rb', line 746

def self.max_output_characters
  @@max_output_characters
end

.max_output_characters=(value) ⇒ Object



750
751
752
# File 'lib/openc3/utilities/running_script.rb', line 750

def self.max_output_characters=(value)
  @@max_output_characters = value
end

.message_logObject



383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/openc3/utilities/running_script.rb', line 383

def self.message_log
  return @@message_log if @@message_log

  if @@instance
    scope = @@instance.scope
    tags = [File.basename(@@instance.filename, '.rb').gsub(/(\s|\W)/, '_')]
  else
    scope = $openc3_scope
    tags = []
  end
  log_dir = File.join(RAILS_ROOT, 'tmp', 'script_logs')
  FileUtils.mkdir_p(log_dir)
  @@message_log = OpenC3::MessageLog.new("sr", log_dir, tags: tags, scope: scope)
end

.pause_on_errorObject



774
775
776
# File 'lib/openc3/utilities/running_script.rb', line 774

def self.pause_on_error
  @@pause_on_error
end

.pause_on_error=(value) ⇒ Object



778
779
780
# File 'lib/openc3/utilities/running_script.rb', line 778

def self.pause_on_error=(value)
  @@pause_on_error = value
end

.set_breakpoint(filename, line_number) ⇒ Object



1003
1004
1005
1006
# File 'lib/openc3/utilities/running_script.rb', line 1003

def self.set_breakpoint(filename, line_number)
  @@breakpoints[filename] ||= {}
  @@breakpoints[filename][line_number] = true
end

.spawn(scope, name, suite_runner = nil, disconnect = false, environment = nil, user_full_name = nil, username = nil, line_no = nil, end_line_no = nil) ⇒ Object



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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/openc3/utilities/running_script.rb', line 402

def self.spawn(scope, name, suite_runner = nil, disconnect = false, environment = nil, user_full_name = nil, username = nil, line_no = nil, end_line_no = nil)
  extension = File.extname(name).to_s.downcase
  script_engine = nil
  if extension == '.py'
    process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
    runner_path = File.join(RAILS_ROOT, 'scripts', 'run_script.py')
  elsif extension == '.rb'
    process_name = 'ruby'
    runner_path = File.join(RAILS_ROOT, 'scripts', 'run_script.rb')
  else
    raise "Suite Runner is not supported for this file type: #{extension}" if suite_runner

    # Extension possibly supported by a script engine
    script_engine_model = OpenC3::ScriptEngineModel.get_model(name: extension, scope: scope)
    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', 'run_script.py')
      else
        process_name = 'ruby'
        runner_path = File.join(RAILS_ROOT, 'scripts', 'run_script.rb')
      end
    else
      raise "Unsupported script file type: #{extension}"
    end
  end

  running_script_id = OpenC3::Store.incr('running-script-id')

  # COSMOS Core username (Enterprise has the actual name)
  username ||= 'Anonymous'
  # COSMOS Core full name (Enterprise has the actual name)
  user_full_name ||= 'Anonymous'
  start_time = Time.now.utc.iso8601

  process = ChildProcess.build(process_name, runner_path.to_s, running_script_id.to_s, scope)
  process.io.inherit! # Helps with debugging
  script_cwd = File.join(RAILS_ROOT, 'tmp', "script_#{running_script_id}")
  FileUtils.mkdir_p(script_cwd)
  process.cwd = script_cwd

  # Check for offline access token
  model = nil
  model = OpenC3::OfflineAccessModel.get_model(name: username, scope: scope) if username != 'Anonymous'

  # Load the global environment variables
  status_environment = {}
  values = OpenC3::EnvironmentModel.all(scope: scope).values
  values.each do |env|
    process.environment[env['key']] = env['value']
    status_environment[env['key']] = env['value']
  end
  # Load the script specific ENV vars set by the GUI
  # These can override the previously defined global env vars
  if environment
    environment.each do |env|
      process.environment[env['key']] = env['value']
      status_environment[env['key']] = env['value']
    end
  end

  script_status = OpenC3::ScriptStatusModel.new(
    name: running_script_id.to_s, # Unique id for this script
    state: 'spawning', # State will be spawning until the script is running
    shard: 0, # Future enhancement of script runner shards
    filename: name, # Initial filename never changes
    current_filename: name, # Current filename updates while we are running
    line_no: 0, # 0 means not running yet
    start_line_no: line_no || 1, # Line number to start running the script
    end_line_no: end_line_no || nil, # Line number to stop running the script
    username: username, # username of the person who started the script
    user_full_name: user_full_name, # full name of the person who started the script
    start_time: start_time, # Time the script started ISO format
    end_time: nil, # Time the script ended ISO format
    disconnect: disconnect, # Disconnect is set to true if the script is running in a disconnected mode
    environment: status_environment, # hash of environment variables set for the script
    suite_runner: suite_runner ? suite_runner : nil, # current suite information if any
    errors: nil, # array of errors that occurred during the script run
    pid: nil, # pid of the script process - set by the script itself when it starts
    script_engine: script_engine, # script engine filename
    updated_at: nil, # Set by create/update - ISO format
    scope: scope # Scope of the script
  )
  script_status.create(isoformat: true)

  # Set proper secrets for running script
  process.environment['SECRET_KEY_BASE'] = nil
  process.environment['OPENC3_REDIS_USERNAME'] = ENV['OPENC3_SR_REDIS_USERNAME']
  process.environment['OPENC3_REDIS_PASSWORD'] = ENV['OPENC3_SR_REDIS_PASSWORD']
  process.environment['OPENC3_BUCKET_USERNAME'] = ENV['OPENC3_SR_BUCKET_USERNAME']
  process.environment['OPENC3_BUCKET_PASSWORD'] = ENV['OPENC3_SR_BUCKET_PASSWORD']
  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']
  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']
    if ENV['OPENC3_SERVICE_PASSWORD']
      process.environment['OPENC3_API_PASSWORD'] = ENV['OPENC3_SERVICE_PASSWORD']
    else
      raise "No authentication available for script"
    end
  end
  process.environment['GEM_HOME'] = ENV['GEM_HOME']
  process.environment['PYTHONUSERBASE'] = ENV['PYTHONUSERBASE']
  # Preserve PYTHONPATH to ensure Python can find both UV venv and user packages
  process.environment['PYTHONPATH'] = ENV['PYTHONPATH']

  # 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
  process.environment['RAILS_ROOT'] = RAILS_ROOT

  process.detach = true
  process.start
  running_script_id
end

Instance Method Details

#check_execute_while_pausedObject



1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
# File 'lib/openc3/utilities/running_script.rb', line 1151

def check_execute_while_paused
  if @execute_while_paused_info
    if @script_status.current_filename == @execute_while_paused_info[:filename]
      bind_variables = true
    else
      bind_variables = false
    end
    if @execute_while_paused_info[:end_line_no]
      # Execute Selection While Paused
      state = @script_status.state
      current_filename = @script_status.current_filename
      line_no = @script_status.line_no
      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)
      # Need to restore state after returning so that the correct line will be shown in ScriptRunner
      @script_status.state = state
      @script_status.current_filename = current_filename
      @script_status.line_no = line_no
      @script_status.update(queued: true)
      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 })
    else
      # Goto While Paused
      start(@execute_while_paused_info[:filename], line_no: @execute_while_paused_info[:line_no], bind_variables: bind_variables, complete: true)
    end
  end
ensure
  @execute_while_paused_info = nil
end

#clear_breakpointsObject



1021
1022
1023
# File 'lib/openc3/utilities/running_script.rb', line 1021

def clear_breakpoints
  ScriptRunnerFrame.clear_breakpoints(unique_filename())
end

#clear_promptObject



678
679
680
681
682
# File 'lib/openc3/utilities/running_script.rb', line 678

def clear_prompt
  # Allow things to continue once the prompt is cleared
  running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :script, prompt_complete: @prompt_id })
  @prompt_id = nil
end

#continueObject

Let the script continue pausing if in step mode



629
630
631
632
# File 'lib/openc3/utilities/running_script.rb', line 629

def continue
  @go = true
  @pause = true if @step
end

#current_backtraceObject



1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/openc3/utilities/running_script.rb', line 1025

def current_backtrace
  trace = []
  if @@run_thread
    temp_trace = @@run_thread.backtrace
    temp_trace.each do |line|
      next if line.include?(OpenC3::PATH)    # Ignore OpenC3 internals
      next if line.include?('lib/ruby/gems') # Ignore system gems
      next if line.include?('app/models/running_script') # Ignore this file
      trace << line
    end
  end
  trace
end

#current_filenameObject



342
343
344
# File 'lib/openc3/utilities/running_script.rb', line 342

def current_filename
  return @script_status.current_filename
end

#current_line_numberObject



345
346
347
# File 'lib/openc3/utilities/running_script.rb', line 345

def current_line_number
  return @script_status.line_no
end

#debug(debug_text) ⇒ Object



970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
# File 'lib/openc3/utilities/running_script.rb', line 970

def debug(debug_text)
  handle_output_io()

  use_script_engine = false
  extension = File.extname(current_filename()).to_s.downcase
  if @script_engine and extension != ".py"
    use_script_engine = true
  end

  if not use_script_engine
    if @script_binding
      # Check for accessing an instance variable or local
      if debug_text =~ /^@\S+$/ || @script_binding.local_variables.include?(debug_text.to_sym)
        debug_text = "puts #{debug_text}" # Automatically add puts to print it
      end
      eval(debug_text, @script_binding, 'debug', 1)
    else
      Object.class_eval(debug_text, 'debug', 1)
    end
  else
    @script_engine.debug(debug_text)
  end

  handle_output_io()
rescue Exception => e
  if e.class == DRb::DRbConnError
    OpenC3::Logger.error("Error Connecting to Command and Telemetry Server")
  else
    OpenC3::Logger.error(e.formatted)
  end
  handle_output_io()
end

#exception_instrumentation(error, filename, line_number) ⇒ Object



944
945
946
947
948
949
950
951
# File 'lib/openc3/utilities/running_script.rb', line 944

def exception_instrumentation(error, filename, line_number)
  if error.class <= OpenC3::StopScript || error.class <= OpenC3::SkipScript || !@use_instrumentation
    raise error
  elsif !error.eql?(@@error)
    line_number = line_number + @line_offset
    handle_exception(error, false, filename, line_number)
  end
end

#execute_while_paused(filename, line_no = 1, end_line_no = nil) ⇒ Object



1039
1040
1041
1042
1043
1044
1045
# File 'lib/openc3/utilities/running_script.rb', line 1039

def execute_while_paused(filename, line_no = 1, end_line_no = nil)
  if @script_status.state == 'paused' or @script_status.state == 'error' or @script_status.state == 'breakpoint'
    @execute_while_paused_info = { filename: filename, line_no: line_no, end_line_no: end_line_no }
  else
    scriptrunner_puts("Cannot execute selection or goto unless script is paused, breakpoint, or in error state")
  end
end

#filenameObject



339
340
341
# File 'lib/openc3/utilities/running_script.rb', line 339

def filename
  return @script_status.filename
end

#goObject

Clears step mode and lets the script continue



643
644
645
646
647
# File 'lib/openc3/utilities/running_script.rb', line 643

def go
  @step = false
  @go = true
  @pause = false
end

#go?Boolean

Returns:

  • (Boolean)


649
650
651
652
653
# File 'lib/openc3/utilities/running_script.rb', line 649

def go?
  temp = @go
  @go = false
  temp
end

#graceful_killObject

Private methods



686
687
688
# File 'lib/openc3/utilities/running_script.rb', line 686

def graceful_kill
  @stop = true
end

#handle_exception(error, fatal, filename = nil, line_number = 0) ⇒ Object



1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
# File 'lib/openc3/utilities/running_script.rb', line 1394

def handle_exception(error, fatal, filename = nil, line_number = 0)
  @exceptions ||= []
  @exceptions << error
  @script_status.errors ||= []
  @script_status.errors << error.formatted
  @@error = error

  if error.class == DRb::DRbConnError
    OpenC3::Logger.error("Error Connecting to Command and Telemetry Server")
  elsif error.class == OpenC3::CheckError
    OpenC3::Logger.error(error.message)
  else
    OpenC3::Logger.error(error.class.to_s.split('::')[-1] + ' : ' + error.message)
    if ENV['OPENC3_FULL_BACKTRACE']
      OpenC3::Logger.error(error.backtrace.join("\n\n"))
    end
  end
  handle_output_io(filename, line_number)

  raise error if !@@pause_on_error and !@continue_after_error and !fatal

  if !fatal and @@pause_on_error
    mark_error()
    wait_for_go_or_stop_or_retry(error)
  end

  if @retry_needed
    @retry_needed = false
    true
  else
    false
  end
end

#handle_line_delayObject



1387
1388
1389
1390
1391
1392
# File 'lib/openc3/utilities/running_script.rb', line 1387

def handle_line_delay
  if @@line_delay > 0.0
    sleep_time = @@line_delay - (Time.now.sys - @pre_line_time)
    sleep(sleep_time) if sleep_time > 0.0
  end
end

#handle_output_io(filename = nil, line_number = nil) ⇒ Object



1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
# File 'lib/openc3/utilities/running_script.rb', line 1053

def handle_output_io(filename = nil, line_number = nil)
  filename = @script_status.current_filename if filename.nil?
  line_number = @script_status.line_no if line_number.nil?

  @output_time = Time.now.sys
  if @output_io.string[-1..-1] == "\n"
    time_formatted = Time.now.sys.formatted
    color = 'BLACK'
    lines_to_write = ''
    out_line_number = line_number.to_s
    out_filename = File.basename(filename) if filename

    # Build each line to write
    string = @output_io.string.clone
    @output_io.string = @output_io.string[string.length..-1]
    line_count = 0
    string.each_line(chomp: true) do |out_line|
      begin
        json = JSON.parse(out_line, allow_nan: true, create_additions: true)
        time_formatted = Time.parse(json["@timestamp"]).sys.formatted if json["@timestamp"]
        if json["log"]
          out_line = json["log"]
        elsif json["message"]
          out_line = json["message"]
        end
      rescue
        # Regular output
      end

      if out_line.length >= 25 and out_line[0..1] == '20' and out_line[10] == ' ' and out_line[23..24] == ' ('
        line_to_write = out_line
      else
        if filename
          line_to_write = time_formatted + " (#{out_filename}:#{out_line_number}): " + out_line
        else
          line_to_write = time_formatted + " (SCRIPTRUNNER): " + out_line
          color = 'BLUE'
        end
      end
      lines_to_write << (line_to_write + "\n")
      line_count += 1
    end # string.each_line

    if lines_to_write.length > @@max_output_characters
      # We want the full @@max_output_characters so don't subtract the additional "ERROR: ..." text
      published_lines = lines_to_write[0...@@max_output_characters]
      published_lines << "\nERROR: Too much to publish. Truncating #{lines_to_write.length} characters of output to #{@@max_output_characters} characters.\n"
    else
      published_lines = lines_to_write
    end
    running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :output, line: published_lines.as_json(), color: color })
    # Add to the message log
    message_log.write(lines_to_write)
  end
end

#handle_pause(filename, line_number) ⇒ Object



1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
# File 'lib/openc3/utilities/running_script.rb', line 1370

def handle_pause(filename, line_number)
  breakpoint = false
  breakpoint = true if @@breakpoints[filename] and @@breakpoints[filename][line_number]

  filename = File.basename(filename)
  if @pause
    @pause = false unless @step
    if breakpoint
      perform_breakpoint(filename, line_number)
    else
      perform_pause()
    end
  else
    perform_breakpoint(filename, line_number) if breakpoint
  end
end

#handle_potential_tab_change(filename) ⇒ Object



1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
# File 'lib/openc3/utilities/running_script.rb', line 1356

def handle_potential_tab_change(filename)
  # Make sure the correct file is shown in script runner
  if @current_file != filename
    if @call_stack.include?(filename)
      index = @call_stack.index(filename)
    else # new file
      @call_stack.push(filename.dup)
      load_file_into_script(filename)
    end

    @current_file = filename
  end
end

#idObject



333
334
335
# File 'lib/openc3/utilities/running_script.rb', line 333

def id
  return @script_status.id
end

#initialize_variablesObject



690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'lib/openc3/utilities/running_script.rb', line 690

def initialize_variables
  @@error = nil
  @go = false
  @pause = false
  @step = false
  @stop = false
  @retry_needed = false
  @use_instrumentation = true
  @call_stack = []
  @pre_line_time = Time.now.sys
  @exceptions = nil
  @script_binding = nil
  @inline_eval = nil
  @script_status.current_filename = @script_status.filename
  @script_status.line_no = 0
  @current_file = nil
  @execute_while_paused_info = nil
end

#load_file_into_script(filename) ⇒ Object



1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
# File 'lib/openc3/utilities/running_script.rb', line 1428

def load_file_into_script(filename)
  mark_breakpoints(filename)
  breakpoints = @@breakpoints[filename]&.filter { |_, present| present }&.map { |line_number, _| line_number - 1 } # -1 because frontend lines are 0-indexed
  breakpoints ||= []
  cached = @@file_cache[filename]
  if cached
    @body = cached
    running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :file, filename: filename, text: @body.to_utf8, breakpoints: breakpoints })
  else
    text = ::Script.body(@script_status.scope, filename)
    raise "Script not found: #{filename}" if text.nil?
    @@file_cache[filename] = text
    @body = text
    running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :file, filename: filename, text: @body.to_utf8, breakpoints: breakpoints })
  end
end

#mark_breakpointObject



1256
1257
1258
1259
# File 'lib/openc3/utilities/running_script.rb', line 1256

def mark_breakpoint
  update_running_script_store("breakpoint")
  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 })
end

#mark_breakpoints(filename) ⇒ Object



1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
# File 'lib/openc3/utilities/running_script.rb', line 1445

def mark_breakpoints(filename)
  breakpoints = @@breakpoints[filename]
  if breakpoints
    breakpoints.each do |line_number, present|
      RunningScript.set_breakpoint(filename, line_number) if present
    end
  else
    ::Script.get_breakpoints(@script_status.scope, filename).each do |line_number|
      RunningScript.set_breakpoint(filename, line_number + 1)
    end
  end
end

#mark_completedObject



1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
# File 'lib/openc3/utilities/running_script.rb', line 1205

def mark_completed
  @script_status.end_time = Time.now.utc.iso8601
  update_running_script_store("completed")
  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 })
  if OpenC3::SuiteRunner.suite_results
    OpenC3::SuiteRunner.suite_results.complete
    # context looks like the following:
    # MySuite:ExampleGroup:script_2
    # MySuite:ExampleGroup Manual Setup
    # MySuite Manual Teardown
    init_split = OpenC3::SuiteRunner.suite_results.context.split()
    parts = init_split[0].split(':')
    if parts[2]
      # Remove test_ or script_ because it doesn't add any info
      parts[2] = parts[2].sub(/^test_/, '').sub(/^script_/, '')
    end
    parts.map! { |part| part[0..9] } # Only take the first 10 characters to prevent huge filenames
    # If the initial split on whitespace has more than 1 item it means
    # a Manual Setup or Teardown was performed. Add this to the filename.
    # NOTE: We're doing this here with a single underscore to preserve
    # double underscores as Suite, Group, Script delimiters
    if parts[1] and init_split.length > 1
      parts[1] += "_#{init_split[-1]}"
    elsif parts[0] and init_split.length > 1
      parts[0] += "_#{init_split[-1]}"
    end
    @suite_report = OpenC3::SuiteRunner.suite_results.report
    # Write out the report to a local file
    log_dir = File.join(RAILS_ROOT, 'tmp', 'script_logs')
    FileUtils.mkdir_p(log_dir)
    filename = File.join(log_dir, File.build_timestamped_filename(['sr', parts.join('__')]))
    File.open(filename, 'wb') do |file|
      file.write(OpenC3::SuiteRunner.suite_results.report)
    end
    # Generate the bucket key by removing the date underscores in the filename to create the bucket file structure
    bucket_key = File.join("#{@script_status.scope}/tool_logs/sr/", File.basename(filename)[0..9].gsub("_", ""), File.basename(filename))
     = {
      # Note: The chars '(' and ')' are used by RunningScripts.vue to differentiate between script logs
      "id" => @script_status.id,
      "user" => @script_status.username,
      "scriptname" => "#{@script_status.current_filename} (#{OpenC3::SuiteRunner.suite_results.context.strip})"
    }
    thread = OpenC3::BucketUtilities.move_log_file_to_bucket(filename, bucket_key, metadata: )
    # Wait for the file to get moved to S3 because after this the process will likely die
    @script_status.report = bucket_key
    @script_status.update(queued: true)
    thread.join
  end
  running_script_publish("cmd-running-script-channel:#{@script_status.id}", "shutdown")
end

#mark_crashedObject



1199
1200
1201
1202
1203
# File 'lib/openc3/utilities/running_script.rb', line 1199

def mark_crashed
  @script_status.end_time = Time.now.utc.iso8601
  update_running_script_store("crashed")
  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 })
end

#mark_errorObject



1194
1195
1196
1197
# File 'lib/openc3/utilities/running_script.rb', line 1194

def mark_error
  update_running_script_store("error")
  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 })
end

#mark_pausedObject



1184
1185
1186
1187
# File 'lib/openc3/utilities/running_script.rb', line 1184

def mark_paused
  update_running_script_store("paused")
  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 })
end

#mark_runningObject



1179
1180
1181
1182
# File 'lib/openc3/utilities/running_script.rb', line 1179

def mark_running
  update_running_script_store("running")
  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 })
end

#mark_waitingObject



1189
1190
1191
1192
# File 'lib/openc3/utilities/running_script.rb', line 1189

def mark_waiting
  update_running_script_store("waiting")
  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 })
end

#message_logObject



398
399
400
# File 'lib/openc3/utilities/running_script.rb', line 398

def message_log
  self.class.message_log
end

#output_threadObject



1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'lib/openc3/utilities/running_script.rb', line 1466

def output_thread
  @@cancel_output = false
  @@output_sleeper = OpenC3::Sleeper.new
  begin
    loop do
      break if @@cancel_output
      handle_output_io() if (Time.now.sys - @output_time) > 5.0
      break if @@cancel_output
      break if @@output_sleeper.sleep(1.0)
    end # loop
  rescue => e
    # Qt.execute_in_main_thread(true) do
    #  ExceptionDialog.new(self, error, "Output Thread")
    # end
  end
end

#parse_options(options) ⇒ Object



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/openc3/utilities/running_script.rb', line 585

def parse_options(options)
  settings = {}
  if options.include?('manual')
    settings['Manual'] = true
    $manual = true
  else
    settings['Manual'] = false
    $manual = false
  end
  if options.include?('pauseOnError')
    settings['Pause on Error'] = true
    @@pause_on_error = true
  else
    settings['Pause on Error'] = false
    @@pause_on_error = false
  end
  if options.include?('continueAfterError')
    settings['Continue After Error'] = true
    @continue_after_error = true
  else
    settings['Continue After Error'] = false
    @continue_after_error = false
  end
  if options.include?('abortAfterError')
    settings['Abort After Error'] = true
    OpenC3::Test.abort_on_exception = true
  else
    settings['Abort After Error'] = false
    OpenC3::Test.abort_on_exception = false
  end
  if options.include?('loop')
    settings['Loop'] = true
  else
    settings['Loop'] = false
  end
  if options.include?('breakLoopOnError')
    settings['Break Loop On Error'] = true
  else
    settings['Break Loop On Error'] = false
  end
  OpenC3::SuiteRunner.settings = settings
end

#pauseObject



655
656
657
658
# File 'lib/openc3/utilities/running_script.rb', line 655

def pause
  @pause = true
  @go    = false
end

#pause?Boolean

Returns:

  • (Boolean)


660
661
662
# File 'lib/openc3/utilities/running_script.rb', line 660

def pause?
  @pause
end

#perform_breakpoint(filename, line_number) ⇒ Object



963
964
965
966
967
968
# File 'lib/openc3/utilities/running_script.rb', line 963

def perform_breakpoint(filename, line_number)
  mark_breakpoint()
  scriptrunner_puts "Hit Breakpoint at #{filename}:#{line_number}"
  handle_output_io(filename, line_number)
  wait_for_go_or_stop()
end

#perform_pauseObject



958
959
960
961
# File 'lib/openc3/utilities/running_script.rb', line 958

def perform_pause
  mark_paused()
  wait_for_go_or_stop()
end

#perform_wait(prompt) ⇒ Object



953
954
955
956
# File 'lib/openc3/utilities/running_script.rb', line 953

def perform_wait(prompt)
  mark_waiting()
  wait_for_go_or_stop(prompt: prompt)
end

#post_line_instrumentation(filename, line_number) ⇒ Object



937
938
939
940
941
942
# File 'lib/openc3/utilities/running_script.rb', line 937

def post_line_instrumentation(filename, line_number)
  if @use_instrumentation
    line_number = line_number + @line_offset
    handle_output_io(filename, line_number)
  end
end

#pre_line_instrumentation(filename, line_number) ⇒ Object



909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
# File 'lib/openc3/utilities/running_script.rb', line 909

def pre_line_instrumentation(filename, line_number)
  @pre_line_time = Time.now.sys
  @script_status.current_filename = filename
  @script_status.line_no = line_number
  if @use_instrumentation
    # Clear go
    @go = false

    # Handle stopping mid-script if necessary
    raise OpenC3::StopScript if @stop

    handle_potential_tab_change(filename)

    # Adjust line number for offset in main script
    line_number = line_number + @line_offset
    detail_string = nil
    if filename
      detail_string = File.basename(filename) << ':' << line_number.to_s
      OpenC3::Logger.detail_string = detail_string
    end

    update_running_script_store("running")
    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 })
    handle_pause(filename, line_number)
    handle_line_delay()
  end
end

#redirect_ioObject



1458
1459
1460
1461
1462
1463
1464
# File 'lib/openc3/utilities/running_script.rb', line 1458

def redirect_io
  # Redirect Standard Output and Standard Error
  $stdout = OpenC3::Stdout.instance
  $stderr = OpenC3::Stderr.instance
  OpenC3::Logger.stdout = true
  OpenC3::Logger.level = OpenC3::Logger::INFO
end

#retry_neededObject



786
787
788
# File 'lib/openc3/utilities/running_script.rb', line 786

def retry_needed
  @retry_needed = true
end

#runObject



790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
# File 'lib/openc3/utilities/running_script.rb', line 790

def run
  if @script_status.suite_runner
    if @script_status.suite_runner['options']
      parse_options(@script_status.suite_runner['options'])
    else
      parse_options({}) # Set default options
    end
    if @script_status.suite_runner['script']
      run_text("OpenC3::SuiteRunner.start(#{@script_status.suite_runner['suite']}, #{@script_status.suite_runner['group']}, '#{@script_status.suite_runner['script']}')", initial_filename: "SCRIPTRUNNER")
    elsif script_status.suite_runner['group']
      run_text("OpenC3::SuiteRunner.#{@script_status.suite_runner['method']}(#{@script_status.suite_runner['suite']}, #{@script_status.suite_runner['group']})", initial_filename: "SCRIPTRUNNER")
    else
      run_text("OpenC3::SuiteRunner.#{@script_status.suite_runner['method']}(#{@script_status.suite_runner['suite']})", initial_filename: "SCRIPTRUNNER")
    end
  else
    if not @script_engine and (@script_status.start_line_no != 1 or !@script_status.end_line_no.nil?)
      run_text("", initial_filename: "SCRIPTRUNNER")
    else
      run_text(@body)
    end
  end
end

#run_text(text, initial_filename: nil) ⇒ Object



1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'lib/openc3/utilities/running_script.rb', line 1261

def run_text(text,
             initial_filename: nil)
  initialize_variables()
  saved_instance = @@instance
  saved_run_thread = @@run_thread
  @@instance = self

  @@run_thread = Thread.new do
    begin
      # Capture STDOUT and STDERR
      $stdout.add_stream(@output_io)
      $stderr.add_stream(@output_io)

      output = "Starting script: #{File.basename(@script_status.filename)}"
      output += " in DISCONNECT mode" if $disconnect
      output += ", line_delay = #{@@line_delay}"
      scriptrunner_puts(output)
      handle_output_io()

      # Start Output Thread
      @@output_thread = Thread.new { output_thread() } unless @@output_thread

      if @script_engine
        if @script_status.start_line_no != 1 or !@script_status.end_line_no.nil?
          if @script_status.end_line_no.nil?
            # Goto line
            start(@script_status.filename, line_no: @script_status.start_line_no, complete: true)
          else
            # Execute selection
            start(@script_status.filename, line_no: @script_status.start_line_no, end_line_no: @script_status.end_line_no, complete: true)
          end
        else
          @script_engine.run_text(text, filename: @script_status.filename)
        end
      else
        if initial_filename == 'SCRIPTRUNNER'
          # Don't instrument pseudo scripts
          instrument_filename = initial_filename
          instrumented_script = text
        else
          # Instrument everything else
          instrument_filename = @script_status.filename
          instrument_filename = initial_filename if initial_filename
          instrumented_script = self.class.instrument_script(text, instrument_filename, true)
        end

        # Execute the script with warnings disabled
        OpenC3.disable_warnings do
          @pre_line_time = Time.now.sys
          Object.class_eval(instrumented_script, instrument_filename, 1)
        end
      end

      handle_output_io()
      scriptrunner_puts "Script completed: #{@script_status.filename}"

    rescue Exception => e # rubocop:disable Lint/RescueException
      if e.class <= OpenC3::StopScript or e.class <= OpenC3::SkipScript
        handle_output_io()
        scriptrunner_puts "Script stopped: #{@script_status.filename}"
      else
        filename, line_number = e.source
        handle_exception(e, true, filename, line_number)
        handle_output_io()
        scriptrunner_puts "Exception in Control Statement - Script stopped: #{@script_status.filename}"
        mark_crashed()
      end
    ensure
      # Stop Capturing STDOUT and STDERR
      # Check for remove_stream because if the tool is quitting the
      # OpenC3::restore_io may have been called which sets $stdout and
      # $stderr to the IO constant
      $stdout.remove_stream(@output_io) if $stdout.respond_to? :remove_stream
      $stderr.remove_stream(@output_io) if $stderr.respond_to? :remove_stream

      # Clear run thread and instance to indicate we are no longer running
      @@instance = saved_instance
      @@run_thread = saved_run_thread
      @active_script = @script
      @script_binding = nil
      # Set the current_filename to the original file and the line_no to 0
      # so the mark_complete method will signal the frontend to reset to the original
      @script_status.current_filename = @script_status.filename
      @script_status.line_no = 0
      if @@output_thread and not @@instance
        @@cancel_output = true
        @@output_sleeper.cancel
        OpenC3.kill_thread(self, @@output_thread)
        @@output_thread = nil
      end
      mark_completed()
    end
  end
end

#scopeObject



336
337
338
# File 'lib/openc3/utilities/running_script.rb', line 336

def scope
  return @script_status.scope
end

#scriptrunner_puts(string, color = 'BLACK') ⇒ Object



1047
1048
1049
1050
1051
# File 'lib/openc3/utilities/running_script.rb', line 1047

def scriptrunner_puts(string, color = 'BLACK')
  line_to_write = Time.now.sys.formatted + " (SCRIPTRUNNER): " + string
  $stdout.puts line_to_write
  running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :output, line: line_to_write, color: color })
end

#stepObject

Sets step mode and lets the script continue but with pause set



635
636
637
638
639
640
# File 'lib/openc3/utilities/running_script.rb', line 635

def step
  running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :step, filename: @script_status.current_filename, line_no: @script_status.line_no, state: @script_status.state })
  @step = true
  @go = true
  @pause = true
end

#stopObject



664
665
666
667
668
669
670
671
672
# File 'lib/openc3/utilities/running_script.rb', line 664

def stop
  if @@run_thread
    @stop = true
    @script_status.end_time = Time.now.utc.iso8601
    update_running_script_store("stopped")
    OpenC3.kill_thread(self, @@run_thread)
    @@run_thread = nil
  end
end

#stop?Boolean

Returns:

  • (Boolean)


674
675
676
# File 'lib/openc3/utilities/running_script.rb', line 674

def stop?
  @stop
end

#stop_message_logObject



717
718
719
720
721
722
723
724
725
726
727
728
# File 'lib/openc3/utilities/running_script.rb', line 717

def stop_message_log
   = {
    "id" => @script_status.id,
    "user" => @script_status.username,
    "scriptname" => unique_filename()
  }
  if @@message_log
    @script_status.log = @@message_log.stop(true, metadata: )
    @script_status.update()
  end
  @@message_log = nil
end

#textObject



782
783
784
# File 'lib/openc3/utilities/running_script.rb', line 782

def text
  @body
end

#unique_filenameObject



709
710
711
712
713
714
715
# File 'lib/openc3/utilities/running_script.rb', line 709

def unique_filename
  if @script_status.filename and !@script_status.filename.empty?
    return @script_status.filename
  else
    return "Untitled" + @script_status.id.to_s
  end
end

#update_running_script_store(state = nil) ⇒ Object

Called to update the running script state every time the state or line_no changes



580
581
582
583
# File 'lib/openc3/utilities/running_script.rb', line 580

def update_running_script_store(state = nil)
  @script_status.state = state if state
  @script_status.update(queued: true)
end

#wait_for_go_or_stop(error = nil, prompt: nil) ⇒ Object

Raises:



1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
# File 'lib/openc3/utilities/running_script.rb', line 1113

def wait_for_go_or_stop(error = nil, prompt: nil)
  count = -1
  @go = false
  @prompt_id = prompt['id'] if prompt
  until (@go or @stop)
    check_execute_while_paused()
    sleep(0.01)
    count += 1
    if count % 100 == 0 # Approximately Every Second
      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 })
      running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :script, method: prompt['method'], prompt_id: prompt['id'], args: prompt['args'], kwargs: prompt['kwargs'] }) if prompt
    end
  end
  clear_prompt() if prompt
  RunningScript.instance.prompt_id = nil
  @go = false
  mark_running()
  raise OpenC3::StopScript if @stop
  raise error if error and !@continue_after_error
end

#wait_for_go_or_stop_or_retry(error = nil) ⇒ Object

Raises:



1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
# File 'lib/openc3/utilities/running_script.rb', line 1134

def wait_for_go_or_stop_or_retry(error = nil)
  count = 0
  @go = false
  until (@go or @stop or @retry_needed)
    check_execute_while_paused()
    sleep(0.01)
    count += 1
    if (count % 100) == 0 # Approximately Every Second
      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 })
    end
  end
  @go = false
  mark_running()
  raise OpenC3::StopScript if @stop
  raise error if error and !@continue_after_error
end