CrontabParser raises an exception on syntax error in config file
[dbuscron] / dbuscrontab.py
1 #!/usr/bin/python
2
3 import os, sys, shutil, signal, tempfile, pipes
4 crontab = '/etc/dbuscrontab'
5 pidfile = '/var/run/dbuscron.pid'
6
7 def create_temp_file(orig_file):
8     try:
9         temp_file = tempfile.mktemp(prefix=os.path.basename(orig_file))
10         shutil.copy(orig_file, temp_file)
11         return temp_file
12     except:
13         raise SystemError('Unable to make copy of dbuscrontab file.')
14
15 def run_system_editor(filename):
16     editor = pipes.quote(os.environ.get('EDITOR', '/usr/bin/vim'))
17     if os.system(editor + ' ' + pipes.quote(filename)) != 0:
18         raise SystemError('Editor returned non-zero status value.')
19
20 def get_dbuscron_pid():
21     try:
22         f = os.popen('initctl status dbuscron', 'r')
23         status = f.readline()
24         f.close()
25         return int(status.strip().split(' ').pop())
26     except:
27         raise SystemError('Unable to get PID of dbuscron job.')
28
29 if __name__ == '__main__':
30
31 # 1. create temporary config file copy
32     temp_file = create_temp_file(crontab)
33     mod_time = os.path.getmtime(temp_file)
34
35 # 2. run system editor on this file
36     run_system_editor(temp_file)
37
38 # 3. check if this file is changed
39     if os.path.getmtime(temp_file) <= mod_time:
40         print 'File was not changed.'
41         sys.exit(2)
42
43 # TODO: 4. check this file's syntax
44
45 # 5. replace system wide config file with new one
46     shutil.move(temp_file, crontab)
47
48 # 6. send sighup to dbuscron daemon
49     pid = get_dbuscron_pid()
50     os.kill(pid, signal.SIGHUP)
51