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