making the source file executable under git was not enough, I suspect setup.py enforc...
[nodemanager.git] / conf_files.py
1 #!/usr/bin/env python
2
3 """configuration files"""
4
5 import grp
6 import os
7 import pwd
8 try:
9     from hashlib import sha1 as sha
10 except ImportError:
11     from sha import sha
12 import string
13
14 import curlwrapper
15 import logger
16 import tools
17 import xmlrpclib
18 from config import Config
19
20 # right after net
21 priority = 2
22
23 class conf_files:
24     def __init__(self, noscripts=False):
25         self.config = Config()
26         self.noscripts = noscripts
27         self.data = None
28
29     def checksum(self, path):
30         try:
31             f = open(path)
32             try: return sha(f.read()).digest()
33             finally: f.close()
34         except IOError: return None
35
36     def system(self, cmd):
37         if not self.noscripts and cmd:
38             logger.verbose('conf_files: running command %s' % cmd)
39             return tools.fork_as(None, os.system, cmd)
40         else: return 0
41
42     def update_conf_file(self, cf_rec):
43         if not cf_rec['enabled']: return
44         dest = cf_rec['dest']
45         err_cmd = cf_rec['error_cmd']
46         mode = string.atoi(cf_rec['file_permissions'], base=8)
47         try:
48             uid = pwd.getpwnam(cf_rec['file_owner'])[2]
49         except:
50             logger.log('conf_files: cannot find user %s -- %s not updated'%(cf_rec['file_owner'], dest))
51             return
52         try:
53             gid = grp.getgrnam(cf_rec['file_group'])[2]
54         except:
55             logger.log('conf_files: cannot find group %s -- %s not updated'%(cf_rec['file_group'], dest))
56             return
57         url = 'https://%s/%s' % (self.config.PLC_BOOT_HOST, cf_rec['source'])
58         # set node_id at the end of the request - hacky
59         if tools.node_id():
60             if url.find('?') >0: url += '&'
61             else:                url += '?'
62             url += "node_id=%d"%tools.node_id()
63         else:
64             logger.log('conf_files: %s -- WARNING, cannot add node_id to request'%dest)
65         try:
66             logger.verbose("conf_files: retrieving URL=%s"%url)
67             contents = curlwrapper.retrieve(url, self.config.cacert)
68         except xmlrpclib.ProtocolError as 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(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         if data.has_key("conf_files"):
84             for f in data['conf_files']:
85                 try: self.update_conf_file(f)
86                 except: logger.log_exc("conf_files: failed to update conf_file")
87         else:
88             logger.log_missing_data("conf_files.run_once", 'conf_files')
89
90
91 def start(): pass
92
93 def GetSlivers(data, config = None, plc = None):
94     logger.log("conf_files: Running.")
95     cf = conf_files()
96     cf.run_once(data)
97     logger.log("conf_files: Done.")
98
99 if __name__ == '__main__':
100     import optparse
101     parser = optparse.OptionParser()
102     parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config', help='PLC configuration file')
103     parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session', help='API session key (or file)')
104     parser.add_option('--noscripts', action='store_true', dest='noscripts', default=False, help='Do not run pre- or post-install scripts')
105     (options, args) = parser.parse_args()
106
107     # Load /etc/planetlab/plc_config
108     config = Config(options.config)
109
110     # Load /etc/planetlab/session
111     if os.path.exists(options.session):
112         with open(options.session) as f:
113             session = f.read().strip()
114     else:
115         session = options.session
116
117     # Initialize XML-RPC client
118     from plcapi import PLCAPI
119     plc = PLCAPI(config.plc_api_uri, config.cacert, auth = session)
120
121     main = conf_files(options.noscripts)
122     data = plc.GetSlivers()
123     main.run_once(data)