Main Page   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members   File Members   Related Pages  

NT_Service.h

Go to the documentation of this file.
00001 // -*- C++ -*-
00002 
00003 //==========================================================================
00004 /**
00005  *  @file    NT_Service.h
00006  *
00007  *  $Id: NT_Service.h,v 1.1.1.4 2003/02/21 18:36:32 chad Exp $
00008  *
00009  *  @author Steve Huston <shuston@riverace.com>
00010  */
00011 //==========================================================================
00012 
00013 #ifndef ACE_NT_SERVICE_H
00014 #define ACE_NT_SERVICE_H
00015 
00016 #include "ace/pre.h"
00017 
00018 #include "ace/config-all.h"
00019 
00020 #if !defined (ACE_LACKS_PRAGMA_ONCE)
00021 # pragma once
00022 #endif /* ACE_LACKS_PRAGMA_ONCE */
00023 
00024 #if defined (ACE_WIN32) && !defined (ACE_HAS_PHARLAP) && \
00025    !defined (ACE_HAS_WINCE)
00026 
00027 #include "ace/ACE.h"
00028 #include "ace/OS_Log_Msg_Attributes.h"
00029 #include "ace/Service_Object.h"
00030 #include "ace/Synch.h"
00031 #include "ace/Task.h"
00032 
00033 // ACE_NT_SERVICE_START_TIMEOUT is an estimate of the number of
00034 // milliseconds your service will take to start.  Default is 5
00035 // seconds; you can pass a different value (or set one) when you
00036 // create the ACE_NT_Service object for your service.
00037 #if !defined ACE_NT_SERVICE_START_TIMEOUT
00038 #define ACE_NT_SERVICE_START_TIMEOUT  5000
00039 #endif /* ACE_NT_SERVICE_TIMEOUT */
00040 
00041 /**
00042  * @class ACE_NT_Service
00043  *
00044  * @brief Provide the base class which defines the interface for controlling
00045  * an NT service.
00046  *
00047  * NT Services can be implemented using the framework defined by
00048  * the ACE_NT_Service class, and the macros defined in this file.
00049  * Some quick refresher notes on NT Services:
00050  *
00051  *   - The main program defines an array of entries describing the
00052  *     services offered.  The ACE_NT_SERVICE_ENTRY macro can help with
00053  *     this.
00054  *   - For each service, a separate ServiceMain and Handler function
00055  *     need to be defined.  These are taken care of by the
00056  *     ACE_NT_SERVICE_DEFINE macro.
00057  *   - When the main program/thread calls
00058  *     StartServiceCtrlDispatcher, NT creates a thread for each
00059  *     service, and runs the ServiceMain function for the service in
00060  *     that new thread.  When that thread exits, the service is gone.
00061  *
00062  *   To use this facility, you could derive a class from
00063  *   ACE_Service_Object (if you want to start via ACE's service
00064  *   configurator), or use any other class to run when the image
00065  *   starts (assuming that NT runs the image).  You must set up an
00066  *   NT SERVICE_TABLE_ENTRY array to define your service(s).  You
00067  *   can use the ACE_NT_SERVICE_... macros defined below for this.
00068  *
00069  *   A SERVICE_TABLE might look like this:
00070  *       ACE_NT_SERVICE_REFERENCE(Svc1);  // If service is in another file
00071  *       SERVICE_TABLE_ENTRY myServices[] = {
00072  *                    ACE_NT_SERVICE_ENTRY ("MyNeatService", Svc1),
00073  *                    { 0, 0 } };
00074  *
00075  *   In the file where your service(s) are implemented, use the
00076  *   ACE_NT_SERVICE_DEFINE macro to set up the following:
00077  *    1. A pointer to the service's implementation object (must be derived
00078  *       from ACE_NT_Service).
00079  *    2. The service's Handler function (forwards all requests to the
00080  *       ACE_NT_Service-derived object's handle_control function).
00081  *    3. The service's ServiceMain function.  Creates a new instance
00082  *       of the ACE_NT_Service-derived class SVCCLASS, unless one has
00083  *       been created already.
00084  *
00085  *   If you are using all the default constructor values, you can
00086  *   let the generated ServiceMain function create the object, else
00087  *   you need to create it by hand before calling
00088  *   StartServiceCtrlDispatcher.  Set the pointer so ServiceMain
00089  *   won't create another one.  Another reason you may want to do
00090  *   the object creation yourself is if you want to also implement
00091  *   suspend and resume functions (the ones inherited from
00092  *   ACE_Service_Object) to do something intelligent to the services
00093  *   which are running, like call their handle_control functions to
00094  *   request suspend and resume actions, similar to what NT would do
00095  *   if a Services control panel applet would do if the user clicks
00096  *   on Suspend.
00097  */
00098 class ACE_Export ACE_NT_Service : public ACE_Task<ACE_MT_SYNCH>
00099 {
00100 
00101 public:
00102   // = Initialization and termination methods.
00103   /// Constructor primarily for use when running the service.
00104   ACE_NT_Service (DWORD start_timeout = ACE_NT_SERVICE_START_TIMEOUT,
00105                   DWORD service_type = SERVICE_WIN32_OWN_PROCESS,
00106                   DWORD controls_mask = SERVICE_ACCEPT_STOP);
00107 
00108   /// Constructor primarily for use when inserting/removing/controlling
00109   /// the service.
00110   ACE_NT_Service (const ACE_TCHAR *name,
00111                   const ACE_TCHAR *desc = 0,
00112                   DWORD start_timeout = ACE_NT_SERVICE_START_TIMEOUT,
00113                   DWORD service_type = SERVICE_WIN32_OWN_PROCESS,
00114                   DWORD controls_mask = SERVICE_ACCEPT_STOP);
00115 
00116   virtual ~ACE_NT_Service (void);
00117 
00118   // = Functions to operate the service
00119 
00120   /**
00121    * Hook called to open the service.  By default, sets the service
00122    * status to SERVICE_START_PENDING, calls the @c svc() method,
00123    * interprets and sets the service status, and returns.
00124    */
00125   virtual int open (void *args = 0);
00126 
00127   /**
00128    * Hook called when terminating the service. Inherited from
00129    * ACE_Shared_Object. Default implementation sets the service status
00130    * to SERVICE_STOPPED.
00131    */
00132   virtual int fini (void);
00133 
00134   /**
00135    * The actual service implementation.  This function need not be overridden
00136    * by applications that are just using SCM capabilities, but must be
00137    * by subclasses when actually running the service.  It is expected that
00138    * this function will set the status to RUNNING.
00139    */
00140   virtual int svc (void);
00141 
00142   /**
00143    * This function is called in response to a request from the Service
00144    * Dispatcher.  It must interact with the <svc> function to effect the
00145    * requested control operation.  The default implementation handles
00146    * all requests as follows:
00147    *    SERVICE_CONTROL_STOP: set stop pending, set cancel flag
00148    *    SERVICE_CONTROL_PAUSE: set pause pending, <suspend>, set paused
00149    *    SERVICE_CONTROL_CONTINUE: set continue pending, <resume>, set running
00150    *    SERVICE_CONTROL_INTERROGATE: reports current status
00151    *    SERVICE_CONTROL_SHUTDOWN: same as SERVICE_CONTROL_STOP.
00152    */
00153   virtual void  handle_control (DWORD control_code);
00154 
00155   /// Set the svc_handle_ member.  This is only a public function because
00156   /// the macro-generated service function calls it.
00157   void svc_handle (const SERVICE_STATUS_HANDLE new_svc_handle);
00158 
00159 
00160   // = Methods which can be used to do SCP-like functions. The first group
00161   // are used to register/insert and remove the service's definition in the
00162   // SCM registry.
00163 
00164   /// Sets the name and description for the service.
00165   /// If desc is 0, it takes the same value as name.
00166   void name (const ACE_TCHAR *name, const ACE_TCHAR *desc = 0);
00167 
00168   /// Get the service name.
00169   const ACE_TCHAR *name (void) const;
00170 
00171   /// Get the service description.
00172   const ACE_TCHAR *desc (void) const;
00173 
00174   /// Sets the host machine
00175   void host (const ACE_TCHAR *host);
00176 
00177   /// Get the host machine.
00178   const ACE_TCHAR *host (void) const;
00179 
00180   /**
00181    * Insert (create) the service in the NT Service Control Manager,
00182    * with the given creation values.  exe_path defaults to the path name
00183    * of the program that calls the function.  All other 0-defaulted arguments
00184    * pass 0 into the service creation, taking NT_specified defaults.
00185    * Returns -1 on error, 0 on success.
00186    */
00187   int insert (DWORD start_type = SERVICE_DEMAND_START,
00188               DWORD error_control = SERVICE_ERROR_IGNORE,
00189               const ACE_TCHAR *exe_path = 0,
00190               const ACE_TCHAR *group_name = 0,
00191               LPDWORD tag_id = 0,
00192               const ACE_TCHAR *dependencies = 0,
00193               const ACE_TCHAR *account_name = 0,
00194               const ACE_TCHAR *password = 0);
00195 
00196   /**
00197    * Remove the service from the NT Service Control Manager.  Returns -1 on
00198    * error, 0 on success.  This just affects the SCM and registry - the
00199    * can and will keep running fine if it is already running.
00200    */
00201   int remove (void);
00202 
00203   /// Sets the startup type for the service.  Returns -1 on error, 0 on success.
00204   int startup (DWORD startup);
00205 
00206   /// Returns the current startup type.
00207   DWORD startup (void);
00208 
00209   // = Methods to control ACE_Log_Msg behavior in the service.
00210 
00211   /**
00212    * Set the ACE_Log_Msg attributes that the service thread will use to
00213    * initialize its ACE_Log_Msg instance. This is how the initiating
00214    * thread's logging ostream, etc. get into the service thread. The
00215    * logging attributes in effect when this function is called are what
00216    * the service thread will have at its disposal when it starts; therefore,
00217    * the main thread should set up logging options for the process, and
00218    * call this function just before calling the StartServiceCtrlDispatcher
00219    * function.
00220    */
00221   void capture_log_msg_attributes (void);
00222 
00223   /**
00224    * Set the ACE_Log_Msg attributes in the current thread to those saved
00225    * in the most recent call to @c capture_log_msg_attributes(). This function
00226    * should be called from the service's service thread. Ideally, it is the
00227    * first method called to be sure that any logging done is incorporated
00228    * correctly into the process's established logging setup.
00229    */
00230   void inherit_log_msg_attributes (void);
00231 
00232   // = Methods which control the service's execution.
00233 
00234   // These methods to start/pause/resume/stop/check the service all
00235   // have the following common behavior with respect to <wait_time>
00236   // and return value.  <wait_time> is a pointer to an ACE_Time_Value
00237   // object.  If not supplied (a zero pointer) the function will wait
00238   // indefinitely for the action to be finalized (service reach
00239   // running state, completely shut down, etc.) or get "stuck" before
00240   // returning.  If the time is supplied, it specifies how long to
00241   // wait for the service to reach a steady state, and on return, it
00242   // is updated to the service's last reported wait hint.  So, if you
00243   // want to control the waiting yourself (for example, you want to
00244   // react to UI events during the wait) specify a <wait_time> of (0,
00245   // 0) and use the updated time to know when to check the service's
00246   // state again.  NOTE!!!! The wait_time things don't work yet.  The
00247   // calls always check status once, and do not wait for it to change.
00248   //
00249   // The return value from start_svc, stop_svc, pause_svc,
00250   // continue_svc is 0 if the request to NT to effect the change was
00251   // made successfully.  The service may refuse to change, or not do
00252   // what you wanted; so if you need to know, supply a <svc_state>
00253   // pointer to receive the service's reported last state on return
00254   // and check it to see if it's what you want.  The functions only
00255   // return -1 when the actual request to the service is refused -
00256   // this would include privilege restrictions and if the service is
00257   // not configured to receive the request (this is most likely to
00258   // happen in the case of pause and continue).
00259 
00260   /**
00261    * Start the service (must have been inserted before).  wait_time is
00262    * the time to wait for the service to reach a steady state before
00263    * returning.  If it is 0, the function waits as long as it takes
00264    * for the service to reach the 'running' state, or gets stuck in
00265    * some other state, or exits.  If <wait_time> is supplied, it is
00266    * updated on return to hold the service's last reported wait hint.
00267    * svc_state can be used to receive the state which the service
00268    * settled in.  If the value is 0, the service never ran.  argc/argv
00269    * are passed to the service's ServiceMain function when it starts.
00270    * Returns 0 for success, -1 for error.
00271    */
00272   int start_svc (ACE_Time_Value *wait_time = 0,
00273                  DWORD *svc_state = 0,
00274                  DWORD argc = 0, const ACE_TCHAR **argv = 0);
00275 
00276   /**
00277    * Requests the service to stop.  Will wait up to <wait_time> for
00278    * the service to actually stop.  If not specified, the function
00279    * waits until the service either stops or gets stuck in some other
00280    * state before it stops.  If <svc_state> is specified, it receives
00281    * the last reported state of the service.  Returns 0 if the request
00282    * was made successfully, -1 if not.
00283    */
00284   int stop_svc (ACE_Time_Value *wait_time = 0, DWORD *svc_state = 0);
00285 
00286   /// Pause the service.
00287   int pause_svc (ACE_Time_Value *wait_time = 0, DWORD *svc_state = 0);
00288 
00289   /// Continue the service.
00290   int continue_svc (ACE_Time_Value *wait_time = 0, DWORD *svc_state = 0);
00291 
00292   /**
00293    * Get the current state for the service.  If <wait_hint> is not 0,
00294    * it receives the service's reported wait hint.  Note that this
00295    * function returns 0 on failure (not -1 as is usual in ACE).  A
00296    * zero return would (probably) only be returned if there is either
00297    * no service with the given name in the SCM database, or the caller
00298    * does not have sufficient rights to access the service state.  The
00299    * set of valid service state values are all greater than 0.
00300    */
00301   DWORD state (ACE_Time_Value *wait_hint = 0);
00302 
00303   /// A version of <state> that returns -1 for failure, 0 for success.
00304   /// The DWORD pointed to by pstate receives the state value.
00305   int state (DWORD *pstate, ACE_Time_Value *wait_hint = 0);
00306 
00307   /**
00308    * Test access to the object's service in the SCM.  The service must
00309    * already have been inserted in the SCM database.  This function
00310    * has no affect on the service itself.  Returns 0 if the specified
00311    * access is allowed, -1 otherwise (either the access is denied, or
00312    * there is a problem with the service's definition - check
00313    * ACE_OS::last_error to get the specific error indication.
00314    */
00315   int test_access (DWORD desired_access = SERVICE_ALL_ACCESS);
00316 
00317   /// Declare the dynamic allocation hooks.
00318   ACE_ALLOC_HOOK_DECLARE;
00319 
00320 protected:
00321   int report_status (DWORD new_status, DWORD time_hint = 0);
00322 
00323   /**
00324    * Return the svc_sc_handle_ member. If the member is null, it
00325    * retrieves the handle from the Service Control Manager and caches
00326    * it.
00327    */
00328   SC_HANDLE svc_sc_handle (void);
00329 
00330   /**
00331    * Waits for the service to reach <desired_state> or get
00332    * (apparently) stuck before it reaches that state.  Will wait at
00333    * most <wait_time> to get to the desired state.  If <wait_time> is
00334    * 0, then the function keeps waiting until the desired state is
00335    * reached or the service doesn't update its state any further.  The
00336    * svc_status_ class member is updated upon return.
00337    */
00338   void wait_for_service_state (DWORD desired_state, 
00339                                ACE_Time_Value *wait_time);
00340 
00341   /// Called by <handle_control> when a stop/shutdown was requested.
00342   virtual void stop_requested (DWORD control_code);
00343 
00344   /// Called by <handle_control> when a pause was requested.
00345   virtual void pause_requested (DWORD control_code);
00346 
00347   /// Called by <handle_control> when a continue was requested.
00348   virtual void continue_requested (DWORD control_code);
00349 
00350   /// Called by <handle_control> when a interrogate was requested.
00351   virtual void interrogate_requested (DWORD control_code);
00352 
00353 protected:
00354   /// Estimate of init time needed
00355   DWORD start_time_;
00356   /// Service handle - doesn't need close.
00357   SERVICE_STATUS_HANDLE svc_handle_;
00358   SERVICE_STATUS svc_status_;
00359 
00360   /// Service's SCM handle
00361   SC_HANDLE svc_sc_handle_;
00362   ACE_TCHAR *name_;
00363   ACE_TCHAR *desc_;
00364   ACE_TCHAR *host_;
00365 
00366   /// ACE_Log_Msg attributes to inherit from the starting thread.
00367   ACE_OS_Log_Msg_Attributes  log_msg_attributes_;
00368 };
00369 
00370 // These macros help to get things set up correctly at compile time
00371 // and to take most of the grudge work out of creating the proper
00372 // functions and doing the registrations.
00373 //
00374 // ACE_NT_SERVICE_DEFINE - defines the 'ServiceMain' function which NT will
00375 //                         call in its own thread when the service control
00376 //                         dispatcher starts.
00377 
00378 #define ACE_NT_SERVICE_DEFINE(SVCNAME, SVCCLASS, SVCDESC)                   \
00379   ACE_NT_Service * _ace_nt_svc_obj_##SVCNAME = 0;                           \
00380   VOID WINAPI ace_nt_svc_handler_##SVCNAME (DWORD fdwControl) {             \
00381     _ace_nt_svc_obj_##SVCNAME->handle_control(fdwControl);                  \
00382   }                                                                         \
00383   VOID WINAPI ace_nt_svc_main_##SVCNAME (DWORD dwArgc,                      \
00384                                          ACE_TCHAR **lpszArgv) {            \
00385     int delete_svc_obj = 0;                                                 \
00386     if (_ace_nt_svc_obj_##SVCNAME == 0) {                                   \
00387       ACE_NEW (_ace_nt_svc_obj_##SVCNAME, SVCCLASS);                        \
00388       if (_ace_nt_svc_obj_##SVCNAME == 0)                                   \
00389         return;                                                             \
00390       delete_svc_obj = 1;                                                   \
00391     }                                                                       \
00392     else                                                                    \
00393       _ace_nt_svc_obj_##SVCNAME->inherit_log_msg_attributes ();             \
00394     _ace_nt_svc_obj_##SVCNAME->init(dwArgc, lpszArgv);                      \
00395     _ace_nt_svc_obj_##SVCNAME->svc_handle(                                  \
00396                   ACE_TEXT_RegisterServiceCtrlHandler(SVCDESC,              \
00397                                           &ace_nt_svc_handler_##SVCNAME));  \
00398     _ace_nt_svc_obj_##SVCNAME->open();                                      \
00399     _ace_nt_svc_obj_##SVCNAME->wait();                                      \
00400     _ace_nt_svc_obj_##SVCNAME->fini();                                      \
00401     if (delete_svc_obj) {                                                   \
00402       delete _ace_nt_svc_obj_##SVCNAME;                                     \
00403       _ace_nt_svc_obj_##SVCNAME = 0;                                        \
00404     }                                                                       \
00405     return;                                                                 \
00406   }
00407 
00408 #define ACE_NT_SERVICE_REFERENCE(SVCNAME)                                  \
00409 extern ACE_NT_Service * _ace_nt_svc_obj_##SVCNAME;                         \
00410 extern VOID WINAPI ace_nt_svc_main_##SVCNAME (DWORD dwArgc,                \
00411                                               ACE_TCHAR **lpszArgv);
00412 
00413 #define ACE_NT_SERVICE_ENTRY(SVCDESC, SVCNAME)                             \
00414                       { SVCDESC, &ace_nt_svc_main_##SVCNAME }
00415 
00416 #define ACE_NT_SERVICE_RUN(SVCNAME, SVCINSTANCE, RET)                      \
00417   ACE_TEXT_SERVICE_TABLE_ENTRY _ace_nt_svc_table[2] =                      \
00418   {                                                                        \
00419     ACE_NT_SERVICE_ENTRY(ACE_TEXT (#SVCNAME), SVCNAME),                    \
00420     { 0, 0 }                                                               \
00421   };                                                                       \
00422   _ace_nt_svc_obj_##SVCNAME = SVCINSTANCE;                                 \
00423   _ace_nt_svc_obj_##SVCNAME->capture_log_msg_attributes ();                \
00424   ACE_OS::last_error (0);                                                  \
00425   int RET = ACE_TEXT_StartServiceCtrlDispatcher(_ace_nt_svc_table);
00426 
00427 #if defined (__ACE_INLINE__)
00428 #include "ace/NT_Service.i"
00429 #endif /* __ACE_INLINE__ */
00430 
00431 #endif /* ACE_WIN32 && !ACE_HAS_PHARLAP && !ACE_HAS_WINCE */
00432 
00433 #include "ace/post.h"
00434 
00435 #endif /* ACE_SERVICE_OBJECT_H */

Generated on Mon Jun 16 11:20:29 2003 for ACE by doxygen1.2.14 written by Dimitri van Heesch, © 1997-2002