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