- fix previously introduced typo
[plcapi.git] / PLC / Methods / GetBootMedium.py
1 import random
2 import base64
3 import os
4 import os.path
5
6 from PLC.Faults import *
7 from PLC.Method import Method
8 from PLC.Parameter import Parameter, Mixed
9 from PLC.Auth import Auth
10
11 from PLC.Nodes import Node, Nodes
12 from PLC.NodeNetworks import NodeNetwork, NodeNetworks
13 from PLC.NodeNetworkSettings import NodeNetworkSetting, NodeNetworkSettings
14
15 #
16 # xxx todo
17 # Thierry on june 5 2007
18
19 # it turns out that having either apache (when invoked through xmlrpc)
20 # or root (when running plcsh directly) run this piece of code is
21 # problematic. In fact although we try to create intermediate dirs
22 # with mode 777, what happens is that root's umask in the plc chroot
23 # jail is set to 0022.
24
25 # the bottom line is, depending on who (apache or root) runs this for
26 # the first time, we can access denied issued (when root comes first)
27 # so probably we'd better implement a scheme where files are stored
28 # directly under /var/tmp or something
29
30 # in addition the sequels of a former run (e.g. with a non-empty
31 # filename) can prevent subsequent runs if the file is not properly
32 # cleaned up after use, which is generally the case if someone invokes
33 # this through plcsh and does not clean up
34 # so maybe a dedicated cleanup method could be useful just in case
35
36
37 # could not define this in the class..
38 boot_medium_actions = [ 'node-preview',
39                         'node-floppy',
40                         'node-iso',
41                         'node-usb',
42                         'generic-iso',
43                         'generic-usb',
44                         ]
45
46 class GetBootMedium(Method):
47     """
48     This method is a redesign based on former, supposedly dedicated, 
49     AdmGenerateNodeConfFile
50
51     As compared with its ancestor, this method provides a much more detailed
52     detailed interface, that allows to
53     (*) either just preview the node config file (in which case 
54         the node key is NOT recomputed, and NOT provided in the output
55     (*) or regenerate the node config file for storage on a floppy 
56         that is, exactly what the ancestor method used todo, 
57         including renewing the node's key
58     (*) or regenerate the config file and bundle it inside an ISO or USB image
59     (*) or just provide the generic ISO or USB boot images 
60         in which case of course the node_id_or_hostname parameter is not used
61
62     action is expected among the following string constants
63     (*) node-preview
64     (*) node-floppy
65     (*) node-iso
66     (*) node-usb
67     (*) generic-iso
68     (*) generic-usb
69
70     Apart for the preview mode, this method generates a new node key for the
71     specified node, effectively invalidating any old boot medium.
72
73     Non-admins can only generate files for nodes at their sites.
74
75     In addition, two return mechanisms are supported.
76     (*) The default behaviour is that the file's content is returned as a 
77         base64-encoded string. This is how the ancestor method used to work.
78         To use this method, pass an empty string as the file parameter.
79
80     (*) Or, for efficiency -- this makes sense only when the API is used 
81         by the web pages that run on the same host -- the caller may provide 
82         a filename, in which case the resulting file is stored in that location instead. 
83         The filename argument can use the following markers, that are expanded 
84         within the method
85         - %d : default root dir (some builtin dedicated area under /var/tmp/)
86                Using this is recommended, and enforced for non-admin users
87         - %n : the node's name when this makes sense, or a mktemp-like name when 
88                generic media is requested
89         - %s : a file suffix appropriate in the context (.txt, .iso or the like)
90         - %v : the bootcd version string (e.g. 4.0)
91         - %p : the PLC name
92         With the file-based return mechanism, the method returns the full pathname 
93         of the result file; it is the caller's responsability to remove 
94         this file after use.
95
96     Options: an optional array of keywords. Currently supported are
97         - 'serial'
98         - 'cramfs'
99
100     Security:
101         When the user's role is not admin, the provided directory *must* be under
102         the %d area
103
104    Housekeeping: 
105         Whenever needed, the method stores intermediate files in a
106         private area, typically not located under the web server's
107         accessible area, and are cleaned up by the method.
108
109     """
110
111     roles = ['admin', 'pi', 'tech']
112
113     accepts = [
114         Auth(),
115         Mixed(Node.fields['node_id'],
116               Node.fields['hostname']),
117         Parameter (str, "Action mode, expected in " + "|".join(boot_medium_actions)),
118         Parameter (str, "Empty string for verbatim result, resulting file full path otherwise"),
119         Parameter ([str], "Options"),
120         ]
121
122     returns = Parameter(str, "Node boot medium, either inlined, or filename, depending to the filename parameter")
123
124     BOOTCDDIR = "/usr/share/bootcd/"
125     BOOTCDBUILD = "/usr/share/bootcd/build.sh"
126     GENERICDIR = "/var/www/html/download/"
127     NODEDIR = "/var/tmp/bootmedium/results"
128     WORKDIR = "/var/tmp/bootmedium/work"
129     DEBUG = False
130     # uncomment this to preserve temporary area and bootcustom logs
131     #DEBUG = True
132
133     ### returns (host, domain) :
134     # 'host' : host part of the hostname
135     # 'domain' : domain part of the hostname
136     def split_hostname (self, node):
137         # Split hostname into host and domain parts
138         parts = node['hostname'].split(".", 1)
139         if len(parts) < 2:
140             raise PLCInvalidArgument, "Node hostname %s is invalid"%node['hostname']
141         return parts
142         
143     # plnode.txt content
144     def floppy_contents (self, node, renew_key):
145
146         if node['peer_id'] is not None:
147             raise PLCInvalidArgument, "Not a local node"
148
149         # If we are not an admin, make sure that the caller is a
150         # member of the site at which the node is located.
151         if 'admin' not in self.caller['roles']:
152             if node['site_id'] not in self.caller['site_ids']:
153                 raise PLCPermissionDenied, "Not allowed to generate a configuration file for %s"%node['hostname']
154
155         # Get node networks for this node
156         primary = None
157         nodenetworks = NodeNetworks(self.api, node['nodenetwork_ids'])
158         for nodenetwork in nodenetworks:
159             if nodenetwork['is_primary']:
160                 primary = nodenetwork
161                 break
162         if primary is None:
163             raise PLCInvalidArgument, "No primary network configured on %s"%node['hostname']
164
165         ( host, domain ) = self.split_hostname (node)
166
167         if renew_key:
168             # Generate 32 random bytes
169             bytes = random.sample(xrange(0, 256), 32)
170             # Base64 encode their string representation
171             node['key'] = base64.b64encode("".join(map(chr, bytes)))
172             # XXX Boot Manager cannot handle = in the key
173             node['key'] = node['key'].replace("=", "")
174             # Save it
175             node.sync()
176
177         # Generate node configuration file suitable for BootCD
178         file = ""
179
180         if renew_key:
181             file += 'NODE_ID="%d"\n' % node['node_id']
182             file += 'NODE_KEY="%s"\n' % node['key']
183
184         if primary['mac']:
185             file += 'NET_DEVICE="%s"\n' % primary['mac'].lower()
186
187         file += 'IP_METHOD="%s"\n' % primary['method']
188
189         if primary['method'] == 'static':
190             file += 'IP_ADDRESS="%s"\n' % primary['ip']
191             file += 'IP_GATEWAY="%s"\n' % primary['gateway']
192             file += 'IP_NETMASK="%s"\n' % primary['netmask']
193             file += 'IP_NETADDR="%s"\n' % primary['network']
194             file += 'IP_BROADCASTADDR="%s"\n' % primary['broadcast']
195             file += 'IP_DNS1="%s"\n' % primary['dns1']
196             file += 'IP_DNS2="%s"\n' % (primary['dns2'] or "")
197
198         file += 'HOST_NAME="%s"\n' % host
199         file += 'DOMAIN_NAME="%s"\n' % domain
200
201         # define various nodenetwork settings attached to the primary nodenetwork
202         settings = NodeNetworkSettings (self.api, {'nodenetwork_id':nodenetwork['nodenetwork_id']})
203
204         categories = set()
205         for setting in settings:
206             if setting['category'] is not None:
207                 categories.add(setting['category'])
208         
209         for category in categories:
210             category_settings = NodeNetworkSettings(self.api,{'nodenetwork_id':nodenetwork['nodenetwork_id'],
211                                                               'category':category})
212             if category_settings:
213                 file += '### Category : %s\n'%category
214                 for setting in category_settings:
215                     file += '%s_%s="%s"\n'%(category.upper(),setting['name'].upper(),setting['value'])
216
217         for nodenetwork in nodenetworks:
218             if nodenetwork['method'] == 'ipmi':
219                 file += 'IPMI_ADDRESS="%s"\n' % nodenetwork['ip']
220                 if nodenetwork['mac']:
221                     file += 'IPMI_MAC="%s"\n' % nodenetwork['mac'].lower()
222                 break
223
224         return file
225
226     def bootcd_version (self):
227         try:
228             f = open (self.BOOTCDDIR + "/build/version.txt")
229             version=f.readline().strip()
230         finally:
231             f.close()
232         return version
233
234     def cleandir (self,tempdir):
235         if not self.DEBUG:
236             os.system("rm -rf %s"%tempdir)
237
238     def call(self, auth, node_id_or_hostname, action, filename, options = []):
239
240         ### check action
241         found=False
242         for boot_medium_action in boot_medium_actions:
243             if action.startswith(boot_medium_action): 
244                 found=True
245                 break
246
247         if not found:
248             raise PLCInvalidArgument, "Unknown action %s"%action
249
250         ### compute file suffix and type
251         if action.find("-iso") >= 0 :
252             suffix=".iso"
253             type = ["iso"]
254         elif action.find("-usb") >= 0:
255             suffix=".usb"
256             type = ["usb"]
257         else:
258             suffix=".txt"
259             type = ["txt"]
260
261         if type != "txt":
262             if 'serial' in options:
263                 suffix = "-serial" + suffix
264                 type.insert(1, "serial")
265             if 'cramfs' in options:
266                 suffix = "-cramfs" + suffix
267                 # XXX must be the same index as above
268                 type.insert(1, "cramfs")
269         type = "_".join(type)
270
271         ### compute a 8 bytes random number
272         tempbytes = random.sample (xrange(0,256), 8);
273         def hexa2 (c):
274             return chr((c>>4)+65) + chr ((c&16)+65)
275         temp = "".join(map(hexa2,tempbytes))
276
277         ### check node if needed
278         if action.find("node-") == 0:
279             nodes = Nodes(self.api, [node_id_or_hostname])
280             if not nodes:
281                 raise PLCInvalidArgument, "No such node %r"%node_id_or_hostname
282             node = nodes[0]
283             nodename = node['hostname']
284             
285         else:
286             node = None
287             nodename = temp
288             
289         ### handle filename
290         filename = filename.replace ("%d",self.NODEDIR)
291         filename = filename.replace ("%n",nodename)
292         filename = filename.replace ("%s",suffix)
293         filename = filename.replace ("%p",self.api.config.PLC_NAME)
294         # only if filename contains "%v", bootcd is maybe not avail ?
295         if filename.find("%v") >=0:
296             filename = filename.replace ("%v",self.bootcd_version())
297
298         ### Check filename location
299         if filename != '':
300             if 'admin' not in self.caller['roles']:
301                 if ( filename.index(self.NODEDIR) != 0):
302                     raise PLCInvalidArgument, "File %s not under %s"%(filename,self.NODEDIR)
303
304             ### output should not exist (concurrent runs ..)
305             if os.path.exists(filename):
306                 raise PLCInvalidArgument, "Resulting file %s already exists"%filename
307
308             ### we can now safely create the file, 
309             ### either we are admin or under a controlled location
310             if not os.path.exists(os.path.dirname(filename)):
311                 try:
312                     os.makedirs (os.path.dirname(filename),0777)
313                 except:
314                     raise PLCPermissionDenied, "Could not create dir %s"%os.path.dirname(filename)
315
316         
317         ### generic media
318         if action == 'generic-iso' or action == 'generic-usb':
319             # this raises an exception if bootcd is missing
320             version = self.bootcd_version()
321             generic_name = "%s-BootCD-%s%s"%(self.api.config.PLC_NAME,
322                                              version,
323                                              suffix)
324             generic_path = "%s/%s" % (self.GENERICDIR,generic_name)
325
326             if filename:
327                 ret=os.system ("cp %s %s"%(generic_path,filename))
328                 if ret==0:
329                     return filename
330                 else:
331                     raise PLCPermissionDenied, "Could not copy %s into"%(generic_path,filename)
332             else:
333                 ### return the generic medium content as-is, just base64 encoded
334                 return base64.b64encode(file(generic_path).read())
335
336         ### config file preview or regenerated
337         if action == 'node-preview' or action == 'node-floppy':
338             if action == 'node-preview': bo=False
339             else: bo=True
340             floppy = self.floppy_contents (node,bo)
341             if filename:
342                 try:
343                     file(filename,'w').write(floppy)
344                 except:
345                     raise PLCPermissionDenied, "Could not write into %s"%filename
346                 return filename
347             else:
348                 return floppy
349
350         ### we're left with node-iso and node-usb
351         if action.startswith('node-iso') or action.startswith('node-usb'):
352
353             ### check we've got required material
354             version = self.bootcd_version()
355             
356             if not os.path.isfile(self.BOOTCDBUILD):
357                 raise PLCAPIError, "Cannot locate bootcd/build.sh script %s"%self.BOOTCDBUILD
358
359             # need a temporary area
360             tempdir = "%s/%s"%(self.WORKDIR,nodename)
361             if not os.path.isdir(tempdir):
362                 try:
363                     os.makedirs(tempdir,0777)
364                 except:
365                     raise PLCPermissionDenied, "Could not create dir %s"%tempdir
366             
367             try:
368                 # generate floppy config
369                 floppy = self.floppy_contents(node,True)
370                 # store it
371                 node_floppy = "%s/%s"%(tempdir,nodename)
372                 try:
373                     file(node_floppy,"w").write(floppy)
374                 except:
375                     raise PLCPermissionDenied, "Could not write into %s"%node_floppy
376
377                 node_image = "%s/%s"%(tempdir,nodename)
378                 # invoke build.sh
379                 if action.find("-serial") > 0:
380                     serial_info = action[action.find("-serial")+len("-serial"):]
381                     if len(serial_info) > 0:
382                         serial_info = serial_info[1:]
383                     else:
384                         serial_info = "ttyS0:115200:n:8"
385                     serial_arg='-s "%s"' % serial_info
386                 else:
387                     serial_arg=""
388
389                 build_command = '%s -f "%s" -O "%s" -t "%s" %s &> %s.log' % (self.BOOTCDBUILD,
390                                                                              node_floppy,
391                                                                              node_image,
392                                                                              type,
393                                                                              serial_arg,
394                                                                              node_image)
395                 if self.DEBUG:
396                     print 'build command:',build_command
397                 ret=os.system(build_command)
398                 if ret != 0:
399                     raise PLCPermissionDenied,"build.sh failed to create node-specific medium"
400
401                 node_image += suffix
402                 if not os.path.isfile (node_image):
403                     raise PLCAPIError,"Unexpected location of build.sh output - %s"%node_image
404             
405                 # cache result
406                 if filename:
407                     ret=os.system("mv %s %s"%(node_image,filename))
408                     if ret != 0:
409                         raise PLCAPIError, "Could not move node image %s into %s"%(node_image,filename)
410                     self.cleandir(tempdir)
411                     return filename
412                 else:
413                     result = file(node_image).read()
414                     self.cleandir(tempdir)
415                     return base64.b64encode(result)
416             except:
417                 self.cleandir(tempdir)
418                 raise
419                 
420         # we're done here, or we missed something
421         raise PLCAPIError,'Unhandled action %s'%action
422