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.



518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/openc3/utilities/running_script.rb', line 518

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.



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

def continue_after_error
  @continue_after_error
end

#exceptionsObject

Returns the value of attribute exceptions.



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

def exceptions
  @exceptions
end

#execute_while_paused_infoObject

Returns the value of attribute execute_while_paused_info.



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

def execute_while_paused_info
  @execute_while_paused_info
end

#prompt_idObject

Returns the value of attribute prompt_id.



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

def prompt_id
  @prompt_id
end

#script_bindingObject

Returns the value of attribute script_binding.



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

def script_binding
  @script_binding
end

#script_engineObject

Returns the value of attribute script_engine.



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

def script_engine
  @script_engine
end

#script_statusObject (readonly)

Returns the value of attribute script_status.



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

def script_status
  @script_status
end

#use_instrumentationObject

Returns the value of attribute use_instrumentation.



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

def use_instrumentation
  @use_instrumentation
end

#user_inputObject

Returns the value of attribute user_input.



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

def user_input
  @user_input
end

Class Method Details

.breakpointsObject



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

def self.breakpoints
  @@breakpoints
end

.clear_breakpoint(filename, line_number) ⇒ Object



990
991
992
993
# File 'lib/openc3/utilities/running_script.rb', line 990

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



995
996
997
998
999
1000
1001
# File 'lib/openc3/utilities/running_script.rb', line 995

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

.file_cacheObject



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

def self.file_cache
  @@file_cache
end

.file_cache=(value) ⇒ Object



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

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

.instanceObject



711
712
713
# File 'lib/openc3/utilities/running_script.rb', line 711

def self.instance
  @@instance
end

.instance=(value) ⇒ Object



715
716
717
# File 'lib/openc3/utilities/running_script.rb', line 715

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

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

Raises:



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/openc3/utilities/running_script.rb', line 795

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



818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
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
# File 'lib/openc3/utilities/running_script.rb', line 818

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



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

def self.instrumented_cache
  @@instrumented_cache
end

.instrumented_cache=(value) ⇒ Object



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

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

.line_delayObject



719
720
721
# File 'lib/openc3/utilities/running_script.rb', line 719

def self.line_delay
  @@line_delay
end

.line_delay=(value) ⇒ Object



723
724
725
# File 'lib/openc3/utilities/running_script.rb', line 723

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

.max_output_charactersObject



727
728
729
# File 'lib/openc3/utilities/running_script.rb', line 727

def self.max_output_characters
  @@max_output_characters
end

.max_output_characters=(value) ⇒ Object



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

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

.message_logObject



370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/openc3/utilities/running_script.rb', line 370

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
  @@message_log = OpenC3::MessageLog.new("sr", File.join(RAILS_ROOT, 'log'), tags: tags, scope: scope)
end

.pause_on_errorObject



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

def self.pause_on_error
  @@pause_on_error
end

.pause_on_error=(value) ⇒ Object



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

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

.set_breakpoint(filename, line_number) ⇒ Object



985
986
987
988
# File 'lib/openc3/utilities/running_script.rb', line 985

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



387
388
389
390
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# File 'lib/openc3/utilities/running_script.rb', line 387

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 = '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 = '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
  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 != '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.as_json(:allow_nan => true).to_json(:allow_nan => true), # nil or Hash of key/value pairs for environment variables
    suite_runner: suite_runner ? suite_runner.as_json(:allow_nan => true).to_json(:allow_nan => true) : nil,
    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']

  # 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



1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
# File 'lib/openc3/utilities/running_script.rb', line 1133

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



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

def clear_breakpoints
  ScriptRunnerFrame.clear_breakpoints(unique_filename())
end

#clear_promptObject



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

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



610
611
612
613
# File 'lib/openc3/utilities/running_script.rb', line 610

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

#current_backtraceObject



1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
# File 'lib/openc3/utilities/running_script.rb', line 1007

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



330
331
332
# File 'lib/openc3/utilities/running_script.rb', line 330

def current_filename
  return @script_status.current_filename
end

#current_line_numberObject



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

def current_line_number
  return @script_status.line_no
end

#debug(debug_text) ⇒ Object



952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
# File 'lib/openc3/utilities/running_script.rb', line 952

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



926
927
928
929
930
931
932
933
# File 'lib/openc3/utilities/running_script.rb', line 926

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



1021
1022
1023
1024
1025
1026
1027
# File 'lib/openc3/utilities/running_script.rb', line 1021

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



327
328
329
# File 'lib/openc3/utilities/running_script.rb', line 327

def filename
  return @script_status.filename
end

#goObject

Clears step mode and lets the script continue



624
625
626
627
628
# File 'lib/openc3/utilities/running_script.rb', line 624

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

#go?Boolean

Returns:

  • (Boolean)


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

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

#graceful_killObject

Private methods



667
668
669
# File 'lib/openc3/utilities/running_script.rb', line 667

def graceful_kill
  @stop = true
end

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



1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
# File 'lib/openc3/utilities/running_script.rb', line 1375

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



1368
1369
1370
1371
1372
1373
# File 'lib/openc3/utilities/running_script.rb', line 1368

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



1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
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
# File 'lib/openc3/utilities/running_script.rb', line 1035

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(:allow_nan => true), color: color })
    # Add to the message log
    message_log.write(lines_to_write)
  end
end

#handle_pause(filename, line_number) ⇒ Object



1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'lib/openc3/utilities/running_script.rb', line 1351

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



1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
# File 'lib/openc3/utilities/running_script.rb', line 1337

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



321
322
323
# File 'lib/openc3/utilities/running_script.rb', line 321

def id
  return @script_status.id
end

#initialize_variablesObject



671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'lib/openc3/utilities/running_script.rb', line 671

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



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
# File 'lib/openc3/utilities/running_script.rb', line 1409

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



1237
1238
1239
1240
# File 'lib/openc3/utilities/running_script.rb', line 1237

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



1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
# File 'lib/openc3/utilities/running_script.rb', line 1426

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



1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
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
# File 'lib/openc3/utilities/running_script.rb', line 1187

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
    running_script_anycable_publish("running-script-channel:#{@script_status.id}", { type: :report, report: OpenC3::SuiteRunner.suite_results.report })
    # Write out the report to a local file
    log_dir = File.join(RAILS_ROOT, 'log')
    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



1181
1182
1183
1184
1185
# File 'lib/openc3/utilities/running_script.rb', line 1181

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



1176
1177
1178
1179
# File 'lib/openc3/utilities/running_script.rb', line 1176

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



1166
1167
1168
1169
# File 'lib/openc3/utilities/running_script.rb', line 1166

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



1161
1162
1163
1164
# File 'lib/openc3/utilities/running_script.rb', line 1161

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



1171
1172
1173
1174
# File 'lib/openc3/utilities/running_script.rb', line 1171

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



383
384
385
# File 'lib/openc3/utilities/running_script.rb', line 383

def message_log
  self.class.message_log
end

#output_threadObject



1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
# File 'lib/openc3/utilities/running_script.rb', line 1447

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



566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'lib/openc3/utilities/running_script.rb', line 566

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



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

def pause
  @pause = true
  @go    = false
end

#pause?Boolean

Returns:

  • (Boolean)


641
642
643
# File 'lib/openc3/utilities/running_script.rb', line 641

def pause?
  @pause
end

#perform_breakpoint(filename, line_number) ⇒ Object



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

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



940
941
942
943
# File 'lib/openc3/utilities/running_script.rb', line 940

def perform_pause
  mark_paused()
  wait_for_go_or_stop()
end

#perform_wait(prompt) ⇒ Object



935
936
937
938
# File 'lib/openc3/utilities/running_script.rb', line 935

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

#post_line_instrumentation(filename, line_number) ⇒ Object



919
920
921
922
923
924
# File 'lib/openc3/utilities/running_script.rb', line 919

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



891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
# File 'lib/openc3/utilities/running_script.rb', line 891

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



1439
1440
1441
1442
1443
1444
1445
# File 'lib/openc3/utilities/running_script.rb', line 1439

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



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

def retry_needed
  @retry_needed = true
end

#runObject



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'lib/openc3/utilities/running_script.rb', line 771

def run
  if @script_status.suite_runner
    @script_status.suite_runner = JSON.parse(@script_status.suite_runner, :allow_nan => true, :create_additions => true) # Convert to hash
    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



1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
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
# File 'lib/openc3/utilities/running_script.rb', line 1242

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



324
325
326
# File 'lib/openc3/utilities/running_script.rb', line 324

def scope
  return @script_status.scope
end

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



1029
1030
1031
1032
1033
# File 'lib/openc3/utilities/running_script.rb', line 1029

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



616
617
618
619
620
621
# File 'lib/openc3/utilities/running_script.rb', line 616

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



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

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)


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

def stop?
  @stop
end

#stop_message_logObject



698
699
700
701
702
703
704
705
706
707
708
709
# File 'lib/openc3/utilities/running_script.rb', line 698

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



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

def text
  @body
end

#unique_filenameObject



690
691
692
693
694
695
696
# File 'lib/openc3/utilities/running_script.rb', line 690

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



561
562
563
564
# File 'lib/openc3/utilities/running_script.rb', line 561

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:



1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
# File 'lib/openc3/utilities/running_script.rb', line 1095

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:



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

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