Sha256: b833d0c63a667dbd98bf7b4e44583771b2625f2367005c9e32a10f604a090dbc

Contents?: true

Size: 1.69 KB

Versions: 2

Compression:

Stored size: 1.69 KB

Contents

module Celluloid
  # Supervisors are actors that watch over other actors and restart them if
  # they crash
  class Supervisor
    include Celluloid
    trap_exit :restart_actor

    # Retrieve the actor this supervisor is supervising
    attr_reader :actor

    class << self
      # Define the root of the supervision tree
      attr_accessor :root

      def supervise(klass, *args, &block)
        new(nil, klass, *args, &block)
      end

      def supervise_as(name, klass, *args, &block)
        new(name, klass, *args, &block)
      end
    end

    def initialize(name, klass, *args, &block)
      @name, @klass, @args, @block = name, klass, args, block
      @started = false

      start_actor
    end

    def finalize
      @actor.terminate if @actor and @actor.alive?
    end

    def start_actor(start_attempts = 3, sleep_interval = 30)
      failures = 0

      begin
        @actor = @klass.new_link(*@args, &@block)
      rescue
        failures += 1
        if failures >= start_attempts
          failures = 0

          Logger.warn("#{@klass} is crashing on initialize too quickly, sleeping for #{sleep_interval} seconds")
          sleep sleep_interval
        end
        retry
      end

      @started = true
      Actor[@name] = @actor if @name
    end

    # When actors die, regardless of the reason, restart them
    def restart_actor(actor, reason)
      # If the actor we're supervising exited cleanly, exit the supervisor cleanly too
      terminate unless reason

      start_actor if @started
    end

    def inspect
      str = "#<#{self.class}(#{@klass}):0x#{object_id.to_s(16)}"
      str << " " << @args.map { |arg| arg.inspect }.join(' ') unless @args.empty?
      str << ">"
    end
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
celluloid-0.11.0 lib/celluloid/supervisor.rb
kulesa-celluloid-0.10.2 lib/celluloid/supervisor.rb