Sha256: 0f0727933d702c5cf514aa5be39935f7d70d5724c0631d525f087eeb79c4ff17

Contents?: true

Size: 1.79 KB

Versions: 2

Compression:

Stored size: 1.79 KB

Contents

require 'daemonic/logging'
require 'daemonic/worker'

module Daemonic
  class Pool
    include Logging

    attr_reader :config

    attr_reader :workers, :desired_workers

    def initialize(config)
      @config = config
      @workers = []
      reload_desired_workers
    end

    def start
      wait_for global_timeout do
        increase if count < desired_workers
        count == desired_workers
      end
      decrease while count > desired_workers
    end

    def restart
      workers.each do |worker|
        worker.restart
        yield worker if block_given?
      end
    end

    def stop
      workers.each do |worker|
        worker.stop
        yield worker if block_given?
      end
    end

    def hup
      reload_desired_workers
      workers.each(&:hup)
      start
    end

    def count
      workers.count { |worker| worker.running? }
    end

    def increase
      workers << start_worker(workers.size)
    end

    def increase!
      @desired_workers += 1
      increase
    end

    def decrease
      workers.pop.stop
    end

    def decrease!
      @desired_workers -= 1
      decrease
    end

    def monitor
      workers.each(&:monitor)
    end

    private

    def start_worker(num)
      Worker.new(
        index:  num,
        config: config,
      ).tap(&:start)
    end

    def reload_desired_workers
      @desired_workers = config.workers
    end

    def global_timeout
      (desired_workers * 2) + 1
    end

    def wait_for(timeout=2)
      deadline = Time.now + timeout
      until Time.now >= deadline
        result = yield
        if result
          return
        else
          sleep 0.1
        end
      end
      fatal "Unable to get to boot the right amount of workers. Running: #{count}, desired: #{desired_workers}."
      stop
      exit 1
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
daemonic-0.0.2 lib/daemonic/pool.rb
daemonic-0.0.1 lib/daemonic/pool.rb