1 # Thierry Parmentelat <thierry.parmentelat@inria.fr>
2 # Copyright (C) 2010 INRIA
10 from TestUser import TestUser
11 from TestBoxQemu import TestBoxQemu
12 from TestSsh import TestSsh
13 from Completer import CompleterTask
15 class CompleterTaskNodeSsh(CompleterTask):
16 def __init__(self, hostname, qemuname, local_key, command=None,
17 boot_state="boot", expected=True, dry_run=False):
18 self.hostname = hostname
19 self.qemuname = qemuname
20 self.boot_state = boot_state
21 self.local_key = local_key
22 self.command = command if command is not None else "hostname;uname -a"
23 self.expected = expected
24 self.dry_run = dry_run
25 self.test_ssh = TestSsh(self.hostname, key=self.local_key)
26 def run(self, silent):
27 command = self.test_ssh.actual_command(self.command)
28 retcod = utils.system(command, silent=silent, dry_run=self.dry_run)
33 def failure_epilogue(self):
34 print("Cannot reach {} in {} mode".format(self.hostname, self.boot_state))
38 def __init__(self, test_plc, test_site, node_spec):
39 self.test_plc = test_plc
40 self.test_site = test_site
41 self.node_spec = node_spec
44 return self.node_spec['node_fields']['hostname']
47 return self.test_plc.options.dry_run
50 def is_qemu_model(model):
51 return model.find("qemu") >= 0
53 return TestNode.is_qemu_model(self.node_spec['node_fields']['model'])
56 def is_real_model(model):
57 return not TestNode.is_qemu_model(model)
59 return TestNode.is_real_model(self.node_spec['node_fields']['model'])
62 return self.test_plc.options.buildname
66 return "qemu-{}".format(self.name())
68 return "real-{}".format(self.name())
70 # this returns a hostname
76 return self.node_spec['host_box']
78 utils.header("WARNING : qemu nodes need a host box")
81 # this returns a TestBoxQemu instance - cached in .test_box_value
84 return self.test_box_value
86 self.test_box_value = TestBoxQemu(self.host_box(),self.buildname())
87 return self.test_box_value
89 def create_node(self):
90 ownername = self.node_spec['owner']
91 user_spec = self.test_site.locate_user(ownername)
92 test_user = TestUser(self.test_plc,self.test_site,user_spec)
93 userauth = test_user.auth()
94 utils.header("node {} created by user {}".format(self.name(), test_user.name()))
95 rootauth = self.test_plc.auth_root()
96 server = self.test_plc.apiserver
97 node_id = server.AddNode(userauth,
98 self.test_site.site_spec['site_fields']['login_base'],
99 self.node_spec['node_fields'])
100 server.SetNodePlainBootstrapfs(userauth,
101 self.node_spec['node_fields']['hostname'],
103 # create as reinstall to avoid user confirmation
104 server.UpdateNode(userauth, self.name(), {'boot_state':'reinstall'})
106 # you are supposed to make sure the tags exist
107 for tagname, tagvalue in self.node_spec['tags'].items():
108 server.AddNodeTag(userauth, node_id, tagname, tagvalue)
110 if not self.test_plc.has_addresses_api():
111 # print 'USING OLD INTERFACE'
112 # populate network interfaces - primary
113 server.AddInterface(userauth, self.name(),
114 self.node_spec['interface_fields'])
116 # print 'USING NEW INTERFACE with separate ip addresses'
117 # this is for setting the 'dns' stuff that now goes with the node
118 server.UpdateNode(userauth, self.name(), self.node_spec['node_fields_nint'])
119 interface_id = server.AddInterface(userauth, self.name(),self.node_spec['interface_fields_nint'])
120 server.AddIpAddress(userauth, interface_id, self.node_spec['ipaddress_fields'])
121 route_fields = self.node_spec['route_fields']
122 route_fields['interface_id'] = interface_id
123 server.AddRoute(userauth, node_id, self.node_spec['route_fields'])
125 # populate network interfaces - others
126 if 'extra_interfaces' in self.node_spec:
127 for interface in self.node_spec['extra_interfaces']:
128 server.AddInterface(userauth, self.name(), interface['interface_fields'])
129 if 'settings' in interface:
130 for attribute, value in interface['settings'].items():
131 # locate node network
132 interface = server.GetInterfaces( userauth,
133 {'ip' : interface['interface_fields']['ip']})[0]
134 interface_id = interface['interface_id']
135 # locate or create node network attribute type
137 interface_tagtype = server.GetTagTypes(userauth, {'name' : attribute})[0]
139 interface_tagtype = server.AddTagType(rootauth,{'category' : 'test',
140 'tagname' : attribute})
142 server.AddInterfaceTag(userauth, interface_id, attribute, value)
144 def delete_node(self):
145 # uses the right auth as far as poss.
147 ownername = self.node_spec['owner']
148 user_spec = self.test_site.locate_user(ownername)
149 test_user = TestUser(self.test_plc, self.test_site, user_spec)
150 auth = test_user.auth()
152 auth = self.test_plc.auth_root()
153 self.test_plc.apiserver.DeleteNode(auth, self.name())
155 # Do most of the stuff locally - will be pushed on host_box - *not* the plc - later if needed
156 def qemu_local_init(self):
157 "all nodes : init a clean local directory for holding node-dep stuff like iso image..."
158 utils.system("rm -rf {}".format(self.nodedir()))
159 utils.system("mkdir {}".format(self.nodedir()))
160 if not self.is_qemu():
162 return utils.system("rsync -v -a --exclude .svn template-qemu/ {}/"\
163 .format(self.nodedir())) == 0
166 "all nodes: invoke GetBootMedium and store result locally"
167 utils.header("Calling GetBootMedium for {}".format(self.name()))
168 # this would clearly belong in the config but, well ..
169 options = self.node_spec['bootmedium_options'] if 'bootmedium_options' in self.node_spec else []
170 encoded = self.test_plc.apiserver.GetBootMedium(
171 self.test_plc.auth_root(), self.name(), 'node-iso', '', options)
173 raise Exception('GetBootmedium failed')
175 filename = "{}/{}.iso".format(self.nodedir(), self.name())
176 utils.header('Storing boot medium into {}'.format(filename))
178 # xxx discovered with python3, but a long stading issue:
179 # encoded at this point is a str instead of a bytes
180 # Quick & dirty : we convert this explicitly to a bytearray
181 # Longer run : clearly it seems like the plcapi server side should
182 # tag its result with <base64></base64> rather than as a string
183 bencoded = str.encode(encoded)
185 print("Dry_run: skipped writing of iso image")
188 # with python3 we need to call decodestring here
189 with open(filename,'wb') as storage:
190 storage.write(base64.decodestring(bencoded))
193 def nodestate_reinstall(self):
194 "all nodes: mark PLCAPI boot_state as reinstall"
195 self.test_plc.apiserver.UpdateNode(self.test_plc.auth_root(),
196 self.name(),{'boot_state':'reinstall'})
199 def nodestate_safeboot(self):
200 "all nodes: mark PLCAPI boot_state as safeboot"
201 self.test_plc.apiserver.UpdateNode(self.test_plc.auth_root(),
202 self.name(),{'boot_state':'safeboot'})
205 def nodestate_boot(self):
206 "all nodes: mark PLCAPI boot_state as boot"
207 self.test_plc.apiserver.UpdateNode(self.test_plc.auth_root(),
208 self.name(),{'boot_state':'boot'})
211 def nodestate_show(self):
212 "all nodes: show PLCAPI boot_state"
214 print("Dry_run: skipped getting current node state")
216 state = self.test_plc.apiserver.GetNodes(self.test_plc.auth_root(), self.name(), ['boot_state'])[0]['boot_state']
217 print(self.name(),':',state)
220 def qemu_local_config(self):
221 "all nodes: compute qemu config qemu.conf and store it locally"
222 if not self.is_qemu():
224 mac = self.node_spec['interface_fields']['mac']
225 hostname = self.node_spec['node_fields']['hostname']
226 ip = self.node_spec['interface_fields']['ip']
227 auth = self.test_plc.auth_root()
228 target_arch = self.test_plc.apiserver.GetPlcRelease(auth)['build']['target-arch']
229 conf_filename = "{}/qemu.conf".format(self.nodedir())
231 print("dry_run: skipped actual storage of qemu.conf")
233 utils.header('Storing qemu config for {} in {}'.format(self.name(), conf_filename))
234 with open(conf_filename,'w') as file:
235 file.write('MACADDR={}\n'.format(mac))
236 file.write('NODE_ISO={}.iso\n'.format(self.name()))
237 file.write('HOSTNAME={}\n'.format(hostname))
238 file.write('IP={}\n'.format(ip))
239 file.write('TARGET_ARCH={}\n'.format(target_arch))
242 def qemu_clean(self):
243 utils.header("Cleaning up qemu for host {} on box {}"\
244 .format(self.name(),self.test_box().hostname()))
245 dry_run = self.dry_run()
246 self.test_box().rmdir(self.nodedir(), dry_run=dry_run)
249 def qemu_export(self):
250 "all nodes: push local node-dep directory on the qemu box"
251 # if relevant, push the qemu area onto the host box
252 if self.test_box().is_local():
254 dry_run = self.dry_run()
255 utils.header("Cleaning any former sequel of {} on {}"\
256 .format(self.name(), self.host_box()))
257 utils.header("Transferring configuration files for node {} onto {}"\
258 .format(self.name(), self.host_box()))
259 return self.test_box().copy(self.nodedir(), recursive=True, dry_run=dry_run) == 0
261 def qemu_start(self):
262 "all nodes: start the qemu instance (also runs qemu-bridge-init start)"
263 model = self.node_spec['node_fields']['model']
264 #starting the Qemu nodes before
268 utils.header("TestNode.qemu_start : {} model {} taken as real node"\
269 .format(self.name(), model))
272 def qemu_timestamp(self):
273 "all nodes: start the qemu instance (also runs qemu-bridge-init start)"
274 test_box = self.test_box()
275 test_box.run_in_buildname("mkdir -p {}".format(self.nodedir()), dry_run=self.dry_run())
276 now = int(time.time())
277 return test_box.run_in_buildname("echo {:d} > {}/timestamp"\
278 .format(now, self.nodedir()), dry_run=self.dry_run()) == 0
280 def start_qemu(self):
281 test_box = self.test_box()
282 utils.header("Starting qemu node {} on {}".format(self.name(), test_box.hostname()))
284 test_box.run_in_buildname("{}/qemu-bridge-init start >> {}/log.txt"\
285 .format(self.nodedir(), self.nodedir()),
286 dry_run=self.dry_run())
287 # kick it off in background, as it would otherwise hang
288 test_box.run_in_buildname("{}/qemu-start-node 2>&1 >> {}/log.txt"\
289 .format(self.nodedir(), self.nodedir()))
292 utils.header("Listing qemu for host {} on box {}"\
293 .format(self.name(), self.test_box().hostname()))
294 command = "{}/qemu-kill-node -l {}".format(self.nodedir(), self.name())
295 self.test_box().run_in_buildname(command, dry_run=self.dry_run())
299 #Prepare the log file before killing the nodes
300 test_box = self.test_box()
301 # kill the right processes
302 utils.header("Stopping qemu for node {} on box {}"\
303 .format(self.name(), self.test_box().hostname()))
304 command = "{}/qemu-kill-node {}".format(self.nodedir(),self.name())
305 self.test_box().run_in_buildname(command, dry_run=self.dry_run())
308 def gather_qemu_logs(self):
309 if not self.is_qemu():
311 remote_log = "{}/log.txt".format(self.nodedir())
312 local_log = "logs/node.qemu.{}.txt".format(self.name())
313 self.test_box().test_ssh.fetch(remote_log,local_log,dry_run=self.dry_run())
315 def keys_clear_known_hosts(self):
316 "remove test nodes entries from the local known_hosts file"
317 TestSsh(self.name()).clear_known_hosts()
320 def create_test_ssh(self):
321 # get the plc's keys for entering the node
322 vservername = self.test_plc.vservername
323 ### # assuming we've run testplc.fetch_keys()
324 ### key = "keys/{vservername}.rsa".format(**locals())
325 # fetch_keys doesn't grab the root key anymore
326 key = "keys/key_admin.rsa"
327 return TestSsh(self.name(), buildname=self.buildname(), key=key)
329 def check_hooks(self):
330 extensions = [ 'py','pl','sh' ]
332 scripts = utils.locate_hooks_scripts('node '+self.name(), path,extensions)
334 for script in scripts:
335 if not self.check_hooks_script(script):
339 def check_hooks_script(self,local_script):
340 # push the script on the node's root context
341 script_name = os.path.basename(local_script)
342 utils.header("NODE hook {} ({})".format(script_name, self.name()))
343 test_ssh = self.create_test_ssh()
344 test_ssh.copy_home(local_script)
345 if test_ssh.run("./"+script_name) != 0:
346 utils.header("WARNING: node hooks check script {} FAILED (ignored)"\
347 .format(script_name))
351 utils.header("SUCCESS: node hook {} OK".format(script_name))
354 def has_libvirt(self):
355 test_ssh = self.create_test_ssh()
356 return test_ssh.run("rpm -q --quiet libvirt-client") == 0
358 def _check_system_slice(self, slicename, dry_run=False):
359 sitename = self.test_plc.plc_spec['settings']['PLC_SLICE_PREFIX']
360 vservername = "{}_{}".format(sitename, slicename)
361 test_ssh = self.create_test_ssh()
362 if self.has_libvirt():
363 utils.header("Checking system slice {} using virsh".format(slicename))
364 return test_ssh.run("virsh --connect lxc:// list | grep -q ' {} '".format(vservername),
365 dry_run = dry_run) == 0
368 utils.output_of(test_ssh.actual_command("cat /vservers/{}/etc/slicefamily 2> /dev/null")\
369 .format(vservername))
370 # get last line only as ssh pollutes the output
371 slicefamily = output.split("\n")[-1]
372 utils.header("Found slicefamily '{}'for slice {}".format(slicefamily,slicename))
375 utils.header("Checking system slice {} using vserver-stat".format(slicename))
376 return test_ssh.run("vserver-stat | grep {}".format(vservername), dry_run=dry_run) == 0