Module: Deployinator::Helpers
- Includes:
- PluginHelpers, VersionHelpers
- Defined in:
- lib/deployinator/helpers.rb,
lib/deployinator/helpers/dsh.rb,
lib/deployinator/helpers/git.rb,
lib/deployinator/helpers/view.rb,
lib/deployinator/helpers/deploy.rb,
lib/deployinator/helpers/plugin.rb,
lib/deployinator/helpers/version.rb,
lib/deployinator/helpers/stack-tail.rb,
lib/deployinator/helpers/concurrency.rb
Defined Under Namespace
Modules: ConcurrencyHelpers, DeployHelpers, DshHelpers, GitHelpers, PluginHelpers, StackTailHelpers, VersionHelpers, ViewHelpers
Constant Summary collapse
- RUN_LOG_PATH =
"run_logs/"
Instance Attribute Summary
Attributes included from PluginHelpers
Instance Method Summary collapse
- #announce(announcement, options = {}) ⇒ Object
- #average_duration(type, stack) ⇒ Object
- #can_remove_stack_lock? ⇒ Boolean
- #clean(msg) ⇒ Object
- #deploy_host? ⇒ Boolean
- #dev_context? ⇒ Boolean
- #diff(r1, r2, stack = "web", time = null) ⇒ Object
- #diff_url(stack, old_build, new_build) ⇒ Object
- #environments ⇒ Object
-
#get_deploy_target_status ⇒ Object
Public: check if the deploy host is up or not show a little slug in the header with the deploy host name and status.
-
#get_from_cache(cache_file, cache_ttl = 5) ⇒ Object
Public: gets the contents from a cache file if it hasn’t expired.
- #get_log ⇒ Object
-
#get_run_logs(opts = {}) ⇒ Object
Public: fetch the run_logs in ‘run_logs/’ based on sevaral parameters.
-
#get_stack_select ⇒ Object
Public: Outputs stack data for use in templating the stack selection box in the header.
- #head_build ⇒ Object
- #http_host ⇒ Object
- #hyperlink(msg) ⇒ Object
- #init(env) ⇒ Object
-
#is_admin?(user_groups = nil, admin_groups = nil) ⇒ Boolean
Public: helper method to check if the current user is part of an group.
-
#link_stack_logfile(filename, stack) ⇒ Object
Creates a current-stackname symlink for each deploy for easier tailing.
- #lock_pushes(stack, who, method) ⇒ Object
-
#log(env, who, msg, stack) ⇒ Object
Public: log a given message to the log_path file.
- #log_and_shout(options = {}) ⇒ Object
-
#log_and_stream(output) ⇒ Object
output to a file, and the streaming output handler Public: helper function to write a message to the logfile and have it streamed in the webfrontend also.
- #log_entries(options = {}) ⇒ Object
- #log_error(msg, e = nil) ⇒ Object
-
#log_string_to_file(string, path) ⇒ Object
Public: wrapper method around appending stdout to a logfile.
-
#move_stack_logfile(stack) ⇒ Object
Moves current-stackname symlink so tailer won’t accidentally pick up on last push race condition.
- #nice_time ⇒ Object
- #nicify_env(env) ⇒ Object
- #not_dev? ⇒ Boolean
- #now ⇒ Object
- #push_lock_info(stack) ⇒ Object
- #push_lock_path(stack) ⇒ Object
- #pushes_locked?(stack) ⇒ Boolean
-
#run_cmd(cmd, timing_metric = nil, log_errors = true) ⇒ Object
Run external command with timing information streams and logs the output of the command as well does not (currently) check exit status codes.
-
#run_cmd_with_retries(cmd, num_retries = 5, sleep_seconds = 2, timing_metric = nil) ⇒ Object
Run external command with timing information streams and logs the output of the command as well If the command fails, it is retried some number of times This defaults to 5, but can be specified with the num_retries parameter If all the retries fail, an exception is thrown Between retries it will sleep for a given period, defaulting to 2 seconds.
- #run_log_path ⇒ Object
-
#run_log_url(filename) ⇒ Object
Public: given a run logs filename, return a full URL to the runlg.
-
#runlog_filename(name = nil) ⇒ Object
gives the filename to send runlog to based on whether we are in the main thread or not We do this because we want to be able to use log_and_stream seamlessly in a parallel thread.
-
#runlog_thread_filename(name) ⇒ Object
gives us the filename to log to in thread output - String filename for thread.
- #send_email(options) ⇒ Object
- #stack ⇒ Object
-
#strip_ws_to_nil(s) ⇒ Object
Public: strips all of the whitespace from a string.
- #timing_log(duration, type, stack, timestamp = nil) ⇒ Object
- #unlock_pushes(stack) ⇒ Object
-
#with_timeout(seconds, description = nil, throw_exception = false, quiet = false, extra_opts = {}, &block) ⇒ Object
Public: wrap a block into a timeout.
- #write_file(str, file) ⇒ Object
-
#write_to_cache(cache_file, contents) ⇒ Object
Public: writes the supplied contents to the cache file, ensuring that encoding is correct.
Methods included from VersionHelpers
curl_get_url, get_build, get_version, get_version_by_url
Methods included from PluginHelpers
#notify_plugins, #raise_event, #register_plugins
Instance Method Details
#announce(announcement, options = {}) ⇒ Object
526 527 528 529 530 531 532 533 534 535 536 537 |
# File 'lib/deployinator/helpers.rb', line 526 def announce(announcement, = {}) raise_event(:announce, {:announcement => announcement, :options => }) if [:send_email] && [:send_email] == true stack = [:stack] send_email({ :subject => "#{stack} deployed #{[:env]} by #{@username}", :html_body => announcement }) end end |
#average_duration(type, stack) ⇒ Object
585 586 587 588 589 590 591 |
# File 'lib/deployinator/helpers.rb', line 585 def average_duration(type, stack) log = `grep "#{type}|#{stack}" #{Deployinator.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 |
#can_remove_stack_lock? ⇒ Boolean
511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/deployinator/helpers.rb', line 511 def can_remove_stack_lock? unless @groups.nil? then Deployinator.admin_groups.each { |cg| return true if @groups.include?(cg) } end # get the lock info to see if the user is the locker info = push_lock_info(@stack) || {} return true if info.empty? if info[:who] == @username return true end return false end |
#clean(msg) ⇒ Object
269 270 271 |
# File 'lib/deployinator/helpers.rb', line 269 def clean(msg) (msg || "").gsub("|", "/").gsub('"', """).gsub("'", "'") end |
#deploy_host? ⇒ Boolean
634 635 636 |
# File 'lib/deployinator/helpers.rb', line 634 def deploy_host? ! Deployinator.deploy_host.nil? end |
#dev_context? ⇒ Boolean
13 14 15 |
# File 'lib/deployinator/helpers.rb', line 13 def dev_context? Deployinator.app_context['context'] == 'dev' end |
#diff(r1, r2, stack = "web", time = null) ⇒ Object
225 226 227 228 229 230 231 |
# File 'lib/deployinator/helpers.rb', line 225 def diff(r1, r2, stack="web", time=null) if (!time) time = Time.now.to_i end redirect "/diff/#{stack}/#{r1}/#{r2}/github?time=#{time}" return end |
#diff_url(stack, old_build, new_build) ⇒ Object
539 540 541 |
# File 'lib/deployinator/helpers.rb', line 539 def diff_url(stack, old_build, new_build) raise_event(:diff, {:stack => stack, :old_build => old_build, :new_build => new_build}) end |
#environments ⇒ Object
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/deployinator/helpers.rb', line 288 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 => "production", :current_version => proc{send(:"#{stack}_production_version")}, :current_build => proc{get_build(send(:"#{stack}_production_version"))}, :next_build => proc{send(:head_build)} }] # Support simplified symbol for methods envs.map! do |env| new_env = env new_env[:current_version] = proc{send(env[:current_version])} if env[:current_version].is_a? Symbol new_env[:current_build] = proc{send(env[:current_build])} if env[:current_build].is_a? Symbol new_env[:next_build] = proc{send(env[:next_build])} if env[:next_build].is_a? Symbol new_env end envs.each_with_index { |env, i| env[:number] = "%02d." % (i + 1); env[:not_last] = (i < envs.size - 1) } end |
#get_deploy_target_status ⇒ Object
Public: check if the deploy host is up or not show a little slug in the header with the deploy host name and status
626 627 628 629 630 631 632 |
# File 'lib/deployinator/helpers.rb', line 626 def get_deploy_target_status status = %x{ssh -o ConnectTimeout=5 #{Deployinator.deploy_host} uptime | awk '{print $2}' }.rstrip if status != 'up' status = "<b>DOWN!</b>" end "#{Deployinator.deploy_host} is #{status}" end |
#get_from_cache(cache_file, cache_ttl = 5) ⇒ Object
Public: gets the contents from a cache file if it hasn’t expired
Paramaters:
cache_file: path to a cache file
cache_ttl : how long in seconds the cached content is good for
A negative number will indicate you don't care how old the cache
file is.
Returns: cached content or false if expired or cache file doesn’t exist.
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/deployinator/helpers.rb', line 381 def get_from_cache(cache_file, cache_ttl=5) if File.exists?(cache_file) now = Time.now file_mtime = File.mtime(cache_file) file_age = now - file_mtime if ((cache_ttl < 0) || (file_age <= cache_ttl)) file = File.open(cache_file, "r:UTF-8") return file.read else # Return False if the cache is old return false end else # Return False if the cache file doesn't exist return false end end |
#get_log ⇒ Object
237 238 239 240 241 |
# File 'lib/deployinator/helpers.rb', line 237 def get_log log_entries.collect do |line| "[" + line.split("|").join("] [") + "]" end.join("<br>") end |
#get_run_logs(opts = {}) ⇒ Object
Public: fetch the run_logs in ‘run_logs/’ based on sevaral parameters
Parameters:
opts
:offset
:limit
:filename - <stack>-<method>
Returns an array of hashes with name and time keys
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 |
# File 'lib/deployinator/helpers.rb', line 323 def get_run_logs(opts={}) offset = opts[:offset] || 0 limit = opts[:limit] || -1 filename = opts[:filename] || "" glob = Deployinator::Helpers::RUN_LOG_PATH + "*.html" files = Dir.glob(glob) # filter for config files files.select! {|file| file.match(/^((?!web[-_]config_diff.html).)*$/) && file.match(/html/)} # filter for princess or production run_logs files.select! {|file| file.match(/#{filename}/)} # map files to hash with name and time keys files.map! do |file| { :name => File.basename(file), :time => Time.at(file[/(\d{8,})/].to_i) } end # sort files chronologically, files.sort_by! {|file| file[:time]}.reverse! # select files within an index range files[offset...offset +limit] end |
#get_stack_select ⇒ Object
Public: Outputs stack data for use in templating the stack selection box in the header.
Returns an array of hashes with the fields “stack” and “current” where “current” is true for the currently selected stack.
447 448 449 450 451 452 453 454 455 |
# File 'lib/deployinator/helpers.rb', line 447 def get_stack_select stacks = Deployinator.get_stacks output = Array.new stacks.each do |s| current = stack == s output << { "stack" => s, "current" => current } end output end |
#head_build ⇒ Object
638 639 640 641 642 643 644 645 646 647 648 649 650 651 |
# File 'lib/deployinator/helpers.rb', line 638 def head_build meth = "#{stack}_head_build" if self.respond_to?(meth) self.send(meth) else if git_info_for_stack.key?(stack.to_sym) rev = get_git_head_rev(stack) puts rev return rev else puts "ERROR: add your stack in git_info_for_stack" end end end |
#http_host ⇒ Object
201 202 203 |
# File 'lib/deployinator/helpers.rb', line 201 def http_host @host end |
#hyperlink(msg) ⇒ Object
281 282 283 284 285 286 |
# File 'lib/deployinator/helpers.rb', line 281 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
25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/deployinator/helpers.rb', line 25 def init(env) @username = 'nobody' @groups = ['nogroup'] @local = false @host = env['HTTP_HOST'] auth_info = raise_event(:auth, {:env => env, :request => request}) if !auth_info.nil? raise "You must login." unless auth_info[:authorized] @username = auth_info[:username] @groups = auth_info[:groups] @host = auth_info[:host] @local = auth_info[:local] end end |
#is_admin?(user_groups = nil, admin_groups = nil) ⇒ Boolean
Public: helper method to check if the current user is part of an group. This method let’s you pass in groups for explicitness and testing but will fall back on @group and Deployinator.admin_groups.
Param:
user_groups - groups a user is part of
admin_groups - admin groups
Returns true if the current user is part of and admin group and false otherwise
690 691 692 693 694 695 696 697 698 699 700 701 702 703 |
# File 'lib/deployinator/helpers.rb', line 690 def is_admin?(user_groups=nil, admin_groups=nil) user_groups ||= @groups admin_groups ||= Deployinator.admin_groups return false if user_groups.nil? return false if admin_groups.nil? intersected_groups = user_groups & admin_groups # if we found an intersection between admin and user groups, the current # user is an admin return (intersected_groups.length > 0) end |
#link_stack_logfile(filename, stack) ⇒ Object
Creates a current-stackname symlink for each deploy for easier tailing
filename - String of the current run log filename stack - String containing the stack for this deploy
50 51 52 |
# File 'lib/deployinator/helpers.rb', line 50 def link_stack_logfile(filename, stack) run_cmd %Q{ln -nfs #{Deployinator.root_dir}/#{run_log_path}#{filename} #{Deployinator.root_dir}/#{run_log_path}current-#{stack}} end |
#lock_pushes(stack, who, method) ⇒ Object
413 414 415 416 417 418 419 420 421 422 423 |
# File 'lib/deployinator/helpers.rb', line 413 def lock_pushes(stack, who, method) log_and_stream("LOCKING #{stack}<br>") if lock_info = push_lock_info(stack) log_and_stream("Pushes locked by #{lock_info[:who]} - #{lock_info[:method]}<br>") return false end dt = Time.now.strftime("%m/%d/%Y %H:%M") log_string_to_file("#{who}|#{method}|#{dt}", push_lock_path(stack)) return true end |
#log(env, who, msg, stack) ⇒ Object
Public: log a given message to the log_path file. The method calls log_string_to_file for lower level logging functionality.
env - String which represents the environment the log was produced in who - String which represents the active user msg - String representing the actual log message stack - String representing the current deploy stack
Returns the return code of log_string_to_file
252 253 254 255 |
# File 'lib/deployinator/helpers.rb', line 252 def log(env, who, msg, stack) s = stack log_string_to_file("#{now}|#{env}|#{clean(who)}|#{clean(msg)}|#{s}|#{@filename}", Deployinator.log_path) end |
#log_and_shout(options = {}) ⇒ Object
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 |
# File 'lib/deployinator/helpers.rb', line 543 def log_and_shout(={}) [:stack] ||= @stack raise "Must have stack" unless [:stack] [:env] ||= "PROD" [:nice_env] ||= nicify_env([:env]) [:user] ||= @username [:start] = @start_time unless [:start] || ! @start_time if ([:start]) [:end] = Time.now.to_i unless .key?(:end) [:duration] = [:end] - [:start] log_and_stream "Ended at #{[:end]}<br>Took: #{[:duration]} seconds<br>" timing_log [:duration], [:nice_env], [:stack] end if ([:old_build] && [:build]) log_str = "#{[:stack]} #{[:nice_env]} deploy: old #{[:old_build]}, new: #{[:build]}" log [:env], [:user], log_str, [:stack] d_url = diff_url([:stack], [:old_build], [:build]) end if ([:old_build] && [:build] && ([:irc_channels] || [:send_email])) announcement = "#{[:stack]} #{[:env]} deployed by #{[:user]}" announcement << " build: #{[:build]} took: #{[:duration]} seconds " announcement << "diff: #{d_url}" if d_url announce announcement, end end |
#log_and_stream(output) ⇒ Object
output to a file, and the streaming output handler Public: helper function to write a message to the logfile and have it streamed in the webfrontend also. The frontend is HTML markuped so you can use HTML in the log message and it will be rendered with the given CSS of the site. Some classes can be used per default in Deployinator to show the output also in an error or info notification box. These are then displayed in a box above the logging output.
output - String to be logged and shown in the output
Examples:
log_and_stream(<div class="stderror"> ERROR! </div>)
log_and_stream(<div class="info_msg"> INFO! </div>)
Returns nothing
77 78 79 80 81 |
# File 'lib/deployinator/helpers.rb', line 77 def log_and_stream(output) write_file output, runlog_filename if runlog_filename return @block.call(output) unless @block.nil? "" end |
#log_entries(options = {}) ⇒ Object
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 |
# File 'lib/deployinator/helpers.rb', line 593 def log_entries( = {}) stacks = [] stacks << "LOG MESSAGE" unless ([:no_limit] || [:no_global]) stacks << [:stack] if [:stack] env = [:env] ? "\\|#{[:env].upcase}\\|" : "" limit = ([:no_limit] && [:no_limit] == true) ? nil : ([:limit] || 40) # stack should be the last part of the log line from the last pipe to the end # modified this to take into account the run_log entry at the end unless stacks.empty? && env.empty? grep = "| egrep '#{env}.*\\|\(#{stacks.join("|")}\)\\|'" end # extra grep does another filter to the line, needed to get CONFIG PRODUCTION if defined? [:extragrep] extragrep = "| egrep -i '#{[:extragrep]}' " end if [:page] num_per_page = 40 limit = "| head -#{num_per_page * [:page].to_i} | tail -#{num_per_page}" else limit = "| head -#{limit}" if limit end log = `tac #{Deployinator.log_path} #{grep} #{extragrep} #{limit}` log.split("\n") end |
#log_error(msg, e = nil) ⇒ Object
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 |
# File 'lib/deployinator/helpers.rb', line 653 def log_error(msg, e = nil) log_msg = e.nil? ? msg : "#{msg} (#{e.})" log_and_stream "<div class=\"stderr\">#{log_msg}</div>" if !e.nil? begin template = open("#{File.dirname(__FILE__)}/templates/exception.mustache").read regex = /(?<file>.*?):(?<line>\d+):.*?`(?<method>.*)'/ context = e.backtrace.map do |line| match = regex.match(line) { :file => match['file'], :line => match['line'], :method => match['method'] } end output = Mustache.render(template, {:exceptions => context}) log_and_stream output rescue log_and_stream e.backtrace.inspect end end # This is so we have something in the log if/when this fails puts log_msg end |
#log_string_to_file(string, path) ⇒ Object
Public: wrapper method around appending stdout to a logfile.
string - String representing the log message path - String representing the path to the logfile
Returns true if echo exited with 0, false for non-zero exit and nil if the call fails
264 265 266 267 |
# File 'lib/deployinator/helpers.rb', line 264 def log_string_to_file(string, path) cmd = %Q{echo "#{string}" >> #{path}} system(cmd) end |
#move_stack_logfile(stack) ⇒ Object
Moves current-stackname symlink so tailer won’t accidentally pick up on last push race condition
stack - String containing the stack for this deploy
58 59 60 |
# File 'lib/deployinator/helpers.rb', line 58 def move_stack_logfile(stack) run_cmd %Q{mv #{Deployinator.root_dir}/#{run_log_path}current-#{stack} #{Deployinator.root_dir}/#{run_log_path}last-#{stack}} end |
#nice_time ⇒ Object
273 274 275 |
# File 'lib/deployinator/helpers.rb', line 273 def nice_time "%Y-%m-%d %H:%M:%S" end |
#nicify_env(env) ⇒ Object
196 197 198 199 |
# File 'lib/deployinator/helpers.rb', line 196 def nicify_env(env) env = "production" if env == "PROD" env.downcase end |
#not_dev? ⇒ Boolean
17 18 19 |
# File 'lib/deployinator/helpers.rb', line 17 def not_dev? Deployinator.app_context['context'] != 'dev' end |
#now ⇒ Object
277 278 279 |
# File 'lib/deployinator/helpers.rb', line 277 def now Time.now.gmtime.strftime(nice_time) end |
#push_lock_info(stack) ⇒ Object
429 430 431 432 |
# File 'lib/deployinator/helpers.rb', line 429 def push_lock_info(stack) d = `test -f #{push_lock_path(stack)} && cat #{push_lock_path(stack)}`.chomp d.empty? ? nil : Hash[*[:who, :method, :lock_time].zip(d.split("|")).flatten] end |
#push_lock_path(stack) ⇒ Object
438 439 440 |
# File 'lib/deployinator/helpers.rb', line 438 def push_lock_path(stack) "#{Deployinator.root(["log"])}/#{stack}-push-lock" end |
#pushes_locked?(stack) ⇒ Boolean
434 435 436 |
# File 'lib/deployinator/helpers.rb', line 434 def pushes_locked?(stack) push_lock_info(stack) end |
#run_cmd(cmd, timing_metric = nil, log_errors = true) ⇒ Object
Run external command with timing information streams and logs the output of the command as well does not (currently) check exit status codes
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 |
# File 'lib/deployinator/helpers.rb', line 139 def run_cmd(cmd, timing_metric=nil, log_errors=true) ret = "" exit_code = 0 start = Time.now.to_i = Time.now.to_s plugin_state = { :cmd => cmd, :timing_metric => timing_metric, :start_time => start, :log_errors => log_errors } raise_event(:run_command_start, plugin_state) log_and_stream "<div class='command'><h4>#{}: Running #{cmd}</h4>\n<p class='output'>" time = Benchmark.measure do Open3.popen3(cmd) do |inn, out, err, wait_thr| 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 = nil log_and_stream(output) unless output.empty? = err.read unless err.eof? if (log_errors) then log_and_stream("<span class='stderr'>STDERR: #{}</span><br>") unless .nil? else log_and_stream("STDERR:" + + "<br>") unless .nil? end unless .nil? then plugin_state[:error_message] = raise_event(:run_command_error, plugin_state) end # Log non-zero exits if wait_thr.value.exitstatus != 0 then log_and_stream("<span class='stderr'>DANGER! #{cmd} had an exit value of: #{wait_thr.value.exitstatus}</span><br>") exit_code = wait_thr.value.exitstatus end end end log_and_stream "</p>" log_and_stream "<h5>Time: #{time}</h5></div>" plugin_state[:exit_code] = exit_code plugin_state[:stdout] = ret plugin_state[:time] = time.real raise_event(:run_command_end, plugin_state) return { :stdout => ret, :exit_code => exit_code } end |
#run_cmd_with_retries(cmd, num_retries = 5, sleep_seconds = 2, timing_metric = nil) ⇒ Object
Run external command with timing information streams and logs the output of the command as well If the command fails, it is retried some number of times This defaults to 5, but can be specified with the num_retries parameter If all the retries fail, an exception is thrown Between retries it will sleep for a given period, defaulting to 2 seconds
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/deployinator/helpers.rb', line 115 def run_cmd_with_retries(cmd, num_retries=5, sleep_seconds=2, timing_metric=nil) for i in 1..num_retries if i == num_retries then result = run_cmd(cmd, timing_metric) else result = run_cmd(cmd, timing_metric, false) end if result[:exit_code] == 0 return result else retries_remaining = num_retries - i unless i == num_retries log_and_stream("`#{cmd}` failed, will retry #{retries_remaining} more times<br>") sleep sleep_seconds end end end raise "Unable to execute `#{cmd}` after retrying #{num_retries} times" end |
#run_log_path ⇒ Object
21 22 23 |
# File 'lib/deployinator/helpers.rb', line 21 def run_log_path RUN_LOG_PATH end |
#run_log_url(filename) ⇒ Object
Public: given a run logs filename, return a full URL to the runlg
Params:
filename - string of the filename
Returns a string URL where that runlog can be viewed
463 464 465 |
# File 'lib/deployinator/helpers.rb', line 463 def run_log_url(filename) "http://#{Deployinator.hostname}/run_logs/view/#{filename}" end |
#runlog_filename(name = nil) ⇒ Object
gives the filename to send runlog to based on whether we are in the main thread or not We do this because we want to be able to use log_and_stream seamlessly in a parallel thread. So, all log_and_stream calls in all but the main thread will log to a seaparate file output - String filename to log to
88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/deployinator/helpers.rb', line 88 def runlog_filename(name=nil) if @filename if Thread.main == Thread.current @filename elsif Thread.current[:logfile_name] Thread.current[:logfile_name] elsif name Thread.current[:logfile_name] = runlog_thread_filename(name) Thread.current[:logfile_name] else raise 'Logfile name not defined in thread. Expecting name parameter to be passed in.' end end end |
#runlog_thread_filename(name) ⇒ Object
gives us the filename to log to in thread output - String filename for thread
105 106 107 |
# File 'lib/deployinator/helpers.rb', line 105 def runlog_thread_filename(name) @filename + '-' + name.to_s end |
#send_email(options) ⇒ Object
233 234 235 |
# File 'lib/deployinator/helpers.rb', line 233 def send_email() Pony.mail() end |
#stack ⇒ Object
205 206 207 |
# File 'lib/deployinator/helpers.rb', line 205 def stack @stack end |
#strip_ws_to_nil(s) ⇒ Object
Public: strips all of the whitespace from a string. If the string only whitespace, return nil.
s - the string to strip whitespace from
Example
if strip_ws_to_nil(hostname).nil?
puts "blank hostname is not valid!"
end
Returns A whitespace-free string or nil.
359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/deployinator/helpers.rb', line 359 def strip_ws_to_nil(s) if s.nil? nil else s = s.gsub(/\s+/, "") if s == '' nil else s end end end |
#timing_log(duration, type, stack, timestamp = nil) ⇒ Object
575 576 577 578 579 580 581 582 583 |
# File 'lib/deployinator/helpers.rb', line 575 def timing_log(duration, type, stack, =nil) if ( == nil) then = Time.now.to_i end current = now() log_string_to_file("#{current}|#{type}|#{stack}|#{duration}", Deployinator.timing_log_path) raise_event(:timing_log, {:duration => duration, :current => current, :type => type, :timestamp => }) end |
#unlock_pushes(stack) ⇒ Object
425 426 427 |
# File 'lib/deployinator/helpers.rb', line 425 def unlock_pushes(stack) system(%Q{rm #{push_lock_path(stack)}}) end |
#with_timeout(seconds, description = nil, throw_exception = false, quiet = false, extra_opts = {}, &block) ⇒ Object
Public: wrap a block into a timeout
seconds - timeout in seconds description - optional description for logging (default:“”) throw_exception - options param to throw exception back up stack quiet - optional boolean for logging as a big red warning using the stderr div class extra_opts - optional hash to pass along to plugins &block - block to call
Example
with_timeout(20){system("curl -s http://google.com")}
with_timeout 30 do; system("curl -s http://google.com"); end
Returns nothing
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
# File 'lib/deployinator/helpers.rb', line 481 def with_timeout(seconds, description=nil, throw_exception=false, quiet=false, extra_opts={}, &block) begin Timeout.timeout(seconds) do yield end rescue Timeout::Error => e info = "#{Time.now}: Timeout: #{e}" info += " for #{description}" unless description.nil? # log and stream if log filename is not undefined if (/undefined/ =~ @filename).nil? if quiet log_and_stream "#{info}<br>" else log_and_stream "<div class=\"stderr\">#{info}</div>" end end state = { :seconds => seconds, :info => info, :stack => stack, :extra_opts => extra_opts } raise_event(:timeout, state) if throw_exception raise e end "" end end |
#write_file(str, file) ⇒ Object
40 41 42 43 44 |
# File 'lib/deployinator/helpers.rb', line 40 def write_file(str, file) File.open("#{RUN_LOG_PATH}#{file}", "a:UTF-8") do |f| f.print str.force_encoding("UTF-8") end end |
#write_to_cache(cache_file, contents) ⇒ Object
Public: writes the supplied contents to the cache file, ensuring that encoding is correct
Parameters:
cache_file: path to the cache file
content: the data to write to the file
Returns nothing
407 408 409 410 411 |
# File 'lib/deployinator/helpers.rb', line 407 def write_to_cache(cache_file, contents) File.open(cache_file, 'w:UTF-8') do |f| f.write(contents.force_encoding('UTF-8')) end end |