Sha256: 2f73e9185a4084606dbbd9c8d37502d428edfd43c01dc89cb1a208d31a066325

Contents?: true

Size: 1.66 KB

Versions: 3

Compression:

Stored size: 1.66 KB

Contents

# -*- encoding: utf-8 -*-

require 'socket'
require 'timeout'

require 'coolio'

module EventedBluepill
  module Socket
    class CmdListenerConnection < Coolio::UNIXSocket
      def initialize(socket, application)
        @application = application
        super(socket)
      end

      def on_read(data)
        command, *args = data.strip.split(":")
        response = begin
          @application.send(command, *args)
        rescue Exception => e
          e
        end
        write(Marshal.dump(response))
      end
    end

    TIMEOUT = 10

    extend self

    def client(base_dir, name, &b)
      UNIXSocket.open(socket_path(base_dir, name), &b)
    end

    def client_command(base_dir, name, command)
      client(base_dir, name) do |socket|
        Timeout.timeout(TIMEOUT) do
          socket.puts command
          Marshal.load(socket)
        end
      end
    rescue EOFError, Timeout::Error
      abort("Socket Timeout: Server may not be responding")
    end

    def server(base_dir, name, application)
      socket_path = self.socket_path(base_dir, name)
      begin
        Coolio::UNIXServer.new(socket_path, CmdListenerConnection, application)
      rescue Errno::EADDRINUSE
        # if sock file has been created. test to see if there is a server
        begin
          UNIXSocket.open(socket_path)
        rescue Errno::ECONNREFUSED
          File.delete(socket_path)
          Coolio::UNIXServer.new(socket_path, CmdListenerConnection, application)
        else
          logger.err("Server is already running!")
          exit(7)
        end
      end
    end

    def socket_path(base_dir, name)
      File.join(base_dir, 'socks', name + ".sock")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
evented_bluepill-0.0.52 lib/evented_bluepill/socket.rb
evented_bluepill-0.0.51 lib/evented_bluepill/socket.rb
evented_bluepill-0.0.50 lib/evented_bluepill/socket.rb