CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/rex/job.rb
Views: 11766
1
# -*- coding: binary -*-
2
module Rex
3
4
###
5
#
6
# This class is the concrete representation of an abstract job.
7
#
8
###
9
class Job
10
11
#
12
# Creates an individual job instance and initializes it with the supplied
13
# parameters.
14
#
15
def initialize(container, jid, name, ctx, run_proc, clean_proc)
16
self.container = container
17
self.jid = jid
18
self.name = name
19
self.run_proc = run_proc
20
self.clean_proc = clean_proc
21
self.ctx = ctx
22
self.start_time = nil
23
self.cleanup_mutex = Mutex.new
24
self.cleaned_up = false
25
end
26
27
def synchronized_cleanup
28
# Avoid start and stop both calling cleanup
29
self.cleanup_mutex.synchronize do
30
unless cleaned_up
31
self.cleaned_up = true
32
self.clean_proc.call(ctx) if self.clean_proc
33
end
34
end
35
end
36
37
#
38
# Runs the job in the context of its own thread if the async flag is false.
39
# Otherwise, the job is run inline.
40
#
41
def start(async = false)
42
self.start_time = ::Time.now
43
if (async)
44
self.job_thread = Rex::ThreadFactory.spawn("JobID(#{jid})-#{name}", false) {
45
# Deschedule our thread momentarily
46
::IO.select(nil, nil, nil, 0.01)
47
48
begin
49
run_proc.call(ctx)
50
ensure
51
synchronized_cleanup
52
container.remove_job(self)
53
end
54
}
55
else
56
begin
57
run_proc.call(ctx)
58
rescue ::Exception
59
container.stop_job(jid)
60
raise $!
61
end
62
end
63
end
64
65
#
66
# Stops the job if it's currently running and calls its cleanup procedure
67
#
68
def stop
69
if (self.job_thread)
70
self.job_thread.kill
71
self.job_thread = nil
72
end
73
74
synchronized_cleanup
75
end
76
77
#
78
# The name of the job.
79
#
80
attr_reader :name
81
82
#
83
# The job identifier as assigned by the job container.
84
#
85
attr_reader :jid
86
87
#
88
# The time at which this job was started.
89
#
90
attr_reader :start_time
91
92
#
93
# Some job context.
94
#
95
attr_reader :ctx
96
97
protected
98
99
attr_writer :name #:nodoc:
100
attr_writer :jid #:nodoc:
101
attr_accessor :job_thread #:nodoc:
102
attr_accessor :container #:nodoc:
103
attr_accessor :run_proc #:nodoc:
104
attr_accessor :clean_proc #:nodoc:
105
attr_writer :ctx #:nodoc:
106
attr_writer :start_time #:nodoc:
107
attr_accessor :cleanup_mutex #:nodoc:
108
attr_accessor :cleaned_up #:nodoc:
109
110
end
111
112
end
113
114