Class: Eye::Server

Inherits:
Object show all
Includes:
Celluloid::IO
Defined in:
lib/eye/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket_path) ⇒ Server

Returns a new instance of Server.


10
11
12
13
14
15
16
17
18
# File 'lib/eye/server.rb', line 10

def initialize(socket_path)
  @socket_path = socket_path
  @server = begin
    UNIXServer.open(socket_path)
  rescue Errno::EADDRINUSE
    unlink_socket_file
    UNIXServer.open(socket_path)
  end
end

Instance Attribute Details

#serverObject (readonly)

Returns the value of attribute server


8
9
10
# File 'lib/eye/server.rb', line 8

def server
  @server
end

#socket_pathObject (readonly)

Returns the value of attribute socket_path


8
9
10
# File 'lib/eye/server.rb', line 8

def socket_path
  @socket_path
end

Instance Method Details

#close_socketObject


69
70
71
72
# File 'lib/eye/server.rb', line 69

def close_socket
  @server.close if @server
  unlink_socket_file
end

#handle_connection(socket) ⇒ Object


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/eye/server.rb', line 24

def handle_connection(socket)
  text = socket.read

  begin
    # TODO, remove in 1.0

    payload = Marshal.load(text)
    raise "unknown payload #{payload.inspect}" unless payload.is_a?(Array)
    cmd, *args = payload

  rescue
    # new format
    begin
      sign, msg_size = text[0...8].unpack('N*')
      raise "unknown protocol #{sign}" unless sign == Eye::Client::SIGN
      content = text[8..-1]
      content << socket.read(msg_size - content.length) while content.length < msg_size
      payload = Marshal.load(content)
      cmd = payload[:command]
      args = payload[:args]

    rescue => ex
      error "Failed to read from socket: #{ex.message}"
      return
    end
  end

  response = Eye::Control.command(cmd, *args, {})
  socket.write(Marshal.dump(response))

rescue Errno::EPIPE
  # client timeouted
  # do nothing

ensure
  socket.close
end

#runObject


20
21
22
# File 'lib/eye/server.rb', line 20

def run
  loop { async.handle_connection @server.accept }
end

62
63
64
65
# File 'lib/eye/server.rb', line 62

def unlink_socket_file
  File.delete(@socket_path) if @socket_path
rescue
end