home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_2691 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  23.3 KB  |  951 lines

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