Class: DaemonController

Inherits:
Object
  • Object
show all
Defined in:
lib/daemon_controller.rb,
lib/daemon_controller/version.rb,
lib/daemon_controller/lock_file.rb

Overview

daemon_controller, library for robust daemon management Copyright © 2010-2025 Asynchronous B.V.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Defined Under Namespace

Classes: AlreadyStarted, ConnectError, Error, InternalCommandErrorResult, InternalCommandOkResult, InternalCommandTimeoutResult, LockFile, StartError, StartTimeout, StopError, StopTimeout, TimeoutError

Constant Summary collapse

ALLOWED_CONNECT_EXCEPTIONS =
[Errno::ECONNREFUSED, Errno::ENETUNREACH,
Errno::ETIMEDOUT, Errno::ECONNRESET, Errno::EINVAL,
Errno::EADDRNOTAVAIL]
SPAWNER_FILE =
File.absolute_path(File.join(File.dirname(__FILE__),
"daemon_controller", "spawn.rb"))
MAJOR =
3
MINOR =
0
TINY =
2
VERSION_STRING =
"#{MAJOR}.#{MINOR}.#{TINY}"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(identifier:, start_command:, ping_command:, pid_file:, log_file:, lock_file: nil, stop_command: nil, restart_command: nil, before_start: nil, start_timeout: 30, start_abort_timeout: 10, stop_timeout: 30, log_file_activity_timeout: 10, ping_interval: 0.1, stop_graceful_signal: "TERM", dont_stop_if_pid_file_invalid: false, daemonize_for_me: false, keep_ios: nil, env: {}, logger: nil) ⇒ DaemonController

Create a new DaemonController object.

See doc/OPTIONS.md for options docs.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/daemon_controller.rb', line 73

def initialize(identifier:, start_command:, ping_command:, pid_file:, log_file:,
  lock_file: nil, stop_command: nil, restart_command: nil, before_start: nil,
  start_timeout: 30, start_abort_timeout: 10, stop_timeout: 30,
  log_file_activity_timeout: 10, ping_interval: 0.1, stop_graceful_signal: "TERM", dont_stop_if_pid_file_invalid: false,
  daemonize_for_me: false, keep_ios: nil, env: {}, logger: nil)
  @identifier = identifier
  @start_command = start_command
  @ping_command = ping_command
  @pid_file = pid_file
  @log_file = log_file

  @lock_file = determine_lock_file(lock_file, identifier, pid_file)
  @stop_command = stop_command
  @restart_command = restart_command
  @before_start = before_start
  @start_timeout = start_timeout
  @start_abort_timeout = start_abort_timeout
  @stop_timeout = stop_timeout
  @log_file_activity_timeout = log_file_activity_timeout
  @ping_interval = ping_interval
  @stop_graceful_signal = stop_graceful_signal
  @dont_stop_if_pid_file_invalid = dont_stop_if_pid_file_invalid
  @daemonize_for_me = daemonize_for_me
  @keep_ios = keep_ios
  @env = env
  @logger = logger
end

Class Method Details

.can_ping_unix_sockets?Boolean

Checks whether ping Unix domain sockets is supported. Currently this is supported on all Ruby implementations, except JRuby.

Returns:

  • (Boolean)


232
233
234
# File 'lib/daemon_controller.rb', line 232

def self.can_ping_unix_sockets?
  RUBY_PLATFORM != "java"
end

Instance Method Details

#connectObject

Connect to the daemon by running the given block, which contains the connection logic. If the daemon isn’t already running, then it will be started.

The block must return nil or raise Errno::ECONNREFUSED, Errno::ENETUNREACH, Errno::ETIMEDOUT, Errno::ECONNRESET, Errno::EINVAL and Errno::EADDRNOTAVAIL to indicate that the daemon cannot be connected to. It must return non-nil if the daemon can be connected to. Upon successful connection, the return value of the block will be returned by #connect.

Note that the block may be called multiple times.

Raises:

  • StartError - an attempt to start the daemon was made, but the start command failed with an error.

  • StartTimeout - an attempt to start the daemon was made, but the daemon did not start in time, or it failed after it has gone into the background.

  • ConnectError - the daemon wasn’t already running, but we couldn’t connect to the daemon even after starting it.



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/daemon_controller.rb', line 134

def connect
  connection = nil
  @lock_file.shared_lock do
    connection = yield
  rescue *ALLOWED_CONNECT_EXCEPTIONS
    connection = nil
  end
  if connection.nil?
    @lock_file.exclusive_lock do
      unless daemon_is_running?
        start_without_locking
      end
      connect_exception = nil
      begin
        connection = yield
      rescue *ALLOWED_CONNECT_EXCEPTIONS => e
        connection = nil
        connect_exception = e
      end
      if connection.nil?
        # Daemon is running but we couldn't connect to it. Possible
        # reasons:
        # - The daemon froze.
        # - Bizarre security restrictions.
        # - There's a bug in the yielded code.
        if connect_exception
          raise ConnectError, "Cannot connect to the daemon: #{connect_exception} (#{connect_exception.class})"
        else
          raise ConnectError, "Cannot connect to the daemon"
        end
      else
        connection
      end
    end
  else
    connection
  end
end

#pidObject

Returns the daemon’s PID, as reported by its PID file. Returns the PID as an integer, or nil there is no valid PID in the PID file.

This method doesn’t check whether the daemon’s actually running. Use #running? if you want to check whether it’s actually running.

Raises SystemCallError or IOError if something went wrong during reading of the PID file.



212
213
214
215
216
# File 'lib/daemon_controller.rb', line 212

def pid
  @lock_file.shared_lock do
    read_pid_file
  end
end

#restartObject

Restarts the daemon. Uses the restart_command if provided, otherwise calls #stop and #start.



195
196
197
198
199
200
201
202
# File 'lib/daemon_controller.rb', line 195

def restart
  if @restart_command
    run_command(@restart_command)
  else
    stop
    start
  end
end

#running?Boolean

Checks whether the daemon is still running. This is done by reading the PID file and then checking whether there is a process with that PID.

Raises SystemCallError or IOError if something went wrong during reading of the PID file.

Returns:

  • (Boolean)


224
225
226
227
228
# File 'lib/daemon_controller.rb', line 224

def running?
  @lock_file.shared_lock do
    daemon_is_running?
  end
end

#startObject

Start the daemon and wait until it can be pinged.

Raises:

  • AlreadyStarted - the daemon is already running.

  • StartError - the start command failed.

  • StartTimeout - the daemon did not start in time. This could also mean that the daemon failed after it has gone into the background.



108
109
110
111
112
# File 'lib/daemon_controller.rb', line 108

def start
  @lock_file.exclusive_lock do
    start_without_locking
  end
end

#stopObject

Stop the daemon and wait until it has exited.

Raises:

  • StopError - the stop command failed.

  • StopTimeout - the daemon didn’t stop in time.



178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/daemon_controller.rb', line 178

def stop
  @lock_file.exclusive_lock do
    timeoutable(@stop_timeout) do
      allow_timeout do
        kill_daemon
        wait_until { !daemon_is_running? }
      end
    end
  end
rescue Timeout::Error
  kill_daemon_with_signal(force: true)
  wait_until { !daemon_is_running? }
  raise StopTimeout, "Daemon '#{@identifier}' did not exit in time (force killed)"
end