Module: Bluepill::Socket

Extended by:
Socket
Included in:
Socket
Defined in:
lib/bluepill/socket.rb

Constant Summary collapse

TIMEOUT =

Used for client commands

60
MAX_ATTEMPTS =
5

Instance Method Summary collapse

Instance Method Details

#client(base_dir, name, &block) ⇒ Object



11
12
13
# File 'lib/bluepill/socket.rb', line 11

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

#client_command(base_dir, name, command) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/bluepill/socket.rb', line 15

def client_command(base_dir, name, command)
  res = nil
  MAX_ATTEMPTS.times do |current_attempt|
    begin
      client(base_dir, name) do |socket|
        Timeout.timeout(TIMEOUT) do
          socket.puts command
          res = Marshal.load(socket.read)
        end
      end
      break
    rescue EOFError, Timeout::Error
      if current_attempt == MAX_ATTEMPTS - 1
        abort("Socket Timeout: Server may not be responding")
      end
      puts "Retry #{current_attempt + 1} of #{MAX_ATTEMPTS}"
    end
  end
  res
end

#server(base_dir, name) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/bluepill/socket.rb', line 36

def server(base_dir, name)
  socket_path = self.socket_path(base_dir, name)
  begin
    UNIXServer.open(socket_path)
  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)
      return UNIXServer.open(socket_path)
    else
      logger.err("Server is already running!")
      exit(7)
    end
  end
end

#socket_path(base_dir, name) ⇒ Object



54
55
56
# File 'lib/bluepill/socket.rb', line 54

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