Class: Script

Inherits:
OpenC3::TargetFile show all
Defined in:
lib/openc3/utilities/script.rb

Constant Summary

Constants inherited from OpenC3::TargetFile

OpenC3::TargetFile::TEMP_FOLDER

Class Method Summary collapse

Methods inherited from OpenC3::TargetFile

body, remote_target_files

Class Method Details

.all(scope, target = nil) ⇒ Object



28
29
30
# File 'lib/openc3/utilities/script.rb', line 28

def self.all(scope, target = nil)
  super(scope, nil, target: target) # No path matchers
end

.create(params) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/openc3/utilities/script.rb', line 165

def self.create(params)
  existing = body(params[:scope], params[:name])
  # Commit if there is no existing or something has changed
  if existing.nil? or existing != params[:text]
    super(params[:scope], params[:name], params[:text])
  end
  breakpoints = params[:breakpoints]
  if breakpoints
    if breakpoints.empty?
      OpenC3::Store.hdel("#{params[:scope]}__script-breakpoints", params[:name])
    else
      OpenC3::Store.hset("#{params[:scope]}__script-breakpoints", params[:name],
        breakpoints.as_json().to_json(allow_nan: true))
    end
  end
end

.delete_temp(scope) ⇒ Object



182
183
184
185
186
187
188
# File 'lib/openc3/utilities/script.rb', line 182

def self.delete_temp(scope)
  files = super(scope)
  files.each do |name|
    # Remove any breakpoints associated with the temp files
    OpenC3::Store.hdel("#{scope}__script-breakpoints", "#{TEMP_FOLDER}/#{File.basename(name)}")
  end
end

.destroy(scope, name) ⇒ Object



190
191
192
193
# File 'lib/openc3/utilities/script.rb', line 190

def self.destroy(scope, name)
  super(scope, name)
  OpenC3::Store.hdel("#{scope}__script-breakpoints", name)
end

.detect_language(text, filename = nil) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/openc3/utilities/script.rb', line 276

def self.detect_language(text, filename = nil)
  if filename
    extension = File.extname(filename)
    if extension == '.rb'
      return 'ruby'
    elsif extension == '.py'
      return 'python'
    elsif extension.length > 0
      return 'other'
    end
  end

  return 'ruby' if text =~ /^\s*(require|load|puts) /
  return 'python' if text =~ /^\s*(import|from) /
  return 'ruby' if text =~ /^\s*end\s*$/
  return 'python' if text =~ /^\s*(if|def|while|else|elif|class).*:\s*$/
  return 'ruby' # otherwise guess Ruby
end

.get_breakpoints(scope, name) ⇒ Object



49
50
51
52
53
# File 'lib/openc3/utilities/script.rb', line 49

def self.get_breakpoints(scope, name)
  breakpoints = OpenC3::Store.hget("#{scope}__script-breakpoints", name.split('*')[0]) # Split '*' that indicates modified
  return JSON.parse(breakpoints, allow_nan: true, create_additions: true) if breakpoints
  []
end

.instrumented(filename, text) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/openc3/utilities/script.rb', line 209

def self.instrumented(filename, text)
  language = detect_language(text, filename)
  if language == 'ruby'
    return {
      'title' => 'Instrumented Script',
      'description' =>
        RunningScript.instrument_script(
          text,
          filename,
          true,
        ).split("\n").as_json().to_json(allow_nan: true),
    }
  elsif language == 'python'
    start = Time.now
    temp = Tempfile.new(%w[instrument .py])
    temp.write(text)
    temp.close

    runner_path = File.join(RAILS_ROOT, 'scripts', 'run_instrument.py')
    process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
    process = ChildProcess.build(process_name, runner_path.to_s, temp.path)
    process.cwd = File.join(RAILS_ROOT, 'scripts')

    stdout = Tempfile.new("child-stdout")
    stdout.sync = true
    stderr = Tempfile.new("child-stderr")
    stderr.sync = true
    process.io.stdout = stdout
    process.io.stderr = stderr
    process.start
    process.wait
    stdout.rewind
    stdout_results = stdout.read
    stdout.close
    stdout.unlink
    stderr.rewind
    stderr_results = stderr.read
    stderr.close
    stderr.unlink
    success = process.exit_code == 0
    puts "Processed Instrumenting #{filename} in #{Time.now - start} seconds"
    # Make sure we're getting the last line which should be the suite
    puts "Stdout Results:#{stdout_results}:"
    puts "Stderr Results:#{stderr_results}:"
    # stdout_results = stdout_results.split("\n")[-1] if stdout_results

    if success
      return {
        'title' => 'Instrumented Script',
        'description' =>
          stdout_results.to_s.split("\n").as_json().to_json(allow_nan: true),
      }
    else
      return {
        'title' => 'Error Instrumenting Script',
        'description' =>
          (stdout_results.to_s + stderr_results.to_s).split("\n").as_json().to_json(allow_nan: true),
      }
    end
  else
    return {
      'title' => 'Instrumenting Not Supported',
      'description' => ['Only Ruby and Python Support Viewing Instrumentation'].as_json.to_json,
    }
  end
end

.lock(scope, name, username) ⇒ Object



32
33
34
35
# File 'lib/openc3/utilities/script.rb', line 32

def self.lock(scope, name, username)
  name = name.split('*')[0] # Split '*' that indicates modified
  OpenC3::Store.hset("#{scope}__script-locks", name, username)
end

.locked?(scope, name) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
# File 'lib/openc3/utilities/script.rb', line 42

def self.locked?(scope, name)
  name = name.split('*')[0] # Split '*' that indicates modified
  locked_by = OpenC3::Store.hget("#{scope}__script-locks", name)
  locked_by ||= false
  locked_by
end

.mnemonics(filename, text) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/openc3/utilities/script.rb', line 295

def self.mnemonics(filename, text)
  # Ruby and Python are currently handled in-browser
  # Script Engine Possibly
  extension = File.extname(filename).to_s.downcase
  script_engine_model = OpenC3::ScriptEngineModel.get_model(name: extension, scope: 'DEFAULT')
  if script_engine_model
    script_engine = script_engine_model.filename
    if File.extname(script_engine).to_s.downcase == '.py'
      process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
      runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.py')
    else
      process_name = 'ruby'
      runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.rb')
    end

    tf = nil
    begin
      tf = Tempfile.new((['mnemonics', extension]))
      tf.write(text)
      tf.close()
      results, status = Open3.capture2e("#{process_name} \"#{runner_path}\" mnemonic_check \"#{tf.path}\"")
      lines = []
      if results and results.length > 0
        results.each_line do |line|
          lines << line
        end
        return(
          { 'title' => 'Mnemonics Check Failed', 'description' => lines.as_json().to_json(allow_nan: true) }
        )
      else
        return(
          {
            'title' => 'Mnemonics Check Successful',
            'description' => ["Mnemonics OK"].as_json().to_json(allow_nan: true),
          }
        )
      end
    ensure
      tf.unlink if tf
    end
  else
    raise "Unsupported script file type: #{extension}"
  end
end

.process_suite(name, contents, new_process: true, username: nil, scope:) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/openc3/utilities/script.rb', line 55

def self.process_suite(name, contents, new_process: true, username: nil, scope:)
  python = false
  python = true if File.extname(name) == '.py'

  start = Time.now

  if python
    temp = Tempfile.new(%w[suite .py])
  else
    temp = Tempfile.new(%w[suite .rb])
  end

  # Remove any carriage returns which ruby doesn't like
  temp.write(contents.gsub(/\r/, ' '))
  temp.close

  # We open a new process so as to not pollute the API with require
  success = true
  if new_process or python
    if python
      runner_path = File.join(RAILS_ROOT, 'scripts', 'run_suite_analysis.py')
      process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
      process = ChildProcess.build(process_name, runner_path.to_s, scope, temp.path)
    else
      runner_path = File.join(RAILS_ROOT, 'scripts', 'run_suite_analysis.rb')
      process = ChildProcess.build('ruby', runner_path.to_s, scope, temp.path)
    end
    process.cwd = File.join(RAILS_ROOT, 'scripts')

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

    # Set proper secrets for running script
    process.environment['SECRET_KEY_BASE'] = nil
    process.environment['OPENC3_REDIS_USERNAME'] = ENV['OPENC3_SR_REDIS_USERNAME'] || 'OPENC3_SR_REDIS_USERNAME not set'
    process.environment['OPENC3_REDIS_PASSWORD'] = ENV['OPENC3_SR_REDIS_PASSWORD'] || 'OPENC3_SR_REDIS_PASSWORD not set'
    process.environment['OPENC3_BUCKET_USERNAME'] = ENV['OPENC3_SR_BUCKET_USERNAME'] || 'OPENC3_SR_BUCKET_USERNAME not set'
    process.environment['OPENC3_BUCKET_PASSWORD'] = ENV['OPENC3_SR_BUCKET_PASSWORD'] || 'OPENC3_SR_BUCKET_PASSWORD not set'
    process.environment['OPENC3_SR_REDIS_USERNAME'] = nil
    process.environment['OPENC3_SR_REDIS_PASSWORD'] = nil
    process.environment['OPENC3_SR_BUCKET_USERNAME'] = nil
    process.environment['OPENC3_SR_BUCKET_PASSWORD'] = nil
    process.environment['OPENC3_API_CLIENT'] = ENV['OPENC3_API_CLIENT'] || 'api'
    if model and model.offline_access_token
      auth = OpenC3::OpenC3KeycloakAuthentication.new(ENV['OPENC3_KEYCLOAK_URL'])
      valid_token = auth.get_token_from_refresh_token(model.offline_access_token)
      if valid_token
        process.environment['OPENC3_API_TOKEN'] = model.offline_access_token
      else
        model.offline_access_token = nil
        model.update
        raise "offline_access token invalid for script"
      end
    else
      process.environment['OPENC3_API_USER'] = ENV['OPENC3_API_USER'] || nil
      if ENV['OPENC3_SERVICE_PASSWORD']
        process.environment['OPENC3_API_PASSWORD'] = ENV['OPENC3_SERVICE_PASSWORD']
      else
        # The viewer user doesn't have an offline access token (because they can't run scripts)
        # but they still want to be able to view suite files
        # Since processing a suite file requires running it they won't get the Suite chrome
        # so return nothing here and allow Script Runner to simply view the suite file
        return '', '', false
      end
    end
    process.environment['GEM_HOME'] = ENV['GEM_HOME'] || '/gems'
    process.environment['PYTHONUSERBASE'] = ENV['PYTHONUSERBASE'] || '/gems/python_packages'
    # 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

    stdout = Tempfile.new("child-stdout")
    stdout.sync = true
    stderr = Tempfile.new("child-stderr")
    stderr.sync = true
    process.io.stdout = stdout
    process.io.stderr = stderr
    process.start
    process.wait
    stdout.rewind
    stdout_results = stdout.read
    stdout.close
    stdout.unlink
    stderr.rewind
    stderr_results = stderr.read
    stderr.close
    stderr.unlink
    success = process.exit_code == 0
  else
    require temp.path
    stdout_results = OpenC3::SuiteRunner.build_suites.as_json().to_json(allow_nan: true)
  end
  temp.delete
  puts "Processed #{name} in #{Time.now - start} seconds"
  # Make sure we're getting the last line which should be the suite
  puts "Stdout Results:#{stdout_results}:"
  puts "Stderr Results:#{stderr_results}:"
  stdout_results = stdout_results.split("\n")[-1] if stdout_results
  return stdout_results, stderr_results, success
end

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



195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/openc3/utilities/script.rb', line 195

def self.run(
  scope,
  name,
  suite_runner = nil,
  disconnect = false,
  environment = nil,
  user_full_name = nil,
  username = nil,
  line_no = nil,
  end_line_no = nil
)
  RunningScript.spawn(scope, name, suite_runner, disconnect, environment, user_full_name, username, line_no, end_line_no)
end

.syntax(filename, text) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
# File 'lib/openc3/utilities/script.rb', line 340

def self.syntax(filename, text)
  if text.nil?
    return(
      { 'title' => 'Syntax Check Failed', 'description' => 'no text passed' }
    )
  end
  language = detect_language(text, filename)
  if language == 'ruby'
    check_process = IO.popen('ruby -c -rubygems 2>&1', 'r+')
    check_process.write("require 'openc3'; require 'openc3/script'; " + text)
    check_process.close_write
    results = check_process.readlines
    check_process.close
    if results
      if results.any?(/Syntax OK/)
        return(
          {
            'title' => 'Syntax Check Successful',
            'description' => results.as_json().to_json(allow_nan: true),
          }
        )
      else
        # Results is an array of strings like this: ":2: syntax error ..."
        # Normally the procedure comes before the first colon but since we
        # are writing to the process this is blank so we throw it away
        results.map! { |result| result.split(':')[1..-1].join(':') }
        return(
          { 'title' => 'Syntax Check Failed', 'description' => results.as_json().to_json(allow_nan: true) }
        )
      end
    else
      return(
        {
          'title' => 'Syntax Check Exception',
          'description' => 'Ruby syntax check unexpectedly returned nil',
        }
      )
    end
  elsif language == 'python'
    # Python
    tf = nil
    begin
      tf = Tempfile.new((['syntax', '.py']))
      tf.write(text)
      tf.close()
      process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
      results, status = Open3.capture2e("#{process_name} -m py_compile #{tf.path}")
      lines = []
      success = status.respond_to?(:success?) ? status.success? : status == 0
      if !success || (results and results.length > 0)
        results.each_line do |line|
          lines << line
        end
        lines << "Syntax Error" if lines.empty?
        return(
          { 'title' => 'Syntax Check Failed', 'description' => lines.as_json().to_json(allow_nan: true) }
        )
      else
        return(
          {
            'title' => 'Syntax Check Successful',
            'description' => ["Syntax OK"].as_json().to_json(allow_nan: true),
          }
        )
      end
    ensure
      tf.unlink if tf
    end
  else
    # Script Engine Possibly
    extension = File.extname(filename).to_s.downcase
    script_engine_model = OpenC3::ScriptEngineModel.get_model(name: extension, scope: 'DEFAULT')
    if script_engine_model
      script_engine = script_engine_model.filename
      if File.extname(script_engine).to_s.downcase == '.py'
        process_name = ENV['OPENC3_PYTHON_BIN'] || '/openc3/python/.venv/bin/python'
        runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.py')
      else
        process_name = 'ruby'
        runner_path = File.join(RAILS_ROOT, 'scripts', 'script_engine_cmd.rb')
      end

      tf = nil
      begin
        tf = Tempfile.new((['syntax', extension]))
        tf.write(text)
        tf.close()
        results, status = Open3.capture2e("#{process_name} \"#{runner_path}\" syntax_check \"#{tf.path}\"")
        lines = []
        if results and results.length > 0
          results.each_line do |line|
            lines << line
          end
          return(
            { 'title' => 'Syntax Check Failed', 'description' => lines.as_json().to_json(allow_nan: true) }
          )
        else
          return(
            {
              'title' => 'Syntax Check Successful',
              'description' => ["Syntax OK"].as_json().to_json(allow_nan: true),
            }
          )
        end
      ensure
        tf.unlink if tf
      end
    else
      raise "Unsupported script file type: #{extension}"
    end
  end
end

.unlock(scope, name) ⇒ Object



37
38
39
40
# File 'lib/openc3/utilities/script.rb', line 37

def self.unlock(scope, name)
  name = name.split('*')[0] # Split '*' that indicates modified
  OpenC3::Store.hdel("#{scope}__script-locks", name)
end