#!/usr/bin/env ruby # better? -> https://github.com/bluepill-rb/bluepill # ~/forever/forever.txt # test: /Users/dux/.rvm/rubies/ruby-2.3.1/bin/ruby /Users/dux/dev/lux-fw/raumdog.com/test.rb # test2: /Users/dux/.rvm/rubies/ruby-2.3.1/bin/ruby /Users/dux/dev/lux-fw/raumdog.com/test2.rb # creates ~/forever/logs and ~/forever/pids # keeps logs in size # 1 1 * * * bash -l -c 'ruby /User/adsad/../forever' require 'colorize' require 'fileutils' @root = File.expand_path('~/forever') @max_file_size_in_mb = 1 def die(data) puts data.red exit end def demonize(id, script) size = @max_file_size_in_mb * 1_000_000 # rotate big files for log_file in ["#{@root}/logs/#{id}.log", "#{@root}/logs/#{id}.err"] if File.size?(log_file).to_i > (size * 3) puts "truncate #{log_file} to #{size}".yellow data = File.read(log_file) data = data[data.length - size, size] File.open(log_file, 'w') { |f| f.write(data) } end end pid_file = "#{@root}/pids/#{id}.pid" pid = File.read(pid_file).chomp rescue nil env_id = "FOREVER_ID=#{id}_END" if pid && `ps aux | grep #{env_id} | grep #{pid}`.index(script) puts "exists #{id.ljust(15)} pid #{pid}".green else print "starting #{id.ljust(15)} pid ".yellow `nohup #{script} #{env_id} >> #{@root}/logs/#{id}.log 2>> #{@root}/logs/#{id}.err < /dev/null & echo $! > #{pid_file}` puts File.read(pid_file) end end file = "#{@root}/forever.txt" die "~/forever/forever.txt not present (#{file})" unless File.exist?(file) FileUtils.mkdir_p "#{@root}/logs" FileUtils.mkdir_p "#{@root}/pids" apps = File.read(file).to_s.split("\n") for line in apps next if line[0,1] == '#' id, script = line.split(/\s*:\s*/, 2) next unless script demonize id, script end