-
Notifications
You must be signed in to change notification settings - Fork 0
/
mudaemon.py
executable file
·327 lines (286 loc) · 9.36 KB
/
mudaemon.py
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
#!/usr/bin/env python
# Multi-usage daemon
# This daemon can be used for file transfert, file conversion...
import sys, os, time, signal, socket
import Logger
from signal import SIGTERM
from signal import SIGHUP
from signal import SIGUSR1
'''This module is used to fork the current process into a daemon.
Almost none of this is necessary (or advisable) if your daemon
is being started by inetd. In that case, stdin, stdout and stderr are
all set up for you to refer to the network connection, and the fork()s
and session manipulation should not be done (to avoid confusing inetd).
Only the chdir() and umask() steps remain as useful.
References:
UNIX Programming FAQ
1.7 How do I get my program to act like a daemon?
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
Advanced Programming in the Unix Environment
W. Richard Stevens, 1992, Addison-Wesley, ISBN 0-201-56317-7.
'''
# Global vars (default values)
ProgPath = os.path.dirname(os.path.realpath(sys.argv[0]))
configuration_file = ProgPath + '/mudaemon.conf'
loglevel = 'info'
logfile = '/tmp/daemon.log'
pidfile = '/tmp/daemon.pid'
polltime = 10
listfile = '/tmp/liste'
command = ''
action = ''
toscan = ''
tosend = ''
ddict = {}
ProgArgs = ''
def stop(signum=0, frame=''):
'''Stopping daemon
'''
log.debug('In stop function')
try:
pf = file(pidfile,'r')
pid = int(pf.read().strip())
log.debug('pid : %d' % pid)
pf.close()
except IOError:
pid = None
if not pid:
log.debug('No pid file')
mess = "Could not stop, pid file '%s' missing.\n"
sys.stderr.write(mess % pidfile)
sys.exit(1)
try:
sys.stdout.write("Stopping daemon...\n")
log.info('Stopping Mu-Daemon...')
while 1:
# tentative d'arret avec SIGUSR1 au lieu
# de SIGTERM
os.kill(pid,SIGUSR1)
time.sleep(1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
log.debug('Remove pidfile %s' % pidfile )
os.remove(pidfile)
if 'stop' == action:
sys.exit(0)
action = 'start'
pid = None
else:
print str(err)
sys.exit(1)
def reload(signum=0, frame=''):
''' Reload daemon
'''
log.info('Reloading MuDaemon...')
read_conf()
def read_conf():
''' Reading configuration file
'''
import ConfigParser
from string import upper
global configuration_file
global loglevel, pidfile
global polltime, command, action
global listfile
global toscan, tosend, ddict
# Get path before parsing config
if os.path.dirname(configuration_file) == '':
cfg_file = os.getcwd() + '/' + configuration_file
configuration_file = cfg_file
sys.stdout.write("Loading configuration file '%s'\n" \
% configuration_file )
sys.stdout.flush()
# lecture du fichier de conf
config = ConfigParser.ConfigParser()
config.read(configuration_file)
# recuperation des optionss
pidfile = config.get('LOG', 'pidfile')
logfile = config.get('LOG', 'logfile')
loglevel = config.get('LOG', 'loglevel')
polltime = config.getint('GLOBAL', 'polltime')
action = config.get('GLOBAL', 'action')
# selon l'action, on lit la section qui correspond
if action == 'FILE':
listfile = config.get(action, 'listfile')
elif action == 'DIRECTORY':
toscan = config.get(action, 'toscan')
tosend = config.get(action, 'tosend')
for S in config.get(action, 'ddict').split(','):
ddict[S] = {}
for O in config.options(S):
option = upper(O)
ddict[S][option] = config.get(S,O)
# de toutes facon l'option command est commune...
command = config.get(action, 'command')
def MyProcess(action=''):
'''Execute command as described in configuration file
'''
import ProcessHandler
global processflag, log
global listfile
global toscan, tosend, ddict
MyAction = ProcessHandler.ProcessHandler(log,(processflag,command))
log.debug ("in MyProcess (flag=%s)" % processflag)
if processflag == 'no':
log.debug ("Nothing to do, sleeping")
elif processflag == 'yes':
if action == 'FILE':
log.debug ("processing FILE action")
MyAction.file(listfile)
elif action == 'DIRECTORY':
log.debug ("processing DIRECTORY action")
MyAction.directory(toscan, tosend, ddict)
else:
log.debug ("No action given")
else:
log.debug ("Flag not set, what's happenning ?")
def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null', pidfile=None, startmsg = 'started with pid %s'):
'''This forks the current process into a daemon.
The stdin, stdout, and stderr arguments are file names that
will be opened and be used to replace the standard file descriptors
in sys.stdin, sys.stdout, and sys.stderr.
These arguments are optional and default to /dev/null.
Note that stderr is opened unbuffered, so
if it shares a file with stdout then interleaved output
may not appear in the order that you expect.
'''
# Do first fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError, e:
sys.stderr.write ("fork #1 failed: (%d) %s" % (e.errno, e.strerror))
sys.exit(1)
# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid()
# Do second fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write ("fork #2 failed: (%d) %s" % (e.errno, e.strerror))
sys.exit(1)
# Now I am a daemon!
# Open file descriptors and print start message
if not stderr: stderr = stdout
si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
pid = str(os.getpid())
sys.stderr.write("\n%s\n" % startmsg % pid)
if pidfile: file(pidfile,'w+').write("%s\n" % pid)
# Redirect standard file descriptors.
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
def startstop(stdout='/dev/null', stderr=None, stdin='/dev/null', pidfile='pid.txt', startmsg = 'Started with pid %s' ):
'''Start, stop restart and reload function.
'''
if len(ProgArgs) > 1:
action = ProgArgs
try:
pf = file(pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if 'reload' == action:
sys.stdout.write("Reloading MUdaemon\n")
sys.stdout.flush()
if not pid:
mess = "Could not reload, pid file '%s' missing\n"
sys.stderr.write(mess % pidfile)
sys.exit(1)
os.kill(pid,SIGHUP)
sys.exit(0)
if 'stop' == action or 'restart' == action:
if not pid:
mess = "Could not stop, pid file '%s' missing.\n"
sys.stderr.write(mess % pidfile)
sys.exit(1)
try:
sys.stdout.write("Stopping daemon...\n")
while 1:
# tentative d'arret avec SIGUSR1 au lieu
# de SIGTERM
os.kill(pid,SIGUSR1)
time.sleep(1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
os.remove(pidfile)
if 'stop' == action:
sys.exit(0)
action = 'start'
pid = None
else:
print str(err)
sys.exit(1)
if 'start' == action:
sys.stdout.write("MUdaemon starting \n")
sys.stdout.flush()
if pid:
mess = "Start aborded since pid file '%s' exists.\n"
sys.stderr.write(mess % pidfile)
sys.exit(1)
daemonize(stdout=stdout, stderr=stderr, stdin=stdin, pidfile=pidfile, startmsg=startmsg)
return
else:
print "usage: %s start|stop|restart|reload" % sys.argv[0]
sys.exit(2)
def main():
'''This is the main function run by the daemon.
This execute the "process_file" function waiting during
"polltime" seconds.
'''
log.info ('Mu-Daemon started with pid %d' % os.getpid() )
while 1:
log.debug('Waiting... (%d sec)' % polltime)
time.sleep(polltime)
log.debug('Do %s process' % action)
MyProcess(action)
if __name__ == "__main__":
processflag = 'yes'
# Options from command line
from optparse import OptionParser
# Define usage and give command line options to parser object
Usage = "usage: %prog [-c CONFIG] {start|stop|reload|restart}"
Parser = OptionParser(usage = Usage)
Parser.add_option("-c", "--configfile",
action = "store",
type = "string",
dest = "Conf_File",
metavar = "FILE",
default = configuration_file,
help = "Path to the configuration file")
(options, args) = Parser.parse_args()
# Use configuration file given or default one
if os.path.exists(options.Conf_File):
configuration_file = options.Conf_File
else:
Parser.error( "Sorry, configuration file \"%s\" "\
"missing or unreadable"\
% options.Conf_File)
# args will always be the tuple of datas containing action
if len(args) == 0:
Parser.print_help()
sys.exit(1)
else:
ProgArgs = args[0]
# Read config file
read_conf()
# Reload configuration file if receiving a HUP signal
signal.signal(signal.SIGHUP, reload)
# Stop daemon if receiving a TERM signal
signal.signal(signal.SIGTERM, stop)
# Start/stop/restart and reload routine
startstop(pidfile=pidfile, stderr=logfile, stdout=logfile)
# Initialize logger
log = Logger.Logger(loglevel)
# Main code
main()