get rid of curlwrapper.CurlException and raise xmlrpclib.ProtocolError instead
[nodemanager.git] / conf_files.py
1 """configuration files"""
2
3 import grp
4 import os
5 import pwd
6 import sha
7 import string
8 import threading
9
10 import curlwrapper
11 import logger
12 import tools
13
14
15 class conf_files:
16     def __init__(self, config, noscripts=False):
17         self.config = config
18         self.noscripts = noscripts
19         self.cond = threading.Condition()
20         self.data = None
21
22     def checksum(self, path):
23         try:
24             f = open(path)
25             try: return sha.new(f.read()).digest()
26             finally: f.close()
27         except IOError: return None
28
29     def system(self, cmd):
30         if not self.noscripts and cmd:
31             logger.log('conf_files: running command %s' % cmd)
32             return tools.fork_as(None, os.system, cmd)
33         else: return 0
34
35     def update_conf_file(self, cf_rec):
36         if not cf_rec['enabled']: return
37         dest = cf_rec['dest']
38         # XXX Remove once old Node Manager is out of service
39         if dest == '/etc/proper/propd.conf': return
40         err_cmd = cf_rec['error_cmd']
41         mode = string.atoi(cf_rec['file_permissions'], base=8)
42         try:
43             uid = pwd.getpwnam(cf_rec['file_owner'])[2]
44         except:
45             logger.log('conf_files: cannot find user %s -- %s not updated'%(cf_rec['file_owner'],dest))
46             return
47         try:
48             gid = grp.getgrnam(cf_rec['file_group'])[2]
49         except:
50             logger.log('conf_files: cannot find group %s -- %s not updated'%(cf_rec['file_group'],dest))
51             return
52         url = 'https://%s/%s' % (self.config.PLC_BOOT_HOST, cf_rec['source'])
53         try:
54             contents = curlwrapper.retrieve(url, self.config.cacert)
55         except xmlrpclib.ProtocolError,e:
56             logger.log('conf_files: failed to retrieve %s from %s, skipping' % (dest, url))
57             return
58         if not cf_rec['always_update'] and sha.new(contents).digest() == self.checksum(dest):
59             return
60         if self.system(cf_rec['preinstall_cmd']):
61             self.system(err_cmd)
62             if not cf_rec['ignore_cmd_errors']: return
63         logger.log('conf_files: installing file %s from %s' % (dest, url))
64         try: os.makedirs(os.path.dirname(dest))
65         except OSError: pass
66         tools.write_file(dest, lambda f: f.write(contents), mode=mode, uidgid=(uid,gid))
67         if self.system(cf_rec['postinstall_cmd']): self.system(err_cmd)
68
69     def run_once(self, data):
70         for f in data['conf_files']:
71             try: self.update_conf_file(f)
72             except: logger.log_exc()
73
74     def run(self):
75         while True:
76             self.cond.acquire()
77             while self.data == None: self.cond.wait()
78             data = self.data
79             self.data = None
80             self.cond.release()
81             self.run_once(data)
82
83     def callback(self, data):
84         if data != None:
85             self.cond.acquire()
86             self.data = data
87             self.cond.notify()
88             self.cond.release()
89
90 main = None
91
92 def start(options, config):
93     global main
94     main = conf_files(config)
95     tools.as_daemon_thread(main.run)
96
97 def GetSlivers(data):
98     global main
99     assert main is not None
100     return main.callback(data)
101
102 if __name__ == '__main__':
103     import optparse
104     parser = optparse.OptionParser()
105     parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config', help='PLC configuration file')
106     parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session', help='API session key (or file)')
107     parser.add_option('--noscripts', action='store_true', dest='noscripts', default=False, help='Do not run pre- or post-install scripts')
108     (options, args) = parser.parse_args()
109
110     # Load /etc/planetlab/plc_config
111     from config import Config
112     config = Config(options.config)
113
114     # Load /etc/planetlab/session
115     if os.path.exists(options.session):
116         session = file(options.session).read().strip()
117     else:
118         session = options.session
119
120     # Initialize XML-RPC client
121     from plcapi import PLCAPI
122     plc = PLCAPI(config.plc_api_uri, config.cacert, auth = session)
123
124     main = conf_files(config, options.noscripts)
125     data = plc.GetSlivers()
126     main.run_once(data)