Source

cx_Freeze_kw / source / bases / Win32Service.c

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 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
 56
 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
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//-----------------------------------------------------------------------------
// Win32Service.c
//   Base executable for handling Windows services.
//-----------------------------------------------------------------------------

#include <Python.h>
#include <windows.h>
#include <Winsvc.h>
#include <cx_Logging.h>

// define constants
#define CX_LOGGING_SECTION_NAME         "Logging"
#define CX_LOGGING_FILE_NAME_KEY        "FileName"
#define CX_LOGGING_LEVEL_KEY            "Level"
#define CX_LOGGING_MAX_FILES_KEY        "MaxFiles"
#define CX_LOGGING_MAX_FILE_SIZE_KEY    "MaxFileSize"
#define CX_LOGGING_PREFIX_KEY           "Prefix"
#define CX_SERVICE_MODULE_NAME          "MODULE_NAME"
#define CX_SERVICE_CLASS_NAME           "CLASS_NAME"
#define CX_SERVICE_NAME                 "NAME"
#define CX_SERVICE_DISPLAY_NAME         "DISPLAY_NAME"
#define CX_SERVICE_DESCRIPTION          "DESCRIPTION"
#define CX_SERVICE_AUTO_START           "AUTO_START"
#define CX_SERVICE_SESSION_CHANGES      "SESSION_CHANGES"

// the following was copied from cx_Interface.c, which is where this
// declaration normally happens
#ifndef PATH_MAX
    #define PATH_MAX _MAX_PATH
#endif

//define structure for holding information about the service
typedef struct {
    PyObject *cls;
    PyObject *nameFormat;
    PyObject *displayNameFormat;
    PyObject *description;
    DWORD startType;
    int sessionChanges;
} udt_ServiceInfo;

// define globals
static HANDLE gControlEvent = NULL;
static SERVICE_STATUS_HANDLE gServiceHandle;
static PyInterpreterState *gInterpreterState = NULL;
static PyObject *gInstance = NULL;
static char gIniFileName[PATH_MAX + 1];

//-----------------------------------------------------------------------------
// FatalError()
//   Called when an attempt to initialize the module zip fails.
//-----------------------------------------------------------------------------
static int FatalError(
    const char *message)		        // message to print
{
    return LogPythonException(message);
}


//-----------------------------------------------------------------------------
// FatalScriptError()
//   Called when an attempt to import the initscript fails.
//-----------------------------------------------------------------------------
static int FatalScriptError(void)
{
    return LogPythonException("initialization script didn't execute properly");
}

#include "Common.c"
#include "BaseModules.c"

//-----------------------------------------------------------------------------
// Service_SetStatus()
//   Set the status for the service.
//-----------------------------------------------------------------------------
static int Service_SetStatus(
    udt_ServiceInfo* info,              // service information
    DWORD status)			            // status to set
{
    SERVICE_STATUS serviceStatus;

    serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    serviceStatus.dwCurrentState = status;
    serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
    if (info->sessionChanges)
        serviceStatus.dwControlsAccepted |= SERVICE_ACCEPT_SESSIONCHANGE;
    serviceStatus.dwWin32ExitCode = 0;
    serviceStatus.dwServiceSpecificExitCode = 0;
    serviceStatus.dwCheckPoint = 0;
    serviceStatus.dwWaitHint = 0;
    if (!SetServiceStatus(gServiceHandle, &serviceStatus))
        return -1;

    return 0;
}


//-----------------------------------------------------------------------------
// Service_Stop()
//   Stop the service. Note that the controlling thread must be ended before
// the main thread is ended or the control GUI does not understand that the
// service has ended.
//-----------------------------------------------------------------------------
static int Service_Stop(
    udt_ServiceInfo* info)              // service information
{
    PyThreadState *threadState;
    PyObject *result;

    // indicate that the service is being stopped
    if (Service_SetStatus(info, SERVICE_STOP_PENDING) < 0)
        return LogWin32Error(GetLastError(), "cannot set service as stopping");

    // create event for the main thread to wait on for the control thread
    gControlEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!gControlEvent)
        return LogWin32Error(GetLastError(), "cannot create control event");

    // create a new Python thread and acquire the global interpreter lock
    threadState = PyThreadState_New(gInterpreterState);
    if (!threadState)
        return LogPythonException("unable to create new thread state");
    PyEval_AcquireThread(threadState);

    // call the "Stop" method
    result = PyObject_CallMethod(gInstance, "Stop", NULL);
    if (!result)
        return LogPythonException("exception calling Stop method");
    Py_DECREF(result);

    // destroy the Python thread and release the global interpreter lock
    PyThreadState_Clear(threadState);
    PyEval_ReleaseThread(threadState);
    PyThreadState_Delete(threadState);

    // indicate that the service has stopped
    if (Service_SetStatus(info, SERVICE_STOPPED) < 0)
        return LogWin32Error(GetLastError(), "cannot set service as stopped");

    // now set the control event
    if (!SetEvent(gControlEvent))
        return LogWin32Error(GetLastError(), "cannot set control event");

    return 0;
}


//-----------------------------------------------------------------------------
// Service_SessionChange()
//   Called when a session has changed.
//-----------------------------------------------------------------------------
static int Service_SessionChange(
    DWORD sessionId,                    // session that has changed
    DWORD eventType)                    // event type
{
    PyThreadState *threadState;
    PyObject *result;

    // create a new Python thread and acquire the global interpreter lock
    threadState = PyThreadState_New(gInterpreterState);
    if (!threadState)
        return LogPythonException("unable to create new thread state");
    PyEval_AcquireThread(threadState);

    // call Python method
    result = PyObject_CallMethod(gInstance, "SessionChanged", "ii",
            sessionId, eventType);
    if (!result)
        return LogPythonException("exception calling SessionChanged method");
    Py_DECREF(result);

    // destroy the Python thread and release the global interpreter lock
    PyThreadState_Clear(threadState);
    PyEval_ReleaseThread(threadState);
    PyThreadState_Delete(threadState);

    return 0;
}


//-----------------------------------------------------------------------------
// Service_Control()
//   Function for controlling a service. Note that the controlling thread
// must be ended before the main thread is ended or the control GUI does not
// understand that the service has ended.
//-----------------------------------------------------------------------------
static DWORD WINAPI Service_Control(
    DWORD controlCode,			        // control code
    DWORD eventType,                    // event type
    LPVOID eventData,                   // event data
    LPVOID context)                     // context
{
    udt_ServiceInfo *serviceInfo = (udt_ServiceInfo*) context;
    WTSSESSION_NOTIFICATION *sessionInfo;

    switch (controlCode) {
        case SERVICE_CONTROL_STOP:
            Service_Stop(serviceInfo);
            break;
        case SERVICE_CONTROL_SESSIONCHANGE:
            sessionInfo = (WTSSESSION_NOTIFICATION*) eventData;
            Service_SessionChange(sessionInfo->dwSessionId, eventType);
            break;
    }

    return NO_ERROR;
}


//-----------------------------------------------------------------------------
// Service_StartLogging()
//   Initialize logging for the service.
//-----------------------------------------------------------------------------
static int Service_StartLogging(
    const char *fileName)		        // name of file for defaults
{
    char defaultLogFileName[PATH_MAX + 1], logFileName[PATH_MAX + 1];
    unsigned logLevel, maxFiles, maxFileSize;
    char *ptr, prefix[100];
    size_t size;

    // determine the default log file name and ini file name
    ptr = strrchr(fileName, '.');
    if (ptr)
       size = ptr - fileName;
    else size = strlen(fileName);
    strcpy(defaultLogFileName, fileName);
    strcpy(&defaultLogFileName[size], ".log");
    if (strlen(gIniFileName) == 0) {
        strcpy(gIniFileName, fileName);
        strcpy(&gIniFileName[size], ".ini");
    }

    // read the entries from the ini file
    logLevel = GetPrivateProfileInt(CX_LOGGING_SECTION_NAME,
            CX_LOGGING_LEVEL_KEY, LOG_LEVEL_ERROR, gIniFileName);
    GetPrivateProfileString(CX_LOGGING_SECTION_NAME, CX_LOGGING_FILE_NAME_KEY,
            defaultLogFileName, logFileName, sizeof(logFileName),
            gIniFileName);
    maxFiles = GetPrivateProfileInt(CX_LOGGING_SECTION_NAME,
            CX_LOGGING_MAX_FILES_KEY, 1, gIniFileName);
    maxFileSize = GetPrivateProfileInt(CX_LOGGING_SECTION_NAME,
            CX_LOGGING_MAX_FILE_SIZE_KEY, DEFAULT_MAX_FILE_SIZE, gIniFileName);
    GetPrivateProfileString(CX_LOGGING_SECTION_NAME, CX_LOGGING_PREFIX_KEY,
            "[%i] %d %t", prefix, sizeof(prefix), gIniFileName);

    // start the logging process
    return StartLogging(logFileName, logLevel, maxFiles, maxFileSize, prefix);
}


//-----------------------------------------------------------------------------
// Service_SetupPython()
//   Setup Python usage for the service.
//-----------------------------------------------------------------------------
static int Service_SetupPython(
    char *programName,                  // name of the program (argv[0])
    udt_ServiceInfo *info)              // info about service (OUT)
{
    PyObject *module, *serviceModule, *temp;
    PyThreadState *threadState;
    char *fileName;

    // initialize Python
    Py_NoSiteFlag = 1;
    Py_FrozenFlag = 1;
    Py_IgnoreEnvironmentFlag = 1;
    PyImport_FrozenModules = gFrozenModules;
    Py_SetPythonHome("");
    Py_SetProgramName(programName);
    fileName = Py_GetProgramFullPath();
    Py_Initialize();

    // initialize logging
    if (Service_StartLogging(fileName) < 0)
        return -1;

    // ensure threading is initialized and interpreter state saved
    PyEval_InitThreads();
    threadState = PyThreadState_Swap(NULL);
    if (!threadState) {
        LogMessage(LOG_LEVEL_ERROR, "cannot set up interpreter state");
        Service_SetStatus(info, SERVICE_STOPPED);
        return -1;
    }
    gInterpreterState = threadState->interp;
    PyThreadState_Swap(threadState);

    // running base script
    LogMessage(LOG_LEVEL_DEBUG, "running base Python script");
    if (ExecuteScript(fileName) < 0)
        return -1;

    // acquire the __main__ module
    module = PyImport_ImportModule("__main__");
    if (!module)
        return LogPythonException("unable to import __main__");

    // determine name to use for the service
    info->nameFormat = PyObject_GetAttrString(module, CX_SERVICE_NAME);
    if (!info->nameFormat)
        return LogPythonException("cannot locate service name");

    // determine display name to use for the service
    info->displayNameFormat = PyObject_GetAttrString(module,
            CX_SERVICE_DISPLAY_NAME);
    if (!info->displayNameFormat)
        return LogPythonException("cannot locate service display name");

    // determine description to use for the service (optional)
    info->description = PyObject_GetAttrString(module,
            CX_SERVICE_DESCRIPTION);
    if (!info->description)
        PyErr_Clear();

    // determine if service should be automatically started (optional)
    info->startType = SERVICE_DEMAND_START;
    temp = PyObject_GetAttrString(module, CX_SERVICE_AUTO_START);
    if (!temp)
        PyErr_Clear();
    else if (temp == Py_True)
        info->startType = SERVICE_AUTO_START;

    // determine if service should monitor session changes (optional)
    info->sessionChanges = 0;
    temp = PyObject_GetAttrString(module, CX_SERVICE_SESSION_CHANGES);
    if (!temp)
        PyErr_Clear();
    else if (temp == Py_True)
        info->sessionChanges = 1;

    // import the module which implements the service
    temp = PyObject_GetAttrString(module, CX_SERVICE_MODULE_NAME);
    if (!temp)
        return LogPythonException("cannot locate service module name");
    serviceModule = PyImport_Import(temp);
    Py_DECREF(temp);
    if (!serviceModule)
        return LogPythonException("cannot import service module");

    // create an instance of the class which implements the service
    temp = PyObject_GetAttrString(module, CX_SERVICE_CLASS_NAME);
    if (!temp)
        return LogPythonException("cannot locate service class name");
    info->cls = PyObject_GetAttr(serviceModule, temp);
    Py_DECREF(temp);
    if (!info->cls)
        return LogPythonException("cannot get class from service module");

    return 0;
}


//-----------------------------------------------------------------------------
// Service_Install()
//   Install the service with the given name.
//-----------------------------------------------------------------------------
static int Service_Install(
    char *programName,                  // name of program being run
    char *name,                         // name of service
    char *configFileName)               // name of configuration file or NULL
{
    PyObject *fullName, *displayName, *formatArgs, *command, *commandArgs;
    char fullPathConfigFileName[PATH_MAX + 1];
    SC_HANDLE managerHandle, serviceHandle;
    SERVICE_DESCRIPTIONA sd;
    udt_ServiceInfo info;

    // set up Python
    if (Service_SetupPython(programName, &info) < 0)
        return -1;

    // determine name and display name to use for the service
    formatArgs = Py_BuildValue("(s)", name);
    if (!formatArgs)
        return LogPythonException("cannot create service name tuple");
    fullName = PyString_Format(info.nameFormat, formatArgs);
    if (!fullName)
        return LogPythonException("cannot create service name");
    displayName = PyString_Format(info.displayNameFormat, formatArgs);
    if (!displayName)
        return LogPythonException("cannot create display name");

    // determine command to use for the service
    command = PyString_FromFormat("\"%s\"", Py_GetProgramFullPath());
    if (!command)
        return LogPythonException("cannot create command");
    if (configFileName) {
        if (!_fullpath(fullPathConfigFileName, configFileName,
                sizeof(fullPathConfigFileName)))
            return LogWin32Error(GetLastError(),
                    "cannot calculate absolute path of config file name");
        commandArgs = PyString_FromFormat(" \"%s\"", fullPathConfigFileName);
        if (!commandArgs)
            return LogPythonException("cannot create command args");
        PyString_Concat(&command, commandArgs);
        if (!command)
            return LogPythonException("cannot append args to command");
    }

    // open up service control manager
    managerHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (!managerHandle)
        return LogWin32Error(GetLastError(), "cannot open service manager");

    // create service
    serviceHandle = CreateService(managerHandle, PyString_AS_STRING(fullName),
            PyString_AS_STRING(displayName), SERVICE_ALL_ACCESS,
            SERVICE_WIN32_OWN_PROCESS, info.startType, SERVICE_ERROR_NORMAL,
            PyString_AS_STRING(command), NULL, NULL, NULL, NULL, NULL);
    if (!serviceHandle)
        return LogWin32Error(GetLastError(), "cannot create service");

    // set the description of the service, if one was specified
    if (info.description) {
        sd.lpDescription = PyString_AS_STRING(info.description);
        if (!ChangeServiceConfig2(serviceHandle, SERVICE_CONFIG_DESCRIPTION,
                    &sd))
            return LogWin32Error(GetLastError(),
                    "cannot set service description");
    }

    // if the service is one that should be automatically started, start it
    if (info.startType == SERVICE_AUTO_START) {
        if (!StartService(serviceHandle, 0, NULL))
            return LogWin32Error(GetLastError(), "cannot start service");
    }

    // close the service handles
    CloseServiceHandle(serviceHandle);
    CloseServiceHandle(managerHandle);

    return 0;
}


//-----------------------------------------------------------------------------
// Service_Uninstall()
//   Uninstall the service with the given name.
//-----------------------------------------------------------------------------
static int Service_Uninstall(
    char *programName,                  // name of program being run
    char *name)                         // name of service
{
    SC_HANDLE managerHandle, serviceHandle;
    PyObject *fullName, *formatArgs;
    SERVICE_STATUS statusInfo;
    udt_ServiceInfo info;

    // set up Python
    if (Service_SetupPython(programName, &info) < 0)
        return -1;

    // determine name of the service
    formatArgs = Py_BuildValue("(s)", name);
    if (!formatArgs)
        return LogPythonException("cannot create service name tuple");
    fullName = PyString_Format(info.nameFormat, formatArgs);
    if (!fullName)
        return LogPythonException("cannot create service name");

    // open up service control manager
    managerHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (!managerHandle)
        return LogWin32Error(GetLastError(), "cannot open service manager");

    // create service
    serviceHandle = OpenService(managerHandle, PyString_AS_STRING(fullName),
            SERVICE_ALL_ACCESS);
    if (!serviceHandle)
        return LogWin32Error(GetLastError(), "cannot open service");
    ControlService(serviceHandle, SERVICE_CONTROL_STOP, &statusInfo);
    if (!DeleteService(serviceHandle))
        return LogWin32Error(GetLastError(), "cannot delete service");
    CloseServiceHandle(serviceHandle);
    CloseServiceHandle(managerHandle);

    return 0;
}


//-----------------------------------------------------------------------------
// Service_Run()
//   Initialize the service.
//-----------------------------------------------------------------------------
static int Service_Run(
    udt_ServiceInfo *info)              // information about the service
{
    PyObject *temp;

    // create an instance of the class which implements the service
    gInstance = PyObject_CallFunctionObjArgs(info->cls, NULL);
    if (!gInstance)
        return LogPythonException("cannot create instance of service class");

    // initialize the instance implementing the service
    LogMessageV(LOG_LEVEL_DEBUG, "initializing with config file %s",
            gIniFileName);
    temp = PyObject_CallMethod(gInstance, "Initialize", "s", gIniFileName);
    if (!temp)
        return LogPythonException("failed to initialize instance properly");
    Py_DECREF(temp);

    // run the service
    LogMessage(LOG_LEVEL_INFO, "starting up service");
    if (Service_SetStatus(info, SERVICE_RUNNING) < 0)
        return LogWin32Error(GetLastError(), "cannot set service as started");
    temp = PyObject_CallMethod(gInstance, "Run", NULL);
    if (!temp)
        return LogPythonException("exception running service");
    Py_DECREF(temp);
    Py_DECREF(gInstance);
    gInstance = NULL;

    // ensure that the Python interpreter lock is NOT held as otherwise
    // waiting for events will take a considerable period of time!
    PyEval_SaveThread();

    return 0;
}


//-----------------------------------------------------------------------------
// Service_Main()
//   Main routine for the service.
//-----------------------------------------------------------------------------
static void WINAPI Service_Main(
    int argc,				            // number of arguments
    char **argv)			            // argument values
{
    udt_ServiceInfo info;

    if (Service_SetupPython(argv[0], &info) < 0)
        return;

    // register the control function
    LogMessage(LOG_LEVEL_DEBUG, "registering control function");
    gServiceHandle = RegisterServiceCtrlHandlerEx("", Service_Control, &info);
    if (!gServiceHandle) {
        LogWin32Error(GetLastError(),
                "cannot register service control handler");
        return;
    }

    // run the service
    if (Service_Run(&info) < 0) {
        Service_SetStatus(&info, SERVICE_STOPPED);
        return;
    }

    // ensure that the main thread does not terminate before the control
    // thread does, as otherwise the service control mechanism does not
    // understand that the service has already ended
    if (gControlEvent) {
        if (WaitForSingleObject(gControlEvent, INFINITE) != WAIT_OBJECT_0)
            LogWin32Error(GetLastError(),
                    "cannot wait for control thread to terminate");

    // otherwise, the service terminated normally by some other means
    } else {
        LogMessage(LOG_LEVEL_INFO, "stopping service (internally)");
        Service_SetStatus(&info, SERVICE_STOPPED);
    }
}


//-----------------------------------------------------------------------------
// main()
//   Main routine for the service.
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
    char *configFileName = NULL;

    SERVICE_TABLE_ENTRY table[] = {
        { "", (LPSERVICE_MAIN_FUNCTION) Service_Main },
        { NULL, NULL }
    };

    gIniFileName[0] = '\0';
    if (argc > 1) {
        if (stricmp(argv[1], "--install") == 0) {
            if (argc == 2) {
                fprintf(stderr, "Incorrect number of parameters.\n");
                fprintf(stderr, "%s --install <NAME> [<CONFIGFILE>]", argv[0]);
                return 1;
            }
            if (argc > 3)
                configFileName = argv[3];
            if (Service_Install(argv[0], argv[2], configFileName) < 0) {
                fprintf(stderr, "Service not installed. ");
                fprintf(stderr, "See log file for details.");
                return 1;
            }
            fprintf(stderr, "Service installed.");
            return 0;
        } else if (stricmp(argv[1], "--uninstall") == 0) {
            if (argc == 2) {
                fprintf(stderr, "Incorrect number of parameters.\n");
                fprintf(stderr, "%s --uninstall <NAME>", argv[0]);
                return 1;
            }
            if (Service_Uninstall(argv[0], argv[2]) < 0) {
                fprintf(stderr, "Service not installed. ");
                fprintf(stderr, "See log file for details.");
                return 1;
            }
            fprintf(stderr, "Service uninstalled.");
            return 0;
        }
        strcpy(gIniFileName, argv[1]);
    }


    return StartServiceCtrlDispatcher(table);
}