blob: 9b5588dc1892c5815584ed69f7f80b945457b352 [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
Vladimir Jigulin34dfa942018-07-23 21:05:48 +040018import six
Vladimir Jigulina6b018b2018-07-18 15:19:01 +040019import requests
Artem Panchenko0594cd72017-06-12 13:25:26 +030020import yaml
21
22from devops.helpers import helpers
Victor Ryzhenkin66d39372017-09-28 19:25:48 +040023from devops.error import DevopsCalledProcessError
Artem Panchenko0594cd72017-06-12 13:25:26 +030024
25from tcp_tests import logger
Victor Ryzhenkin66d39372017-09-28 19:25:48 +040026from tcp_tests.helpers import ext
27from tcp_tests.helpers.utils import retry
Artem Panchenko0594cd72017-06-12 13:25:26 +030028from tcp_tests.managers.execute_commands import ExecuteCommandsMixin
29from tcp_tests.managers.k8s import cluster
Sergey Vasilenkofd1fd612017-09-20 13:09:51 +030030from k8sclient.client.rest import ApiException
Artem Panchenko0594cd72017-06-12 13:25:26 +030031
32LOG = logger.logger
33
34
35class K8SManager(ExecuteCommandsMixin):
36 """docstring for K8SManager"""
37
38 __config = None
39 __underlay = None
40
41 def __init__(self, config, underlay, salt):
42 self.__config = config
43 self.__underlay = underlay
44 self._salt = salt
45 self._api_client = None
46 super(K8SManager, self).__init__(
47 config=config, underlay=underlay)
48
49 def install(self, commands):
50 self.execute_commands(commands,
51 label='Install Kubernetes services')
52 self.__config.k8s.k8s_installed = True
53 self.__config.k8s.kube_host = self.get_proxy_api()
54
55 def get_proxy_api(self):
56 k8s_proxy_ip_pillars = self._salt.get_pillar(
vrovachev99228d32017-06-08 19:46:10 +040057 tgt='I@haproxy:proxy:enabled:true and I@kubernetes:master',
Artem Panchenko0594cd72017-06-12 13:25:26 +030058 pillar='haproxy:proxy:listen:k8s_secure:binds:address')
vrovachev99228d32017-06-08 19:46:10 +040059 k8s_hosts = self._salt.get_pillar(
60 tgt='I@haproxy:proxy:enabled:true and I@kubernetes:master',
61 pillar='kubernetes:pool:apiserver:host')
Artem Panchenko0594cd72017-06-12 13:25:26 +030062 k8s_proxy_ip = set([ip
63 for item in k8s_proxy_ip_pillars
Dina Belovae6fdffb2017-09-19 13:58:34 -070064 for node, ip in item.items() if ip])
vrovachev99228d32017-06-08 19:46:10 +040065 k8s_hosts = set([ip
Dina Belovae6fdffb2017-09-19 13:58:34 -070066 for item in k8s_hosts
67 for node, ip in item.items() if ip])
vrovachev99228d32017-06-08 19:46:10 +040068 assert len(k8s_hosts) == 1, (
69 "Found more than one Kubernetes API hosts in pillars:{0}, "
70 "expected one!").format(k8s_hosts)
71 k8s_host = k8s_hosts.pop()
72 assert k8s_host in k8s_proxy_ip, (
73 "Kubernetes API host:{0} not found in proxies:{} "
74 "on k8s master nodes. K8s proxies are expected on "
75 "nodes with K8s master").format(k8s_host, k8s_proxy_ip)
76 return k8s_host
Artem Panchenko0594cd72017-06-12 13:25:26 +030077
78 @property
79 def api(self):
80 if self._api_client is None:
81 self._api_client = cluster.K8sCluster(
82 user=self.__config.k8s_deploy.kubernetes_admin_user,
83 password=self.__config.k8s_deploy.kubernetes_admin_password,
84 host=self.__config.k8s.kube_host,
85 port=self.__config.k8s.kube_apiserver_port,
86 default_namespace='default')
87 return self._api_client
88
Vladimir Jigulin34dfa942018-07-23 21:05:48 +040089 def ctl_hosts(self):
90 return [node for node in self.__config.underlay.ssh if
91 ext.UNDERLAY_NODE_ROLES.k8s_controller in node['roles']]
92
Victor Ryzhenkin66d39372017-09-28 19:25:48 +040093 @property
94 def ctl_host(self):
Vladimir Jigulin34dfa942018-07-23 21:05:48 +040095 return self.ctl_hosts()[0]['node_name']
Victor Ryzhenkin66d39372017-09-28 19:25:48 +040096
Artem Panchenko0594cd72017-06-12 13:25:26 +030097 def get_pod_phase(self, pod_name, namespace=None):
98 return self.api.pods.get(
99 name=pod_name, namespace=namespace).phase
100
101 def wait_pod_phase(self, pod_name, phase, namespace=None, timeout=60):
102 """Wait phase of pod_name from namespace while timeout
103
104 :param str: pod_name
105 :param str: namespace
106 :param list or str: phase
107 :param int: timeout
108
109 :rtype: None
110 """
111 if isinstance(phase, str):
112 phase = [phase]
113
114 def check():
115 return self.get_pod_phase(pod_name, namespace) in phase
116
117 helpers.wait(check, timeout=timeout,
118 timeout_msg='Timeout waiting, pod {pod_name} is not in '
119 '"{phase}" phase'.format(
120 pod_name=pod_name, phase=phase))
121
122 def wait_pods_phase(self, pods, phase, timeout=60):
123 """Wait timeout seconds for phase of pods
124
125 :param pods: list of K8sPod
126 :param phase: list or str
127 :param timeout: int
128
129 :rtype: None
130 """
131 if isinstance(phase, str):
132 phase = [phase]
133
134 def check(pod_name, namespace):
135 return self.get_pod_phase(pod_name, namespace) in phase
136
137 def check_all_pods():
138 return all(check(pod.name, pod.metadata.namespace) for pod in pods)
139
140 helpers.wait(
141 check_all_pods,
142 timeout=timeout,
143 timeout_msg='Timeout waiting, pods {0} are not in "{1}" '
144 'phase'.format([pod.name for pod in pods], phase))
145
146 def check_pod_create(self, body, namespace=None, timeout=300, interval=5):
147 """Check creating sample pod
148
149 :param k8s_pod: V1Pod
150 :param namespace: str
151 :rtype: V1Pod
152 """
153 LOG.info("Creating pod in k8s cluster")
Vladimir Jigulin34dfa942018-07-23 21:05:48 +0400154 if isinstance(body, six.string_types):
155 body = yaml.load(body)
Artem Panchenko0594cd72017-06-12 13:25:26 +0300156 LOG.debug(
157 "POD spec to create:\n{}".format(
158 yaml.dump(body, default_flow_style=False))
159 )
160 LOG.debug("Timeout for creation is set to {}".format(timeout))
161 LOG.debug("Checking interval is set to {}".format(interval))
162 pod = self.api.pods.create(body=body, namespace=namespace)
Vladimir Jigulin34dfa942018-07-23 21:05:48 +0400163 pod.wait_running(timeout=timeout, interval=interval)
Artem Panchenko0594cd72017-06-12 13:25:26 +0300164 LOG.info("Pod '{0}' is created in '{1}' namespace".format(
165 pod.name, pod.namespace))
166 return self.api.pods.get(name=pod.name, namespace=pod.namespace)
167
168 def wait_pod_deleted(self, podname, timeout=60, interval=5):
169 helpers.wait(
170 lambda: podname not in [pod.name for pod in self.api.pods.list()],
171 timeout=timeout,
172 interval=interval,
173 timeout_msg="Pod deletion timeout reached!"
174 )
175
176 def check_pod_delete(self, k8s_pod, timeout=300, interval=5,
177 namespace=None):
178 """Deleting pod from k8s
179
180 :param k8s_pod: tcp_tests.managers.k8s.nodes.K8sNode
181 :param k8sclient: tcp_tests.managers.k8s.cluster.K8sCluster
182 """
183 LOG.info("Deleting pod '{}'".format(k8s_pod.name))
184 LOG.debug("Pod status:\n{}".format(k8s_pod.status))
185 LOG.debug("Timeout for deletion is set to {}".format(timeout))
186 LOG.debug("Checking interval is set to {}".format(interval))
187 self.api.pods.delete(body=k8s_pod, name=k8s_pod.name,
188 namespace=namespace)
189 self.wait_pod_deleted(k8s_pod.name, timeout, interval)
190 LOG.debug("Pod '{}' is deleted".format(k8s_pod.name))
191
192 def check_service_create(self, body, namespace=None):
193 """Check creating k8s service
194
195 :param body: dict, service spec
196 :param namespace: str
197 :rtype: K8sService object
198 """
199 LOG.info("Creating service in k8s cluster")
200 LOG.debug(
201 "Service spec to create:\n{}".format(
202 yaml.dump(body, default_flow_style=False))
203 )
204 service = self.api.services.create(body=body, namespace=namespace)
205 LOG.info("Service '{0}' is created in '{1}' namespace".format(
206 service.name, service.namespace))
207 return self.api.services.get(name=service.name,
208 namespace=service.namespace)
209
210 def check_ds_create(self, body, namespace=None):
211 """Check creating k8s DaemonSet
212
213 :param body: dict, DaemonSet spec
214 :param namespace: str
215 :rtype: K8sDaemonSet object
216 """
217 LOG.info("Creating DaemonSet in k8s cluster")
218 LOG.debug(
219 "DaemonSet spec to create:\n{}".format(
220 yaml.dump(body, default_flow_style=False))
221 )
222 ds = self.api.daemonsets.create(body=body, namespace=namespace)
223 LOG.info("DaemonSet '{0}' is created in '{1}' namespace".format(
224 ds.name, ds.namespace))
225 return self.api.daemonsets.get(name=ds.name, namespace=ds.namespace)
226
227 def check_ds_ready(self, dsname, namespace=None):
228 """Check if k8s DaemonSet is ready
229
230 :param dsname: str, ds name
231 :return: bool
232 """
233 ds = self.api.daemonsets.get(name=dsname, namespace=namespace)
234 return (ds.status.current_number_scheduled ==
235 ds.status.desired_number_scheduled)
236
237 def wait_ds_ready(self, dsname, namespace=None, timeout=60, interval=5):
238 """Wait until all pods are scheduled on nodes
239
240 :param dsname: str, ds name
241 :param timeout: int
242 :param interval: int
243 """
244 helpers.wait(
245 lambda: self.check_ds_ready(dsname, namespace=namespace),
246 timeout=timeout, interval=interval)
247
Artem Panchenko501e67e2017-06-14 14:59:18 +0300248 def check_deploy_create(self, body, namespace=None):
249 """Check creating k8s Deployment
250
251 :param body: dict, Deployment spec
252 :param namespace: str
253 :rtype: K8sDeployment object
254 """
255 LOG.info("Creating Deployment in k8s cluster")
256 LOG.debug(
257 "Deployment spec to create:\n{}".format(
258 yaml.dump(body, default_flow_style=False))
259 )
260 deploy = self.api.deployments.create(body=body, namespace=namespace)
261 LOG.info("Deployment '{0}' is created in '{1}' namespace".format(
262 deploy.name, deploy.namespace))
263 return self.api.deployments.get(name=deploy.name,
264 namespace=deploy.namespace)
265
266 def check_deploy_ready(self, deploy_name, namespace=None):
267 """Check if k8s Deployment is ready
268
269 :param deploy_name: str, deploy name
270 :return: bool
271 """
Dina Belovae6fdffb2017-09-19 13:58:34 -0700272 deploy = self.api.deployments.get(name=deploy_name,
273 namespace=namespace)
Artem Panchenko501e67e2017-06-14 14:59:18 +0300274 return deploy.status.available_replicas == deploy.status.replicas
275
Dina Belovae6fdffb2017-09-19 13:58:34 -0700276 def wait_deploy_ready(self, deploy_name, namespace=None, timeout=60,
277 interval=5):
Artem Panchenko501e67e2017-06-14 14:59:18 +0300278 """Wait until all pods are scheduled on nodes
279
280 :param deploy_name: str, deploy name
281 :param timeout: int
282 :param interval: int
283 """
284 helpers.wait(
285 lambda: self.check_deploy_ready(deploy_name, namespace=namespace),
286 timeout=timeout, interval=interval)
287
Artem Panchenko0594cd72017-06-12 13:25:26 +0300288 def check_namespace_create(self, name):
289 """Check creating k8s Namespace
290
291 :param name: str
292 :rtype: K8sNamespace object
293 """
Sergey Vasilenkofd1fd612017-09-20 13:09:51 +0300294 try:
295 ns = self.api.namespaces.get(name=name)
296 LOG.info("Namespace '{0}' is already exists".format(ns.name))
297 except ApiException as e:
Dennis Dmitriev9b02c8b2017-11-13 15:31:35 +0200298 if hasattr(e, "status") and 404 == e.status:
299 LOG.info("Creating Namespace in k8s cluster")
300 ns = self.api.namespaces.create(
301 body={'metadata': {'name': name}})
302 LOG.info("Namespace '{0}' is created".format(ns.name))
303 # wait 10 seconds until a token for new service account
304 # is created
305 time.sleep(10)
306 ns = self.api.namespaces.get(name=ns.name)
307 else:
308 raise
Sergey Vasilenkofd1fd612017-09-20 13:09:51 +0300309 return ns
Artem Panchenko0594cd72017-06-12 13:25:26 +0300310
311 def create_objects(self, path):
312 if isinstance(path, str):
313 path = [path]
314 params = ' '.join(["-f {}".format(p) for p in path])
315 cmd = 'kubectl create {params}'.format(params=params)
316 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400317 node_name=self.ctl_host) as remote:
Artem Panchenko0594cd72017-06-12 13:25:26 +0300318 LOG.info("Running command '{cmd}' on node {node}".format(
319 cmd=cmd,
320 node=remote.hostname)
321 )
322 result = remote.check_call(cmd)
323 LOG.info(result['stdout'])
324
325 def get_running_pods(self, pod_name, namespace=None):
326 pods = [pod for pod in self.api.pods.list(namespace=namespace)
327 if (pod_name in pod.name and pod.status.phase == 'Running')]
328 return pods
329
330 def get_pods_number(self, pod_name, namespace=None):
331 pods = self.get_running_pods(pod_name, namespace)
332 return len(pods)
333
334 def get_running_pods_by_ssh(self, pod_name, namespace=None):
335 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400336 node_name=self.ctl_host) as remote:
Artem Panchenko0594cd72017-06-12 13:25:26 +0300337 result = remote.check_call("kubectl get pods --namespace {} |"
338 " grep {} | awk '{{print $1 \" \""
339 " $3}}'".format(namespace,
340 pod_name))['stdout']
341 running_pods = [data.strip().split()[0] for data in result
342 if data.strip().split()[1] == 'Running']
343 return running_pods
344
345 def get_pods_restarts(self, pod_name, namespace=None):
346 pods = [pod.status.container_statuses[0].restart_count
347 for pod in self.get_running_pods(pod_name, namespace)]
348 return sum(pods)
vrovacheva9d08332017-06-22 20:01:59 +0400349
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400350 def run_conformance(self, timeout=60 * 60, log_out='k8s_conformance.log',
Vladimir Jigulinee1faa52018-06-25 13:00:51 +0400351 raise_on_err=True, node_name=None,
352 api_server='http://127.0.0.1:8080'):
353 if node_name is None:
354 node_name = self.ctl_host
355 cmd = "set -o pipefail; docker run --net=host -e API_SERVER="\
356 "'{api}' {image} | tee '{log}'".format(
357 api=api_server, image=self.__config.k8s.k8s_conformance_image,
358 log=log_out)
359 return self.__underlay.check_call(
360 cmd=cmd, node_name=node_name, timeout=timeout,
361 raise_on_err=raise_on_err)
Artem Panchenko501e67e2017-06-14 14:59:18 +0300362
363 def get_k8s_masters(self):
364 k8s_masters_fqdn = self._salt.get_pillar(tgt='I@kubernetes:master',
365 pillar='linux:network:fqdn')
366 return [self._K8SManager__underlay.host_by_node_name(node_name=v)
367 for pillar in k8s_masters_fqdn for k, v in pillar.items()]
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400368
Vladimir Jigulina6b018b2018-07-18 15:19:01 +0400369 def kubectl_run(self, name, image, port, replicas=None):
370 cmd = "kubectl run {0} --image={1} --port={2}".format(
371 name, image, port)
372 if replicas is not None:
373 cmd += " --replicas={}".format(replicas)
374 return self.__underlay.check_call(cmd=cmd, node_name=self.ctl_host)
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400375
Vladimir Jigulina6b018b2018-07-18 15:19:01 +0400376 def kubectl_expose(self, resource, name, port, type, target_name=None):
377 cmd = "kubectl expose {0} {1} --port={2} --type={3}".format(
378 resource, name, port, type)
379 if target_name is not None:
380 cmd += " --name={}".format(target_name)
381 return self.__underlay.check_call(cmd=cmd, node_name=self.ctl_host)
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400382
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400383 def kubectl_annotate(self, resource, name, annotation):
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400384 with self.__underlay.remote(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400385 node_name=self.ctl_host) as remote:
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400386 result = remote.check_call(
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400387 "kubectl annotate {0} {1} {2}".format(
388 resource, name, annotation
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400389 )
390 )
391 return result
392
Vladimir Jigulina6b018b2018-07-18 15:19:01 +0400393 def get_svc_ip(self, name, namespace='kube-system', external=False):
394 cmd = "kubectl get svc {0} -n {1} | awk '{{print ${2}}}' | tail -1".\
395 format(name, namespace, 4 if external else 3)
396 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
397 return result['stdout'][0].strip()
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400398
Victor Ryzhenkin66d39372017-09-28 19:25:48 +0400399 @retry(300, exception=DevopsCalledProcessError)
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400400 def nslookup(self, host, src):
Vladimir Jigulin34dfa942018-07-23 21:05:48 +0400401 self.__underlay.check_call(
402 "nslookup {0} {1}".format(host, src), node_name=self.ctl_host)
Victor Ryzhenkin14354ac2017-09-27 17:42:30 +0400403
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400404 @retry(300, exception=DevopsCalledProcessError)
405 def curl(self, url):
406 """
407 Run curl on controller and return stdout
408
409 :param url: url to curl
410 :return: response string
411 """
Vladimir Jigulin34dfa942018-07-23 21:05:48 +0400412 result = self.__underlay.check_call(
413 "curl -s -S \"{}\"".format(url), node_name=self.ctl_host)
414 LOG.debug("curl \"{0}\" result: {1}".format(url, result['stdout']))
415 return result['stdout']
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400416
Victor Ryzhenkin3ffa2b42017-10-05 16:38:44 +0400417# ---------------------------- Virtlet methods -------------------------------
418 def install_jq(self):
419 """Install JQuery on node. Required for changing yamls on the fly.
420
421 :return:
422 """
423 cmd = "apt install jq -y"
424 return self.__underlay.check_call(cmd, node_name=self.ctl_host)
425
Victor Ryzhenkin3ffa2b42017-10-05 16:38:44 +0400426 def git_clone(self, project, target):
427 cmd = "git clone {0} {1}".format(project, target)
428 return self.__underlay.check_call(cmd, node_name=self.ctl_host)
429
430 def run_vm(self, name=None, yaml_path='~/virtlet/examples/cirros-vm.yaml'):
431 if not name:
432 name = 'virtlet-vm-{}'.format(uuid4())
433 cmd = (
434 "kubectl convert -f {0} --local "
435 "-o json | jq '.metadata.name|=\"{1}\"' | kubectl create -f -")
436 self.__underlay.check_call(cmd.format(yaml_path, name),
437 node_name=self.ctl_host)
438 return name
439
440 def get_vm_info(self, name, jsonpath="{.status.phase}", expected=None):
441 cmd = "kubectl get po {} -n default".format(name)
442 if jsonpath:
443 cmd += " -o jsonpath={}".format(jsonpath)
444 return self.__underlay.check_call(
445 cmd, node_name=self.ctl_host, expected=expected)
446
447 def wait_active_state(self, name, timeout=180):
448 helpers.wait(
449 lambda: self.get_vm_info(name)['stdout'][0] == 'Running',
450 timeout=timeout,
451 timeout_msg="VM {} didn't Running state in {} sec. "
452 "Current state: ".format(
453 name, timeout, self.get_vm_info(name)['stdout'][0]))
454
455 def delete_vm(self, name, timeout=180):
456 cmd = "kubectl delete po -n default {}".format(name)
457 self.__underlay.check_call(cmd, node_name=self.ctl_host)
458
459 helpers.wait(
460 lambda:
461 "Error from server (NotFound):" in
462 " ".join(self.get_vm_info(name, expected=[0, 1])['stderr']),
463 timeout=timeout,
464 timeout_msg="VM {} didn't Running state in {} sec. "
465 "Current state: ".format(
466 name, timeout, self.get_vm_info(name)['stdout'][0]))
467
468 def adjust_cirros_resources(
469 self, cpu=2, memory='256',
470 target_yaml='virtlet/examples/cirros-vm-exp.yaml'):
471 # We will need to change params in case of example change
472 cmd = ("cd ~/virtlet/examples && "
473 "cp cirros-vm.yaml {2} && "
474 "sed -r 's/^(\s*)(VirtletVCPUCount\s*:\s*\"1\"\s*$)/ "
475 "\1VirtletVCPUCount: \"{0}\"/' {2} && "
476 "sed -r 's/^(\s*)(memory\s*:\s*128Mi\s*$)/\1memory: "
477 "{1}Mi/' {2}".format(cpu, memory, target_yaml))
478 self.__underlay.check_call(cmd, node_name=self.ctl_host)
479
480 def get_domain_name(self, vm_name):
481 cmd = ("~/virtlet/examples/virsh.sh list --name | "
482 "grep -i {0} ".format(vm_name))
483 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
484 return result['stdout'].strip()
485
486 def get_vm_cpu_count(self, domain_name):
487 cmd = ("~/virtlet/examples/virsh.sh dumpxml {0} | "
488 "grep 'cpu' | grep -o '[[:digit:]]*'".format(domain_name))
489 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
490 return int(result['stdout'].strip())
491
492 def get_vm_memory_count(self, domain_name):
493 cmd = ("~/virtlet/examples/virsh.sh dumpxml {0} | "
494 "grep 'memory unit' | "
495 "grep -o '[[:digit:]]*'".format(domain_name))
496 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
497 return int(result['stdout'].strip())
498
499 def get_domain_id(self, domain_name):
500 cmd = ("virsh dumpxml {} | grep id=\' | "
501 "grep -o [[:digit:]]*".format(domain_name))
502 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
503 return int(result['stdout'].strip())
504
505 def list_vm_volumes(self, domain_name):
506 domain_id = self.get_domain_id(domain_name)
507 cmd = ("~/virtlet/examples/virsh.sh domblklist {} | "
508 "tail -n +3 | awk {{'print $2'}}".format(domain_id))
509 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
Dennis Dmitriev9b02c8b2017-11-13 15:31:35 +0200510 return result['stdout'].strip()
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400511
Victor Ryzhenkinac37a752018-02-21 17:55:45 +0400512 def run_virtlet_conformance(self, timeout=60 * 120,
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400513 log_file='virtlet_conformance.log'):
514 if self.__config.k8s.run_extended_virtlet_conformance:
515 ci_image = "cloud-images.ubuntu.com/xenial/current/" \
516 "xenial-server-cloudimg-amd64-disk1.img"
517 cmd = ("set -o pipefail; "
518 "docker run --net=host {0} /virtlet-e2e-tests "
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400519 "-include-cloud-init-tests -junitOutput report.xml "
520 "-image {2} -sshuser ubuntu -memoryLimit 1024 "
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400521 "-alsologtostderr -cluster-url http://127.0.0.1:8080 "
522 "-ginkgo.focus '\[Conformance\]' "
523 "| tee {1}".format(
524 self.__config.k8s_deploy.kubernetes_virtlet_image,
525 log_file, ci_image))
526 else:
527 cmd = ("set -o pipefail; "
528 "docker run --net=host {0} /virtlet-e2e-tests "
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400529 "-junitOutput report.xml "
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400530 "-alsologtostderr -cluster-url http://127.0.0.1:8080 "
531 "-ginkgo.focus '\[Conformance\]' "
532 "| tee {1}".format(
533 self.__config.k8s_deploy.kubernetes_virtlet_image,
534 log_file))
535 LOG.info("Executing: {}".format(cmd))
536 with self.__underlay.remote(
537 node_name=self.ctl_host) as remote:
538 result = remote.check_call(cmd, timeout=timeout)
539 stderr = result['stderr']
540 stdout = result['stdout']
541 LOG.info("Test results stdout: {}".format(stdout))
542 LOG.info("Test results stderr: {}".format(stderr))
543 return result
544
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400545 def start_k8s_cncf_verification(self, timeout=60 * 90):
546 cncf_cmd = ("curl -L https://raw.githubusercontent.com/cncf/"
547 "k8s-conformance/master/sonobuoy-conformance.yaml"
548 " | kubectl apply -f -")
549 with self.__underlay.remote(
550 node_name=self.ctl_host) as remote:
551 remote.check_call(cncf_cmd, timeout=60)
552 self.wait_pod_phase('sonobuoy', 'Running',
553 namespace='sonobuoy', timeout=120)
554 wait_cmd = ('kubectl logs -n sonobuoy sonobuoy | '
555 'grep "sonobuoy is now blocking"')
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400556
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400557 expected = [0, 1]
558 helpers.wait(
559 lambda: remote.check_call(
560 wait_cmd, expected=expected).exit_code == 0,
561 interval=30, timeout=timeout,
562 timeout_msg="Timeout for CNCF reached."
563 )
564
565 def extract_file_to_node(self, system='docker',
566 container='virtlet',
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400567 file_path='report.xml',
568 out_dir='.',
569 **kwargs):
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400570 """
571 Download file from docker or k8s container to node
572
573 :param system: docker or k8s
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400574 :param container: Full name of part of name
575 :param file_path: File path in container
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400576 :param kwargs: Used to control pod and namespace
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400577 :param out_dir: Output directory
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400578 :return:
579 """
580 with self.__underlay.remote(
581 node_name=self.ctl_host) as remote:
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400582 if system is 'docker':
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400583 cmd = ("docker ps --all | grep \"{0}\" |"
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400584 " awk '{{print $1}}'".format(container))
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400585 result = remote.check_call(cmd, raise_on_err=False)
586 if result['stdout']:
587 container_id = result['stdout'][0].strip()
588 else:
589 LOG.info('No container found, skipping extraction...')
590 return
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400591 cmd = "docker start {}".format(container_id)
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400592 remote.check_call(cmd, raise_on_err=False)
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400593 cmd = "docker cp \"{0}:/{1}\" \"{2}\"".format(
594 container_id, file_path, out_dir)
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400595 remote.check_call(cmd, raise_on_err=False)
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400596 else:
597 # system is k8s
598 pod_name = kwargs.get('pod_name')
599 pod_namespace = kwargs.get('pod_namespace')
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400600 cmd = 'kubectl cp \"{0}/{1}:/{2}\" \"{3}\"'.format(
601 pod_namespace, pod_name, file_path, out_dir)
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400602 remote.check_call(cmd, raise_on_err=False)
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400603
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400604 def download_k8s_logs(self, files):
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400605 """
606 Download JUnit report and conformance logs from cluster
607 :param files:
608 :return:
609 """
Victor Ryzhenkin8ff3c3f2018-01-17 19:37:05 +0400610 master_host = self.__config.salt.salt_master_host
611 with self.__underlay.remote(host=master_host) as r:
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400612 for log_file in files:
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400613 cmd = "rsync -r \"{0}:/root/{1}\" /root/".format(
614 self.ctl_host, log_file)
Victor Ryzhenkin53b7ad22018-02-08 20:05:40 +0400615 r.check_call(cmd, raise_on_err=False)
616 LOG.info("Downloading the artifact {0}".format(log_file))
617 r.download(destination=log_file, target=os.getcwd())
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400618
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400619 def combine_xunit(self, path, output):
620 """
621 Function to combine multiple xmls with test results to
622 one.
623
624 :param path: Path where xmls to combine located
625 :param output: Path to xml file where output will stored
626 :return:
627 """
628 with self.__underlay.remote(node_name=self.ctl_host) as r:
Tatyana Leontovichfe1834c2018-04-19 13:52:05 +0300629 cmd = ("apt-get install python-setuptools -y; "
Vladimir Jigulin3c1ea6c2018-07-19 13:59:05 +0400630 "pip install "
631 "https://github.com/mogaika/xunitmerge/archive/master.zip")
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400632 LOG.debug('Installing xunitmerge')
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400633 r.check_call(cmd, raise_on_err=False)
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400634 LOG.debug('Merging xunit')
635 cmd = ("cd {0}; arg = ''; "
636 "for i in $(ls | grep xml); "
637 "do arg=\"$arg $i\"; done && "
638 "xunitmerge $arg {1}".format(path, output))
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400639 r.check_call(cmd, raise_on_err=False)
Victor Ryzhenkincf26c932018-03-29 20:08:21 +0400640
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400641 def manage_cncf_archive(self):
642 """
643 Function to untar archive, move files, that we are needs to the
644 home folder, prepare it to downloading and clean the trash.
645 Will generate files: e2e.log, junit_01.xml, cncf_results.tar.gz
646 and version.txt
647 :return:
648 """
649
650 # Namespace and pod name may be hardcoded since this function is
651 # very specific for cncf and cncf is not going to change
652 # those launch pod name and namespace.
653 get_tar_name_cmd = ("kubectl logs -n sonobuoy sonobuoy | "
654 "grep 'Results available' | "
655 "sed 's/.*\///' | tr -d '\"'")
656
657 with self.__underlay.remote(
658 node_name=self.ctl_host) as remote:
659 tar_name = remote.check_call(get_tar_name_cmd)['stdout'][0].strip()
660 untar = "mkdir result && tar -C result -xzf {0}".format(tar_name)
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400661 remote.check_call(untar, raise_on_err=False)
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400662 manage_results = ("mv result/plugins/e2e/results/e2e.log . && "
663 "mv result/plugins/e2e/results/junit_01.xml . ;"
664 "kubectl version > version.txt")
665 remote.check_call(manage_results, raise_on_err=False)
666 cleanup_host = "rm -rf result"
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400667 remote.check_call(cleanup_host, raise_on_err=False)
Victor Ryzhenkin87a31422018-03-16 22:25:27 +0400668 # This one needed to use download fixture, since I don't know
669 # how possible apply fixture arg dynamically from test.
670 rename_tar = "mv {0} cncf_results.tar.gz".format(tar_name)
Victor Ryzhenkin4e4126c2018-05-22 19:09:20 +0400671 remote.check_call(rename_tar, raise_on_err=False)
Vladimir Jigulin62bcf462018-05-28 18:17:01 +0400672
673 def update_k8s_images(self, tag):
674 """
675 Update k8s images tag version in cluster meta and apply required
676 for update states
677
678 :param tag: New version tag of k8s images
679 :return:
680 """
681 master_host = self.__config.salt.salt_master_host
682
683 def update_image_tag_meta(config, image_name):
684 image_old = config.get(image_name)
685 image_base = image_old.split(':')[0]
686 image_new = "{}:{}".format(image_base, tag)
687 LOG.info("Changing k8s '{0}' image cluster meta to '{1}'".format(
688 image_name, image_new))
689
690 with self.__underlay.remote(host=master_host) as r:
691 cmd = "salt-call reclass.cluster_meta_set" \
692 " name={0} value={1}".format(image_name, image_new)
693 r.check_call(cmd)
694 return image_new
695
696 cfg = self.__config
697
698 update_image_tag_meta(cfg.k8s_deploy, "kubernetes_hyperkube_image")
699 update_image_tag_meta(cfg.k8s_deploy, "kubernetes_pause_image")
700 cfg.k8s.k8s_conformance_image = update_image_tag_meta(
701 cfg.k8s, "k8s_conformance_image")
702
703 steps_path = cfg.k8s_deploy.k8s_update_steps_path
704 update_commands = self.__underlay.read_template(steps_path)
705 self.execute_commands(
706 update_commands, label="Updating kubernetes to '{}'".format(tag))
Vladimir Jigulinee1faa52018-06-25 13:00:51 +0400707
708 def get_keepalived_vip(self):
709 """
710 Return k8s VIP IP address
711
712 :return: str, IP address
713 """
714 ctl_vip_pillar = self._salt.get_pillar(
715 tgt="I@kubernetes:control:enabled:True",
716 pillar="_param:cluster_vip_address")[0]
Vladimir Jigulin34dfa942018-07-23 21:05:48 +0400717 return ctl_vip_pillar.values()[0]
Vladimir Jigulina6b018b2018-07-18 15:19:01 +0400718
719 def get_sample_deployment(self, name, **kwargs):
720 return K8SSampleDeployment(self, name, **kwargs)
721
Vladimir Jigulin34dfa942018-07-23 21:05:48 +0400722 def is_pod_exists_with_prefix(self, prefix, namespace, phase='Running'):
723 for pod in self.api.pods.list(namespace=namespace):
724 if pod.name.startswith(prefix) and pod.phase == phase:
725 return True
726 return False
727
728 def get_pod_ips_from_container(self, pod_name, exclude_local=True):
729 """ Not all containers have 'ip' binary on-board """
730 cmd = "kubectl exec {0} ip a|grep \"inet \"|awk '{{print $2}}'".format(
731 pod_name)
732 result = self.__underlay.check_call(cmd, node_name=self.ctl_host)
733 ips = [line.strip().split('/')[0] for line in result['stdout']]
734 if exclude_local:
735 ips = [ip for ip in ips if not ip.startswith("127.")]
736 return ips
737
738 def create_pod_from_file(self, path, namespace=None):
739 with open(path) as f:
740 data = f.read()
741 return self.check_pod_create(data, namespace=namespace)
742
Vladimir Jigulina6b018b2018-07-18 15:19:01 +0400743
744class K8SSampleDeployment:
745 def __init__(self, manager, name, replicas=2,
746 image='gcr.io/google-samples/node-hello:1.0', port=8080):
747 self.manager = manager
748 self.name = name
749 self.image = image
750 self.port = port
751 self.replicas = replicas
752
753 def run(self):
754 self.manager.kubectl_run(self.name, self.image, self.port,
755 replicas=self.replicas)
756
757 def expose(self, service_type='ClusterIP', target_name=None):
758 self.manager.kubectl_expose(
759 'deployment', self.name, self.port, service_type, target_name)
760
761 def get_svc_ip(self, external=False):
762 return self.manager.get_svc_ip(self.name, namespace='default',
763 external=external)
764
765 def curl(self, external=False):
766 url = "http://{0}:{1}".format(
767 self.get_svc_ip(external=external), self.port)
768 if external:
769 return requests.get(url).text
770 else:
771 return self.manager.curl(url)
772
773 def is_service_available(self, external=False):
774 return "Hello Kubernetes!" in self.curl(external=external)
775
776 def wait_for_ready(self):
777 return self.manager.wait_deploy_ready(self.name)