production.rake 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. def failed; "[ \033[31mFAIL\033[0m ]"; end
  2. def ok; "[ \033[32mOK\033[0m ]"; end
  3. def run_as_root
  4. return true if ENV['USER'] == 'root'
  5. puts "#{failed} Please run this command as root or with sudo\n\n"
  6. exit -1
  7. end
  8. def runit_installed
  9. return true unless `which sv` && $?.to_i != 0
  10. puts "#{failed} Please install runit: \n\nsudo apt-get install runit\n\n"
  11. exit -1
  12. end
  13. def remove_upstart_config
  14. return true unless File.exists?('/etc/init/huginn.conf')
  15. puts "#{failed} Please stop huginn and remove the huginn upstart init scripts:\n\n"
  16. puts "sudo stop huginn"
  17. puts "sudo rm /etc/init/huginn*\n\n"
  18. exit -1
  19. end
  20. namespace :production do
  21. task :check do |t|
  22. remove_upstart_config
  23. runit_installed
  24. puts "#{ok} Everything is fine" if t.application.top_level_tasks.include? 'production:check'
  25. end
  26. task :stop => :check do
  27. puts "Stopping huginn ..."
  28. run_sv('stop')
  29. end
  30. task :start => :check do
  31. puts "Startig huginn ..."
  32. run_sv('start')
  33. end
  34. task :status => :check do
  35. run_sv('status')
  36. end
  37. task :restart => :check do
  38. puts "Restarting huginn ..."
  39. run_sv('restart')
  40. end
  41. task :export => :check do
  42. run_as_root
  43. Rake::Task['production:stop'].execute
  44. puts "Exporting new services ..."
  45. run('rm -rf /etc/service/huginn*')
  46. run('foreman export runit -a huginn -l /home/huginn/huginn/log /etc/service')
  47. services = Dir.glob('/etc/service/huginn*')
  48. while services.length > 0
  49. services.each do |p|
  50. supervise = File.join(p, 'supervise')
  51. next if !Dir.exists?(supervise)
  52. run("chown -R huginn:huginn #{p}")
  53. services.delete(p)
  54. end
  55. sleep 0.1
  56. end
  57. end
  58. end
  59. def run_sv(command)
  60. Dir.glob('/etc/service/huginn*').each do |p|
  61. with_retries do
  62. run("sv #{command} #{File.basename(p)}")
  63. end
  64. end
  65. end
  66. def run(cmd, verbose=false)
  67. output = `#{cmd}`
  68. if $?.to_i != 0
  69. raise "'#{cmd}' exited with a non-zero return value: #{output}"
  70. end
  71. puts output if verbose && output.strip != ''
  72. output
  73. end
  74. def with_retries(&block)
  75. tries ||= 5
  76. output = block.call
  77. rescue StandardError => e
  78. retry unless (tries -= 1).zero?
  79. raise e
  80. else
  81. puts output
  82. end