blob: 7476b6006463d727e7d5441f7df8692beb9b2181 [file] [log] [blame]
Artem Panchenko0594cd72017-06-12 13:25:26 +03001# Copyright 2017 Mirantis, Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +040015import os
Artem Panchenko0594cd72017-06-12 13:25:26 +030016import time
Victor Ryzhenkin3ffa2b42017-10-05 16:38:44 +040017from uuid import uuid4
Artem Panchenko0594cd72017-06-12 13:25:26 +030018
19import yaml
20
21from devops.helpers import helpers
Victor Ryzhenkin66d39372017-09-28 19:25:48 +040022from devops.error import DevopsCalledProcessError
Artem Panchenko0594cd72017-06-12 13:25:26 +030023
24from tcp_tests import logger
Victor Ryzhenkin66d39372017-09-28 19:25:48 +040025from tcp_tests.helpers import ext
26from tcp_tests.helpers.utils import retry
Artem Panchenko0594cd72017-06-12 13:25:26 +030027from tcp_tests.managers.execute_commands import ExecuteCommandsMixin
28from tcp_tests.managers.k8s import cluster
Sergey Vasilenkofd1fd612017-09-20 13:09:51 +030029from k8sclient.client.rest import ApiException
Artem Panchenko0594cd72017-06-12 13:25:26 +030030
31LOG = logger.logger
32
33
34class K8SManager(ExecuteCommandsMixin):
35 """docstring for K8SManager"""
36
37 __config = None
38 __underlay = None
39
40 def __init__(self, config, underlay, salt):
41 self.__config = config
42 self.__underlay = underlay
43 self._salt = salt
44 self._api_client = None
45 super(K8SManager, self).__init__(
46 config=config, underlay=underlay)
47
48 def install(self, commands):
49 self.execute_commands(commands,
50 label='Install Kubernetes services')
51 self.__config.k8s.k8s_installed = True
52 self.__config.k8s.kube_host = self.get_proxy_api()
53
54 def get_proxy_api(self):
55 k8s_proxy_ip_pillars = self._salt.get_pillar(
vrovachev99228d32017-06-08 19:46:10 +040056 tgt='I@haproxy:proxy:enabled:true and I@kubernetes:master',
Artem Panchenko0594cd72017-06-12 13:25:26 +030057 pillar='haproxy:proxy:listen:k8s_secure:binds:address')
vrovachev99228d32017-06-08 19:46:10 +040058 k8s_hosts = self._salt.get_pillar(
59 tgt='I@haproxy:proxy:enabled:true and I@kubernetes:master',
60 pillar='kubernetes:pool:apiserver:host')
Artem Panchenko0594cd72017-06-12 13:25:26 +030061 k8s_proxy_ip = set([ip
62 for item in k8s_proxy_ip_pillars
Dina Belovae6fdffb2017-09-19 13:58:34 -070063 for node, ip in item.items() if ip])
vrovachev99228d32017-06-08 19:46:10 +040064 k8s_hosts = set([ip
Dina Belovae6fdffb2017-09-19 13:58:34 -070065 for item in k8s_hosts
66 for node, ip in item.items() if ip])
vrovachev99228d32017-06-08 19:46:10 +040067 assert len(k8s_hosts) == 1, (
68 "Found more than one Kubernetes API hosts in pillars:{0}, "
69 "expected one!").format(k8s_hosts)
70 k8s_host = k8s_hosts.pop()
71 assert k8s_host in k8s_proxy_ip, (
72 "Kubernetes API host:{0} not found in proxies:{} "
73 "on k8s master nodes. K8s proxies are expected on "
74 "nodes with K8s master").format(k8s_host, k8s_proxy_ip)
75 return k8s_host
Artem Panchenko0594cd72017-06-12 13:25:26 +030076
77 @property
78 def api(self):
79 if self._api_client is None:
80 self._api_client = cluster.K8sCluster(
81 user=self.__config.k8s_deploy.kubernetes_admin_user,
82 password=self.__config.k8s_deploy.kubernetes_admin_password,
83 host=self.__config.k8s.kube_host,
84 port=self.__config.k8s.kube_apiserver_port,
85 default_namespace='default')
86 return self._api_client
87
Victor Ryzhenkin66d39372017-09-28 19:25:48 +040088 @property
89 def ctl_host(self):
90 nodes = [node for node in self.__config.underlay.ssh if
91 ext.UNDERLAY_NODE_ROLES.k8s_controller in node['roles']]
92 return nodes[0]['node_name']
93
Artem Panchenko0594cd72017-06-12 13:25:26 +030094 def get_pod_phase(self, pod_name, namespace=None):
95 return self.api.pods.get(
96 name=pod_name, namespace=namespace).phase
97
98 def wait_pod_phase(self, pod_name, phase, namespace=None, timeout=60):
99 """Wait phase of pod_name from namespace while timeout
100
101 :param str: pod_name
102 :param str: namespace
103 :param list or str: phase
104 :param int: timeout
105
106 :rtype: None
107 """
108 if isinstance(phase, str):
109 phase = [phase]
110
111 def check():
112 return self.get_pod_phase(pod_name, namespace) in phase
113
114 helpers.wait(check, timeout=timeout,
115 timeout_msg='Timeout waiting, pod {pod_name} is not in '
116 '"{phase}" phase'.format(
117 pod_name=pod_name, phase=phase))
118
119 def wait_pods_phase(self, pods, phase, timeout=60):
120 """Wait timeout seconds for phase of pods
121
122 :param pods: list of K8sPod
123 :param phase: list or str
124 :param timeout: int
125
126 :rtype: None
127 """
128 if isinstance(phase, str):
129 phase = [phase]
130
131 def check(pod_name, namespace):
132 return self.get_pod_phase(pod_name, namespace) in phase
133
134 def check_all_pods():
135 return all(check(pod.name, pod.metadata.namespace) for pod in pods)
136
137 helpers.wait(
138 check_all_pods,
139 timeout=timeout,
140 timeout_msg='Timeout waiting, pods {0} are not in "{1}" '
141 'phase'.format([pod.name for pod in pods], phase))
142
143 def check_pod_create(self, body, namespace=None, timeout=300, interval=5):
144 """Check creating sample pod
145
146 :param k8s_pod: V1Pod
147 :param namespace: str
148 :rtype: V1Pod
149 """
150 LOG.info("Creating pod in k8s cluster")
151 LOG.debug(
152 "POD spec to create:\n{}".format(
153 yaml.dump(body, default_flow_style=False))
154 )
155 LOG.debug("Timeout for creation is set to {}".format(timeout))
156 LOG.debug("Checking interval is set to {}".format(interval))
157 pod = self.api.pods.create(body=body, namespace=namespace)
158 pod.wait_running(timeout=300, interval=5)
159 LOG.info("Pod '{0}' is created in '{1}' namespace".format(
160 pod.name, pod.namespace))
161 return self.api.pods.get(name=pod.name, namespace=pod.namespace)
162
163 def wait_pod_deleted(self, podname, timeout=60, interval=5):
164 helpers.wait(
165 lambda: podname not in [pod.name for pod in self.api.pods.list()],
166 timeout=timeout,
167 interval=interval,
168 timeout_msg="Pod deletion timeout reached!"
169 )
170
171 def check_pod_delete(self, k8s_pod, timeout=300, interval=5,
172 namespace=None):
173 """Deleting pod from k8s
174
175 :param k8s_pod: tcp_tests.managers.k8s.nodes.K8sNode
176 :param k8sclient: tcp_tests.managers.k8s.cluster.K8sCluster
177 """
178 LOG.info("Deleting pod '{}'".format(k8s_pod.name))
179 LOG.debug("Pod status:\n{}".format(k8s_pod.status))
180 LOG.debug("Timeout for deletion is set to {}".format(timeout))
181 LOG.debug("Checking interval is set to {}".format(interval))
182 self.api.pods.delete(body=k8s_pod, name=k8s_pod.name,
183 namespace=namespace)
184 self.wait_pod_deleted(k8s_pod.name, timeout, interval)
185 LOG.debug("Pod '{}' is deleted".format(k8s_pod.name))
186
187 def check_service_create(self, body, namespace=None):
188 """Check creating k8s service
189
190 :param body: dict, service spec
191 :param namespace: str
192 :rtype: K8sService object
193 """
194 LOG.info("Creating service in k8s cluster")
195 LOG.debug(
196 "Service spec to create:\n{}".format(
197 yaml.dump(body, default_flow_style=False))
198 )
199 service = self.api.services.create(body=body, namespace=namespace)
200 LOG.info("Service '{0}' is created in '{1}' namespace".format(
201 service.name, service.namespace))
202 return self.api.services.get(name=service.name,
203 namespace=service.namespace)
204
205 def check_ds_create(self, body, namespace=None):
206 """Check creating k8s DaemonSet
207
208 :param body: dict, DaemonSet spec
209 :param namespace: str
210 :rtype: K8sDaemonSet object
211 """
212 LOG.info("Creating DaemonSet in k8s cluster")
213 LOG.debug(
214 "DaemonSet spec to create:\n{}".format(
215 yaml.dump(body, default_flow_style=False))
216 )
217 ds = self.api.daemonsets.create(body=body, namespace=namespace)
218 LOG.info("DaemonSet '{0}' is created in '{1}' namespace".format(
219 ds.name, ds.namespace))
220 return self.api.daemonsets.get(name=ds.name, namespace=ds.namespace)
221
222 def check_ds_ready(self, dsname, namespace=None):
223 """Check if k8s DaemonSet is ready
224
225 :param dsname: str, ds name
226 :return: bool
227 """
228 ds = self.api.daemonsets.get(name=dsname, namespace=namespace)
229 return (ds.status.current_number_scheduled ==
230 ds.status.desired_number_scheduled)
231
232 def wait_ds_ready(self, dsname, namespace=None, timeout=60, interval=5):
233 """Wait until all pods are scheduled on nodes
234
235 :param dsname: str, ds name
236 :param timeout: int
237 :param interval: int
238 """
239 helpers.wait(
240 lambda: self.check_ds_ready(dsname, namespace=namespace),
241 timeout=timeout, interval=interval)
242
Artem Panchenko501e67e2017-06-14 14:59:18 +0300243 def check_deploy_create(self, body, namespace=None):
244 """Check creating k8s Deployment
245
246 :param body: dict, Deployment spec
247 :param namespace: str
248 :rtype: K8sDeployment object
249 """
250 LOG.info("Creating Deployment in k8s cluster")
251 LOG.debug(
252 "Deployment spec to create:\n{}".format(
253 yaml.dump(body, default_flow_style=False))
254 )
255 deploy = self.api.deployments.create(body=body, namespace=namespace)
256 LOG.info("Deployment '{0}' is created in '{1}' namespace".format(
257 deploy.name, deploy.namespace))
258 return self.api.deployments.get(name=deploy.name,
259 namespace=deploy.namespace)
260
261 def check_deploy_ready(self, deploy_name, namespace=None):
262 """Check if k8s Deployment is ready
263
264 :param deploy_name: str, deploy name
265 :return: bool
266 """
Dina Belovae6fdffb2017-09-19 13:58:34 -0700267 deploy = self.api.deployments.get(name=deploy_name,
268 namespace=namespace)
Artem Panchenko501e67e2017-06-14 14:59:18 +0300269 return deploy.status.available_replicas == deploy.status.replicas
270
Dina Belovae6fdffb2017-09-19 13:58:34 -0700271 def wait_deploy_ready(self, deploy_name, namespace=None, timeout=60,
272 interval=5):
Artem Panchenko501e67e2017-06-14 14:59:18 +0300273 """Wait until all pods are scheduled on nodes
274
275 :param deploy_name: str, deploy name
276 :param timeout: int
277 :param interval: int
278 """
279 helpers.wait(
280 lambda: self.check_deploy_ready(deploy_name, namespace=namespace),
281 timeout=timeout, interval=interval)
282
Artem Panchenko0594cd72017-06-12 13:25:26 +0300283 def check_namespace_create(self, name):
284 """Check creating k8s Namespace
285
286 :param name: str
287 :rtype: K8sNamespace object
288 """
Sergey Vasilenkofd1fd612017-09-20 13:09:51 +0300289 try:
290 ns = self.api.namespaces.get(name=name)
291 LOG.info("Namespace '{0}' is already exists".format(ns.name))
292 except ApiException as e:
Dennis Dmitriev9b02c8b2017-11-13 15:31:35 +0200293 if hasattr(e, "status") and 404 == e.status:
294 LOG.info("Creating Namespace in k8s cluster")
295 ns = self.api.namespaces.create(
296 body={'metadata': {'name': name}})
297 LOG.info("Namespace '{0}' is created".format(ns.name))
298 # wait 10 seconds until a token for new service account
299 # is created
300 time.sleep(10)
301 ns = self.api.namespaces.get(name=ns.name)
302 else:
303 raise
Sergey Vasilenkofd1fd612017-09-20 13:09:51 +0300304 return ns
Artem Panchenko0594cd72017-06-12 13:25:26 +0300305
306 def create_objects(self, path):
307 if isinstance(path, str):
308 path = [path]
309 params = ' '.join(["-f {}".format(p) for p in path])
310 cmd = 'kubectl create {params}'.format(params=params)
311 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400312 node_name=self.ctl_host) as remote:
Artem Panchenko0594cd72017-06-12 13:25:26 +0300313 LOG.info("Running command '{cmd}' on node {node}".format(
314 cmd=cmd,
315 node=remote.hostname)
316 )
317 result = remote.check_call(cmd)
318 LOG.info(result['stdout'])
319
320 def get_running_pods(self, pod_name, namespace=None):
321 pods = [pod for pod in self.api.pods.list(namespace=namespace)
322 if (pod_name in pod.name and pod.status.phase == 'Running')]
323 return pods
324
325 def get_pods_number(self, pod_name, namespace=None):
326 pods = self.get_running_pods(pod_name, namespace)
327 return len(pods)
328
329 def get_running_pods_by_ssh(self, pod_name, namespace=None):
330 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400331 node_name=self.ctl_host) as remote:
Artem Panchenko0594cd72017-06-12 13:25:26 +0300332 result = remote.check_call("kubectl get pods --namespace {} |"
333 " grep {} | awk '{{print $1 \" \""
334 " $3}}'".format(namespace,
335 pod_name))['stdout']
336 running_pods = [data.strip().split()[0] for data in result
337 if data.strip().split()[1] == 'Running']
338 return running_pods
339
340 def get_pods_restarts(self, pod_name, namespace=None):
341 pods = [pod.status.container_statuses[0].restart_count
342 for pod in self.get_running_pods(pod_name, namespace)]
343 return sum(pods)
vrovacheva9d08332017-06-22 20:01:59 +0400344
345 def run_conformance(self, timeout=60 * 60):
346 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400347 node_name=self.ctl_host) as remote:
vrovacheva9d08332017-06-22 20:01:59 +0400348 result = remote.check_call(
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400349 "set -o pipefail; docker run --net=host -e API_SERVER="
350 "'http://127.0.0.1:8080' {} | tee k8s_conformance.log".format(
vrovacheva9d08332017-06-22 20:01:59 +0400351 self.__config.k8s.k8s_conformance_image),
352 timeout=timeout)['stdout']
353 return result
Artem Panchenko501e67e2017-06-14 14:59:18 +0300354
355 def get_k8s_masters(self):
356 k8s_masters_fqdn = self._salt.get_pillar(tgt='I@kubernetes:master',
357 pillar='linux:network:fqdn')
358 return [self._K8SManager__underlay.host_by_node_name(node_name=v)
359 for pillar in k8s_masters_fqdn for k, v in pillar.items()]
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400360
361 def kubectl_run(self, name, image, port):
362 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400363 node_name=self.ctl_host) as remote:
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400364 result = remote.check_call(
365 "kubectl run {0} --image={1} --port={2}".format(
366 name, image, port
367 )
368 )
369 return result
370
371 def kubectl_expose(self, resource, name, port, type):
372 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400373 node_name=self.ctl_host) as remote:
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400374 result = remote.check_call(
375 "kubectl expose {0} {1} --port={2} --type={3}".format(
376 resource, name, port, type
377 )
378 )
379 return result
380
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400381 def kubectl_annotate(self, resource, name, annotation):
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400382 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400383 node_name=self.ctl_host) as remote:
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400384 result = remote.check_call(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400385 "kubectl annotate {0} {1} {2}".format(
386 resource, name, annotation
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400387 )
388 )
389 return result
390
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400391 def get_svc_ip(self, name, namespace='kube-system'):
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400392 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400393 node_name=self.ctl_host) as remote:
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400394 result = remote.check_call(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400395 "kubectl get svc {0} -n {1} | "
396 "awk '{{print $2}}' | tail -1".format(name, namespace)
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400397 )
398 return result['stdout'][0].strip()
399
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400400 @retry(300, exception=DevopsCalledProcessError)
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400401 def nslookup(self, host, src):
402 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400403 node_name=self.ctl_host) as remote:
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400404 remote.check_call("nslookup {0} {1}".format(host, src))
405
Victor Ryzhenkin3ffa2b42017-10-05 16:38:44 +0400406# ---------------------------- Virtlet methods -------------------------------
407 def install_jq(self):
408 """Install JQuery on node. Required for changing yamls on the fly.
409
410 :return:
411 """
412 cmd = "apt install jq -y"
413 return self.__underlay.check_call(cmd, node_name=self.ctl_host)
414
Victor Ryzhenkin3ffa2b42017-10-05 16:38:44 +0400415 def git_clone(self, project, target):
416 cmd = "git clone {0} {1}".format(project, target)
417 return self.__underlay.check_call(cmd, node_name=self.ctl_host)
418
419 def run_vm(self, name=None, yaml_path='~/virtlet/examples/cirros-vm.yaml'):
420 if not name:
421 name = 'virtlet-vm-{}'.format(uuid4())
422 cmd = (
423 "kubectl convert -f {0} --local "
424 "-o json | jq '.metadata.name|=\"{1}\"' | kubectl create -f -")
425 self.__underlay.check_call(cmd.format(yaml_path, name),
426 node_name=self.ctl_host)
427 return name
428
429 def get_vm_info(self, name, jsonpath="{.status.phase}", expected=None):
430 cmd = "kubectl get po {} -n default".format(name)
431 if jsonpath:
432 cmd += " -o jsonpath={}".format(jsonpath)
433 return self.__underlay.check_call(
434 cmd, node_name=self.ctl_host, expected=expected)
435
436 def wait_active_state(self, name, timeout=180):
437 helpers.wait(
438 lambda: self.get_vm_info(name)['stdout'][0] == 'Running',
439 timeout=timeout,
440 timeout_msg="VM {} didn't Running state in {} sec. "
441 "Current state: ".format(
442 name, timeout, self.get_vm_info(name)['stdout'][0]))
443
444 def delete_vm(self, name, timeout=180):
445 cmd = "kubectl delete po -n default {}".format(name)
446 self.__underlay.check_call(cmd, node_name=self.ctl_host)
447
448 helpers.wait(
449 lambda:
450 "Error from server (NotFound):" in
451 " ".join(self.get_vm_info(name, expected=[0, 1])['stderr']),
452 timeout=timeout,
453 timeout_msg="VM {} didn't Running state in {} sec. "
454 "Current state: ".format(
455 name, timeout, self.get_vm_info(name)['stdout'][0]))
456
457 def adjust_cirros_resources(
458 self, cpu=2, memory='256',
459 target_yaml='virtlet/examples/cirros-vm-exp.yaml'):
460 # We will need to change params in case of example change
461 cmd = ("cd ~/virtlet/examples && "
462 "cp cirros-vm.yaml {2} && "
463 "sed -r 's/^(\s*)(VirtletVCPUCount\s*:\s*\"1\"\s*$)/ "
464 "\1VirtletVCPUCount: \"{0}\"/' {2} && "
465 "sed -r 's/^(\s*)(memory\s*:\s*128Mi\s*$)/\1memory: "
466 "{1}Mi/' {2}".format(cpu, memory, target_yaml))
467 self.__underlay.check_call(cmd, node_name=self.ctl_host)
468
469 def get_domain_name(self, vm_name):
470 cmd = ("~/virtlet/examples/virsh.sh list --name | "
471 "grep -i {0} ".format(vm_name))
472 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
473 return result['stdout'].strip()
474
475 def get_vm_cpu_count(self, domain_name):
476 cmd = ("~/virtlet/examples/virsh.sh dumpxml {0} | "
477 "grep 'cpu' | grep -o '[[:digit:]]*'".format(domain_name))
478 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
479 return int(result['stdout'].strip())
480
481 def get_vm_memory_count(self, domain_name):
482 cmd = ("~/virtlet/examples/virsh.sh dumpxml {0} | "
483 "grep 'memory unit' | "
484 "grep -o '[[:digit:]]*'".format(domain_name))
485 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
486 return int(result['stdout'].strip())
487
488 def get_domain_id(self, domain_name):
489 cmd = ("virsh dumpxml {} | grep id=\' | "
490 "grep -o [[:digit:]]*".format(domain_name))
491 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
492 return int(result['stdout'].strip())
493
494 def list_vm_volumes(self, domain_name):
495 domain_id = self.get_domain_id(domain_name)
496 cmd = ("~/virtlet/examples/virsh.sh domblklist {} | "
497 "tail -n +3 | awk {{'print $2'}}".format(domain_id))
498 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
Dennis Dmitriev9b02c8b2017-11-13 15:31:35 +0200499 return result['stdout'].strip()
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400500
Victor Ryzhenkinac37a752018-02-21 17:55:45 +0400501 def run_virtlet_conformance(self, timeout=60 * 120,
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400502 log_file='virtlet_conformance.log'):
503 if self.__config.k8s.run_extended_virtlet_conformance:
504 ci_image = "cloud-images.ubuntu.com/xenial/current/" \
505 "xenial-server-cloudimg-amd64-disk1.img"
506 cmd = ("set -o pipefail; "
507 "docker run --net=host {0} /virtlet-e2e-tests "
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400508 "-include-cloud-init-tests -junitOutput report.xml "
509 "-image {2} -sshuser ubuntu -memoryLimit 1024 "
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400510 "-alsologtostderr -cluster-url http://127.0.0.1:8080 "
511 "-ginkgo.focus '\[Conformance\]' "
512 "| tee {1}".format(
513 self.__config.k8s_deploy.kubernetes_virtlet_image,
514 log_file, ci_image))
515 else:
516 cmd = ("set -o pipefail; "
517 "docker run --net=host {0} /virtlet-e2e-tests "
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400518 "-junitOutput report.xml "
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400519 "-alsologtostderr -cluster-url http://127.0.0.1:8080 "
520 "-ginkgo.focus '\[Conformance\]' "
521 "| tee {1}".format(
522 self.__config.k8s_deploy.kubernetes_virtlet_image,
523 log_file))
524 LOG.info("Executing: {}".format(cmd))
525 with self.__underlay.remote(
526 node_name=self.ctl_host) as remote:
527 result = remote.check_call(cmd, timeout=timeout)
528 stderr = result['stderr']
529 stdout = result['stdout']
530 LOG.info("Test results stdout: {}".format(stdout))
531 LOG.info("Test results stderr: {}".format(stderr))
532 return result
533
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400534 def start_k8s_cncf_verification(self, timeout=60 * 90):
535 cncf_cmd = ("curl -L https://raw.githubusercontent.com/cncf/"
536 "k8s-conformance/master/sonobuoy-conformance.yaml"
537 " | kubectl apply -f -")
538 with self.__underlay.remote(
539 node_name=self.ctl_host) as remote:
540 remote.check_call(cncf_cmd, timeout=60)
541 self.wait_pod_phase('sonobuoy', 'Running',
542 namespace='sonobuoy', timeout=120)
543 wait_cmd = ('kubectl logs -n sonobuoy sonobuoy | '
544 'grep "sonobuoy is now blocking"')
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400545
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400546 expected = [0, 1]
547 helpers.wait(
548 lambda: remote.check_call(
549 wait_cmd, expected=expected).exit_code == 0,
550 interval=30, timeout=timeout,
551 timeout_msg="Timeout for CNCF reached."
552 )
553
554 def extract_file_to_node(self, system='docker',
555 container='virtlet',
556 file_path='report.xml', **kwargs):
557 """
558 Download file from docker or k8s container to node
559
560 :param system: docker or k8s
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400561 :param container: Full name of part of name
562 :param file_path: File path in container
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400563 :param kwargs: Used to control pod and namespace
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400564 :return:
565 """
566 with self.__underlay.remote(
567 node_name=self.ctl_host) as remote:
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400568 if system is 'docker':
569 cmd = ("docker ps --all | grep {0} |"
570 " awk '{{print $1}}'".format(container))
571 result = remote.check_call(cmd)
572 container_id = result['stdout'][0].strip()
573 cmd = "docker start {}".format(container_id)
574 remote.check_call(cmd)
575 cmd = "docker cp {0}:/{1} .".format(container_id, file_path)
576 remote.check_call(cmd)
577 else:
578 # system is k8s
579 pod_name = kwargs.get('pod_name')
580 pod_namespace = kwargs.get('pod_namespace')
581 cmd = 'kubectl cp {0}/{1}:/{2} .'.format(
582 pod_namespace, pod_name, file_path)
583 remote.check_call(cmd)
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400584
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400585 def download_k8s_logs(self, files):
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400586 """
587 Download JUnit report and conformance logs from cluster
588 :param files:
589 :return:
590 """
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400591 master_host = self.__config.salt.salt_master_host
592 with self.__underlay.remote(host=master_host) as r:
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400593 for log_file in files:
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400594 cmd = "rsync -r {0}:/root/{1} /root/".format(self.ctl_host,
595 log_file)
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400596 r.check_call(cmd, raise_on_err=False)
597 LOG.info("Downloading the artifact {0}".format(log_file))
598 r.download(destination=log_file, target=os.getcwd())
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400599
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400600 def combine_xunit(self, path, output):
601 """
602 Function to combine multiple xmls with test results to
603 one.
604
605 :param path: Path where xmls to combine located
606 :param output: Path to xml file where output will stored
607 :return:
608 """
609 with self.__underlay.remote(node_name=self.ctl_host) as r:
Tatyana Leontovichfe1834c2018-04-19 13:52:05 +0300610 cmd = ("apt-get install python-setuptools -y; "
Vladimir Jigulinb76d33f2018-05-23 21:04:06 +0400611 "pip install git+https://github.com/mogaika/xunitmerge.git")
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400612 LOG.debug('Installing xunitmerge')
613 r.check_call(cmd)
614 LOG.debug('Merging xunit')
615 cmd = ("cd {0}; arg = ''; "
616 "for i in $(ls | grep xml); "
617 "do arg=\"$arg $i\"; done && "
618 "xunitmerge $arg {1}".format(path, output))
619 r.check_call(cmd)
620
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400621 def manage_cncf_archive(self):
622 """
623 Function to untar archive, move files, that we are needs to the
624 home folder, prepare it to downloading and clean the trash.
625 Will generate files: e2e.log, junit_01.xml, cncf_results.tar.gz
626 and version.txt
627 :return:
628 """
629
630 # Namespace and pod name may be hardcoded since this function is
631 # very specific for cncf and cncf is not going to change
632 # those launch pod name and namespace.
633 get_tar_name_cmd = ("kubectl logs -n sonobuoy sonobuoy | "
634 "grep 'Results available' | "
635 "sed 's/.*\///' | tr -d '\"'")
636
637 with self.__underlay.remote(
638 node_name=self.ctl_host) as remote:
639 tar_name = remote.check_call(get_tar_name_cmd)['stdout'][0].strip()
640 untar = "mkdir result && tar -C result -xzf {0}".format(tar_name)
641 remote.check_call(untar)
642 manage_results = ("mv result/plugins/e2e/results/e2e.log . && "
643 "mv result/plugins/e2e/results/junit_01.xml . ;"
644 "kubectl version > version.txt")
645 remote.check_call(manage_results, raise_on_err=False)
646 cleanup_host = "rm -rf result"
647 remote.check_call(cleanup_host)
648 # This one needed to use download fixture, since I don't know
649 # how possible apply fixture arg dynamically from test.
650 rename_tar = "mv {0} cncf_results.tar.gz".format(tar_name)
651 remote.check_call(rename_tar)