make this actually work
[mirror/userdir-ldap.git] / ud-replicated
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2014 Stephen Gran <sgran@debian.org>
4 #
5 # Run ud-replicate on a trigger
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining a copy
8 # of this software and associated documentation files (the "Software"), to deal
9 # in the Software without restriction, including without limitation the rights
10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 # copies of the Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be included in
15 # all copies or substantial portions of the Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 # THE SOFTWARE.
24
25 from dsa_mq.connection import Connection
26 from dsa_mq.config import Config
27
28 import logging
29 import logging.handlers
30 import optparse
31 import os
32 import platform
33 import subprocess
34 import sys
35 import time
36
37 parser = optparse.OptionParser()
38 parser.add_option("-D", "--dryrun",
39                   action="store_true", default=False,
40                   help="Dry run mode")
41
42 parser.add_option("-d", "--debug",
43                   action="store_true", default=False,
44                   help="Enable debug output")
45
46 (options, args) = parser.parse_args()
47 options.section = 'dsa-udreplicate'
48 options.config = '/etc/dsa/pubsub.conf'
49 config = Config(options)
50 mq_conf  = {
51     'rabbit_userid': config.username,
52     'rabbit_password': config.password,
53     'rabbit_virtual_host': config.vhost,
54     'rabbit_hosts': ['pubsub02.debian.org', 'pubsub01.debian.org'],
55     'use_ssl': False
56 }
57
58 lvl = logging.INFO
59 if config.debug:
60     lvl = logging.DEBUG
61
62 FORMAT='%(asctime)s ud-replicated: %(levelname)s %(message)s'
63 SFORMAT='ud-replicated[%(process)s]: %(message)s'
64 logging.basicConfig(format=FORMAT, level=lvl)
65 LOG = logging.getLogger(__name__)
66 logsock = '/dev/log'
67 if os.path.exists('/var/run/log'): # Kfreebsd randomly different
68     logsock = '/var/run/log'
69 syslog_handler = logging.handlers.SysLogHandler(address = logsock)
70 formatter = logging.Formatter(SFORMAT)
71 syslog_handler.setFormatter(formatter)
72 LOG.addHandler(syslog_handler)
73
74 last_run = 0
75
76 def do_replicate(message):
77     global last_run
78     last_update = int(time.time())
79     timestamp   = last_update
80
81     if isinstance(message, dict):
82         timestamp = message.get('timestamp', last_update)
83         message   = message.get('message', 'update required')
84     LOG.debug("Got message at %s: %s" % (last_update, message))
85     if last_run > timestamp, last_update):
86         return
87
88     command = ['/usr/bin/ud-replicate']
89     if options.dryrun:
90         LOG.debug("Would have run %s" % command)
91     else:
92         old_term = os.environ.get('TERM')
93         os.environ['TERM'] = 'dumb'
94         try:
95             subprocess.check_call(command)
96         except:
97             LOG.error('%s failed:', ' '.join(command))
98         else:
99             LOG.debug('%s finished with ret: 0' % ' '.join(command))
100         finally:
101             os.environ['TERM'] = old_term
102     last_run = last_update
103
104 def main():
105     conn = Connection(conf=mq_conf)
106     conn.declare_topic_consumer(config.topic,
107                                 callback=do_replicate,
108                                 queue_name=config.queue,
109                                 exchange_name=config.exchange,
110                                 ack_on_error=False)
111
112     try:
113         conn.consume()
114     except KeyboardInterrupt:
115         pass
116     except Exception as e:
117         LOG.error(e)
118     finally:
119         conn.close()
120         sys.exit(0)
121
122 if __name__ == '__main__':
123     do_replicate(
124         {'timestamp': time.time(),
125         'message': 'startup complete'})
126     main()