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