Class: HDeploy::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/hdeploy/cli.rb

Instance Method Summary collapse

Constructor Details

#initializeCLI

Returns a new instance of CLI.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/hdeploy/cli.rb', line 10

def initialize
  @config = HDeploy::Conf.instance
  @client = HDeploy::APIClient.instance
  @domain_name = @conf['cli']['domain_name']
  @app = @conf['cli']['default_app']
  @env = @conf['cli']['default_env']
  @force = false
  @fakebuild = false


  @conf.each do |k|
    next unless k[0..3] == 'app:'
    @conf[k].each do |k2,v|
      @conf[k][k2] = File.expand_path(v) if k2 =~ /\_path$/
    end
  end
end

Instance Method Details

#app(newapp) ⇒ Object




96
97
98
99
# File 'lib/hdeploy/cli.rb', line 96

def app(newapp)
  @app = newapp
  puts "set app to #{newapp}"
end

#build(branch = 'master') ⇒ Object



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
452
453
454
455
456
457
458
# File 'lib/hdeploy/cli.rb', line 357

def build(branch = 'master')

  prune_build_env

  # Starting now..
  start_time = Time.new

  # Copy GIT directory
  c = @conf['build'][@app]
  repo = File.expand_path(c['repo'])

  raise "Error in source dir #{repo}. Please run hdeploy initrepo" unless Dir.exists? (File.join(repo, '.git'))
  directory = File.expand_path(File.join(c['build_dir'], (@app + start_time.strftime('.%Y%m%d_%H_%M_%S.'))) + ENV['USER'] + (@fakebuild? '.fakebuild' : ''))
  FileUtils.mkdir_p directory

  # Update GIT directory
  Dir.chdir(repo)

  subgit  = `find . -mindepth 2 -name .git -type d`
  if subgit.length > 0
    subgit.split("\n").each do |d|
      if Dir.exists? d
        FileUtils.rm_rf d
      end
    end
  end

  [
    'git clean -xdf',
    'git reset --hard HEAD',
    'git clean -xdf',
    'git checkout master',
    'git pull',
    'git remote show origin',
    'git remote prune origin',
  ].each do |cmd|
    mysystem(cmd)
  end

  # Choose branch
  mysystem("git checkout #{branch}")

  if branch != 'master'
    [
      'git reset --hard HEAD',
      'git clean -xdf',
      'git pull'
    ].each do |cmd|
      mysystem(cmd)
    end
  end


  # Copy GIT
  if c['subdir'].empty?
    mysystem "rsync -av --exclude=.git #{c['repo']}/ #{directory}/"
  else
    mysystem "rsync -av --exclude=.git #{c['repo']}/c['subdir']/ #{directory}/"
  end

  # Get a tag
  gitrev = (`git log -1 --pretty=oneline`)[0..11] # not 39.
  build_tag = @app + start_time.strftime('.%Y%m%d_%H_%M_%S.') + branch + '.' + gitrev + '.' + ENV['USER'] + (@fakebuild? '.fakebuild' : '')

  notify "build start - #{ENV['USER']} - #{build_tag}"

  Dir.chdir(directory)

  # Write the tag in the dest directory
  File.write 'REVISION', (gitrev + "\n")

  # Run the build process # FIXME: add sanity check
  try_files = %w[build.sh build/build.sh hdeploy/build.sh]
  if File.exists? 'hdeploy.ini'
    repoconf = IniFile.load('hdeploy.ini')['global']
    try_files.unshift(repoconf['build_script']) if repoconf['build_script']
  end

  unless @fakebuild
    build_script = false
    try_files.each do |f|
      if File.exists?(f) and File.executable?(f)
        build_script = f
        break
      end
    end

    raise "no executable build script file. Tried files: #{try_files.join(' ')}" unless build_script
    mysystem(build_script)
  end

  # Make tarball
  FileUtils.mkdir_p c['artifacts']
  mysystem("tar czf #{File.join(c['artifacts'],build_tag)}.tar.gz .")

  # FIXME: upload to S3
  register_tarball(build_tag)

  notify "build success - #{ENV['USER']} - #{build_tag}"

  prune_build_env
end

#distribute(build_tag) ⇒ Object



477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/hdeploy/cli.rb', line 477

def distribute(build_tag)
  r = @client.put("/distribute/#{@app}/#{@env}",build_tag)
  if r =~ /^OK /
    h = JSON.parse(@client.get("/srv/by_app/#{@app}/#{@env}"))

    # On all servers, do a standard check deploy.
    system("#{_fab} -f $(hdeploy_filepath fabfile.py) -H #{h.keys.join(',')} -P host_monkeypatch:#{@domain_name} -- sudo hdeploy_node check_deploy")

    # And on a single server, run the single hook.
    hookparams = { app: @app, env: @env, artifact: build_tag, servers:h.keys.join(','), user: ENV['USER'] }.collect {|k,v| "#{k}:#{v}" }.join(" ")
    system("#{_fab} -f $(hdeploy_filepath fabfile.py) -H #{h.keys.sample} -P host_monkeypatch:#{@domain_name} -- 'echo #{hookparams} | sudo hdeploy_node post_distribute_run_once'")
  end
end

#env(newenv) ⇒ Object



311
312
313
314
# File 'lib/hdeploy/cli.rb', line 311

def env(newenv)
  @env = newenv
  puts "set env to #{@env}"
end

#fabObject

looking for python ‘fabric’



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/hdeploy/cli.rb', line 78

def fab # looking for python 'fabric'
  return @conf['cli']['fab'] if @conf['cli']['fab']

  try_files = %w[
    /usr/local/bin/fab
    /usr/bin/fab
    /opt/hdeploy/embedded/bin/fab
    /opt/hdeploy/bin/fab
  ]

  try_files.each do |f|
    return f if File.executable?(f)
  end

  raise "could not find fabric. tried #{try_files.join(' ')}"
end

#fakebuildObject



332
333
334
# File 'lib/hdeploy/cli.rb', line 332

def fakebuild
  @fakebuild = true
end

#forceObject



307
308
309
# File 'lib/hdeploy/cli.rb', line 307

def force
  @force=true
end

#fulldeploy(build_tag) ⇒ Object



472
473
474
475
# File 'lib/hdeploy/cli.rb', line 472

def fulldeploy(build_tag)
  distribute(build_tag)
  symlink(build_tag)
end

#helpObject



320
321
322
323
324
325
326
327
328
329
330
# File 'lib/hdeploy/cli.rb', line 320

def help
  puts "Possible commands:"
  puts "  env:branch"
  puts "  build (or build:branch)"
  puts "  app:appname"
  puts "  distribute:nameofartifact"
  puts "  symlink:nameofartifact"
  puts "  list"
  puts ""
  puts "Example: hdeploy env:production build"
end

#initObject



340
341
342
343
344
345
346
347
348
349
# File 'lib/hdeploy/cli.rb', line 340

def init
  c = @conf['build'][@app]
  repo = File.expand_path(c['repo'])

  if !(Dir.exists?(File.join(repo,'.git')))
    FileUtils.rm_rf repo
    FileUtils.mkdir_p File.join(repo,'..')
    mysystem("git clone #{c['git']} #{repo}")
  end
end

#initrepoObject



336
337
338
# File 'lib/hdeploy/cli.rb', line 336

def initrepo
  init()
end

#list_servers(recipe = 'common') ⇒ Object



101
102
103
# File 'lib/hdeploy/cli.rb', line 101

def list_servers(recipe = 'common')
  return @client.get("/srv_by_recipe/#{recipe}")
end

#mysystem(cmd) ⇒ Object



73
74
75
76
# File 'lib/hdeploy/cli.rb', line 73

def mysystem(cmd)
  system cmd
  raise "error running #{cmd} #{$?}" unless $?.success?
end

#notify(msg) ⇒ Object



351
352
353
354
355
# File 'lib/hdeploy/cli.rb', line 351

def notify(msg)
  if File.executable?('/usr/local/bin/hdeploy_hipchat')
    mysystem("/usr/local/bin/hdeploy_hipchat #{msg}")
  end
end

#prune(prune_env = 'nowhere') ⇒ Object



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
# File 'lib/hdeploy/cli.rb', line 155

def prune(prune_env='nowhere')

  c = @conf['build'][@app]
  prune_count = c['prune'].to_i #FIXME: integrity check.
  raise "no proper prune count" unless prune_count >= 3 and prune_count < 20

  dist = JSON.parse(@client.get("/distribute/#{@app}"))
  if dist.has_key? prune_env

    # Now we want to be careful to not eliminate any current artifact (ie. symlinked)
    # or any target either. Usually they would both be the same obviously.

    artifacts_to_keep = {}

    dist_states = JSON.parse(@client.get("/distribute_state/#{@app}"))
    dist_states.each do |dist_state|
      if prune_env == 'nowhere'
        # We take EVERYTHING into account
        artifacts_to_keep[dist_state['current']] = true
        dist_state['artifacts'].each do |art|
          artifacts_to_keep[art] = true
        end

      elsif dist_state['env'] == prune_env
        # Otherwise, we only take into account the current env
        artifacts_to_keep[dist_state['current']] = true
      end
    end

    # If the prune_env is not 'nowhere', we also want to keep the target
    # fixme: check integrity of reply
    artifacts_to_keep[@client.get("/target/#{@app}/#{prune_env}")] = true

    if dist[prune_env].length <= prune_count
      return "nothing to prune in env. #{prune_env}"
    end

    delete_max_count = dist[prune_env].length - prune_count
    delete_count = 0

    dist[prune_env].sort.each do |artifact|

      next if artifacts_to_keep.has_key? artifact

      delete_count += 1
      if prune_env == 'nowhere'
        # we must also delete file
        puts @client.delete("/artifact/#{@app}/#{artifact}")
      else
        puts @client.delete("/distribute/#{@app}/#{prune_env}/#{artifact}")
      end
      break if delete_count >= delete_max_count
    end

    return ""
  else
    return "Nothing to prune"
  end

  prune_artifacts
end

#prune_artifactsObject



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
# File 'lib/hdeploy/cli.rb', line 105

def prune_artifacts
  c = @conf['build'][@app]
  keepnum = c['prune'] || 5
  keepnum = keepnum.to_i

  artdir = c['artifacts']

  artlist = []
  Dir.entries(artdir).sort.each do |f|
    if f =~ /(#{@app}\..*)\.tar\.gz$/
      artlist << $1
    end
  end

  distributed_by_env = JSON.parse(@client.get("/distribute/#{@app}"))
  distributed = {}
  distributed_by_env.each do |env,list|
    list.each do |artname|
      distributed[artname] = true
    end
  end

  artlist = artlist.delete_if {|a| distributed.has_key? a }

  while artlist.length > keepnum
    art = artlist.shift
    artfile = art + ".tar.gz"
    puts "File.unlink #{File.join(artdir,artfile)}"
    File.unlink File.join(artdir,artfile)
  end
end

#prune_build_envObject



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/hdeploy/cli.rb', line 137

def prune_build_env
  c = @conf[@app]
  keepnum = c['prune_build_env'] || 2
  keepnum = keepnum.to_i

  raise "incorrect dir config" unless c['build_dir']
  builddir = File.expand_path(c['build_dir'])
  return unless Dir.exists?(builddir)
  dirs = Dir.entries(builddir).delete_if{|d| d == '.' or d == '..' }.sort
  puts "build env pruning: keeping maximum #{keepnum} builds"

  while dirs.length > keepnum
    dirtodel = dirs.shift
    puts "FileUtils.rm_rf #{File.join(builddir,dirtodel)}"
    FileUtils.rm_rf File.join(builddir,dirtodel)
  end
end

#register_tarball(build_tag) ⇒ Object



460
461
462
463
464
465
466
467
468
469
470
# File 'lib/hdeploy/cli.rb', line 460

def register_tarball(build_tag)
  # Register tarball
  filename = build_tag + '.tar.gz'
  checksum = Digest::MD5.file(File.join(@conf['build'][@app]['artifacts'], filename))

  @client.put("/artifact/#{@app}/#{build_tag}", JSON.pretty_generate({
    source: "http://build.gyg.io:8502/#{filename}",
    altsource: "",
    checksum: checksum,
  }))
end

#run!Object



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
# File 'lib/hdeploy/cli.rb', line 28

def run!
  #begin
    cmds = []
    ARGV.each do |arg|
      cmd = arg.split(':',2)
      if cmd[0][0] == '_'
        raise "you cant use cmd starting with a _"
      end

      unless respond_to?(cmd[0])
        raise "no such command '#{cmd[0]}' in #{self.class} (#{__FILE__})"
      end
      cmds << cmd
    end

    cmds.each do |cmd|
      m = method(cmd[0]).parameters

      # only zero or one param
      raise "method #{cmd[0]} takes several parameters. This is a programming mistake. Ask Patrick to edit #{__FILE__}" if m.length > 1

      if m.length == 1
        if cmd.length > 1
          # in this case it always works
          puts send(cmd[0],cmd[1])
        elsif m[0][0] == :opt
          puts send(cmd[0])
        else
          # This means you didn't give parameter to command that wants an option
          raise "method #{cmd[0]} requires an option. please specify with #{cmd[0]}:parameter"
        end
      else
        if cmd.length > 1
          raise "method #{cmd[0]} does not take parameters and you gave parameter #{cmd[1]}"
        else
          puts send(cmd[0])
        end
      end
    end
  #rescue Exception => e
  #  puts "ERROR: #{e}"
  #  exit 1
  #end
end

#stateObject



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
# File 'lib/hdeploy/cli.rb', line 217

def state
  dist = JSON.parse(@client.get("/distribute/#{@app}"))
  dist_state = JSON.parse(@client.get("/distribute_state/#{@app}"))
  targets = JSON.parse(@client.get("/target/#{@app}"))

  # What I'm trying to do here is, for each artifact from 'dist', figure where it actually is.
  # For this, I need to know how many servers are active per env, then I can cross-reference the artifacts
  todisplay = {}
  dist.each do |env,artlist|
    next if env == 'nowhere'
    todisplay[env] = {}
    artlist.each do |art|
      todisplay[env][art] = []
    end
  end

  servers_by_env = {}
  current_links = {}

  dist_state.each do |stdata|
    env,hostname,artifacts,current = stdata.values_at('env','hostname','artifacts','current')

    servers_by_env[env] = {} unless servers_by_env.has_key? env
    servers_by_env[env][hostname] = true

    current_links[env] = {} unless current_links.has_key? env
    current_links[env][hostname] = current

    artifacts.each do |art|
      if todisplay.has_key? env
        if todisplay[env].has_key? art
          todisplay[env][art] << hostname
        end
      end
    end
  end

  # now that we have a servers by env, we can tell for each artifact what is distributed for it, and where it's missing.

  ret = "---------------------------------------------------\n" +
        "Artifact distribution state for app #{@app}\n" +
        "---------------------------------------------------\n\n"

  ret += "Inactive: "
  if dist['nowhere'].length == 0
    ret += "none\n\n"
  else
    ret += "\n" + dist['nowhere'].collect{|art| "- #{art}"}.sort.join("\n") + "\n\n"
  end

  todisplay.each do |env,artifacts|
    srvnum = servers_by_env[env].length
    txt = "ENV \"#{env}\" (#{srvnum} servers)\n"
    ret += ("-" * txt.length) + "\n" + txt + ("-" * txt.length) + "\n"
    ret += "TARGET: " + targets[env].to_s

    # Consistent targets?
    current_by_art = {}
    inconsistent = []
    current_links[env].each do |srv,link|
      inconsistent << srv if link != targets[env]
      current_by_art[link] = [] unless current_by_art.has_key? link
      current_by_art[link] << srv
    end
    if inconsistent.length > 0
      ret += " (#{inconsistent.length}/#{servers_by_env[env].length} inconsistent servers: #{inconsistent.join(', ')})\n\n"
    else
      ret += " (All OK)\n\n"
    end

    # distributed artifacts. Sort by key.
    artifacts.keys.sort.each do |art|
      hosts = artifacts[art]
      ret += "- #{art}"
      ret += " (target)" if art == targets[env]
      ret += " (current #{current_by_art[art].length}/#{servers_by_env[env].length})" if current_by_art.has_key? art

      # and if it's not distributed somewhere
      if hosts.length < servers_by_env[env].length
        ret += " (missing on: #{(servers_by_env[env].keys - hosts).join(', ')})"
      end

      ret += "\n"
    end
    ret += "\n"
  end

  ret
end


502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/hdeploy/cli.rb', line 502

def symlink(target)
  target(target)

  h = JSON.parse(@client.get("/srv/by_app/#{@app}/#{@env}"))

  raise "no server with #{@app}/#{@env}" unless h.keys.length > 0
  h.each do |host,conf|
    if !(conf['artifacts'].include? target)
      raise "artifact #{target} is not present on server #{host}. Please run hdeploy env:#{@env} distribute:#{target}"
    end
  end

  # On all servers, do a standard symlink
  system("#{_fab} -f $(hdeploy_filepath fabfile.py) -H #{h.keys.join(',')} -P host_monkeypatch:#{@domain_name} -- 'echo app:#{@app} env:#{@env} | sudo hdeploy_node symlink'")

  # And on a single server, run the single hook.
  hookparams = { app: @app, env: @env, artifact: target, servers:h.keys.join(','), user: ENV['USER'] }.collect {|k,v| "#{k}:#{v}" }.join(" ")
  system("#{_fab} -f $(hdeploy_filepath fabfile.py) -H #{h.keys.sample} -P host_monkeypatch:#{@domain_name} -- 'echo #{hookparams} | sudo hdeploy_node post_symlink_run_once'")
end

#target(artid = 'someid') ⇒ Object

Does this really have to exist? Or should I just put it in the symlink method?



492
493
494
495
496
497
498
499
500
# File 'lib/hdeploy/cli.rb', line 492

def target(artid = 'someid')

  # We just check if the artifact is set to be distributed to the server
  # for the actual presence we will only check in the symlink part.

  todist = JSON.parse(@client.get("/distribute/#{@app}/#{@env}"))
  raise "artifact #{artid} is not set to be distributed for #{@app}/#{@env}" unless todist.has_key? artid
  return @client.put("/target/#{@app}/#{@env}", artid)
end

#undistribute(build_tag) ⇒ Object



316
317
318
# File 'lib/hdeploy/cli.rb', line 316

def undistribute(build_tag)
  @client.delete("/distribute/#{@app}/#{@env}/#{build_tag}")
end