adapting to kvm boxes under /vservers
[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_export (self):
205         "all nodes: push local node-dep directory on the qemu box"
206         # if relevant, push the qemu area onto the host box
207         if self.test_box().is_local():
208             return True
209         dry_run=self.dry_run()
210         utils.header ("Cleaning any former sequel of %s on %s"%(self.name(),self.host_box()))
211         self.test_box().rmdir(self.nodedir(), dry_run=dry_run)
212         utils.header ("Transferring configuration files for node %s onto %s"%(self.name(),self.host_box()))
213         return self.test_box().copy(self.nodedir(),recursive=True,dry_run=dry_run)==0
214             
215     def qemu_start (self):
216         "all nodes: start the qemu instance (also runs qemu-bridge-init start)"
217         model=self.node_spec['node_fields']['model']
218         #starting the Qemu nodes before 
219         if self.is_qemu():
220             self.start_qemu()
221         else:
222             utils.header("TestNode.qemu_start : %s model %s taken as real node"%(self.name(),model))
223         return True
224
225     def timestamp_qemu (self):
226         "all nodes: start the qemu instance (also runs qemu-bridge-init start)"
227         test_box = self.test_box()
228         test_box.run_in_buildname("mkdir -p %s"%self.nodedir(), dry_run=self.dry_run())
229         now=int(time.time())
230         return test_box.run_in_buildname("echo %d > %s/timestamp"%(now,self.nodedir()), dry_run=self.dry_run())==0
231
232     def start_qemu (self):
233         test_box = self.test_box()
234         utils.header("Starting qemu node %s on %s"%(self.name(),test_box.hostname()))
235
236         test_box.run_in_buildname("%s/qemu-bridge-init start >> %s/log.txt"%(self.nodedir(),self.nodedir()),
237                                   dry_run=self.dry_run())
238         # kick it off in background, as it would otherwise hang
239         test_box.run_in_buildname("%s/qemu-start-node 2>&1 >> %s/log.txt"%(self.nodedir(),self.nodedir()))
240
241     def list_qemu (self):
242         utils.header("Listing qemu for host %s on box %s"%(self.name(),self.test_box().hostname()))
243         command="%s/qemu-kill-node -l %s"%(self.nodedir(),self.name())
244         self.test_box().run_in_buildname(command, dry_run=self.dry_run())
245         return True
246
247     def kill_qemu (self):
248         #Prepare the log file before killing the nodes
249         test_box = self.test_box()
250         # kill the right processes 
251         utils.header("Stopping qemu for node %s on box %s"%(self.name(),self.test_box().hostname()))
252         command="%s/qemu-kill-node %s"%(self.nodedir(),self.name())
253         self.test_box().run_in_buildname(command, dry_run=self.dry_run())
254         return True
255
256     def gather_qemu_logs (self):
257         if not self.is_qemu():
258             return True
259         remote_log="%s/log.txt"%self.nodedir()
260         local_log="logs/node.qemu.%s.txt"%self.name()
261         self.test_box().test_ssh.fetch(remote_log,local_log,dry_run=self.dry_run())
262
263     def keys_clear_known_hosts (self):
264         "remove test nodes entries from the local known_hosts file"
265         TestSsh(self.name()).clear_known_hosts()
266         return True
267
268     def create_test_ssh(self):
269         # get the plc's keys for entering the node
270         vservername=self.test_plc.vservername
271 ###        # assuming we've run testplc.fetch_keys()
272 ###        key = "keys/%(vservername)s.rsa"%locals()
273         # fetch_keys doesn't grab the root key anymore
274         key = "keys/key_admin.rsa"
275         return TestSsh(self.name(), buildname=self.buildname(), key=key)
276
277     def check_hooks (self):
278         extensions = [ 'py','pl','sh' ]
279         path='hooks/node'
280         scripts=utils.locate_hooks_scripts ('node '+self.name(), path,extensions)
281         overall = True
282         for script in scripts:
283             if not self.check_hooks_script (script):
284                 overall = False
285         return overall
286
287     def check_hooks_script (self,local_script):
288         # push the script on the node's root context
289         script_name=os.path.basename(local_script)
290         utils.header ("NODE hook %s (%s)"%(script_name,self.name()))
291         test_ssh=self.create_test_ssh()
292         test_ssh.copy_home(local_script)
293         if test_ssh.run("./"+script_name) != 0:
294             utils.header ("WARNING: node hooks check script %s FAILED (ignored)"%script_name)
295             #return False
296             return True
297         else:
298             utils.header ("SUCCESS: node hook %s OK"%script_name)
299             return True
300
301     def has_libvirt (self):
302         test_ssh=self.create_test_ssh()
303         return test_ssh.run ("rpm -q --quiet libvirt-client")==0
304
305     def _check_system_slice (self, slicename,dry_run=False):
306         sitename=self.test_plc.plc_spec['PLC_SLICE_PREFIX']
307         vservername="%s_%s"%(sitename,slicename)
308         test_ssh=self.create_test_ssh()
309         if self.has_libvirt():
310             utils.header("Checking system slice %s using virsh"%slicename)
311             return test_ssh.run("virsh --connect lxc:// list | grep -q ' %s '"%vservername,
312                                 dry_run=dry_run)==0
313         else:
314             (retcod,output)=utils.output_of(test_ssh.actual_command("cat /vservers/%s/etc/slicefamily 2> /dev/null")%vservername)
315             # get last line only as ssh pollutes the output
316             slicefamily=output.split("\n")[-1]
317             utils.header("Found slicefamily '%s'for slice %s"%(slicefamily,slicename))
318             if retcod != 0: 
319                 return False
320             utils.header("Checking system slice %s using vserver-stat"%slicename)
321             return test_ssh.run("vserver-stat | grep %s"%vservername,dry_run=dry_run)==0
322         
323