Class: Daemonizr

Inherits:
Object
  • Object
show all
Defined in:
lib/daemonizr.rb

Defined Under Namespace

Classes: ClusterAlreadyRunningException, ClusterDoesNotExistException

Constant Summary collapse

CLUSTERS =
{}

Instance Method Summary collapse

Constructor Details

#initialize(instance_name, options = {}) ⇒ Daemonizr

Returns a new instance of Daemonizr.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/daemonizr.rb', line 8

def initialize(instance_name, options = {})
  @name = instance_name
  @pid_path = options[:pid_path]
  @log_to_stdout = true
  
  if options[:log_file].is_a?(String)
    raise ArgumentError.new("Invalid log_level value.") unless [:debug, :info, :warn, :error, :fatal, nil].include?(options[:log_level])
    @logger = Logger.new(options[:log_file]) 
    @logger.level = eval("Logger::#{(options[:log_level] || :info).to_s.upcase}")
  end
end

Instance Method Details

#monitor_cluster!(interval = 5) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/daemonizr.rb', line 38

def monitor_cluster!(interval = 5)
  log :info, "Monitoring of clusters starting..."
  while "ruby" > "java" do
    CLUSTERS.each_key do |cluster_name|
      CLUSTERS[cluster_name][:processes].each_key do |process_id|
        unless CLUSTERS[cluster_name][:processes][process_id].running?
          log :warn, "Process ##{process_id} of cluster '#{cluster_name}' is not running. Restarting..."
          start_daemon(cluster_name, process_id)
        end
      end
    end
    
    begin
      sleep interval
    rescue Interrupt
      # Process was killed. Stop clusters.
      puts "\n"
      log :info, "Received SIGTERM. Stopping all clusters and stop monitoring."
      stop_all_clusters
      log :info, "Monitoring stopped."
      return true
    end
  end
end

#start_cluster(name, count, prok) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/daemonizr.rb', line 20

def start_cluster(name, count, prok)
  log :info, "Starting new cluster named '#{name}' with #{count} processes..."
  raise "Can't start another cluster with the name #{name}. Already running." if cluster_exists?(name)
  CLUSTERS[name] = { :count => count, :proc => prok, :processes => {} }
  (1..count).each do |id|
    log :debug, "Asking to start process #{id}/#{count} for cluster '#{name}'..."
    start_daemon(name, id)
  end
  true
end

#stop_all_clustersObject



31
32
33
34
35
36
# File 'lib/daemonizr.rb', line 31

def stop_all_clusters
  log :debug, "Stopping all clusters..."
  CLUSTERS.each_key do |k|
    stop_cluster(k)
  end
end