b018598a77cb7e75775d9e07dde7e39a7b83b99c
[tests.git] / system / TestNode.py
1 # Thierry Parmentelat <thierry.parmentelat@inria.fr>
2 # Copyright (C) 2010 INRIA 
3 #
4 import sys
5 import os, os.path
6 import time
7 import base64
8
9 import utils
10 from TestUser import TestUser
11 from TestBoxQemu import TestBoxQemu
12 from TestSsh import TestSsh
13 from Completer import CompleterTask
14
15 class CompleterTaskNodeSsh(CompleterTask):
16     def __init__(self, hostname, qemuname, local_key, command=None,
17                   boot_state="boot", expected=True, dry_run=False):
18         self.hostname = hostname
19         self.qemuname = qemuname
20         self.boot_state = boot_state
21         self.local_key = local_key
22         self.command = command if command is not None else "hostname;uname -a"
23         self.expected = expected
24         self.dry_run = dry_run
25         self.test_ssh =  TestSsh(self.hostname, key=self.local_key)
26     def run(self, silent):
27         command = self.test_ssh.actual_command(self.command)
28         retcod = utils.system(command, silent=silent, dry_run=self.dry_run)
29         if self.expected:
30             return retcod == 0
31         else:
32             return retcod != 0
33     def failure_epilogue(self):
34         print("Cannot reach {} in {} mode".format(self.hostname, self.boot_state))
35
36 class TestNode:
37
38     def __init__(self, test_plc, test_site, node_spec):
39         self.test_plc = test_plc
40         self.test_site = test_site
41         self.node_spec = node_spec
42         
43     def name(self):
44         return self.node_spec['node_fields']['hostname']
45     
46     def dry_run(self):
47         return self.test_plc.options.dry_run
48
49     @staticmethod
50     def is_qemu_model(model):
51         return model.find("qemu") >= 0
52     def is_qemu(self):
53         return TestNode.is_qemu_model(self.node_spec['node_fields']['model'])
54
55     @staticmethod
56     def is_real_model(model):
57         return not TestNode.is_qemu_model(model)
58     def is_real(self):
59         return TestNode.is_real_model(self.node_spec['node_fields']['model'])
60
61     def buildname(self):
62         return self.test_plc.options.buildname
63         
64     def nodedir(self):
65         if self.is_qemu():
66             return "qemu-{}".format(self.name())
67         else:
68             return "real-{}".format(self.name())
69
70     # this returns a hostname
71     def host_box(self):
72         if self.is_real():
73             return 'localhost'
74         else:
75             try:
76                 return self.node_spec['host_box']
77             except:
78                 utils.header("WARNING : qemu nodes need a host box")
79                 return 'localhost'
80
81     # this returns a TestBoxQemu instance - cached in .test_box_value
82     def test_box(self):
83         try:
84             return self.test_box_value
85         except:
86             self.test_box_value = TestBoxQemu(self.host_box(),self.buildname())
87             return self.test_box_value
88
89     def create_node(self):
90         ownername = self.node_spec['owner']
91         user_spec = self.test_site.locate_user(ownername)
92         test_user = TestUser(self.test_plc,self.test_site,user_spec)
93         userauth = test_user.auth()
94         utils.header("node {} created by user {}".format(self.name(), test_user.name()))
95         rootauth = self.test_plc.auth_root()
96         server  =  self.test_plc.apiserver
97         node_id = server.AddNode(userauth,
98                                  self.test_site.site_spec['site_fields']['login_base'],
99                                  self.node_spec['node_fields'])
100         server.SetNodePlainBootstrapfs(userauth,
101                                        self.node_spec['node_fields']['hostname'],
102                                        'YES')
103         # create as reinstall to avoid user confirmation
104         server.UpdateNode(userauth, self.name(), {'boot_state':'reinstall'})
105
106         if not self.test_plc.has_addresses_api():
107 #            print 'USING OLD INTERFACE'
108             # populate network interfaces - primary
109             server.AddInterface(userauth,self.name(),
110                                 self.node_spec['interface_fields'])
111         else:
112 #            print 'USING NEW INTERFACE with separate ip addresses'
113             # this is for setting the 'dns' stuff that now goes with the node
114             server.UpdateNode(userauth, self.name(), self.node_spec['node_fields_nint'])
115             interface_id = server.AddInterface(userauth, self.name(),self.node_spec['interface_fields_nint'])
116             server.AddIpAddress(userauth, interface_id, self.node_spec['ipaddress_fields'])
117             route_fields = self.node_spec['route_fields']
118             route_fields['interface_id'] = interface_id
119             server.AddRoute(userauth, node_id, self.node_spec['route_fields'])
120             pass
121         # populate network interfaces - others
122         if 'extra_interfaces' in self.node_spec:
123             for interface in self.node_spec['extra_interfaces']:
124                 server.AddInterface(userauth,self.name(), interface['interface_fields'])
125                 if 'settings' in interface:
126                     for attribute, value in interface['settings'].items():
127                         # locate node network
128                         interface = server.GetInterfaces(userauth,{'ip':interface['interface_fields']['ip']})[0]
129                         interface_id = interface['interface_id']
130                         # locate or create node network attribute type
131                         try:
132                             interface_tagtype = server.GetTagTypes(userauth,{'name':attribute})[0]
133                         except:
134                             interface_tagtype = server.AddTagType(rootauth,{'category':'test',
135                                                                             'tagname':attribute})
136                         # attach value
137                         server.AddInterfaceTag(userauth,interface_id,attribute,value)
138
139     def delete_node(self):
140         # uses the right auth as far as poss.
141         try:
142             ownername = self.node_spec['owner']
143             user_spec = self.test_site.locate_user(ownername)
144             test_user = TestUser(self.test_plc,self.test_site,user_spec)
145             auth = test_user.auth()
146         except:
147             auth = self.test_plc.auth_root()
148         self.test_plc.apiserver.DeleteNode(auth,self.name())
149
150     # Do most of the stuff locally - will be pushed on host_box - *not* the plc - later if needed
151     def qemu_local_init(self):
152         "all nodes : init a clean local directory for holding node-dep stuff like iso image..."
153         utils.system("rm -rf {}".format(self.nodedir()))
154         utils.system("mkdir {}".format(self.nodedir()))
155         if not self.is_qemu():
156             return True
157         return utils.system("rsync -v -a --exclude .svn template-qemu/ {}/"\
158                             .format(self.nodedir())) == 0
159
160     def bootcd(self):
161         "all nodes: invoke GetBootMedium and store result locally"
162         utils.header("Calling GetBootMedium for {}".format(self.name()))
163         # this would clearly belong in the config but, well ..
164         options = []
165         if self.is_qemu():
166             options.append('serial')
167             options.append('no-hangcheck')
168             options.append('systemd-debug')
169         encoded = self.test_plc.apiserver.GetBootMedium(self.test_plc.auth_root(), 
170                                                         self.name(), 'node-iso', '', options)
171         if encoded == '':
172             raise Exception('GetBootmedium failed')
173
174         filename = "{}/{}.iso".format(self.nodedir(), self.name())
175         utils.header('Storing boot medium into {}'.format(filename))
176
177         # xxx discovered with python3, but a long stading issue:
178         # encoded at this point is a str instead of a bytes
179         # Quick & dirty : we convert this explicitly to a bytearray
180         # Longer run : clearly it seems like the plcapi server side should
181         # tag its result with <base64></base64> rather than as a string
182         bencoded = str.encode(encoded)
183         if self.dry_run():
184             print("Dry_run: skipped writing of iso image")
185             return True
186         else:
187             # with python3 we need to call decodestring here
188             with open(filename,'wb') as storage:
189                 storage.write(base64.decodestring(bencoded))
190             return True
191
192     def nodestate_reinstall(self):
193         "all nodes: mark PLCAPI boot_state as reinstall"
194         self.test_plc.apiserver.UpdateNode(self.test_plc.auth_root(),
195                                            self.name(),{'boot_state':'reinstall'})
196         return True
197     
198     def nodestate_safeboot(self):
199         "all nodes: mark PLCAPI boot_state as safeboot"
200         self.test_plc.apiserver.UpdateNode(self.test_plc.auth_root(),
201                                            self.name(),{'boot_state':'safeboot'})
202         return True
203     
204     def nodestate_boot(self):
205         "all nodes: mark PLCAPI boot_state as boot"
206         self.test_plc.apiserver.UpdateNode(self.test_plc.auth_root(),
207                                            self.name(),{'boot_state':'boot'})
208         return True
209
210     def nodestate_show(self):
211         "all nodes: show PLCAPI boot_state"
212         if self.dry_run():
213             print("Dry_run: skipped getting current node state")
214             return True
215         state = self.test_plc.apiserver.GetNodes(self.test_plc.auth_root(), self.name(), ['boot_state'])[0]['boot_state']
216         print(self.name(),':',state)
217         return True
218     
219     def qemu_local_config(self):
220         "all nodes: compute qemu config qemu.conf and store it locally"
221         if not self.is_qemu():
222             return
223         mac = self.node_spec['interface_fields']['mac']
224         hostname = self.node_spec['node_fields']['hostname']
225         ip = self.node_spec['interface_fields']['ip']
226         auth = self.test_plc.auth_root()
227         target_arch = self.test_plc.apiserver.GetPlcRelease(auth)['build']['target-arch']
228         conf_filename = "{}/qemu.conf".format(self.nodedir())
229         if self.dry_run():
230             print("dry_run: skipped actual storage of qemu.conf")
231             return True
232         utils.header('Storing qemu config for {} in {}'.format(self.name(), conf_filename))
233         with open(conf_filename,'w') as file:
234             file.write('MACADDR={}\n'.format(mac))
235             file.write('NODE_ISO={}.iso\n'.format(self.name()))
236             file.write('HOSTNAME={}\n'.format(hostname))
237             file.write('IP={}\n'.format(ip))
238             file.write('TARGET_ARCH={}\n'.format(target_arch))
239         return True
240
241     def qemu_clean(self):
242         utils.header("Cleaning up qemu for host {} on box {}"\
243                      .format(self.name(),self.test_box().hostname()))
244         dry_run = self.dry_run()
245         self.test_box().rmdir(self.nodedir(), dry_run=dry_run)
246         return True
247
248     def qemu_export(self):
249         "all nodes: push local node-dep directory on the qemu box"
250         # if relevant, push the qemu area onto the host box
251         if self.test_box().is_local():
252             return True
253         dry_run = self.dry_run()
254         utils.header("Cleaning any former sequel of {} on {}"\
255                      .format(self.name(), self.host_box()))
256         utils.header("Transferring configuration files for node {} onto {}"\
257                      .format(self.name(), self.host_box()))
258         return self.test_box().copy(self.nodedir(), recursive=True, dry_run=dry_run) == 0
259             
260     def qemu_start(self):
261         "all nodes: start the qemu instance (also runs qemu-bridge-init start)"
262         model = self.node_spec['node_fields']['model']
263         #starting the Qemu nodes before 
264         if self.is_qemu():
265             self.start_qemu()
266         else:
267             utils.header("TestNode.qemu_start : {} model {} taken as real node"\
268                          .format(self.name(), model))
269         return True
270
271     def qemu_timestamp(self):
272         "all nodes: start the qemu instance (also runs qemu-bridge-init start)"
273         test_box = self.test_box()
274         test_box.run_in_buildname("mkdir -p {}".format(self.nodedir()), dry_run=self.dry_run())
275         now = int(time.time())
276         return test_box.run_in_buildname("echo {:d} > {}/timestamp"\
277                                          .format(now, self.nodedir()), dry_run=self.dry_run()) == 0
278
279     def start_qemu(self):
280         test_box = self.test_box()
281         utils.header("Starting qemu node {} on {}".format(self.name(), test_box.hostname()))
282
283         test_box.run_in_buildname("{}/qemu-bridge-init start >> {}/log.txt"\
284                                   .format(self.nodedir(), self.nodedir()),
285                                   dry_run=self.dry_run())
286         # kick it off in background, as it would otherwise hang
287         test_box.run_in_buildname("{}/qemu-start-node 2>&1 >> {}/log.txt"\
288                                   .format(self.nodedir(), self.nodedir()))
289
290     def list_qemu(self):
291         utils.header("Listing qemu for host {} on box {}"\
292                      .format(self.name(), self.test_box().hostname()))
293         command = "{}/qemu-kill-node -l {}".format(self.nodedir(), self.name())
294         self.test_box().run_in_buildname(command, dry_run=self.dry_run())
295         return True
296
297     def kill_qemu(self):
298         #Prepare the log file before killing the nodes
299         test_box = self.test_box()
300         # kill the right processes 
301         utils.header("Stopping qemu for node {} on box {}"\
302                      .format(self.name(), self.test_box().hostname()))
303         command = "{}/qemu-kill-node {}".format(self.nodedir(),self.name())
304         self.test_box().run_in_buildname(command, dry_run=self.dry_run())
305         return True
306
307     def gather_qemu_logs(self):
308         if not self.is_qemu():
309             return True
310         remote_log = "{}/log.txt".format(self.nodedir())
311         local_log = "logs/node.qemu.{}.txt".format(self.name())
312         self.test_box().test_ssh.fetch(remote_log,local_log,dry_run=self.dry_run())
313
314     def keys_clear_known_hosts(self):
315         "remove test nodes entries from the local known_hosts file"
316         TestSsh(self.name()).clear_known_hosts()
317         return True
318
319     def create_test_ssh(self):
320         # get the plc's keys for entering the node
321         vservername = self.test_plc.vservername
322 ###        # assuming we've run testplc.fetch_keys()
323 ###        key = "keys/{vservername}.rsa".format(**locals())
324         # fetch_keys doesn't grab the root key anymore
325         key = "keys/key_admin.rsa"
326         return TestSsh(self.name(), buildname=self.buildname(), key=key)
327
328     def check_hooks(self):
329         extensions = [ 'py','pl','sh' ]
330         path = 'hooks/node'
331         scripts = utils.locate_hooks_scripts('node '+self.name(), path,extensions)
332         overall = True
333         for script in scripts:
334             if not self.check_hooks_script(script):
335                 overall = False
336         return overall
337
338     def check_hooks_script(self,local_script):
339         # push the script on the node's root context
340         script_name = os.path.basename(local_script)
341         utils.header("NODE hook {} ({})".format(script_name, self.name()))
342         test_ssh = self.create_test_ssh()
343         test_ssh.copy_home(local_script)
344         if test_ssh.run("./"+script_name) != 0:
345             utils.header("WARNING: node hooks check script {} FAILED (ignored)"\
346                          .format(script_name))
347             #return False
348             return True
349         else:
350             utils.header("SUCCESS: node hook {} OK".format(script_name))
351             return True
352
353     def has_libvirt(self):
354         test_ssh = self.create_test_ssh()
355         return test_ssh.run("rpm -q --quiet libvirt-client") == 0
356
357     def _check_system_slice(self, slicename, dry_run=False):
358         sitename = self.test_plc.plc_spec['settings']['PLC_SLICE_PREFIX']
359         vservername = "{}_{}".format(sitename, slicename)
360         test_ssh = self.create_test_ssh()
361         if self.has_libvirt():
362             utils.header("Checking system slice {} using virsh".format(slicename))
363             return test_ssh.run("virsh --connect lxc:// list | grep -q ' {} '".format(vservername),
364                                 dry_run = dry_run) == 0
365         else:
366             retcod, output = \
367                     utils.output_of(test_ssh.actual_command("cat /vservers/{}/etc/slicefamily 2> /dev/null")\
368                                     .format(vservername))
369             # get last line only as ssh pollutes the output
370             slicefamily = output.split("\n")[-1]
371             utils.header("Found slicefamily '{}'for slice {}".format(slicefamily,slicename))
372             if retcod != 0: 
373                 return False
374             utils.header("Checking system slice {} using vserver-stat".format(slicename))
375             return test_ssh.run("vserver-stat | grep {}".format(vservername), dry_run=dry_run) == 0
376         
377