Class: Win32::Daemon

Inherits:
Object
  • Object
show all
Extended by:
Windows::ServiceFunctions, Windows::ServiceStructs
Includes:
Windows::ServiceConstants, Windows::ServiceFunctions, Windows::ServiceStructs
Defined in:
lib/win32/daemon.rb

Overview

The Daemon class

Constant Summary collapse

VERSION =

The version of this library

Win32::Service::VERSION
STOPPED =

Service is not running

SERVICE_STOPPED
START_PENDING =

Service has received a start signal but is not yet running

SERVICE_START_PENDING
STOP_PENDING =

Service has received a stop signal but is not yet stopped

SERVICE_STOP_PENDING
RUNNING =

Service is running

SERVICE_RUNNING
CONTINUE_PENDING =

Service has received a signal to resume but is not yet running

SERVICE_CONTINUE_PENDING
PAUSE_PENDING =

Service has received a signal to pause but is not yet paused

SERVICE_PAUSE_PENDING
PAUSED =

Service is paused

SERVICE_PAUSED
CONTROL_STOP =

Notifies service that it should stop

SERVICE_CONTROL_STOP
CONTROL_PAUSE =

Notifies service that it should pause

SERVICE_CONTROL_PAUSE
CONTROL_CONTINUE =

Notifies service that it should resume

SERVICE_CONTROL_CONTINUE
CONTROL_INTERROGATE =

Notifies service that it should return its current status information

SERVICE_CONTROL_INTERROGATE
CONTROL_PARAMCHANGE =

Notifies a service that its parameters have changed

SERVICE_CONTROL_PARAMCHANGE
CONTROL_NETBINDADD =

Notifies a service that there is a new component for binding

SERVICE_CONTROL_NETBINDADD
CONTROL_NETBINDREMOVE =

Notifies a service that a component for binding has been removed

SERVICE_CONTROL_NETBINDREMOVE
CONTROL_NETBINDENABLE =

Notifies a service that a component for binding has been enabled

SERVICE_CONTROL_NETBINDENABLE
CONTROL_NETBINDDISABLE =

Notifies a service that a component for binding has been disabled

SERVICE_CONTROL_NETBINDDISABLE
IDLE =
0
SetTheServiceStatus =

Wraps SetServiceStatus.

Proc.new do |dwCurrentState, dwWin32ExitCode, dwCheckPoint, dwWaitHint|
  ss = SERVICE_STATUS.new # Current status of the service.

  # Disable control requests until the service is started.
  if dwCurrentState == SERVICE_START_PENDING
    ss[:dwControlsAccepted] = 0
  else
    ss[:dwControlsAccepted] =
    SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN |
    SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_PARAMCHANGE
  end

  # Initialize ss structure.
  ss[:dwServiceType]             = SERVICE_WIN32_OWN_PROCESS
  ss[:dwServiceSpecificExitCode] = 0
  ss[:dwCurrentState]            = dwCurrentState
  ss[:dwWin32ExitCode]           = dwWin32ExitCode
  ss[:dwCheckPoint]              = dwCheckPoint
  ss[:dwWaitHint]                = dwWaitHint

  @@dwServiceState = dwCurrentState

  # Send status of the service to the Service Controller.
  unless SetServiceStatus(@@ssh, ss)
    SetEvent(@@hStopEvent)
  end
end
ERROR_CALL_NOT_IMPLEMENTED =
0x78
Service_Ctrl_ex =

Handles control signals from the service control manager.

Proc.new do |dwCtrlCode, dwEventType, lpEventData, lpContext|
  @@waiting_control_code = dwCtrlCode
  return_value = NO_ERROR

  begin
    dwState = SERVICE_RUNNING

    case dwCtrlCode
      when SERVICE_CONTROL_STOP
        dwState = SERVICE_STOP_PENDING
      when SERVICE_CONTROL_SHUTDOWN
        dwState = SERVICE_STOP_PENDING
      when SERVICE_CONTROL_PAUSE
        dwState = SERVICE_PAUSED
      when SERVICE_CONTROL_CONTINUE
        dwState = SERVICE_RUNNING
      # else
      # TODO: Handle other control codes? Retain the current state?
    end

    # Set the status of the service except on interrogation.
    unless dwCtrlCode == SERVICE_CONTROL_INTERROGATE
      SetTheServiceStatus.call(dwState, NO_ERROR, 0, 0)
    end

    # Tell service_main thread to stop.
    if dwCtrlCode == SERVICE_CONTROL_STOP || dwCtrlCode == SERVICE_CONTROL_SHUTDOWN
      if SetEvent(@@hStopEvent) == 0
        SetTheServiceStatus.call(SERVICE_STOPPED, FFI.errno, 0, 0)
      end
    end
  rescue
    return_value = ERROR_CALL_NOT_IMPLEMENTED
  end

  return_value
end
Service_Main =

Called by the service control manager after the call to StartServiceCtrlDispatcher.

FFI::Function.new(:void, %i{ulong pointer}, blocking: false) do |dwArgc, lpszArgv|
  begin
    # Obtain the name of the service.
    if lpszArgv.address != 0
      argv = lpszArgv.get_array_of_string(0, dwArgc)
      lpszServiceName = argv[0]
    else
      lpszServiceName = ""
    end

    # Args passed to Service.start
    if dwArgc > 1
      @@Argv = argv[1..-1]
    else
      @@Argv = nil
    end

    # Register the service ctrl handler.
    @@ssh = RegisterServiceCtrlHandlerEx(
      lpszServiceName,
      Service_Ctrl_ex,
      nil
    )

    # No service to stop, no service handle to notify, nothing to do but exit.
    return if @@ssh == 0

    # The service has started.
    SetTheServiceStatus.call(SERVICE_RUNNING, NO_ERROR, 0, 0)

    SetEvent(@@hStartEvent)

    # Main loop for the service.
    while WaitForSingleObject(@@hStopEvent, 1000) != WAIT_OBJECT_0
    end

    # Main loop for the service.
    while WaitForSingleObject(@@hStopCompletedEvent, 1000) != WAIT_OBJECT_0
    end
  ensure
    # Stop the service.
    SetTheServiceStatus.call(SERVICE_STOPPED, NO_ERROR, 0, 0)
  end
end
ThreadProc =
FFI::Function.new(:ulong, [:pointer]) do |lpParameter|
  ste = FFI::MemoryPointer.new(SERVICE_TABLE_ENTRY, 2)

  s = SERVICE_TABLE_ENTRY.new(ste[0])
  s[:lpServiceName] = FFI::MemoryPointer.from_string("")
  s[:lpServiceProc] = lpParameter

  s = SERVICE_TABLE_ENTRY.new(ste[1])
  s[:lpServiceName] = nil
  s[:lpServiceProc] = nil

  # No service to step, no service handle, no ruby exceptions, just terminate the thread..
  unless StartServiceCtrlDispatcher(ste)
    return 1
  end

  return 0
end

Constants included from Windows::ServiceConstants

Windows::ServiceConstants::DELETE, Windows::ServiceConstants::ERROR_FILE_NOT_FOUND, Windows::ServiceConstants::ERROR_INSUFFICIENT_BUFFER, Windows::ServiceConstants::ERROR_MORE_DATA, Windows::ServiceConstants::ERROR_RESOURCE_NAME_NOT_FOUND, Windows::ServiceConstants::ERROR_RESOURCE_TYPE_NOT_FOUND, Windows::ServiceConstants::FORMAT_MESSAGE_FROM_SYSTEM, Windows::ServiceConstants::FORMAT_MESSAGE_IGNORE_INSERTS, Windows::ServiceConstants::IDLE_CONTROL_CODE, Windows::ServiceConstants::INFINITE, Windows::ServiceConstants::NO_ERROR, Windows::ServiceConstants::SC_ACTION_NONE, Windows::ServiceConstants::SC_ACTION_REBOOT, Windows::ServiceConstants::SC_ACTION_RESTART, Windows::ServiceConstants::SC_ACTION_RUN_COMMAND, Windows::ServiceConstants::SC_ENUM_PROCESS_INFO, Windows::ServiceConstants::SC_MANAGER_ALL_ACCESS, Windows::ServiceConstants::SC_MANAGER_CONNECT, Windows::ServiceConstants::SC_MANAGER_CREATE_SERVICE, Windows::ServiceConstants::SC_MANAGER_ENUMERATE_SERVICE, Windows::ServiceConstants::SC_MANAGER_LOCK, Windows::ServiceConstants::SC_MANAGER_MODIFY_BOOT_CONFIG, Windows::ServiceConstants::SC_MANAGER_QUERY_LOCK_STATUS, Windows::ServiceConstants::SC_STATUS_PROCESS_INFO, Windows::ServiceConstants::SERVICE_ACCEPT_HARDWAREPROFILECHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_NETBINDCHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_PARAMCHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_PAUSE_CONTINUE, Windows::ServiceConstants::SERVICE_ACCEPT_POWEREVENT, Windows::ServiceConstants::SERVICE_ACCEPT_PRESHUTDOWN, Windows::ServiceConstants::SERVICE_ACCEPT_SESSIONCHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_SHUTDOWN, Windows::ServiceConstants::SERVICE_ACCEPT_STOP, Windows::ServiceConstants::SERVICE_ACCEPT_TIMECHANGE, Windows::ServiceConstants::SERVICE_ACCEPT_TRIGGEREVENT, Windows::ServiceConstants::SERVICE_ACTIVE, Windows::ServiceConstants::SERVICE_ADAPTER, Windows::ServiceConstants::SERVICE_ALL_ACCESS, Windows::ServiceConstants::SERVICE_AUTO_START, Windows::ServiceConstants::SERVICE_BOOT_START, Windows::ServiceConstants::SERVICE_CHANGE_CONFIG, Windows::ServiceConstants::SERVICE_CONFIG_DELAYED_AUTO_START_INFO, Windows::ServiceConstants::SERVICE_CONFIG_DESCRIPTION, Windows::ServiceConstants::SERVICE_CONFIG_FAILURE_ACTIONS, Windows::ServiceConstants::SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, Windows::ServiceConstants::SERVICE_CONFIG_PRESHUTDOWN_INFO, Windows::ServiceConstants::SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO, Windows::ServiceConstants::SERVICE_CONFIG_SERVICE_SID_INFO, Windows::ServiceConstants::SERVICE_CONTINUE_PENDING, Windows::ServiceConstants::SERVICE_CONTROL_CONTINUE, Windows::ServiceConstants::SERVICE_CONTROL_DEVICEEVENT, Windows::ServiceConstants::SERVICE_CONTROL_HARDWAREPROFILECHANGE, Windows::ServiceConstants::SERVICE_CONTROL_INTERROGATE, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDADD, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDDISABLE, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDENABLE, Windows::ServiceConstants::SERVICE_CONTROL_NETBINDREMOVE, Windows::ServiceConstants::SERVICE_CONTROL_PARAMCHANGE, Windows::ServiceConstants::SERVICE_CONTROL_PAUSE, Windows::ServiceConstants::SERVICE_CONTROL_POWEREVENT, Windows::ServiceConstants::SERVICE_CONTROL_PRESHUTDOWN, Windows::ServiceConstants::SERVICE_CONTROL_SESSIONCHANGE, Windows::ServiceConstants::SERVICE_CONTROL_SHUTDOWN, Windows::ServiceConstants::SERVICE_CONTROL_STOP, Windows::ServiceConstants::SERVICE_CONTROL_TIMECHANGE, Windows::ServiceConstants::SERVICE_CONTROL_TRIGGEREVENT, Windows::ServiceConstants::SERVICE_DEMAND_START, Windows::ServiceConstants::SERVICE_DISABLED, Windows::ServiceConstants::SERVICE_DRIVER, Windows::ServiceConstants::SERVICE_ENUMERATE_DEPENDENTS, Windows::ServiceConstants::SERVICE_ERROR_CRITICAL, Windows::ServiceConstants::SERVICE_ERROR_IGNORE, Windows::ServiceConstants::SERVICE_ERROR_NORMAL, Windows::ServiceConstants::SERVICE_ERROR_SEVERE, Windows::ServiceConstants::SERVICE_FILE_SYSTEM_DRIVER, Windows::ServiceConstants::SERVICE_INACTIVE, Windows::ServiceConstants::SERVICE_INTERACTIVE_PROCESS, Windows::ServiceConstants::SERVICE_INTERROGATE, Windows::ServiceConstants::SERVICE_KERNEL_DRIVER, Windows::ServiceConstants::SERVICE_NO_CHANGE, Windows::ServiceConstants::SERVICE_PAUSED, Windows::ServiceConstants::SERVICE_PAUSE_CONTINUE, Windows::ServiceConstants::SERVICE_PAUSE_PENDING, Windows::ServiceConstants::SERVICE_QUERY_CONFIG, Windows::ServiceConstants::SERVICE_QUERY_STATUS, Windows::ServiceConstants::SERVICE_RECOGNIZER_DRIVER, Windows::ServiceConstants::SERVICE_RUNNING, Windows::ServiceConstants::SERVICE_START, Windows::ServiceConstants::SERVICE_START_PENDING, Windows::ServiceConstants::SERVICE_STATE_ALL, Windows::ServiceConstants::SERVICE_STOP, Windows::ServiceConstants::SERVICE_STOPPED, Windows::ServiceConstants::SERVICE_STOP_PENDING, Windows::ServiceConstants::SERVICE_SYSTEM_START, Windows::ServiceConstants::SERVICE_TYPE_ALL, Windows::ServiceConstants::SERVICE_USER_DEFINED_CONTROL, Windows::ServiceConstants::SERVICE_WIN32, Windows::ServiceConstants::SERVICE_WIN32_OWN_PROCESS, Windows::ServiceConstants::SERVICE_WIN32_SHARE_PROCESS, Windows::ServiceConstants::SE_PRIVILEGE_ENABLED, Windows::ServiceConstants::TOKEN_ADJUST_PRIVILEGES, Windows::ServiceConstants::TOKEN_QUERY, Windows::ServiceConstants::WAIT_FAILED, Windows::ServiceConstants::WAIT_OBJECT_0, Windows::ServiceConstants::WAIT_TIMEOUT

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.mainloopObject

This is a shortcut for Daemon.new + Daemon#mainloop.



210
211
212
# File 'lib/win32/daemon.rb', line 210

def self.mainloop
  new.mainloop
end

Instance Method Details

#mainloopObject

This is the method that actually puts your code into a loop and allows it to run as a service. The code that is actually run while in the mainloop is what you defined in your own Daemon#service_main method.



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/win32/daemon.rb', line 218

def mainloop
  @@waiting_control_code = IDLE_CONTROL_CODE
  @@dwServiceState = 0

  # Redirect STDIN, STDOUT and STDERR to the NUL device if they're still
  # associated with a tty. This helps newbs avoid Errno::EBADF errors.
  STDIN.reopen("NUL") if STDIN.isatty
  STDOUT.reopen("NUL") if STDOUT.isatty
  STDERR.reopen("NUL") if STDERR.isatty

  # Calling init here so that init failures never even tries to start the
  # service. Of course that means that init methods must be very quick
  # because the SCM will be receiving no START_PENDING messages while
  # init's running.
  #
  # TODO: Fix?
  service_init if respond_to?("service_init")

  # Create the event to signal the service to start.
  @@hStartEvent = CreateEvent(nil, 1, 0, nil)

  if @@hStartEvent == 0
    raise SystemCallError.new("CreateEvent", FFI.errno)
  end

  # Create the event to signal the service to stop.
  @@hStopEvent = CreateEvent(nil, 1, 0, nil)

  if @@hStopEvent == 0
    raise SystemCallError.new("CreateEvent", FFI.errno)
  end

  # Create the event to signal the service that stop has completed
  @@hStopCompletedEvent = CreateEvent(nil, 1, 0, nil)

  if @@hStopCompletedEvent == 0
    raise SystemCallError.new("CreateEvent", FFI.errno)
  end

  hThread = CreateThread(nil, 0, ThreadProc, Service_Main, 0, nil)

  if hThread == 0
    raise SystemCallError.new("CreateThread", FFI.errno)
  end

  events = FFI::MemoryPointer.new(:pointer, 2)
  events.put_pointer(0, FFI::Pointer.new(hThread))
  events.put_pointer(FFI::Pointer.size, FFI::Pointer.new(@@hStartEvent))

  while (index = WaitForMultipleObjects(2, events, 0, 1000)) == WAIT_TIMEOUT
  end

  if index == WAIT_FAILED
    raise SystemCallError.new("WaitForMultipleObjects", FFI.errno)
  end

  # The thread exited, so the show is off.
  if index == WAIT_OBJECT_0
    raise "Service_Main thread exited abnormally"
  end

  thr = Thread.new do
    begin
      while WaitForSingleObject(@@hStopEvent, 1000) == WAIT_TIMEOUT
        # Check to see if anything interesting has been signaled
        case @@waiting_control_code
          when SERVICE_CONTROL_PAUSE
            service_pause if respond_to?("service_pause")
          when SERVICE_CONTROL_CONTINUE
            service_resume if respond_to?("service_resume")
          when SERVICE_CONTROL_INTERROGATE
            service_interrogate if respond_to?("service_interrogate")
          when SERVICE_CONTROL_SHUTDOWN
            service_shutdown if respond_to?("service_shutdown")
          when SERVICE_CONTROL_PARAMCHANGE
            service_paramchange if respond_to?("service_paramchange")
          when SERVICE_CONTROL_NETBINDADD
            service_netbindadd if respond_to?("service_netbindadd")
          when SERVICE_CONTROL_NETBINDREMOVE
            service_netbindremove if respond_to?("service_netbindremove")
          when SERVICE_CONTROL_NETBINDENABLE
            service_netbindenable if respond_to?("service_netbindenable")
          when SERVICE_CONTROL_NETBINDDISABLE
            service_netbinddisable if respond_to?("service_netbinddisable")
        end

        # handle user defined control codes
        if @@waiting_control_code >= 128 && @@waiting_control_code <= 255
          if respond_to?("service_user_defined_control")
            service_user_defined_control(@@waiting_control_code)
          end
        end

        @@waiting_control_code = IDLE_CONTROL_CODE
      end

      service_stop if respond_to?("service_stop")
    ensure
      SetEvent(@@hStopCompletedEvent)
    end
  end

  if respond_to?("service_main")
    service_main(*@@Argv)
  end

  thr.join
end

#running?Boolean

Returns whether or not the service is in a running state, i.e. the service status is either RUNNING, PAUSED or IDLE.

This is typically used within your service_main method to setup the main loop. For example:

class MyDaemon < Daemon
   def service_main
      while running?
         # Your main loop here
      end
   end
end

Returns:

  • (Boolean)


362
363
364
# File 'lib/win32/daemon.rb', line 362

def running?
  [SERVICE_RUNNING, SERVICE_PAUSED, 0].include?(@@dwServiceState)
end

#stateObject

Returns the state of the service (as an constant integer) which can be any of the service status constants, e.g. RUNNING, PAUSED, etc.

This method is typically used within your service_main method to setup the loop. For example:

class MyDaemon < Daemon
  def service_main
    while state == RUNNING || state == PAUSED || state == IDLE
      # Your main loop here
    end
  end
end

See the Daemon#running? method for an abstraction of the above code.



343
344
345
# File 'lib/win32/daemon.rb', line 343

def state
  @@dwServiceState
end