Module: Deployinator::Helpers

Defined in:
helpers.rb,
helpers/dsh.rb,
helpers/git.rb,
helpers/demo.rb,
helpers/graphite.rb

Defined Under Namespace

Modules: DemoHelpers, DshHelpers, GitHelpers, GraphiteHelpers

Constant Summary collapse

RUN_LOG_PATH =
"run_logs/"
AUTH_FREE_URLS =

list of URLs that don't require authorization (can take regular expressions) this should be in a config

[]
OK_PATH_REGEX =
%r{^(#{AUTH_FREE_URLS.compact.join("|")})$}

Instance Method Summary collapse

Instance Method Details

#after_stream(args, extra = {}) ⇒ Object


320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'helpers.rb', line 320

def after_stream(args, extra={})
  # for some day... web hooks post deploy
  # urls = SVN.export(SVN::URL + "/devtools/trunk/deploy_hooks.txt")
  # args.merge!(extra)
  # urls.split("\n").each { |url| Net::HTTP.post_form(URI.parse(url), args)

  # unlock_pushes

  if (args["stack"] && args["method"])
    if args["method"].match(/config_push/)
      args["stack"] = "config"
      env = args["method"].match(/prod/) ? "production" : "princess"
    else
      env = args["method"][/(qa|production|princess|prod|webs|stage|config)/i, 1] || "other"
      env = "production" if env.match(/prod|webs/)
    end

    # ping graphite!
    graphite_plot("deploys.#{args["stack"]}.#{env} 1")
  end
end

#announce(announcement, options = {}) ⇒ Object


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
# File 'helpers.rb', line 238

def announce(announcement, options = {})
  d_url = diff_url(options[:stack], options[:old_build], options[:build])

  irc_announce(announcement.dup, options[:irc_channels]) if options[:irc_channels]

  if options[:send_email] && options[:send_email] == true
    stack = options[:stack] || "web"

    diff_html = ""

    if (options[:old_build] && options[:build])
      # generate diff with compare.php - TBD
    end

    if diff_html && diff_html.match(/<!-- extra -->/)
      diff_html.gsub!(/<!-- extra -->/, "<pre margin='5px;'>#{announcement}</pre>")
    else
      diff_html = (diff_html || "") + announcement
    end

    send_email({
      :subject => "#{stack} deployed #{options[:env]} by #{@username}",
      :html_body => diff_html
    })
  end

  if Deployinator.new_relic_options
    opts = Deployinator.new_relic_options
    
    new_relic_url = "https://rpm.newrelic.com/deployments.xml"
    raise "Must have New Relic apikey and appid" unless opts[:apikey] && opts[:appid]

    cmd = %Q{curl -s --connect-timeout 10 -H "x-api-key:#{opts[:apikey]}" \
                  -d "deployment[application_id]=#{opts[:appid]}" \
                  -d "deployment[user]=#{@username}" \
                  -d "deployment[description]=#{d_url}" \
                  -d "deployment[revision]=#{options[:env]}: #{options[:build]}" \
                  #{new_relic_url} }
    run_cmd cmd
  end
end

#average_duration(type, stack) ⇒ Object


222
223
224
225
226
227
228
# File 'helpers.rb', line 222

def average_duration(type, stack)
  log = `#{log_host} 'grep "#{type}|#{stack}" #{timing_log_path} | #{tac} | head -5'`
  timings = log.split("\n").collect { |line| line.split("|").last.to_f }
  avg_time = (timings.empty?) ? 30 : timings.inject(0) {|a,v| a+v} / timings.size
  puts "avg time for #{stack}/#{type}: #{avg_time}"
  avg_time
end

#before_stream(args) ⇒ Object


313
314
315
316
317
318
# File 'helpers.rb', line 313

def before_stream(args)
  @start_time = Time.now
  unless args["method"].match(/unlock/)
    # lock_pushes(@username, args["method"])
  end
end

#clean(msg) ⇒ Object


309
310
311
# File 'helpers.rb', line 309

def clean(msg)
  (msg || "").gsub("|", "/").gsub('"', "&quot;").gsub("'", "&apos;")
end

#dep_method(env) ⇒ Object


35
36
37
38
# File 'helpers.rb', line 35

def dep_method(env)
  return "undefined" unless form_hash(env, "method")
  "#{@stack}-#{form_hash(env, "method")}"
end

#deploy_host_cmdObject


143
144
145
# File 'helpers.rb', line 143

def deploy_host_cmd
  "sh -c"
end

#diff(r1, r2, stack = "web") ⇒ Object


191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'helpers.rb', line 191

def diff(r1, r2, stack="web")
  if use_github(stack.to_sym, r1, r2)
    redirect "/diff/#{stack}/#{r1}/#{r2}/github"
    return
  end
  @r1 = r1
  @r2 = r2
  @paths = diff_paths_for_stack[stack.to_sym]
  @date1 = SVN.time_of_rev(r1) + 1
  @date2 = SVN.time_of_rev(r2)

  mustache :diff
end

#diff_url(stack, old_build, new_build) ⇒ Object

Actual helper methods


135
136
137
# File 'helpers.rb', line 135

def diff_url(stack, old_build, new_build)
  "#{Deployinator.protocol}://#{Deployinator.hostname}/diff/#{stack}/#{old_build}/#{new_build}"
end

#environmentsObject


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'helpers.rb', line 392

def environments
  custom_env = "#{stack}_environments"
  envs = send(custom_env) if respond_to?(custom_env.to_sym)
  envs ||=
  [{
    :name            => "production",
    :title           => "Deploy #{stack} production",
    :method          => "#{stack}_production",
    :current_version => proc{send(:"#{stack}_production_version")},
    :current_build   => proc{Version.get_build(send(:"#{stack}_production_version"))},
    :next_build      => proc{send(:head_build)}
  }]

  envs.each_with_index { |env, i| env[:number] = "%02d." % (i + 1); env[:not_last] = (i < envs.size - 1) }
end

#form_hash(env, key) ⇒ Object


40
41
42
43
# File 'helpers.rb', line 40

def form_hash(env, key)
  fh = env["rack.request.form_hash"]
  fh && fh.key?(key) && fh[key]
end

#get_logObject


288
289
290
291
292
# File 'helpers.rb', line 288

def get_log
  log_entries.collect do |line|
    "[" + line.split("|").join("] [") + "]"
  end.join("<br>")
end

#get_stacks_select_boxObject


408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'helpers.rb', line 408

def get_stacks_select_box
  stacks = Dir.glob('stacks/*.rb')
  output = "<select name='stacks' id='stacks'>"
  stacks.each do |s|
    s = s.gsub("stacks/", "").gsub(".rb", "")
    output << "<option value='#{s}'"
    output << " selected='selected'" if s == stack
    output << ">#{s}</option>"
  end
  output << "</select>"

  output
end

#head_buildObject


170
171
172
173
174
175
176
177
178
179
180
181
# File 'helpers.rb', line 170

def head_build
  meth = "#{stack}_head_build"
  if self.respond_to?(meth)
    self.send(meth)
  else
    if github_info_for_stack.key?(stack)
      %x{git ls-remote #{git_url(stack)} HEAD | cut -c1-7}.chomp
    else
      SVN.version_of(Deployinator.svn_default_repo)
    end
  end
end

350
351
352
353
354
355
# File 'helpers.rb', line 350

def hyperlink(msg)
  (msg || "").gsub(/([A-Z]{2,10}-[0-9]{2,})/) do |issue|
    issue_url = Deployinator.issue_tracker.call(issue)
    "<a href='#{issue_url}' target='_blank'>#{issue}</a>"
  end
end

#init(env) ⇒ Object


22
23
24
25
26
27
28
29
30
31
32
33
# File 'helpers.rb', line 22

def init(env)
  @username = (env["HTTP_X_USERNAME"] || ENV["HTTP_X_USERNAME"]) or raise "Must be logged in"
  @groups   = CGI.unescape(env["HTTP_X_GROUPS"] || ENV["HTTP_X_GROUPS"]).split("|")
  @host     = env["HTTP_HOST"]
  @local    = @host.match(/local|dev/)
  @ny4      = @host.match(/ny4/)
  if @username == "nobody" && ! request.path_info.match(OK_PATH_REGEX)
    raise "Must be logged in"
  end
  @stack = form_hash(env, "stack") unless @stack
  @filename = "#{Time.now.to_i}-#{@username}-#{dep_method(env)}.html"
end

#irc_announce(message, channels = []) ⇒ Object


280
281
282
283
284
285
286
# File 'helpers.rb', line 280

def irc_announce(message, channels=[])
  channels = channels.split(",") if channels.is_a?(String)
  message = "message=#{CGI.escape(message)}&channels=#{CGI.escape(channels.join(","))}"
  devbot_url = Deployinator.devbot_url
  cmd = %Q{curl -s --connect-timeout 10 -d "#{message}" #{devbot_url}}
  `#{cmd}`
end

#log(env, who, msg, stack) ⇒ Object


294
295
296
297
# File 'helpers.rb', line 294

def log(env, who, msg, stack)
  s = stack
  log_string_to_file("#{now}|#{env}|#{clean(who)}|#{clean(msg)}|#{s}", log_path)
end

#log_and_shout(options = {}) ⇒ Object


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
# File 'helpers.rb', line 94

def log_and_shout(options={})
  options[:stack] ||= @stack

  raise "Must have stack" unless options[:stack]

  # newlines in any of these will corrupt the logfile, so strip them out
  newoptions = {}
  options.each do |key, value|
    value.chomp! if value.respond_to?(:"chomp!")
    newoptions[key] = value
  end
  options = newoptions

  options[:env] ||= "PROD"
  options[:nice_env] = nicify_env(options[:env])
  options[:user] ||= @username
  options[:start] = @start_time unless options[:start] || ! @start_time

  if (options[:start])
    options[:end] = Time.now unless options.key?(:end)
    options[:duration] = options[:end] - options[:start]

    log_and_stream "Ended at #{options[:end]}<br>Took: #{options[:duration]} seconds<br>"
    timing_log options[:duration], options[:nice_env], options[:stack]
  end

  if (options[:old_build] && options[:build])
    log_str = "#{options[:stack]} #{options[:nice_env]} deploy: old #{options[:old_build]}, new: #{options[:build]}"
    log options[:env], options[:user], log_str, options[:stack]
    d_url = diff_url(options[:stack], options[:old_build], options[:build])
  end

  if (options[:old_build] && options[:build] && (options[:irc_channels] || options[:send_email]))
    announcement = "#{options[:stack]} #{options[:env]} deployed by #{options[:user]}"
    announcement << " build: #{options[:build]} took: #{options[:duration]} seconds diff: #{d_url}"
    announce announcement, options
  end
end

#log_and_stream(output) ⇒ Object

output to a file, and the streaming output handler


54
55
56
57
# File 'helpers.rb', line 54

def log_and_stream(output)
  write_file output, @filename if @filename
  @block.call(output)
end

#log_entries(options = {}) ⇒ Object


205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'helpers.rb', line 205

def log_entries(options = {})
  stacks = []
  stacks << "GLOBAL" unless (options[:no_limit] || options[:no_global])
  stacks << options[:stack] if options[:stack]
  env = options[:env] ? "\\|#{options[:env].upcase}\\|" : ""
  limit = (options[:no_limit] && options[:no_limit] == true) ? nil : (options[:limit] || 40)

  unless stacks.empty? && env.empty?
    grep = "| egrep '#{env}.*\\|#{stacks.join("|")}'"
  end

  limit = "| head -#{limit}" if limit

  log = `#{log_host} "#{tac} #{log_path} #{grep} #{limit}"`
  log.split("\n")
end

#log_string_to_file(string, path) ⇒ Object


304
305
306
307
# File 'helpers.rb', line 304

def log_string_to_file(string, path)
  cmd = %Q{#{log_host} 'echo  "#{string}" >> #{path}'}
  system(cmd)
end

#log_to_hash(opts = {}) ⇒ Object


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
# File 'helpers.rb', line 365

def log_to_hash(opts={})
  times = {}
  last_time = 0
  l = log_entries(opts).map do |ll|
    fields = ll.split("|")
    times[fields[1]] ||= []
    times[fields[1]] << fields[0]
    utc_time = Time.parse(fields[0] + "UTC")
    {
      :timestamp => fields[0],
      :time      => utc_time,
      :time_secs => utc_time.to_i,
      :env       => fields[1],
      :who       => fields[2],
      :msg       => hyperlink(fields[3]),
      :old       => fields[3] && fields[3][/old[\s:]*(\w+)/, 1],
      :new       => fields[3] && fields[3][/new[\s:]*(\w+)/, 1],
      :stack     => fields[4]
    }
  end
  times.each { |e,t| t.shift }
  l.map do |le|
    le[:last_time] = times[le[:env]].shift || 0
    le
  end
end

#mac_os_x?Boolean

Returns:

  • (Boolean)

357
358
359
# File 'helpers.rb', line 357

def mac_os_x?
  `uname -s`.chomp == "Darwin"
end

#nice_timeObject


342
343
344
# File 'helpers.rb', line 342

def nice_time
  "%Y-%m-%d %H:%M:%S"
end

#nicify_env(env) ⇒ Object


89
90
91
92
# File 'helpers.rb', line 89

def nicify_env(env)
  env = "production" if env == "PROD"
  env.downcase
end

#nowObject


346
347
348
# File 'helpers.rb', line 346

def now
  Time.now.gmtime.strftime(nice_time)
end

#run_cmd(cmd) ⇒ Object

Run external command with timing information streams and logs the output of the command as well does not (currently) check exit status codes


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
# File 'helpers.rb', line 62

def run_cmd(cmd)
  ret = ""
  start = Time.now.to_i
  log_and_stream "<div class='command'><h4>Running #{cmd}</h4><p class='output'>"
  time = Benchmark.measure do
    ret_code = Open4.popen4(cmd) do |pid, inn, out, err|
      output = ""
      until out.eof?
        # raise "Timeout" if output.empty? && Time.now.to_i - start > 300
        chr = out.read(1)
        output << chr
        ret << chr
        if chr == "\n" || chr == "\r"
          log_and_stream output + "<br>"
          output = ""
        end
      end
      log_and_stream(output) unless output.empty?
      log_and_stream("<span class='stderr'>STDERR: #{err.read}</span><br>") unless err.eof?
    end
    raise 'process_failed' unless ret_code == 0
  end
  log_and_stream "</p>"
  log_and_stream "<h5>Time: #{time}</h5></div>"
  return ret
end

#run_log_pathObject


14
15
16
# File 'helpers.rb', line 14

def run_log_path
  RUN_LOG_PATH
end

#send_email(options) ⇒ Object


230
231
232
233
234
235
236
# File 'helpers.rb', line 230

def send_email(options)
  if Pony.options.keys.count == 0 
    log_and_stream "Pony not configuration; not sending mail."
  else 
    Pony.mail(options)
  end 
end

#set_block(&block) ⇒ Object


18
19
20
# File 'helpers.rb', line 18

def set_block(&block)
  @block = block
end

#stackObject


139
140
141
# File 'helpers.rb', line 139

def stack
  @stack
end

#stack_production_version(stack, extra = "htdocs/", has_x = false) ⇒ Object


152
153
154
155
156
# File 'helpers.rb', line 152

def stack_production_version(stack, extra="htdocs/", has_x=false)
  # has_x is totally unused, but putting it here to have the same signature as stack_qa_version
  puts %Q{#{deploy_host_cmd} cat #{stack}/#{extra}version.txt}
  %x{#{deploy_host_cmd} cat #{stack}/#{extra}version.txt}.chomp
end

#stack_qa_version(stack, extra = "htdocs/", has_x = true) ⇒ Object


147
148
149
150
# File 'helpers.rb', line 147

def stack_qa_version(stack, extra="htdocs/", has_x=true)
  stack = stack + "-x" if has_x
  %x{#{deploy_host_cmd} cat #{checkout_root}/#{stack}/#{extra}version.txt}.chomp
end

#tacObject


361
362
363
# File 'helpers.rb', line 361

def tac
  mac_os_x? ? "tail -r" : "tac"
end

#timing_log(duration, type, stack) ⇒ Object


299
300
301
302
# File 'helpers.rb', line 299

def timing_log(duration, type, stack)
  log_string_to_file("#{now}|#{type}|#{stack}|#{duration}", timing_log_path)
  graphite_plot("deploylong.#{stack}.#{type} #{duration}")
end

#use_github(stack, rev1, rev2) ⇒ Object


183
184
185
186
187
188
189
# File 'helpers.rb', line 183

def use_github(stack, rev1, rev2)
  # Hackery
  return true if Deployinator::Helpers.respond_to?(stack.to_s + "_git_repo_url")
  return false if [rev1, rev2].all? {|r| r.match(/^\d{5}$/)}
  return true if github_info_for_stack.key?(stack)
  return false
end

#write_file(str, file) ⇒ Object


45
46
47
48
49
50
51
# File 'helpers.rb', line 45

def write_file(str, file)
  File.open("#{RUN_LOG_PATH}#{file}", "a") do |f|
    # escape the script tags so we dont get redirects when looking at logs
    str = str.gsub(%r{(<script>.*?</script>)}) {|script| CGI.escapeHTML(script)}
    f.print str
  end
end