home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / win32serviceutil.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  22.8 KB  |  871 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.7)
  3.  
  4. import win32service
  5. import win32api
  6. import win32con
  7. import winerror
  8. import sys
  9. import pywintypes
  10. import os
  11. error = RuntimeError
  12.  
  13. def LocatePythonServiceExe(exeName = None):
  14.     if not exeName and hasattr(sys, 'frozen'):
  15.         return sys.executable
  16.     if None is None:
  17.         if os.path.splitext(win32service.__file__)[0].endswith('_d'):
  18.             exeName = 'PythonService_d.exe'
  19.         else:
  20.             exeName = 'PythonService.exe'
  21.     if os.path.isfile(exeName):
  22.         return win32api.GetFullPathName(exeName)
  23.     baseName = None.path.splitext(os.path.basename(exeName))[0]
  24.     
  25.     try:
  26.         exeName = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, 'Software\\Python\\%s\\%s' % (baseName, sys.winver))
  27.         if os.path.isfile(exeName):
  28.             return exeName
  29.         raise None("The executable '%s' is registered as the Python service exe, but it does not exist as specified" % exeName)
  30.     except win32api.error:
  31.         for path in [
  32.             sys.prefix] + sys.path:
  33.             look = os.path.join(path, exeName)
  34.             if os.path.isfile(look):
  35.                 return win32api.GetFullPathName(look)
  36.         
  37.         
  38.         try:
  39.             return win32api.SearchPath(None, exeName)[0]
  40.         except win32api.error:
  41.             msg = '%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again.' % (exeName, exeName)
  42.             raise error(msg)
  43.         
  44.  
  45.  
  46.  
  47.  
  48. def _GetServiceShortName(longName):
  49.     access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
  50.     hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Services', 0, access)
  51.     num = win32api.RegQueryInfoKey(hkey)[0]
  52.     longName = longName.lower()
  53.     for x in range(0, num):
  54.         svc = win32api.RegEnumKey(hkey, x)
  55.         skey = win32api.RegOpenKey(hkey, svc, 0, access)
  56.         
  57.         try:
  58.             thisName = str(win32api.RegQueryValueEx(skey, 'DisplayName')[0])
  59.             if thisName.lower() == longName:
  60.                 return svc
  61.             continue
  62.             except win32api.error:
  63.                 continue
  64.             
  65.         return None
  66.  
  67.  
  68.  
  69. def SmartOpenService(hscm, name, access):
  70.     
  71.     try:
  72.         return win32service.OpenService(hscm, name, access)
  73.     except win32api.error:
  74.         details = None
  75.         if details.winerror not in [
  76.             winerror.ERROR_SERVICE_DOES_NOT_EXIST,
  77.             winerror.ERROR_INVALID_NAME]:
  78.             raise 
  79.  
  80.     name = win32service.GetServiceKeyName(hscm, name)
  81.     return win32service.OpenService(hscm, name, access)
  82.  
  83.  
  84. def LocateSpecificServiceExe(serviceName):
  85.     hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Services\\%s' % serviceName, 0, win32con.KEY_ALL_ACCESS)
  86.     
  87.     try:
  88.         return win32api.RegQueryValueEx(hkey, 'ImagePath')[0]
  89.     finally:
  90.         hkey.Close()
  91.  
  92.  
  93.  
  94. def InstallPerfmonForService(serviceName, iniName, dllName = None):
  95.     if not dllName:
  96.         dllName = win32api.GetProfileVal('Python', 'dll', '', iniName)
  97.     if not dllName:
  98.         
  99.         try:
  100.             tryName = os.path.join(os.path.split(win32service.__file__)[0], 'perfmondata.dll')
  101.             if os.path.isfile(tryName):
  102.                 dllName = tryName
  103.         except AttributeError:
  104.             pass
  105.         
  106.  
  107.     if not dllName:
  108.         raise ValueError('The name of the performance DLL must be available')
  109.     dllName = win32api.GetFullPathName(dllName)
  110.     hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Services\\%s' % serviceName, 0, win32con.KEY_ALL_ACCESS)
  111.     
  112.     try:
  113.         subKey = win32api.RegCreateKey(hkey, 'Performance')
  114.         
  115.         try:
  116.             win32api.RegSetValueEx(subKey, 'Library', 0, win32con.REG_SZ, dllName)
  117.             win32api.RegSetValueEx(subKey, 'Open', 0, win32con.REG_SZ, 'OpenPerformanceData')
  118.             win32api.RegSetValueEx(subKey, 'Close', 0, win32con.REG_SZ, 'ClosePerformanceData')
  119.             win32api.RegSetValueEx(subKey, 'Collect', 0, win32con.REG_SZ, 'CollectPerformanceData')
  120.         finally:
  121.             win32api.RegCloseKey(subKey)
  122.  
  123.     finally:
  124.         win32api.RegCloseKey(hkey)
  125.  
  126.     
  127.     try:
  128.         import perfmon
  129.         (path, fname) = os.path.split(iniName)
  130.         oldPath = os.getcwd()
  131.         if path:
  132.             os.chdir(path)
  133.         
  134.         try:
  135.             perfmon.LoadPerfCounterTextStrings('python.exe ' + fname)
  136.         finally:
  137.             os.chdir(oldPath)
  138.  
  139.     except win32api.error:
  140.         details = None
  141.         print 'The service was installed OK, but the performance monitor'
  142.         print 'data could not be loaded.', details
  143.  
  144.  
  145.  
  146. def _GetCommandLine(exeName, exeArgs):
  147.     if exeArgs is not None:
  148.         return exeName + ' ' + exeArgs
  149.     return None
  150.  
  151.  
  152. def InstallService(pythonClassString, serviceName, displayName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
  153.     if startType is None:
  154.         startType = win32service.SERVICE_DEMAND_START
  155.     serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
  156.     if bRunInteractive:
  157.         serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
  158.     if errorControl is None:
  159.         errorControl = win32service.SERVICE_ERROR_NORMAL
  160.     exeName = '"%s"' % LocatePythonServiceExe(exeName)
  161.     commandLine = _GetCommandLine(exeName, exeArgs)
  162.     hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
  163.     
  164.     try:
  165.         hs = win32service.CreateService(hscm, serviceName, displayName, win32service.SERVICE_ALL_ACCESS, serviceType, startType, errorControl, commandLine, None, 0, serviceDeps, userName, password)
  166.         if description is not None:
  167.             
  168.             try:
  169.                 win32service.ChangeServiceConfig2(hs, win32service.SERVICE_CONFIG_DESCRIPTION, description)
  170.             except NotImplementedError:
  171.                 pass
  172.             
  173.  
  174.         win32service.CloseServiceHandle(hs)
  175.     finally:
  176.         win32service.CloseServiceHandle(hscm)
  177.  
  178.     InstallPythonClassString(pythonClassString, serviceName)
  179.     if perfMonIni is not None:
  180.         InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
  181.  
  182.  
  183. def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, displayName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
  184.     
  185.     try:
  186.         import perfmon
  187.         perfmon.UnloadPerfCounterTextStrings('python.exe ' + serviceName)
  188.     except (ImportError, win32api.error):
  189.         pass
  190.  
  191.     exeName = '"%s"' % LocatePythonServiceExe(exeName)
  192.     if startType is None:
  193.         startType = win32service.SERVICE_NO_CHANGE
  194.     if errorControl is None:
  195.         errorControl = win32service.SERVICE_NO_CHANGE
  196.     hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
  197.     serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
  198.     if bRunInteractive:
  199.         serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
  200.     commandLine = _GetCommandLine(exeName, exeArgs)
  201.     
  202.     try:
  203.         hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
  204.         
  205.         try:
  206.             win32service.ChangeServiceConfig(hs, serviceType, startType, errorControl, commandLine, None, 0, serviceDeps, userName, password, displayName)
  207.             if description is not None:
  208.                 
  209.                 try:
  210.                     win32service.ChangeServiceConfig2(hs, win32service.SERVICE_CONFIG_DESCRIPTION, description)
  211.                 except NotImplementedError:
  212.                     pass
  213.                 
  214.  
  215.         finally:
  216.             win32service.CloseServiceHandle(hs)
  217.  
  218.     finally:
  219.         win32service.CloseServiceHandle(hscm)
  220.  
  221.     InstallPythonClassString(pythonClassString, serviceName)
  222.     if perfMonIni is not None:
  223.         InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
  224.  
  225.  
  226. def InstallPythonClassString(pythonClassString, serviceName):
  227.     if pythonClassString:
  228.         key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, 'System\\CurrentControlSet\\Services\\%s\\PythonClass' % serviceName)
  229.         
  230.         try:
  231.             win32api.RegSetValue(key, None, win32con.REG_SZ, pythonClassString)
  232.         finally:
  233.             win32api.RegCloseKey(key)
  234.  
  235.  
  236.  
  237. def SetServiceCustomOption(serviceName, option, value):
  238.     
  239.     try:
  240.         serviceName = serviceName._svc_name_
  241.     except AttributeError:
  242.         pass
  243.  
  244.     key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, 'System\\CurrentControlSet\\Services\\%s\\Parameters' % serviceName)
  245.     
  246.     try:
  247.         if type(value) == type(0):
  248.             win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value)
  249.         else:
  250.             win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value)
  251.     finally:
  252.         win32api.RegCloseKey(key)
  253.  
  254.  
  255.  
  256. def GetServiceCustomOption(serviceName, option, defaultValue = None):
  257.     
  258.     try:
  259.         serviceName = serviceName._svc_name_
  260.     except AttributeError:
  261.         pass
  262.  
  263.     key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, 'System\\CurrentControlSet\\Services\\%s\\Parameters' % serviceName)
  264.     
  265.     try:
  266.         return win32api.RegQueryValueEx(key, option)[0]
  267.     except win32api.error:
  268.         return defaultValue
  269.     finally:
  270.         win32api.RegCloseKey(key)
  271.  
  272.  
  273.  
  274. def RemoveService(serviceName):
  275.     
  276.     try:
  277.         import perfmon
  278.         perfmon.UnloadPerfCounterTextStrings('python.exe ' + serviceName)
  279.     except (ImportError, win32api.error):
  280.         pass
  281.  
  282.     hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
  283.     
  284.     try:
  285.         hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
  286.         win32service.DeleteService(hs)
  287.         win32service.CloseServiceHandle(hs)
  288.     finally:
  289.         win32service.CloseServiceHandle(hscm)
  290.  
  291.     import win32evtlogutil
  292.     
  293.     try:
  294.         win32evtlogutil.RemoveSourceFromRegistry(serviceName)
  295.     except win32api.error:
  296.         pass
  297.  
  298.  
  299.  
  300. def ControlService(serviceName, code, machine = None):
  301.     hscm = win32service.OpenSCManager(machine, None, win32service.SC_MANAGER_ALL_ACCESS)
  302.     
  303.     try:
  304.         hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
  305.         
  306.         try:
  307.             status = win32service.ControlService(hs, code)
  308.         finally:
  309.             win32service.CloseServiceHandle(hs)
  310.  
  311.     finally:
  312.         win32service.CloseServiceHandle(hscm)
  313.  
  314.     return status
  315.  
  316.  
  317. def __FindSvcDeps(findName):
  318.     if type(findName) is pywintypes.UnicodeType:
  319.         findName = str(findName)
  320.     dict = { }
  321.     k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Services')
  322.     num = 0
  323.     while None:
  324.         
  325.         try:
  326.             svc = win32api.RegEnumKey(k, num)
  327.         except win32api.error:
  328.             break
  329.  
  330.         num = num + 1
  331.         sk = win32api.RegOpenKey(k, svc)
  332.         
  333.         try:
  334.             (deps, typ) = win32api.RegQueryValueEx(sk, 'DependOnService')
  335.         except win32api.error:
  336.             deps = ()
  337.  
  338.         for dep in deps:
  339.             dep = dep.lower()
  340.             dep_on = dict.get(dep, [])
  341.             dep_on.append(svc)
  342.             dict[dep] = dep_on
  343.         
  344.         continue
  345.         return __ResolveDeps(findName, dict)
  346.  
  347.  
  348. def __ResolveDeps(findName, dict):
  349.     items = dict.get(findName.lower(), [])
  350.     retList = []
  351.     for svc in items:
  352.         retList.insert(0, svc)
  353.         retList = __ResolveDeps(svc, dict) + retList
  354.     
  355.     return retList
  356.  
  357.  
  358. def WaitForServiceStatus(serviceName, status, waitSecs, machine = None):
  359.     for i in range(waitSecs * 4):
  360.         now_status = QueryServiceStatus(serviceName, machine)[1]
  361.         if now_status == status:
  362.             break
  363.         win32api.Sleep(250)
  364.     else:
  365.         raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, 'QueryServiceStatus', win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
  366.  
  367.  
  368. def __StopServiceWithTimeout(hs, waitSecs = 30):
  369.     
  370.     try:
  371.         status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP)
  372.     except pywintypes.error:
  373.         exc = None
  374.         if exc.winerror != winerror.ERROR_SERVICE_NOT_ACTIVE:
  375.             raise 
  376.  
  377.     for i in range(waitSecs):
  378.         status = win32service.QueryServiceStatus(hs)
  379.         if status[1] == win32service.SERVICE_STOPPED:
  380.             break
  381.         win32api.Sleep(1000)
  382.     else:
  383.         raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, 'ControlService', win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
  384.  
  385.  
  386. def StopServiceWithDeps(serviceName, machine = None, waitSecs = 30):
  387.     hscm = win32service.OpenSCManager(machine, None, win32service.SC_MANAGER_ALL_ACCESS)
  388.     
  389.     try:
  390.         deps = __FindSvcDeps(serviceName)
  391.         for dep in deps:
  392.             hs = win32service.OpenService(hscm, dep, win32service.SERVICE_ALL_ACCESS)
  393.             
  394.             try:
  395.                 __StopServiceWithTimeout(hs, waitSecs)
  396.             finally:
  397.                 win32service.CloseServiceHandle(hs)
  398.  
  399.         
  400.         hs = win32service.OpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
  401.         
  402.         try:
  403.             __StopServiceWithTimeout(hs, waitSecs)
  404.         finally:
  405.             win32service.CloseServiceHandle(hs)
  406.  
  407.     finally:
  408.         win32service.CloseServiceHandle(hscm)
  409.  
  410.  
  411.  
  412. def StopService(serviceName, machine = None):
  413.     return ControlService(serviceName, win32service.SERVICE_CONTROL_STOP, machine)
  414.  
  415.  
  416. def StartService(serviceName, args = None, machine = None):
  417.     hscm = win32service.OpenSCManager(machine, None, win32service.SC_MANAGER_ALL_ACCESS)
  418.     
  419.     try:
  420.         hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
  421.         
  422.         try:
  423.             win32service.StartService(hs, args)
  424.         finally:
  425.             win32service.CloseServiceHandle(hs)
  426.  
  427.     finally:
  428.         win32service.CloseServiceHandle(hscm)
  429.  
  430.  
  431.  
  432. def RestartService(serviceName, args = None, waitSeconds = 30, machine = None):
  433.     
  434.     try:
  435.         StopService(serviceName, machine)
  436.     except pywintypes.error:
  437.         exc = None
  438.         if exc.winerror != winerror.ERROR_SERVICE_NOT_ACTIVE:
  439.             raise 
  440.  
  441.     for i in range(waitSeconds):
  442.         
  443.         try:
  444.             StartService(serviceName, args, machine)
  445.         continue
  446.         except pywintypes.error:
  447.             exc = None
  448.             if exc.winerror != winerror.ERROR_SERVICE_ALREADY_RUNNING:
  449.                 raise 
  450.             win32api.Sleep(1000)
  451.             continue
  452.         
  453.  
  454.     else:
  455.         print 'Gave up waiting for the old service to stop!'
  456.  
  457.  
  458. def _DebugCtrlHandler(evt):
  459.     if evt in (win32con.CTRL_C_EVENT, win32con.CTRL_BREAK_EVENT):
  460.         print 'Stopping debug service.'
  461.         g_debugService.SvcStop()
  462.         return True
  463.  
  464.  
  465. def DebugService(cls, argv = []):
  466.     global g_debugService, g_debugService
  467.     import servicemanager
  468.     print 'Debugging service %s - press Ctrl+C to stop.' % (cls._svc_name_,)
  469.     servicemanager.Debugging(True)
  470.     servicemanager.PrepareToHostSingle(cls)
  471.     g_debugService = cls(argv)
  472.     win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, True)
  473.     
  474.     try:
  475.         g_debugService.SvcRun()
  476.     finally:
  477.         win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, False)
  478.         servicemanager.Debugging(False)
  479.         g_debugService = None
  480.  
  481.  
  482.  
  483. def GetServiceClassString(cls, argv = None):
  484.     if argv is None:
  485.         argv = sys.argv
  486.     import pickle
  487.     modName = pickle.whichmodule(cls, cls.__name__)
  488.     if modName == '__main__':
  489.         
  490.         try:
  491.             fname = win32api.GetFullPathName(argv[0])
  492.             path = os.path.split(fname)[0]
  493.             fname = os.path.join(path, win32api.FindFiles(fname)[0][8])
  494.         except win32api.error:
  495.             raise error("Could not resolve the path name '%s' to a full path" % argv[0])
  496.  
  497.         modName = os.path.splitext(fname)[0]
  498.     return modName + '.' + cls.__name__
  499.  
  500.  
  501. def QueryServiceStatus(serviceName, machine = None):
  502.     hscm = win32service.OpenSCManager(machine, None, win32service.SC_MANAGER_CONNECT)
  503.     
  504.     try:
  505.         hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_QUERY_STATUS)
  506.         
  507.         try:
  508.             status = win32service.QueryServiceStatus(hs)
  509.         finally:
  510.             win32service.CloseServiceHandle(hs)
  511.  
  512.     finally:
  513.         win32service.CloseServiceHandle(hscm)
  514.  
  515.     return status
  516.  
  517.  
  518. def usage():
  519.     
  520.     try:
  521.         fname = os.path.split(sys.argv[0])[1]
  522.     except:
  523.         fname = sys.argv[0]
  524.  
  525.     print "Usage: '%s [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'" % fname
  526.     print "Options for 'install' and 'update' commands only:"
  527.     print ' --username domain\\username : The Username the service is to run under'
  528.     print ' --password password : The password for the username'
  529.     print ' --startup [manual|auto|disabled] : How the service starts, default = manual'
  530.     print ' --interactive : Allow the service to interact with the desktop.'
  531.     print ' --perfmonini file: .ini file to use for registering performance monitor data'
  532.     print ' --perfmondll file: .dll file to use when querying the service for'
  533.     print '   performance data, default = perfmondata.dll'
  534.     print "Options for 'start' and 'stop' commands only:"
  535.     print ' --wait seconds: Wait for the service to actually start or stop.'
  536.     print "                 If you specify --wait with the 'stop' option, the service"
  537.     print '                 and all dependent services will be stopped, each waiting'
  538.     print '                 the specified period.'
  539.     sys.exit(1)
  540.  
  541.  
  542. def HandleCommandLine(cls, serviceClassString = None, argv = None, customInstallOptions = '', customOptionHandler = None):
  543.     err = 0
  544.     if argv is None:
  545.         argv = sys.argv
  546.     if len(argv) <= 1:
  547.         usage()
  548.     serviceName = cls._svc_name_
  549.     serviceDisplayName = cls._svc_display_name_
  550.     if serviceClassString is None:
  551.         serviceClassString = GetServiceClassString(cls)
  552.     import getopt
  553.     
  554.     try:
  555.         (opts, args) = getopt.getopt(argv[1:], customInstallOptions, [
  556.             'password=',
  557.             'username=',
  558.             'startup=',
  559.             'perfmonini=',
  560.             'perfmondll=',
  561.             'interactive',
  562.             'wait='])
  563.     except getopt.error:
  564.         details = None
  565.         print details
  566.         usage()
  567.  
  568.     userName = None
  569.     password = None
  570.     perfMonIni = None
  571.     perfMonDll = None
  572.     startup = None
  573.     interactive = None
  574.     waitSecs = 0
  575.     for opt, val in opts:
  576.         if opt == '--username':
  577.             userName = val
  578.             continue
  579.         if opt == '--password':
  580.             password = val
  581.             continue
  582.         if opt == '--perfmonini':
  583.             perfMonIni = val
  584.             continue
  585.         if opt == '--perfmondll':
  586.             perfMonDll = val
  587.             continue
  588.         if opt == '--interactive':
  589.             interactive = 1
  590.             continue
  591.         if opt == '--startup':
  592.             map = {
  593.                 'manual': win32service.SERVICE_DEMAND_START,
  594.                 'auto': win32service.SERVICE_AUTO_START,
  595.                 'disabled': win32service.SERVICE_DISABLED }
  596.             
  597.             try:
  598.                 startup = map[val.lower()]
  599.             except KeyError:
  600.                 print "'%s' is not a valid startup option" % val
  601.             
  602.  
  603.         if opt == '--wait':
  604.             
  605.             try:
  606.                 waitSecs = int(val)
  607.             except ValueError:
  608.                 print '--wait must specify an integer number of seconds.'
  609.                 usage()
  610.             
  611.  
  612.     arg = args[0]
  613.     knownArg = 0
  614.     if arg == 'start':
  615.         knownArg = 1
  616.         print 'Starting service %s' % serviceName
  617.         
  618.         try:
  619.             StartService(serviceName, args[1:])
  620.             if waitSecs:
  621.                 WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs)
  622.         except win32service.error:
  623.             exc = None
  624.             print 'Error starting service: %s' % exc.strerror
  625.             err = exc.winerror
  626.         
  627.  
  628.     if arg == 'restart':
  629.         knownArg = 1
  630.         print 'Restarting service %s' % serviceName
  631.         RestartService(serviceName, args[1:])
  632.         if waitSecs:
  633.             WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs)
  634.         
  635.     elif arg == 'debug':
  636.         knownArg = 1
  637.         if not hasattr(sys, 'frozen'):
  638.             svcArgs = ' '.join(args[1:])
  639.             
  640.             try:
  641.                 exeName = LocateSpecificServiceExe(serviceName)
  642.             except win32api.error:
  643.                 exc = None
  644.                 if exc[0] == winerror.ERROR_FILE_NOT_FOUND:
  645.                     print 'The service does not appear to be installed.'
  646.                     print 'Please install the service before debugging it.'
  647.                     sys.exit(1)
  648.                 raise 
  649.  
  650.             
  651.             try:
  652.                 os.system('%s -debug %s %s' % (exeName, serviceName, svcArgs))
  653.             except KeyboardInterrupt:
  654.                 pass
  655.             
  656.  
  657.         DebugService(cls, args)
  658.     if not knownArg and len(args) != 1:
  659.         usage()
  660.     if arg == 'install':
  661.         knownArg = 1
  662.         
  663.         try:
  664.             serviceDeps = cls._svc_deps_
  665.         except AttributeError:
  666.             serviceDeps = None
  667.  
  668.         
  669.         try:
  670.             exeName = cls._exe_name_
  671.         except AttributeError:
  672.             exeName = None
  673.  
  674.         
  675.         try:
  676.             exeArgs = cls._exe_args_
  677.         except AttributeError:
  678.             exeArgs = None
  679.  
  680.         
  681.         try:
  682.             description = cls._svc_description_
  683.         except AttributeError:
  684.             description = None
  685.  
  686.         print 'Installing service %s' % (serviceName,)
  687.         
  688.         try:
  689.             InstallService(serviceClassString, serviceName, serviceDisplayName, serviceDeps = serviceDeps, startType = startup, bRunInteractive = interactive, userName = userName, password = password, exeName = exeName, perfMonIni = perfMonIni, perfMonDll = perfMonDll, exeArgs = exeArgs, description = description)
  690.             if customOptionHandler:
  691.                 customOptionHandler(*(opts,))
  692.             print 'Service installed'
  693.         except win32service.error:
  694.             exc = None
  695.             if exc.winerror == winerror.ERROR_SERVICE_EXISTS:
  696.                 arg = 'update'
  697.             else:
  698.                 print 'Error installing service: %s (%d)' % (exc.strerror, exc.winerror)
  699.                 err = exc.winerror
  700.         except ValueError:
  701.             msg = None
  702.             print 'Error installing service: %s' % str(msg)
  703.             err = -1
  704.             
  705.             try:
  706.                 RemoveService(serviceName)
  707.             except win32api.error:
  708.                 print 'Warning - could not remove the partially installed service.'
  709.             
  710.  
  711.         
  712.  
  713.     if arg == 'update':
  714.         knownArg = 1
  715.         
  716.         try:
  717.             serviceDeps = cls._svc_deps_
  718.         except AttributeError:
  719.             serviceDeps = None
  720.  
  721.         
  722.         try:
  723.             exeName = cls._exe_name_
  724.         except AttributeError:
  725.             exeName = None
  726.  
  727.         
  728.         try:
  729.             exeArgs = cls._exe_args_
  730.         except AttributeError:
  731.             exeArgs = None
  732.  
  733.         
  734.         try:
  735.             description = cls._svc_description_
  736.         except AttributeError:
  737.             description = None
  738.  
  739.         print 'Changing service configuration'
  740.         
  741.         try:
  742.             ChangeServiceConfig(serviceClassString, serviceName, serviceDeps = serviceDeps, startType = startup, bRunInteractive = interactive, userName = userName, password = password, exeName = exeName, displayName = serviceDisplayName, perfMonIni = perfMonIni, perfMonDll = perfMonDll, exeArgs = exeArgs, description = description)
  743.             if customOptionHandler:
  744.                 customOptionHandler(*(opts,))
  745.             print 'Service updated'
  746.         except win32service.error:
  747.             exc = None
  748.             print 'Error changing service configuration: %s (%d)' % (exc.strerror, exc.winerror)
  749.             err = exc.winerror
  750.         
  751.  
  752.     if arg == 'remove':
  753.         knownArg = 1
  754.         print 'Removing service %s' % serviceName
  755.         
  756.         try:
  757.             RemoveService(serviceName)
  758.             print 'Service removed'
  759.         except win32service.error:
  760.             exc = None
  761.             print 'Error removing service: %s (%d)' % (exc.strerror, exc.winerror)
  762.             err = exc.winerror
  763.         
  764.  
  765.     if arg == 'stop':
  766.         knownArg = 1
  767.         print 'Stopping service %s' % serviceName
  768.         
  769.         try:
  770.             if waitSecs:
  771.                 StopServiceWithDeps(serviceName, waitSecs = waitSecs)
  772.             else:
  773.                 StopService(serviceName)
  774.         except win32service.error:
  775.             exc = None
  776.             print 'Error stopping service: %s (%d)' % (exc.strerror, exc.winerror)
  777.             err = exc.winerror
  778.         
  779.  
  780.     if not knownArg:
  781.         err = -1
  782.         print "Unknown command - '%s'" % arg
  783.         usage()
  784.     return err
  785.  
  786.  
  787. class ServiceFramework:
  788.     _svc_deps_ = None
  789.     _exe_name_ = None
  790.     _exe_args_ = None
  791.     _svc_description_ = None
  792.     
  793.     def __init__(self, args):
  794.         import servicemanager
  795.         self.ssh = servicemanager.RegisterServiceCtrlHandler(args[0], self.ServiceCtrlHandlerEx, True)
  796.         servicemanager.SetEventSourceName(self._svc_name_)
  797.         self.checkPoint = 0
  798.  
  799.     
  800.     def GetAcceptedControls(self):
  801.         accepted = 0
  802.         if hasattr(self, 'SvcStop'):
  803.             accepted = accepted | win32service.SERVICE_ACCEPT_STOP
  804.         if hasattr(self, 'SvcPause') and hasattr(self, 'SvcContinue'):
  805.             accepted = accepted | win32service.SERVICE_ACCEPT_PAUSE_CONTINUE
  806.         if hasattr(self, 'SvcShutdown'):
  807.             accepted = accepted | win32service.SERVICE_ACCEPT_SHUTDOWN
  808.         return accepted
  809.  
  810.     
  811.     def ReportServiceStatus(self, serviceStatus, waitHint = 5000, win32ExitCode = 0, svcExitCode = 0):
  812.         if self.ssh is None:
  813.             return None
  814.         if None == win32service.SERVICE_START_PENDING:
  815.             accepted = 0
  816.         else:
  817.             accepted = self.GetAcceptedControls()
  818.         if serviceStatus in [
  819.             win32service.SERVICE_RUNNING,
  820.             win32service.SERVICE_STOPPED]:
  821.             checkPoint = 0
  822.         else:
  823.             self.checkPoint = self.checkPoint + 1
  824.             checkPoint = self.checkPoint
  825.         status = (win32service.SERVICE_WIN32_OWN_PROCESS, serviceStatus, accepted, win32ExitCode, svcExitCode, checkPoint, waitHint)
  826.         win32service.SetServiceStatus(self.ssh, status)
  827.  
  828.     
  829.     def SvcInterrogate(self):
  830.         self.ReportServiceStatus(win32service.SERVICE_RUNNING)
  831.  
  832.     
  833.     def SvcOther(self, control):
  834.         
  835.         try:
  836.             print 'Unknown control status - %d' % control
  837.         except IOError:
  838.             pass
  839.  
  840.  
  841.     
  842.     def ServiceCtrlHandler(self, control):
  843.         self.ServiceCtrlHandlerEx(control, 0, None)
  844.  
  845.     
  846.     def SvcOtherEx(self, control, event_type, data):
  847.         self.SvcOther(control)
  848.  
  849.     
  850.     def ServiceCtrlHandlerEx(self, control, event_type, data):
  851.         if control == win32service.SERVICE_CONTROL_STOP:
  852.             self.SvcStop()
  853.         elif control == win32service.SERVICE_CONTROL_PAUSE:
  854.             self.SvcPause()
  855.         elif control == win32service.SERVICE_CONTROL_CONTINUE:
  856.             self.SvcContinue()
  857.         elif control == win32service.SERVICE_CONTROL_INTERROGATE:
  858.             self.SvcInterrogate()
  859.         elif control == win32service.SERVICE_CONTROL_SHUTDOWN:
  860.             self.SvcShutdown()
  861.         else:
  862.             self.SvcOtherEx(control, event_type, data)
  863.  
  864.     
  865.     def SvcRun(self):
  866.         self.ReportServiceStatus(win32service.SERVICE_RUNNING)
  867.         self.SvcDoRun()
  868.         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
  869.  
  870.  
  871.