Merge changes that existed in branch concerning slicefamily w/ trunk.
[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 import xmlrpclib
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.verbose('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         err_cmd = cf_rec['error_cmd']
39         mode = string.atoi(cf_rec['file_permissions'], base=8)
40         try:
41             uid = pwd.getpwnam(cf_rec['file_owner'])[2]
42         except:
43             logger.log('conf_files: cannot find user %s -- %s not updated'%(cf_rec['file_owner'],dest))
44             return
45         try:
46             gid = grp.getgrnam(cf_rec['file_group'])[2]
47         except:
48             logger.log('conf_files: cannot find group %s -- %s not updated'%(cf_rec['file_group'],dest))
49             return
50         url = 'https://%s/%s' % (self.config.PLC_BOOT_HOST, cf_rec['source'])
51         # set node_id at the end of the request - hacky
52         if tools.node_id():
53             if url.find('?') >0: url += '&'
54             else:                url += '?'
55             url += "node_id=%d"%tools.node_id()
56         else:
57             logger.log('%s -- WARNING, cannot add node_id to request'%dest)
58         # pass slicefamily as well, as stored in /etc/planetlab/slicefamily ont the node
59         if tools.slicefamily():
60             if url.find('?') >0: url += '&'
61             else:                url += '?'
62             url += "slicefamily=%s"%tools.slicefamily()
63         try:
64             logger.verbose("retrieving URL=%s"%url)
65             contents = curlwrapper.retrieve(url, self.config.cacert)
66         except xmlrpclib.ProtocolError,e:
67             logger.log('conf_files: failed to retrieve %s from %s, skipping' % (dest, url))
68             return
69         if not cf_rec['always_update'] and sha.new(contents).digest() == self.checksum(dest):
70             return
71         if self.system(cf_rec['preinstall_cmd']):
72             self.system(err_cmd)
73             if not cf_rec['ignore_cmd_errors']: return
74         logger.log('conf_files: installing file %s from %s' % (dest, url))
75         try: os.makedirs(os.path.dirname(dest))
76         except OSError: pass
77         tools.write_file(dest, lambda f: f.write(contents), mode=mode, uidgid=(uid,gid))
78         if self.system(cf_rec['postinstall_cmd']): self.system(err_cmd)
79
80     def run_once(self, data):
81         for f in data['conf_files']:
82             try: self.update_conf_file(f)
83             except: logger.log_exc()
84
85     def run(self):
86         while True:
87             self.cond.acquire()
88             while self.data == None: self.cond.wait()
89             data = self.data
90             self.data = None
91             self.cond.release()
92             self.run_once(data)
93
94     def callback(self, data):
95         if data != None:
96             self.cond.acquire()
97             self.data = data
98             self.cond.notify()
99             self.cond.release()
100
101 main = None
102
103 def start(options, config):
104     global main
105     main = conf_files(config)
106     tools.as_daemon_thread(main.run)
107
108 def GetSlivers(data):
109     global main
110     assert main is not None
111     return main.callback(data)
112
113 if __name__ == '__main__':
114     import optparse
115     parser = optparse.OptionParser()
116     parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config', help='PLC configuration file')
117     parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session', help='API session key (or file)')
118     parser.add_option('--noscripts', action='store_true', dest='noscripts', default=False, help='Do not run pre- or post-install scripts')
119     (options, args) = parser.parse_args()
120
121     # Load /etc/planetlab/plc_config
122     from config import Config
123     config = Config(options.config)
124
125     # Load /etc/planetlab/session
126     if os.path.exists(options.session):
127         session = file(options.session).read().strip()
128     else:
129         session = options.session
130
131     # Initialize XML-RPC client
132     from plcapi import PLCAPI
133     plc = PLCAPI(config.plc_api_uri, config.cacert, auth = session)
134
135     main = conf_files(config, options.noscripts)
136     data = plc.GetSlivers()
137     main.run_once(data)