-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathinstall
More file actions
executable file
·434 lines (371 loc) · 14.4 KB
/
install
File metadata and controls
executable file
·434 lines (371 loc) · 14.4 KB
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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
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
339
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
#!/usr/bin/env ruby
##################################################################
# This part of the code might be running on Ruby versions other
# than 2.0. Testing on multiple Ruby versions is required for
# changes to this part of the code.
##################################################################
class Proxy
instance_methods.each do |m|
undef_method m unless m =~ /(^__|^send$|^object_id$)/
end
def initialize(*targets)
@targets = targets
end
protected
def method_missing(name, *args, &block)
@targets.map do |target|
target.__send__(name, *args, &block)
end
end
end
log_file_path = "/tmp/codedeploy-agent.update.log"
require 'logger'
if($stdout.isatty)
# if we are being run in a terminal, log to stdout and the log file.
@log = Logger.new(Proxy.new(File.open(log_file_path, 'a+'), $stdout))
else
# keep at most 2MB of old logs rotating out 1MB at a time
@log = Logger.new(log_file_path, 2, 1048576)
# make sure anything coming out of ruby ends up in the log file
$stdout.reopen(log_file_path, 'a+')
$stderr.reopen(log_file_path, 'a+')
end
@log.level = Logger::INFO
begin
require 'fileutils'
require 'openssl'
require 'open-uri'
require 'uri'
require 'getoptlong'
require 'tempfile'
def usage
print <<EOF
install [--sanity-check] [--proxy http://hostname:port] <package-type>
--sanity-check [optional]
--proxy [optional]
package-type: 'rpm', 'deb', 'debdpkg' or 'auto'
Installs fetches the latest package version of the specified type and
installs it. rpms are installed with yum; debs are installed using gdebi.
The 'debdpkg' option forces the installation of deb packages with the dpkg command.
This program is invoked automatically to update the agent once per day using
the same package manager the codedeploy-agent is initially installed with.
To use this script for a hands free install on any system specify a package
type of 'auto'. This will detect if yum or gdebi is present on the system
and select the one present if possible. If both rpm and deb package managers
are detected the automatic detection will abort
When using the automatic setup, if the system has apt-get but not gdebi,
the gdebi will be installed using apt-get first.
If --sanity-check is specified, the install script will wait for 3 minutes post installation
to check for a running agent.
To use a HTTP proxy, specify --proxy followed by the proxy server
defined by http://hostname:port
This install script needs Ruby version 2.x installed as a prerequisite.
Currently recommanded Ruby versions are 2.0.0, 2.1.8, 2.2.4 and 2.3.0, and 2.4.0.
If multiple Ruby versions are installed, the default ruby version will be used.
If the default ruby version does not satisfy reqirement, the newest version will be used.
If you do not have a supported Ruby version installed, please install one of them first.
EOF
end
def supported_ruby_versions
['2.4', '2.3', '2.2', '2.1', '2.0']
end
# check ruby version, only version 2.x works
def check_ruby_version_and_symlink
@log.info("Starting Ruby version check.")
actual_ruby_version = RUBY_VERSION.split('.').map{|s|s.to_i}[0,2]
supported_ruby_versions.each do |version|
if ((actual_ruby_version <=> version.split('.').map{|s|s.to_i}) == 0)
return File.join(RbConfig::CONFIG["bindir"], RbConfig::CONFIG["RUBY_INSTALL_NAME"] + RbConfig::CONFIG["EXEEXT"])
end
end
supported_ruby_versions.each do |version|
if(File.exist?("/usr/bin/ruby#{version}"))
return "/usr/bin/ruby#{version}"
elsif (File.symlink?("/usr/bin/ruby#{version}"))
@log.error("The symlink /usr/bin/ruby#{version} exists, but it's linked to a non-existent directory or non-executable file.")
exit(1)
end
end
unsupported_ruby_version_error
exit(1)
end
def unsupported_ruby_version_error
@log.error("Current running Ruby version for "+ENV['USER']+" is "+RUBY_VERSION+", but Ruby version 2.x needs to be installed.")
@log.error('If you already have the proper Ruby version installed, please either create a symlink to /usr/bin/ruby2.x,')
@log.error( "or run this install script with right interpreter. Otherwise please install Ruby 2.x for "+ENV['USER']+" user.")
@log.error('You can get more information by running the script with --help option.')
end
def parse_args()
if (ARGV.length > 4)
usage
@log.error('Too many arguments.')
exit(1)
elsif (ARGV.length < 1)
usage
@log.error('Expected package type as argument.')
exit(1)
end
@sanity_check = false
@reexeced = false
@http_proxy = nil
@args = Array.new(ARGV)
opts = GetoptLong.new(['--sanity-check', GetoptLong::NO_ARGUMENT], ['--help', GetoptLong::NO_ARGUMENT], ['--re-execed', GetoptLong::NO_ARGUMENT], ['--proxy', GetoptLong::OPTIONAL_ARGUMENT])
opts.each do |opt, args|
case opt
when '--sanity-check'
@sanity_check = true
when '--help'
usage
when '--re-execed'
@reexeced = true
when '--proxy'
if (args != '')
@http_proxy = args
end
end
end
if (ARGV.length < 1)
usage
@log.error('Expected package type as argument.')
exit(1)
end
@type = ARGV.shift.downcase;
end
def force_ruby2x(ruby_interpreter_path)
# change interpreter when symlink /usr/bin/ruby2.x exists, but running with non-supported ruby version
actual_ruby_version = RUBY_VERSION.split('.').map{|s|s.to_i}
left_bound = '2.0.0'.split('.').map{|s|s.to_i}
right_bound = '2.4.1'.split('.').map{|s|s.to_i}
if (actual_ruby_version <=> left_bound) < 0
if(!@reexeced)
@log.info("The current Ruby version is not 2.x! Restarting the installer with #{ruby_interpreter_path}")
exec("#{ruby_interpreter_path}", __FILE__, '--re-execed' , *@args)
else
unsupported_ruby_version_error
exit(1)
end
elsif ((actual_ruby_version <=> right_bound) > 0)
@log.warn("The Ruby version in #{ruby_interpreter_path} is "+RUBY_VERSION+", . Attempting to install anyway.")
end
end
if (Process.uid != 0)
@log.error('Must run as root to install packages')
exit(1)
end
parse_args()
########## Force running as Ruby 2.x or fail here ##########
ruby_interpreter_path = check_ruby_version_and_symlink
force_ruby2x(ruby_interpreter_path)
def run_command(*args)
exit_ok = system(*args)
$stdout.flush
$stderr.flush
@log.debug("Exit code: #{$?.exitstatus}")
return exit_ok
end
def get_ec2_metadata_region
begin
uri = URI.parse('http://169.254.169.254/latest/meta-data/placement/availability-zone')
az = uri.read(:read_timeout => 120)
az.strip
rescue
@log.warn("Could not get region from EC2 metadata service at '#{uri.to_s}'")
return nil
end
if (az !~ /[a-z]{2}-[a-z]+-\d+[a-z]/)
@log.warn("Invalid availability zone name: '#{az}'.")
return nil
else
return az.chop
end
end
def get_region
@log.info('Checking AWS_REGION environment variable for region information...')
region = ENV['AWS_REGION']
return region if region
@log.info('Checking EC2 metadata service for region information...')
region = get_ec2_metadata_region
return region if region
@log.info('Using fail-safe default region: us-east-1')
return 'us-east-1'
end
def get_s3_uri(region, bucket, key)
if (region == 'us-east-1')
URI.parse("https://#{bucket}.s3.amazonaws.com/#{key}")
elsif (region.split("-")[0] == 'cn')
URI.parse("https://#{bucket}.s3.#{region}.amazonaws.com.cn/#{key}")
else
URI.parse("https://#{bucket}.s3-#{region}.amazonaws.com/#{key}")
end
end
def get_package_from_s3(region, bucket, key, package_file)
@log.info("Downloading package from bucket #{bucket} and key #{key}...")
uri = get_s3_uri(region, bucket, key)
# stream package file to disk
retries ||= 0
exceptions = [OpenURI::HTTPError, OpenSSL::SSL::SSLError]
begin
uri.open(:ssl_verify_mode => OpenSSL::SSL::VERIFY_PEER, :redirect => true, :read_timeout => 120, :proxy => @http_proxy) do |s3|
package_file.write(s3.read)
end
rescue *exceptions => e
@log.error("Could not find package to download at '#{uri.to_s}' - Retrying... Attempt: '#{retries.to_s}'")
if (retries < 5)
sleep 2 ** retries
retries += 1
retry
else
@log.error("Could not download CodeDeploy Agent Package. Exiting Install script.")
exit(1)
end
end
end
def get_version_file_from_s3(region, bucket, key)
@log.info("Downloading version file from bucket #{bucket} and key #{key}...")
uri = get_s3_uri(region, bucket, key)
begin
require 'json'
version_string = uri.read(:ssl_verify_mode => OpenSSL::SSL::VERIFY_PEER, :redirect => true, :read_timeout => 120, :proxy => @http_proxy)
JSON.parse(version_string)
rescue OpenURI::HTTPError => e
@log.error("Could not find version file to download at '#{uri.to_s}'")
exit(1)
end
end
def install_from_s3(region, bucket, version_file_key, type, install_cmd)
version_data = get_version_file_from_s3(region, bucket, version_file_key)
package_key = version_data[type]
package_base_name = File.basename(package_key)
package_extension = File.extname(package_base_name)
package_name = File.basename(package_base_name, package_extension)
package_file = Tempfile.new(["#{package_name}.tmp-", package_extension]) # unique file with 0600 permissions
get_package_from_s3(region, bucket, package_key, package_file)
package_file.close
install_cmd << package_file.path
@log.info("Executing `#{install_cmd.join(" ")}`...")
if (!run_command(*install_cmd))
@log.error("Error installing #{package_file.path}.")
package_file.unlink
exit(1)
end
package_file.unlink
end
def do_sanity_check(cmd)
if @sanity_check
@log.info("Waiting for 3 minutes before I check for a running agent")
sleep(3 * 60)
res = run_command(cmd, 'codedeploy-agent', 'status')
if (res.nil? || res == false)
@log.info("No codedeploy agent seems to be running. Starting the agent.")
run_command(cmd, 'codedeploy-agent', 'start-no-update')
end
end
end
@log.info("Starting update check.")
if (@type == 'auto')
@log.info('Attempting to automatically detect supported package manager type for system...')
has_yum = run_command('which yum >/dev/null 2>/dev/null')
has_apt_get = run_command('which apt-get >/dev/null 2>/dev/null')
has_gdebi = run_command('which gdebi >/dev/null 2>/dev/null')
has_zypper = run_command('which zypper >/dev/null 2>/dev/null')
if (has_yum && (has_apt_get || has_gdebi))
@log.error('Detected both supported rpm and deb package managers. Please specify which package type to use manually.')
exit(1)
end
if(has_yum)
@type = 'rpm'
elsif(has_zypper)
@type = 'zypper'
elsif(has_gdebi)
@type = 'deb'
elsif(has_apt_get)
@type = 'deb'
@log.warn('apt-get found but no gdebi. Installing gdebi with `apt-get install gdebi-core -y`...')
#use -y to answer yes to confirmation prompts
if(!run_command('/usr/bin/apt-get', 'install', 'gdebi-core', '-y'))
@log.error('Could not install gdebi.')
exit(1)
end
else
@log.error('Could not detect any supported package managers.')
exit(1)
end
end
region = get_region
bucket = "aws-codedeploy-#{region}"
version_file_key = 'latest/VERSION'
case @type
when 'help'
usage
when 'rpm'
running_version = `rpm -q codedeploy-agent`
running_version.strip!
target_version = get_version_file_from_s3(region, bucket, version_file_key)['rpm']
if target_version.include? running_version
@log.info('Running version matches target version, skipping install')
else
#use -y to answer yes to confirmation prompts
install_cmd = ['/usr/bin/yum', '-y', 'localinstall']
install_from_s3(region, bucket, version_file_key, @type, install_cmd)
do_sanity_check('/sbin/service')
end
when 'deb'
running_agent = `dpkg -s codedeploy-agent`
running_agent_info = running_agent.split
version_index = running_agent_info.index('Version:')
if !version_index.nil?
running_version = running_agent_info[version_index + 1]
else
running_version = "No running version"
end
@log.info("Running version " + running_version)
target_version = get_version_file_from_s3(region, bucket, version_file_key)['deb']
if target_version.include? running_version
@log.info('Running version matches target version, skipping install')
else
#use -n for non-interactive mode
#use -o to not overwrite config files unless they have not been changed
install_cmd = ['/usr/bin/gdebi', '-n', '-o', 'Dpkg::Options::=--force-confdef', '-o', 'Dpkg::Options::=--force-confold']
install_from_s3(region, bucket, version_file_key, @type, install_cmd)
do_sanity_check('/usr/sbin/service')
end
when 'zypper'
#use -n for non-interactive mode
install_cmd = ['/usr/bin/zypper', 'install', '-n']
install_from_s3(region, bucket, version_file_key, 'rpm', install_cmd)
when 'debdpkg'
running_agent = `dpkg -s codedeploy-agent`
running_agent_info = running_agent.split
version_index = running_agent_info.index('Version:')
if !version_index.nil?
running_version = running_agent_info[version_index + 1]
else
running_version = "No running version"
end
@log.info("Running version " + running_version)
target_version = get_version_file_from_s3(region, bucket, version_file_key)['deb']
if target_version.include? running_version
@log.info('Running version matches target version, skipping install')
else
#use --force-confdef,confold to ignore existing config files
install_cmd = ['/usr/bin/dpkg', '--install', '--force-confdef,confold']
install_from_s3(region, bucket, version_file_key, "deb", install_cmd)
do_sanity_check('/usr/sbin/service')
end
else
@log.error("Unsupported package type '#{@type}'")
exit(1)
end
@log.info("Update check complete.")
@log.info("Stopping updater.")
rescue SystemExit => e
# don't log exit() as an error
raise e
rescue Exception => e
# make sure all unhandled exceptions are logged to the log
@log.error("Unhandled exception: #{e.inspect}")
e.backtrace.each do |line|
@log.error(" at " + line)
end
exit(1)
end