forked from zendesk/samson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob_execution.rb
235 lines (185 loc) · 4.95 KB
/
job_execution.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
require 'thread_safe'
require 'airbrake'
class JobExecution
# Whether or not execution is enabled. This allows completely disabling job
# execution for testing purposes.
cattr_accessor(:enabled, instance_reader: true) do
Rails.application.config.samson.enable_job_execution
end
# The directory in which repositories should be cached.
cattr_accessor(:cached_repos_dir, instance_reader: true) do
Rails.application.config.samson.cached_repos_dir
end
attr_reader :output
attr_reader :job
attr_reader :viewers
def initialize(reference, job)
@output = OutputBuffer.new
@executor = TerminalExecutor.new(@output)
@viewers = JobViewers.new(@output)
@subscribers = []
@job, @reference = job, reference
end
def start!
ActiveRecord::Base.clear_active_connections!
@thread = Thread.new do
begin
run!
rescue => e
error!(e)
ensure
@output.close unless @output.closed?
ActiveRecord::Base.clear_active_connections!
JobExecution.finished_job(@job)
end
end
end
def error!(exception)
message = "JobExecution failed: #{exception.message}"
Airbrake.notify(exception,
error_message: message,
parameters: {
job_id: @job.id
}
)
@output.write(message + "\n")
@job.error! if @job.active?
end
def run!
@job.run!
output_aggregator = OutputAggregator.new(@output)
result = Dir.mktmpdir do |dir|
execute!(dir)
end
ActiveRecord::Base.connection.verify!
if result
@job.success!
else
@job.fail!
end
@output.close
@job.update_output!(output_aggregator.to_s)
@subscribers.each do |subscriber|
subscriber.call(@job)
end
end
def wait!
@thread.try(:join)
end
def stop!
@executor.stop!
wait!
end
def subscribe(&block)
@subscribers << block
end
private
def execute!(dir)
unless setup!(dir)
if ProjectLock.owned?(@job.project)
ProjectLock.release(@job.project)
end
@job.error!
return
end
FileUtils.mkdir_p(artifact_cache_dir)
@output.write("Executing deploy\n")
commands = [
"export DEPLOYER=#{@job.user.email}",
"export DEPLOYER_EMAIL=#{@job.user.email}",
"export DEPLOYER_NAME=\"#{@job.user.name}\"",
"export REVISION=#{@reference}",
"export CACHE_DIR=#{artifact_cache_dir}",
"cd #{dir}",
*@job.commands
]
ActiveRecord::Base.clear_active_connections!
@executor.execute!(*commands)
end
def setup!(dir)
repo_url = @job.project.repository_url
@output.write("Beginning git repo setup\n")
commands = [
<<-SHELL,
if [ -d #{repo_cache_dir} ]
then cd #{repo_cache_dir} && git fetch -ap
else
git -c core.askpass=true clone --mirror #{repo_url} #{repo_cache_dir}
fi
SHELL
"git clone #{repo_cache_dir} #{dir}",
"cd #{dir}",
"git checkout --quiet #{@reference}"
]
@output.write("Attempting to lock repository...\n")
if grab_lock
@output.write("Repo locked, starting to clone...\n")
@executor.execute!(*commands).tap do |status|
if status
commit = commit_from_ref(repo_cache_dir, @reference)
ActiveRecord::Base.connection.verify!
@job.update_commit!(commit)
ProjectLock.release(@job.project)
end
end
else
@output.write("Could not get exclusive lock on repo. Maybe another stage is being deployed.\n")
false
end
end
def commit_from_ref(repo_dir, ref)
description = Dir.chdir(repo_dir) do
Tempfile.create("ref-description") do |file|
system("git", "describe", "--long", "--tags", "--all", ref, out: file.fileno)
file.rewind
file.read.strip
end
end
description.split("-").last.sub(/^g/, "")
end
def repo_cache_dir
File.join(cached_repos_dir, @job.project_id.to_s)
end
def artifact_cache_dir
File.join(repo_cache_dir, "artifacts")
end
def grab_lock
lock = false
end_time = Time.now + 10.minutes
holder = @job.deploy ? @job.deploy.stage.name : @job.user.name
until lock || Time.now > end_time
sleep 1
if Time.now.to_i % 10 == 0
@output.write("Waiting for repository while cloning for: #{ProjectLock.owner(@job.project)}\n")
end
lock ||= ProjectLock.grab(@job.project, holder)
end
lock
end
class << self
def setup
Thread.main[:job_executions] = ThreadSafe::Hash.new
end
def find_by_job(job)
find_by_id(job.id)
end
def find_by_id(id)
registry[id.to_i]
end
def start_job(reference, job)
new(reference, job).tap do |job_execution|
registry[job.id] = job_execution.tap(&:start!) if enabled
end
end
def all
registry.values
end
def finished_job(job)
registry.delete(job.id)
end
private
def registry
Thread.main[:job_executions]
end
end
end