production.rake 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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.exist?('/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 "Starting huginn ..."
  32. run_sv('start')
  33. end
  34. task :force_stop => :check do
  35. puts "Force stopping huginn ..."
  36. run_sv('force-stop')
  37. end
  38. task :status => :check do
  39. run_sv('status')
  40. end
  41. task :restart => :check do
  42. puts "Restarting huginn ..."
  43. run_sv('restart')
  44. end
  45. task :export => :check do
  46. run_as_root
  47. Rake::Task['production:stop'].execute
  48. puts "Exporting new services ..."
  49. run('rm -rf /etc/service/huginn*')
  50. run('foreman export runit -a huginn -l /home/huginn/huginn/log /etc/service')
  51. services = Dir.glob('/etc/service/huginn*')
  52. while services.length > 0
  53. services.each do |p|
  54. supervise = File.join(p, 'supervise')
  55. next if !Dir.exist?(supervise)
  56. run("chown -R huginn:huginn #{p}")
  57. services.delete(p)
  58. end
  59. sleep 0.1
  60. end
  61. end
  62. end
  63. def run_sv(command)
  64. Dir.glob('/etc/service/huginn*').each do |p|
  65. with_retries do
  66. run("sv #{command} #{File.basename(p)}")
  67. end
  68. end
  69. end
  70. def run(cmd, verbose=false)
  71. output = `#{cmd}`
  72. if $?.to_i != 0
  73. raise "'#{cmd}' exited with a non-zero return value: #{output}"
  74. end
  75. puts output if verbose && output.strip != ''
  76. output
  77. end
  78. def with_retries(&block)
  79. tries ||= 5
  80. output = block.call
  81. rescue StandardError => e
  82. retry unless (tries -= 1).zero?
  83. raise e
  84. else
  85. puts output
  86. end