Class: SimplyGenius::Atmos::Ipc

Inherits:
Object
  • Object
show all
Includes:
GemLogger::LoggerSupport
Defined in:
lib/simplygenius/atmos/ipc.rb

Instance Method Summary collapse

Constructor Details

#initialize(sock_dir = Dir.tmpdir) ⇒ Ipc

Returns a new instance of Ipc.



11
12
13
# File 'lib/simplygenius/atmos/ipc.rb', line 11

def initialize(sock_dir=Dir.tmpdir)
  @sock_dir = sock_dir
end

Instance Method Details

#generate_client_scriptObject



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/simplygenius/atmos/ipc.rb', line 40

def generate_client_script
  script_file = File.join(@sock_dir, 'atmos_ipc.rb')
  File.write(script_file, <<~EOF
    #!/usr/bin/env ruby
    require 'socket'
    UNIXSocket.open('#{@socket_path}') {|c| c.puts(ARGV[0] || $stdin.read); puts c.gets }
  EOF
  )
  FileUtils.chmod('+x', script_file)
  return script_file
end

#listen(&block) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/simplygenius/atmos/ipc.rb', line 15

def listen(&block)
  raise "Already listening" if @server

  begin
    @socket_path = File.join(@sock_dir, 'atmos-ipc')
    FileUtils.rm_f(@socket_path)
    @server = UNIXServer.open(@socket_path)
  rescue ArgumentError => e
    if e.message =~ /too long unix socket path/ && @sock_dir != Dir.tmpdir
      logger.warn("Using tmp for ipc socket as path too long: #{@socket_path}")
      @sock_dir = Dir.tmpdir
      retry
    end
  end

  begin
    thread = Thread.new { run }
    block.call(@socket_path)
  ensure
    @server.close
    FileUtils.rm_f(@socket_path)
    @server = nil
  end
end