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