Support cramfs and serial images.
[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         Security:
97         When the user's role is not admin, the provided directory *must* be under
98         the %d area
99
100         Housekeeping: 
101         Whenever needed, the method stores intermediate files in a
102         private area, typically not located under the web server's
103         accessible area, and are cleaned up by the method.
104
105     """
106
107     roles = ['admin', 'pi', 'tech']
108
109     accepts = [
110         Auth(),
111         Mixed(Node.fields['node_id'],
112               Node.fields['hostname']),
113         Parameter (str, "Action mode, expected in " + "|".join(boot_medium_actions)),
114         Parameter (str, "Empty string for verbatim result, resulting file full path otherwise"),
115         Parameter ([str], "Options"),
116         ]
117
118     returns = Parameter(str, "Node boot medium, either inlined, or filename, depending to the filename parameter")
119
120     BOOTCDDIR = "/usr/share/bootcd/"
121     BOOTCDBUILD = "/usr/share/bootcd/build.sh"
122     GENERICDIR = "/var/www/html/download/"
123     NODEDIR = "/var/tmp/bootmedium/results"
124     WORKDIR = "/var/tmp/bootmedium/work"
125     DEBUG = False
126     # uncomment this to preserve temporary area and bootcustom logs
127     #DEBUG = True
128
129     ### returns (host, domain) :
130     # 'host' : host part of the hostname
131     # 'domain' : domain part of the hostname
132     def split_hostname (self, node):
133         # Split hostname into host and domain parts
134         parts = node['hostname'].split(".", 1)
135         if len(parts) < 2:
136             raise PLCInvalidArgument, "Node hostname %s is invalid"%node['hostname']
137         return parts
138         
139     # plnode.txt content
140     def floppy_contents (self, node, renew_key):
141
142         if node['peer_id'] is not None:
143             raise PLCInvalidArgument, "Not a local node"
144
145         # If we are not an admin, make sure that the caller is a
146         # member of the site at which the node is located.
147         if 'admin' not in self.caller['roles']:
148             if node['site_id'] not in self.caller['site_ids']:
149                 raise PLCPermissionDenied, "Not allowed to generate a configuration file for %s"%node['hostname']
150
151         # Get node networks for this node
152         primary = None
153         nodenetworks = NodeNetworks(self.api, node['nodenetwork_ids'])
154         for nodenetwork in nodenetworks:
155             if nodenetwork['is_primary']:
156                 primary = nodenetwork
157                 break
158         if primary is None:
159             raise PLCInvalidArgument, "No primary network configured on %s"%node['hostname']
160
161         ( host, domain ) = self.split_hostname (node)
162
163         if renew_key:
164             # Generate 32 random bytes
165             bytes = random.sample(xrange(0, 256), 32)
166             # Base64 encode their string representation
167             node['key'] = base64.b64encode("".join(map(chr, bytes)))
168             # XXX Boot Manager cannot handle = in the key
169             node['key'] = node['key'].replace("=", "")
170             # Save it
171             node.sync()
172
173         # Generate node configuration file suitable for BootCD
174         file = ""
175
176         if renew_key:
177             file += 'NODE_ID="%d"\n' % node['node_id']
178             file += 'NODE_KEY="%s"\n' % node['key']
179
180         if primary['mac']:
181             file += 'NET_DEVICE="%s"\n' % primary['mac'].lower()
182
183         file += 'IP_METHOD="%s"\n' % primary['method']
184
185         if primary['method'] == 'static':
186             file += 'IP_ADDRESS="%s"\n' % primary['ip']
187             file += 'IP_GATEWAY="%s"\n' % primary['gateway']
188             file += 'IP_NETMASK="%s"\n' % primary['netmask']
189             file += 'IP_NETADDR="%s"\n' % primary['network']
190             file += 'IP_BROADCASTADDR="%s"\n' % primary['broadcast']
191             file += 'IP_DNS1="%s"\n' % primary['dns1']
192             file += 'IP_DNS2="%s"\n' % (primary['dns2'] or "")
193
194         file += 'HOST_NAME="%s"\n' % host
195         file += 'DOMAIN_NAME="%s"\n' % domain
196
197         # define various nodenetwork settings attached to the primary nodenetwork
198         settings = NodeNetworkSettings (self.api, {'nodenetwork_id':nodenetwork['nodenetwork_id']})
199
200         categories = set()
201         for setting in settings:
202             if setting['category'] is not None:
203                 categories.add(setting['category'])
204         
205         for category in categories:
206             category_settings = NodeNetworkSettings(self.api,{'nodenetwork_id':nodenetwork['nodenetwork_id'],
207                                                               'category':category})
208             if category_settings:
209                 file += '### Category : %s\n'%category
210                 for setting in category_settings:
211                     file += '%s_%s="%s"\n'%(category.upper(),setting['name'].upper(),setting['value'])
212
213         for nodenetwork in nodenetworks:
214             if nodenetwork['method'] == 'ipmi':
215                 file += 'IPMI_ADDRESS="%s"\n' % nodenetwork['ip']
216                 if nodenetwork['mac']:
217                     file += 'IPMI_MAC="%s"\n' % nodenetwork['mac'].lower()
218                 break
219
220         return file
221
222     def bootcd_version (self):
223         try:
224             f = open (self.BOOTCDDIR + "/build/version.txt")
225             version=f.readline().strip()
226         finally:
227             f.close()
228         return version
229
230     def cleandir (self,tempdir):
231         if not self.DEBUG:
232             os.system("rm -rf %s"%tempdir)
233
234     def call(self, auth, node_id_or_hostname, action, filename, options = []):
235
236         ### check action
237         if action not in boot_medium_actions:
238             raise PLCInvalidArgument, "Unknown action %s"%action
239
240         ### compute file suffix and type
241         if action.find("-iso") >= 0 :
242             suffix=".iso"
243             type = ["iso"]
244         elif action.find("-usb") >= 0:
245             suffix=".usb"
246             type = ["usb"]
247         else:
248             suffix=".txt"
249             type = ["txt"]
250
251         if type != "txt":
252             if 'serial' in options:
253                 suffix = "-serial" + suffix
254                 type.insert(1, "serial")
255             if 'cramfs' in options:
256                 suffix = "-cramfs" + suffix
257                 # XXX must be the same index as above
258                 type.insert(1, "cramfs")
259         type = "_".join(type)
260
261         ### compute a 8 bytes random number
262         tempbytes = random.sample (xrange(0,256), 8);
263         def hexa2 (c):
264             return chr((c>>4)+65) + chr ((c&16)+65)
265         temp = "".join(map(hexa2,tempbytes))
266
267         ### check node if needed
268         if action.find("node-") == 0:
269             nodes = Nodes(self.api, [node_id_or_hostname])
270             if not nodes:
271                 raise PLCInvalidArgument, "No such node %r"%node_id_or_hostname
272             node = nodes[0]
273             nodename = node['hostname']
274             
275         else:
276             node = None
277             nodename = temp
278             
279         ### handle filename
280         filename = filename.replace ("%d",self.NODEDIR)
281         filename = filename.replace ("%n",nodename)
282         filename = filename.replace ("%s",suffix)
283         filename = filename.replace ("%p",self.api.config.PLC_NAME)
284         # only if filename contains "%v", bootcd is maybe not avail ?
285         if filename.find("%v") >=0:
286             filename = filename.replace ("%v",self.bootcd_version())
287
288         ### Check filename location
289         if filename != '':
290             if 'admin' not in self.caller['roles']:
291                 if ( filename.index(self.NODEDIR) != 0):
292                     raise PLCInvalidArgument, "File %s not under %s"%(filename,self.NODEDIR)
293
294             ### output should not exist (concurrent runs ..)
295             if os.path.exists(filename):
296                 raise PLCInvalidArgument, "Resulting file %s already exists"%filename
297
298             ### we can now safely create the file, 
299             ### either we are admin or under a controlled location
300             if not os.path.exists(os.path.dirname(filename)):
301                 try:
302                     os.makedirs (os.path.dirname(filename),0777)
303                 except:
304                     raise PLCPermissionDenied, "Could not create dir %s"%os.path.dirname(filename)
305
306         
307         ### generic media
308         if action == 'generic-iso' or action == 'generic-usb':
309             # this raises an exception if bootcd is missing
310             version = self.bootcd_version()
311             generic_name = "%s-BootCD-%s%s"%(self.api.config.PLC_NAME,
312                                              version,
313                                              suffix)
314             generic_path = "%s/%s" % (self.GENERICDIR,generic_name)
315
316             if filename:
317                 ret=os.system ("cp %s %s"%(generic_path,filename))
318                 if ret==0:
319                     return filename
320                 else:
321                     raise PLCPermissionDenied, "Could not copy %s into"%(generic_path,filename)
322             else:
323                 ### return the generic medium content as-is, just base64 encoded
324                 return base64.b64encode(file(generic_path).read())
325
326         ### floppy preview
327         if action == 'node-preview':
328             floppy = self.floppy_contents (node,False)
329             if filename:
330                 try:
331                     file(filename,'w').write(floppy)
332                 except:
333                     raise PLCPermissionDenied, "Could not write into %s"%filename
334                 return filename
335             else:
336                 return floppy
337
338         if action == 'node-floppy':
339             floppy = self.floppy_contents (node,True)
340             if filename:
341                 try:
342                     file(filename,'w').write(floppy)
343                 except:
344                     raise PLCPermissionDenied, "Could not write into %s"%filename
345                 return filename
346             else:
347                 return floppy
348
349         ### we're left with node-iso and node-usb
350         if action == 'node-iso' or action == 'node-usb':
351
352             ### check we've got required material
353             version = self.bootcd_version()
354             
355             if not os.path.isfile(self.BOOTCDBUILD):
356                 raise PLCAPIError, "Cannot locate bootcd/build.sh script %s"%self.BOOTCDBUILD
357
358             # need a temporary area
359             tempdir = "%s/%s"%(self.WORKDIR,nodename)
360             if not os.path.isdir(tempdir):
361                 try:
362                     os.makedirs(tempdir,0777)
363                 except:
364                     raise PLCPermissionDenied, "Could not create dir %s"%tempdir
365             
366             try:
367                 # generate floppy config
368                 floppy = self.floppy_contents(node,True)
369                 # store it
370                 node_floppy = "%s/%s"%(tempdir,nodename)
371                 try:
372                     file(node_floppy,"w").write(floppy)
373                 except:
374                     raise PLCPermissionDenied, "Could not write into %s"%node_floppy
375
376                 node_image = "%s/%s"%(tempdir,nodename)
377                 # invoke build.sh
378                 build_command = '%s -f "%s" -O "%s" -t "%s" &> %s.log' % (self.BOOTCDBUILD,
379                                                                           node_floppy,
380                                                                           node_image,
381                                                                           type,
382                                                                           node_image)
383                 if self.DEBUG:
384                     print 'build command:',build_command
385                 ret=os.system(build_command)
386                 if ret != 0:
387                     raise PLCPermissionDenied,"build.sh failed to create node-specific medium"
388
389                 node_image += suffix
390                 if not os.path.isfile (node_image):
391                     raise PLCAPIError,"Unexpected location of build.sh output - %s"%node_image
392             
393                 # cache result
394                 if filename:
395                     ret=os.system("mv %s %s"%(node_image,filename))
396                     if ret != 0:
397                         raise PLCAPIError, "Could not move node image %s into %s"%(node_image,filename)
398                     self.cleandir(tempdir)
399                     return filename
400                 else:
401                     result = file(node_image).read()
402                     self.cleandir(tempdir)
403                     return base64.b64encode(result)
404             except:
405                 self.cleandir(tempdir)
406                 raise
407                 
408         # we're done here, or we missed something
409         raise PLCAPIError,'Unhandled action %s'%action
410