Class: Themigrator::Script

Inherits:
Object
  • Object
show all
Defined in:
lib/themigrator/script.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script, log_file, attr = {}, &finish_cbk) ⇒ Script

new creates a new script but doesn’t start until called run Arguments:

  • script : Fullpath of the file to execute

  • log_file: Fullpath of the file to save the log

  • attr: Extra attributes that could be handy (not used internally by Script)

  • finish_cbk: A block that will receive the following arguments

    1 The script itself
    


15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/themigrator/script.rb', line 15

def initialize(script, log_file, attr = {}, &finish_cbk)
  require 'byebug'
  @attr = attr
  @script = script
  @log_file = log_file
  @log_fd = File.open(@log_file, "w", 0600)
  @wd_dir = File.dirname(script)
  @pid = nil
  @thread = nil
  @start_time = Time.now
  @end_time = nil
  @finish_cbk = finish_cbk
end

Instance Attribute Details

#attrObject (readonly)

Returns the value of attribute attr.



5
6
7
# File 'lib/themigrator/script.rb', line 5

def attr
  @attr
end

#log_fileObject (readonly)

Returns the value of attribute log_file.



5
6
7
# File 'lib/themigrator/script.rb', line 5

def log_file
  @log_file
end

#scriptObject (readonly)

Returns the value of attribute script.



5
6
7
# File 'lib/themigrator/script.rb', line 5

def script
  @script
end

Instance Method Details

#exitcodeObject



67
68
69
# File 'lib/themigrator/script.rb', line 67

def exitcode
  @thread.value
end

#invoke_cbksObject



58
59
60
# File 'lib/themigrator/script.rb', line 58

def invoke_cbks
  @finish_cbk.call(self)  
end

#runObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/themigrator/script.rb', line 33

def run
  @thread = Thread.new do
	@pid = Process.spawn(@script, 
    err: @log_fd, 
    out: @log_fd, 
    chdir: @wd_dir)
	pid, status = Process.wait2(@pid)
	@end_time = Time.now
	close
	return_code = if status.signaled?
	  signal = Signal.list.find{|k,v|
 v == status.termsig
	  }
	  signal.nil? ? :unknown_signal : signal[0].downcase.to_sym
	else
	  status.exitstatus
	end

	Thread.new { invoke_cbks } if @finish_cbk

	return_code
  end
  sleep 0
end

#run_timeObject



29
30
31
# File 'lib/themigrator/script.rb', line 29

def run_time
  @end_time - @start_time if @end_time
end

#stopObject



71
72
73
74
75
76
77
78
79
# File 'lib/themigrator/script.rb', line 71

def stop
  if running?
	send_int
	if wait(5) == nil
	  send_kill
	end
	wait
  end
end

#success?Boolean

Returns:

  • (Boolean)


81
82
83
# File 'lib/themigrator/script.rb', line 81

def success?
  exitcode == 0
end

#wait(seconds = nil) ⇒ Object

Waits for the process to be over



63
64
65
# File 'lib/themigrator/script.rb', line 63

def wait(seconds = nil)
  @thread.join(seconds) 
end