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