Class: Exots::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/exots/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script_path:, socket_path:, pid_path: nil, runner: Runner::Node, timeout: 5.0, auto_stop: true) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/exots/client.rb', line 12

def initialize(script_path:, socket_path:, pid_path: nil, runner: Runner::Node, timeout: 5.0, auto_stop: true)
  @script_path = script_path
  @socket_path = socket_path
  @pid_path = pid_path
  @runner = runner
  @timeout = timeout
  @running = false
  @context = nil
  @owner = false
  @owner_pid = nil

  at_exit { stop } if auto_stop
end

Instance Attribute Details

#pidObject (readonly)

Returns the value of attribute pid.



10
11
12
# File 'lib/exots/client.rb', line 10

def pid
  @pid
end

#pid_pathObject (readonly)

Returns the value of attribute pid_path.



10
11
12
# File 'lib/exots/client.rb', line 10

def pid_path
  @pid_path
end

#socket_pathObject (readonly)

Returns the value of attribute socket_path.



10
11
12
# File 'lib/exots/client.rb', line 10

def socket_path
  @socket_path
end

Instance Method Details

#call(method, params = {}) ⇒ Object



26
27
28
29
# File 'lib/exots/client.rb', line 26

def call(method, params = {})
  start unless @running
  @context.call(method, params)
end

#startObject



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
# File 'lib/exots/client.rb', line 31

def start
  return @context if @running

  lock_path = "#{@socket_path}.lock"
  # Ensure lock directory exists
  FileUtils.mkdir_p(File.dirname(lock_path))

  File.open(lock_path, File::RDWR | File::CREAT, 0o644) do |f|
    f.flock(File::LOCK_EX)

    if server_alive?
      @running = true
      @owner = false
    else
      File.unlink(@socket_path) if File.exist?(@socket_path)
      spawn_process
      wait_for_socket
      @running = true
      @owner = true
      @owner_pid = Process.pid
    end
  end

  @context = Context.new(@socket_path)
end

#stopObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/exots/client.rb', line 57

def stop
  if @owner && @pid && Process.pid == @owner_pid && process_running?
    Process.kill('TERM', @pid)
    begin
      Timeout.timeout(2) { Process.wait(@pid) }
    rescue Timeout::Error
      Process.kill('KILL', @pid)
      Process.wait(@pid)
    rescue Errno::ECHILD
      # Already gone
    end
  end
rescue Errno::ESRCH
  # Process already gone
ensure
  if @owner && Process.pid == @owner_pid
    cleanup_files
    File.unlink("#{@socket_path}.lock") if File.exist?("#{@socket_path}.lock")
  end
  @running = false
  @pid = nil
  @context = nil
  @owner = false
  @owner_pid = nil
end