OSDN Git Service

Add return code
[pysilhouette/pysilhouette.git.git] / pysilhouette / scheduler.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of Pysilhouette.
5 #
6 # Copyright (c) 2009 HDE, Inc.
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining a copy
9 # of this software and associated documentation files (the "Software"), to deal
10 # in the Software without restriction, including without limitation the rights
11 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 # copies of the Software, and to permit persons to whom the Software is
13 # furnished to do so, subject to the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be included in
16 # all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 # THE SOFTWARE.
25 #
26
27 """
28 @author: Kei Funagayama <kei@karesansui-project.info>
29 """
30
31 import os
32 import sys
33 import time
34 import signal
35 import traceback
36 import logging
37
38 from pysilhouette.log import reload_conf
39 from pysilhouette.prep import readconf, getopts, chkopts
40 from pysilhouette.util import write_pidfile, create_fifo
41
42 def sigterm_handler(signum, frame):
43     global logger
44     logger.info('Stop the schedulerd with signal- pid=%s, signal=%s' % (os.getpid(), signum))
45
46 def scheduler():
47     global opts
48     global cf
49     global logger
50
51     if os.access(cf["observer.mkfifo.path"], os.F_OK|os.R_OK|os.W_OK) is False:
52         try:
53             os.unlink(cf["observer.mkfifo.path"])
54             logger.info('Deleted filo file. - file=%s' % cf["observer.mkfifo.path"])
55         except:
56             pass # Not anything
57         create_fifo(cf["observer.mkfifo.path"],
58                     cf["observer.mkfifo.user.name"],
59                     cf["observer.mkfifo.group.name"],
60                     cf["observer.mkfifo.perms"],
61                     )
62
63         logger.info('The fifo file was created. - file=%s' % cf["observer.mkfifo.path"])
64
65     if opts.daemon is True:
66         pid = os.getpid()
67         if write_pidfile(opts.pidfile, pid):
68             logger.info('The process file was created. - file=%s' % opts.pidfile)
69         else:
70             logger.info('Could not create process file. - file=%s' % opts.pidfile)
71             return 1
72
73     logger.info('schedulerd started!!')
74     
75     while True:
76         try:
77             fp = open(cf["observer.mkfifo.path"], 'w')
78             try:
79                 fp.write(cf['observer.mkfifo.start.code'])
80                 logger.info('Start code was written. - file=%s : code=%s'
81                             % (cf["observer.mkfifo.path"], cf['observer.mkfifo.start.code']))
82             finally:
83                 fp.close()
84
85             logger.debug('interval start, interval=%s' % (cf['scheduler.interval']))
86             time.sleep(int(cf['scheduler.interval']))
87         except IOError, i:
88             if i.errno == 4:
89                 return 0 # When ending with the signal
90
91     # beyond expectation
92     logger.error('file=%s - 2 error write FIFO, code=%s'
93                      % (self.fifo, cf['observer.mkfifo.start.code']))
94     return 1
95     
96 def main(): 
97     global opts
98     global cf
99     global logger
100
101     (opts, args) = getopts()
102     if chkopts(opts) is True:
103         return 1
104
105     cf = readconf(opts.config)
106     if cf is None:
107         print >>sys.stderr, 'Failed to load the config file "%s". (%s)' % (opts.config, sys.argv[0])
108         return 1
109     
110     if reload_conf(cf["env.sys.log.conf.path"]):
111         logger = logging.getLogger('pysilhouette.scheduler')
112     else:
113         print >>sys.stderr, 'Failed to load the log file. (%s)' % sys.argv[0]
114         return 1
115     
116     try:
117         try:
118             signal.signal(signal.SIGTERM, sigterm_handler)
119             ret = scheduler() # start!!
120             return ret
121         except KeyboardInterrupt, k:
122             logger.critical('Keyboard interrupt occurred. - %s' % str(k.args))
123             print >>sys.stderr, 'Keyboard interrupt occurred. - %s' % str(k.args)
124         except Exception, e:
125             logger.critical('A system error has occurred. - %s' % str(e.args))
126             print >>sys.stderr, 'A system error has occurred. - %s' % str(e.args)
127             print >>sys.stderr, traceback.format_exc()
128             t_logger = logging.getLogger('pysilhouette_traceback')
129             t_logger.critical(traceback.format_exc())
130             
131     finally:
132         if opts.daemon is True and os.path.isfile(opts.pidfile):
133             os.unlink(opts.pidfile)
134             logger.info('Process file has been deleted.. - pidfile=%s' % opts.pidfile)
135
136     return 1
137
138 if __name__ == '__main__':
139     sys.exit(main())