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