root/trunk/umit_scheduler.py @ 4099

Revision 4099, 4.5 kB (checked in by gpolo, 4 years ago)

Adjusted umit_scheduler to run as a Windows service under py2exe

Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# Copyright (C) 2007 Insecure.Com LLC.
5#
6# Author: Guilherme Polo <ggpolo@gmail.com>
7#
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22"""
23Core Scheduler Controller
24"""
25
26# If you want to start Scheduler at system startup, please, especify here
27# umit config dir. XXX outdated comment
28# CONFIG_DIR = /home/myuser/.umit
29CONFIG_DIR = ''
30
31import os
32import sys
33import signal
34
35from umitCore.BGProcess import WindowsService
36from umitCore import Scheduler
37from umitCore.I18N import _
38from umitCore.Paths import Path
39
40HOME_CONF = None
41RUNNING_FILE = None
42if hasattr(sys, 'frozen'):
43    FROZEN_CFG = os.path.join(os.path.dirname(sys.path[0]), ".scheduserhome")
44else:
45    FROZEN_CFG = None
46
47class UMITSchedulerWinService(WindowsService):
48    _svc_name_ = 'umit-scheduler'
49    _svc_display_name_ = "%s service" % _svc_name_
50    _svc_description_ = _svc_display_name_
51    _exe_args_ = None # This is defined at bottom (when not using py2exe)
52
53    def __init__(self, args):
54        WindowsService.__init__(self, args)
55
56    def run(self):
57        # _exe_args_ will be our sys.argv when this runs as a Windows service
58        # as long as we don't run under py2exe.
59        if FROZEN_CFG is not None:
60            cfg = open(FROZEN_CFG, 'r')
61            home_path = cfg.read()
62            cfg.close()
63            args = (sys.path[0], home_path)
64        else:
65            args = sys.argv[1:]
66        Scheduler.main('start', winhndl=self.hndl_waitstop, *args)
67
68
69def setup_homedir(usethis):
70    """
71    Setting umit home directory.
72    """
73    Path.force_set_umit_conf(usethis)
74
75    global HOME_CONF, RUNNING_FILE
76
77    HOME_CONF = os.path.split(Path.get_umit_conf())[0]
78    RUNNING_FILE = os.path.join(HOME_CONF, 'schedrunning')
79
80
81def usage():
82    """
83    Show help
84    """
85    print (_("Usage:") +
86            (" %s start|stop|cleanup|running <config_dir>" % __file__))
87
88
89def main(args, verbose=True):
90    # Quoting paths since they may contain spaces
91    UMITSchedulerWinService._exe_args_ = '"%s" "%s"' % (sys.path[0], HOME_CONF)
92
93    schedcontrol = Scheduler.SchedulerControl(RUNNING_FILE, HOME_CONF,
94            verbose, UMITSchedulerWinService)
95    cmds = {"start": schedcontrol.start,
96            "stop": schedcontrol.stop,
97            "cleanup": schedcontrol.cleanup,
98            "running": schedcontrol.running
99            }
100
101    cmd_args = ()
102    try:
103        if args[0] == 'cleanup':
104            cmd_args += (True, )
105        return cmds[args[0]](*cmd_args)
106    except KeyError, e:
107        if verbose:
108            print "Invalid command especified: %s" % e
109            usage()
110        return 1
111
112
113def pre_main():
114    if len(sys.argv) < 2 or len(sys.argv) > 3:
115        usage()
116        return 0
117
118    if CONFIG_DIR: # forcing especified dir
119        setup_homedir(CONFIG_DIR)
120    else:
121        try:
122            setup_homedir(sys.argv[2])
123        except IndexError: # no path especified
124            setup_homedir(os.path.join(os.path.expanduser("~"), '.umit'))
125
126    return main(sys.argv[1:])
127
128
129if FROZEN_CFG is not None:
130    def write_frozen_cfg():
131        setup_homedir(os.path.join(os.path.expanduser('~'), '.umit'))
132        conf = open(FROZEN_CFG, 'w')
133        conf.write(HOME_CONF)
134        conf.close()
135
136    import win32serviceutil
137    # HandleCommandLine is used by py2exe when defining a service with
138    # cmdline_style as 'custom'
139    def HandleCommandLine():
140        # XXX I will need the user home before starting the Scheduler,
141        # I wish changing UMITSchedulerWinService._exe_args_ would work
142        # here too, but it doesn't. The workaround here is far from
143        # ideal.
144        if sys.argv[1] == 'install':
145            write_frozen_cfg()
146        elif sys.argv[1] in ('start', 'debug'):
147            if not os.path.isfile(FROZEN_CFG):
148                write_frozen_cfg()
149
150        win32serviceutil.HandleCommandLine(UMITSchedulerWinService)
151
152if __name__ == "__main__":
153    sys.exit(pre_main())
Note: See TracBrowser for help on using the browser.