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