aca528e2385694dff7c293471093c6dbbede2e8e
2 # Copyright 2019 Telefonica Investigacion y Desarrollo, S.A.U.
3 # This file is part of OSM
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact with: nfvlabs@tid.es
30 from uuid
import uuid4
32 from n2vc
.k8s_conn
import K8sConnector
33 from n2vc
.exceptions
import K8sException
36 class K8sHelmConnector(K8sConnector
):
39 ##################################################################################################
40 ########################################## P U B L I C ###########################################
41 ##################################################################################################
48 kubectl_command
: str = '/usr/bin/kubectl',
49 helm_command
: str = '/usr/bin/helm',
55 :param fs: file system for kubernetes and helm configuration
56 :param db: database object to write current operation status
57 :param kubectl_command: path to kubectl executable
58 :param helm_command: path to helm executable
60 :param on_update_db: callback called when k8s connector updates database
64 K8sConnector
.__init
__(
68 on_update_db
=on_update_db
71 self
.info('Initializing K8S Helm connector')
73 # random numbers for release name generation
74 random
.seed(time
.time())
79 # exception if kubectl is not installed
80 self
.kubectl_command
= kubectl_command
81 self
._check
_file
_exists
(filename
=kubectl_command
, exception_if_not_exists
=True)
83 # exception if helm is not installed
84 self
._helm
_command
= helm_command
85 self
._check
_file
_exists
(filename
=helm_command
, exception_if_not_exists
=True)
87 # initialize helm client-only
88 self
.debug('Initializing helm client-only...')
89 command
= '{} init --client-only'.format(self
._helm
_command
)
91 asyncio
.ensure_future(self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False))
92 # loop = asyncio.get_event_loop()
93 # loop.run_until_complete(self._local_async_exec(command=command, raise_exception_on_error=False))
94 except Exception as e
:
95 self
.warning(msg
='helm init failed (it was already initialized): {}'.format(e
))
97 self
.info('K8S Helm connector initialized')
102 namespace
: str = 'kube-system',
103 reuse_cluster_uuid
=None
106 It prepares a given K8s cluster environment to run Charts on both sides:
110 :param k8s_creds: credentials to access a given K8s cluster, i.e. a valid '.kube/config'
111 :param namespace: optional namespace to be used for helm. By default, 'kube-system' will be used
112 :param reuse_cluster_uuid: existing cluster uuid for reuse
113 :return: uuid of the K8s cluster and True if connector has installed some software in the cluster
114 (on error, an exception will be raised)
117 cluster_uuid
= reuse_cluster_uuid
119 cluster_uuid
= str(uuid4())
121 self
.debug('Initializing K8S environment. namespace: {}'.format(namespace
))
123 # create config filename
124 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
125 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
126 f
= open(config_filename
, "w")
130 # check if tiller pod is up in cluster
131 command
= '{} --kubeconfig={} --namespace={} get deployments'\
132 .format(self
.kubectl_command
, config_filename
, namespace
)
133 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
135 output_table
= K8sHelmConnector
._output
_to
_table
(output
=output
)
137 # find 'tiller' pod in all pods
138 already_initialized
= False
140 for row
in output_table
:
141 if row
[0].startswith('tiller-deploy'):
142 already_initialized
= True
144 except Exception as e
:
148 n2vc_installed_sw
= False
149 if not already_initialized
:
150 self
.info('Initializing helm in client and server: {}'.format(cluster_uuid
))
151 command
= '{} --kubeconfig={} --tiller-namespace={} --home={} init'\
152 .format(self
._helm
_command
, config_filename
, namespace
, helm_dir
)
153 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
154 n2vc_installed_sw
= True
156 # check client helm installation
157 check_file
= helm_dir
+ '/repository/repositories.yaml'
158 if not self
._check
_file
_exists
(filename
=check_file
, exception_if_not_exists
=False):
159 self
.info('Initializing helm in client: {}'.format(cluster_uuid
))
160 command
= '{} --kubeconfig={} --tiller-namespace={} --home={} init --client-only'\
161 .format(self
._helm
_command
, config_filename
, namespace
, helm_dir
)
162 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
164 self
.info('Helm client already initialized')
166 self
.info('Cluster initialized {}'.format(cluster_uuid
))
168 return cluster_uuid
, n2vc_installed_sw
175 repo_type
: str = 'chart'
178 self
.debug('adding {} repository {}. URL: {}'.format(repo_type
, name
, url
))
181 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
182 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
185 command
= '{} --kubeconfig={} --home={} repo update'.format(self
._helm
_command
, config_filename
, helm_dir
)
186 self
.debug('updating repo: {}'.format(command
))
187 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
189 # helm repo add name url
190 command
= '{} --kubeconfig={} --home={} repo add {} {}'\
191 .format(self
._helm
_command
, config_filename
, helm_dir
, name
, url
)
192 self
.debug('adding repo: {}'.format(command
))
193 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
200 Get the list of registered repositories
202 :return: list of registered repositories: [ (name, url) .... ]
205 self
.debug('list repositories for cluster {}'.format(cluster_uuid
))
208 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
209 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
211 command
= '{} --kubeconfig={} --home={} repo list --output yaml'\
212 .format(self
._helm
_command
, config_filename
, helm_dir
)
214 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
215 if output
and len(output
) > 0:
216 return yaml
.load(output
, Loader
=yaml
.SafeLoader
)
220 async def repo_remove(
226 Remove a repository from OSM
228 :param cluster_uuid: the cluster
229 :param name: repo name in OSM
230 :return: True if successful
233 self
.debug('list repositories for cluster {}'.format(cluster_uuid
))
236 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
237 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
239 command
= '{} --kubeconfig={} --home={} repo remove {}'\
240 .format(self
._helm
_command
, config_filename
, helm_dir
, name
)
242 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
248 uninstall_sw
: bool = False
251 self
.debug('Resetting K8s environment. cluster uuid: {}'.format(cluster_uuid
))
253 # get kube and helm directories
254 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
255 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=False)
257 # uninstall releases if needed
258 releases
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
259 if len(releases
) > 0:
263 kdu_instance
= r
.get('Name')
264 chart
= r
.get('Chart')
265 self
.debug('Uninstalling {} -> {}'.format(chart
, kdu_instance
))
266 await self
.uninstall(cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
)
267 except Exception as e
:
268 self
.error('Error uninstalling release {}: {}'.format(kdu_instance
, e
))
270 msg
= 'Cluster has releases and not force. Cannot reset K8s environment. Cluster uuid: {}'\
271 .format(cluster_uuid
)
273 raise K8sException(msg
)
277 self
.debug('Uninstalling tiller from cluster {}'.format(cluster_uuid
))
279 # find namespace for tiller pod
280 command
= '{} --kubeconfig={} get deployments --all-namespaces'\
281 .format(self
.kubectl_command
, config_filename
)
282 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
283 output_table
= K8sHelmConnector
._output
_to
_table
(output
=output
)
285 for r
in output_table
:
287 if 'tiller-deploy' in r
[1]:
290 except Exception as e
:
293 msg
= 'Tiller deployment not found in cluster {}'.format(cluster_uuid
)
296 self
.debug('namespace for tiller: {}'.format(namespace
))
298 force_str
= '--force'
301 # delete tiller deployment
302 self
.debug('Deleting tiller deployment for cluster {}, namespace {}'.format(cluster_uuid
, namespace
))
303 command
= '{} --namespace {} --kubeconfig={} {} delete deployment tiller-deploy'\
304 .format(self
.kubectl_command
, namespace
, config_filename
, force_str
)
305 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
307 # uninstall tiller from cluster
308 self
.debug('Uninstalling tiller from cluster {}'.format(cluster_uuid
))
309 command
= '{} --kubeconfig={} --home={} reset'\
310 .format(self
._helm
_command
, config_filename
, helm_dir
)
311 self
.debug('resetting: {}'.format(command
))
312 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
314 self
.debug('namespace not found')
316 # delete cluster directory
317 dir = self
.fs
.path
+ '/' + cluster_uuid
318 self
.debug('Removing directory {}'.format(dir))
319 shutil
.rmtree(dir, ignore_errors
=True)
328 timeout
: float = 300,
330 db_dict
: dict = None,
334 self
.debug('installing {} in cluster {}'.format(kdu_model
, cluster_uuid
))
337 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
338 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
341 # params_str = K8sHelmConnector._params_to_set_option(params)
342 params_str
, file_to_delete
= self
._params
_to
_file
_option
(cluster_uuid
=cluster_uuid
, params
=params
)
346 timeout_str
= '--timeout {}'.format(timeout
)
351 atomic_str
= '--atomic'
356 parts
= kdu_model
.split(sep
=':')
358 version_str
= '--version {}'.format(parts
[1])
361 # generate a name for the release. Then, check if already exists
363 while kdu_instance
is None:
364 kdu_instance
= K8sHelmConnector
._generate
_release
_name
(kdu_model
)
366 result
= await self
._status
_kdu
(
367 cluster_uuid
=cluster_uuid
,
368 kdu_instance
=kdu_instance
,
371 if result
is not None:
372 # instance already exists: generate a new one
378 command
= '{} install {} --output yaml --kubeconfig={} --home={} {} {} --name={} {} {}'\
379 .format(self
._helm
_command
, atomic_str
, config_filename
, helm_dir
,
380 params_str
, timeout_str
, kdu_instance
, kdu_model
, version_str
)
381 self
.debug('installing: {}'.format(command
))
384 # exec helm in a task
385 exec_task
= asyncio
.ensure_future(
386 coro_or_future
=self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
388 # write status in another task
389 status_task
= asyncio
.ensure_future(
390 coro_or_future
=self
._store
_status
(
391 cluster_uuid
=cluster_uuid
,
392 kdu_instance
=kdu_instance
,
399 # wait for execution task
400 await asyncio
.wait([exec_task
])
405 output
, rc
= exec_task
.result()
409 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
411 # remove temporal values yaml file
413 os
.remove(file_to_delete
)
416 await self
._store
_status
(
417 cluster_uuid
=cluster_uuid
,
418 kdu_instance
=kdu_instance
,
426 msg
= 'Error executing command: {}\nOutput: {}'.format(command
, output
)
428 raise K8sException(msg
)
430 self
.debug('Returning kdu_instance {}'.format(kdu_instance
))
433 async def instances_list(
438 returns a list of deployed releases in a cluster
440 :param cluster_uuid: the cluster
444 self
.debug('list releases for cluster {}'.format(cluster_uuid
))
447 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
448 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
450 command
= '{} --kubeconfig={} --home={} list --output yaml'\
451 .format(self
._helm
_command
, config_filename
, helm_dir
)
453 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
455 if output
and len(output
) > 0:
456 return yaml
.load(output
, Loader
=yaml
.SafeLoader
).get('Releases')
464 kdu_model
: str = None,
466 timeout
: float = 300,
471 self
.debug('upgrading {} in cluster {}'.format(kdu_model
, cluster_uuid
))
474 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
475 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
478 # params_str = K8sHelmConnector._params_to_set_option(params)
479 params_str
, file_to_delete
= self
._params
_to
_file
_option
(cluster_uuid
=cluster_uuid
, params
=params
)
483 timeout_str
= '--timeout {}'.format(timeout
)
488 atomic_str
= '--atomic'
492 if kdu_model
and ':' in kdu_model
:
493 parts
= kdu_model
.split(sep
=':')
495 version_str
= '--version {}'.format(parts
[1])
499 command
= '{} upgrade {} --output yaml --kubeconfig={} --home={} {} {} {} {} {}'\
500 .format(self
._helm
_command
, atomic_str
, config_filename
, helm_dir
,
501 params_str
, timeout_str
, kdu_instance
, kdu_model
, version_str
)
502 self
.debug('upgrading: {}'.format(command
))
506 # exec helm in a task
507 exec_task
= asyncio
.ensure_future(
508 coro_or_future
=self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
510 # write status in another task
511 status_task
= asyncio
.ensure_future(
512 coro_or_future
=self
._store
_status
(
513 cluster_uuid
=cluster_uuid
,
514 kdu_instance
=kdu_instance
,
521 # wait for execution task
522 await asyncio
.wait([exec_task
])
526 output
, rc
= exec_task
.result()
530 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
532 # remove temporal values yaml file
534 os
.remove(file_to_delete
)
537 await self
._store
_status
(
538 cluster_uuid
=cluster_uuid
,
539 kdu_instance
=kdu_instance
,
547 msg
= 'Error executing command: {}\nOutput: {}'.format(command
, output
)
549 raise K8sException(msg
)
551 # return new revision number
552 instance
= await self
.get_instance_info(cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
)
554 revision
= int(instance
.get('Revision'))
555 self
.debug('New revision: {}'.format(revision
))
568 self
.debug('rollback kdu_instance {} to revision {} from cluster {}'
569 .format(kdu_instance
, revision
, cluster_uuid
))
572 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
573 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
575 command
= '{} rollback --kubeconfig={} --home={} {} {} --wait'\
576 .format(self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
, revision
)
578 # exec helm in a task
579 exec_task
= asyncio
.ensure_future(
580 coro_or_future
=self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
582 # write status in another task
583 status_task
= asyncio
.ensure_future(
584 coro_or_future
=self
._store
_status
(
585 cluster_uuid
=cluster_uuid
,
586 kdu_instance
=kdu_instance
,
588 operation
='rollback',
593 # wait for execution task
594 await asyncio
.wait([exec_task
])
599 output
, rc
= exec_task
.result()
602 await self
._store
_status
(
603 cluster_uuid
=cluster_uuid
,
604 kdu_instance
=kdu_instance
,
606 operation
='rollback',
612 msg
= 'Error executing command: {}\nOutput: {}'.format(command
, output
)
614 raise K8sException(msg
)
616 # return new revision number
617 instance
= await self
.get_instance_info(cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
)
619 revision
= int(instance
.get('Revision'))
620 self
.debug('New revision: {}'.format(revision
))
631 Removes an existing KDU instance. It would implicitly use the `delete` call (this call would happen
632 after all _terminate-config-primitive_ of the VNF are invoked).
634 :param cluster_uuid: UUID of a K8s cluster known by OSM
635 :param kdu_instance: unique name for the KDU instance to be deleted
636 :return: True if successful
639 self
.debug('uninstall kdu_instance {} from cluster {}'.format(kdu_instance
, cluster_uuid
))
642 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
643 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
645 command
= '{} --kubeconfig={} --home={} delete --purge {}'\
646 .format(self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
)
648 output
, rc
= await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
650 return self
._output
_to
_table
(output
)
652 async def inspect_kdu(
658 self
.debug('inspect kdu_model {} from (optional) repo: {}'.format(kdu_model
, repo_url
))
660 return await self
._exec
_inspect
_comand
(inspect_command
='', kdu_model
=kdu_model
, repo_url
=repo_url
)
662 async def values_kdu(
668 self
.debug('inspect kdu_model values {} from (optional) repo: {}'.format(kdu_model
, repo_url
))
670 return await self
._exec
_inspect
_comand
(inspect_command
='values', kdu_model
=kdu_model
, repo_url
=repo_url
)
678 self
.debug('inspect kdu_model {} readme.md from repo: {}'.format(kdu_model
, repo_url
))
680 return await self
._exec
_inspect
_comand
(inspect_command
='readme', kdu_model
=kdu_model
, repo_url
=repo_url
)
682 async def status_kdu(
688 # call internal function
689 return await self
._status
_kdu
(
690 cluster_uuid
=cluster_uuid
,
691 kdu_instance
=kdu_instance
,
697 ##################################################################################################
698 ########################################## P R I V A T E #########################################
699 ##################################################################################################
702 async def _exec_inspect_comand(
704 inspect_command
: str,
711 repo_str
= ' --repo {}'.format(repo_url
)
712 idx
= kdu_model
.find('/')
715 kdu_model
= kdu_model
[idx
:]
717 inspect_command
= '{} inspect {} {}{}'.format(self
._helm
_command
, inspect_command
, kdu_model
, repo_str
)
718 output
, rc
= await self
._local
_async
_exec
(command
=inspect_command
, encode_utf8
=True)
722 async def _status_kdu(
726 show_error_log
: bool = False,
727 return_text
: bool = False
730 self
.debug('status of kdu_instance {}'.format(kdu_instance
))
733 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
734 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
736 command
= '{} --kubeconfig={} --home={} status {} --output yaml'\
737 .format(self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
)
739 output
, rc
= await self
._local
_async
_exec
(
741 raise_exception_on_error
=True,
742 show_error_log
=show_error_log
751 data
= yaml
.load(output
, Loader
=yaml
.SafeLoader
)
753 # remove field 'notes'
755 del data
.get('info').get('status')['notes']
759 # parse field 'resources'
761 resources
= str(data
.get('info').get('status').get('resources'))
762 resource_table
= self
._output
_to
_table
(resources
)
763 data
.get('info').get('status')['resources'] = resource_table
764 except Exception as e
:
769 async def get_instance_info(
774 instances
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
775 for instance
in instances
:
776 if instance
.get('Name') == kdu_instance
:
778 self
.debug('Instance {} not found'.format(kdu_instance
))
782 def _generate_release_name(
785 # check embeded chart (file or dir)
786 if chart_name
.startswith('/'):
787 # extract file or directory name
788 chart_name
= chart_name
[chart_name
.rfind('/')+1:]
790 elif '://' in chart_name
:
791 # extract last portion of URL
792 chart_name
= chart_name
[chart_name
.rfind('/')+1:]
796 if c
.isalpha() or c
.isnumeric():
803 # if does not start with alpha character, prefix 'a'
804 if not name
[0].isalpha():
809 def get_random_number():
810 r
= random
.randrange(start
=1, stop
=99999999)
815 name
= name
+ get_random_number()
818 async def _store_status(
823 check_every
: float = 10,
824 db_dict
: dict = None,
825 run_once
: bool = False
829 await asyncio
.sleep(check_every
)
830 detailed_status
= await self
.status_kdu(cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
)
831 status
= detailed_status
.get('info').get('Description')
833 self
.debug('STATUS:\n{}'.format(status
))
834 self
.debug('DETAILED STATUS:\n{}'.format(detailed_status
))
837 result
= await self
.write_app_status_to_db(
840 detailed_status
=str(detailed_status
),
843 self
.info('Error writing in database. Task exiting...')
845 except asyncio
.CancelledError
:
846 self
.debug('Task cancelled')
848 except Exception as e
:
854 async def _is_install_completed(
860 status
= await self
._status
_kdu
(cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
, return_text
=False)
862 # extract info.status.resources-> str
865 # NAME READY UP-TO-DATE AVAILABLE AGE
866 # halting-horse-mongodb 0/1 1 0 0s
867 # halting-petit-mongodb 1/1 1 0 0s
869 resources
= K8sHelmConnector
._get
_deep
(status
, ('info', 'status', 'resources'))
872 resources
= K8sHelmConnector
._output
_to
_table
(resources
)
874 num_lines
= len(resources
)
876 while index
< num_lines
:
878 line1
= resources
[index
]
880 # find '==>' in column 0
881 if line1
[0] == '==>':
882 line2
= resources
[index
]
884 # find READY in column 1
885 if line2
[1] == 'READY':
887 line3
= resources
[index
]
889 while len(line3
) > 1 and index
< num_lines
:
890 ready_value
= line3
[1]
891 parts
= ready_value
.split(sep
='/')
892 current
= int(parts
[0])
893 total
= int(parts
[1])
895 self
.debug('NOT READY:\n {}'.format(line3
))
897 line3
= resources
[index
]
900 except Exception as e
:
906 def _get_deep(dictionary
: dict, members
: tuple):
911 value
= target
.get(m
)
916 except Exception as e
:
920 # find key:value in several lines
922 def _find_in_lines(p_lines
: list, p_key
: str) -> str:
925 if line
.startswith(p_key
+ ':'):
926 parts
= line
.split(':')
927 the_value
= parts
[1].strip()
929 except Exception as e
:
934 # params for use in -f file
935 # returns values file option and filename (in order to delete it at the end)
936 def _params_to_file_option(self
, cluster_uuid
: str, params
: dict) -> (str, str):
938 if params
and len(params
) > 0:
939 kube_dir
, helm_dir
, config_filename
, cluster_dir
= \
940 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
942 def get_random_number():
943 r
= random
.randrange(start
=1, stop
=99999999)
951 value
= params
.get(key
)
952 if '!!yaml' in str(value
):
953 value
= yaml
.load(value
[7:])
956 values_file
= get_random_number() + '.yaml'
957 with
open(values_file
, 'w') as stream
:
958 yaml
.dump(params2
, stream
, indent
=4, default_flow_style
=False)
960 return '-f {}'.format(values_file
), values_file
964 # params for use in --set option
966 def _params_to_set_option(params
: dict) -> str:
968 if params
and len(params
) > 0:
971 value
= params
.get(key
, None)
972 if value
is not None:
974 params_str
+= '--set '
978 params_str
+= '{}={}'.format(key
, value
)
982 def _output_to_lines(output
: str) -> list:
983 output_lines
= list()
984 lines
= output
.splitlines(keepends
=False)
988 output_lines
.append(line
)
992 def _output_to_table(output
: str) -> list:
993 output_table
= list()
994 lines
= output
.splitlines(keepends
=False)
996 line
= line
.replace('\t', ' ')
998 output_table
.append(line_list
)
999 cells
= line
.split(sep
=' ')
1003 line_list
.append(cell
)
1006 def _get_paths(self
, cluster_name
: str, create_if_not_exist
: bool = False) -> (str, str, str, str):
1008 Returns kube and helm directories
1010 :param cluster_name:
1011 :param create_if_not_exist:
1012 :return: kube, helm directories, config filename and cluster dir.
1013 Raises exception if not exist and cannot create
1017 if base
.endswith("/") or base
.endswith("\\"):
1020 # base dir for cluster
1021 cluster_dir
= base
+ '/' + cluster_name
1022 if create_if_not_exist
and not os
.path
.exists(cluster_dir
):
1023 self
.debug('Creating dir {}'.format(cluster_dir
))
1024 os
.makedirs(cluster_dir
)
1025 if not os
.path
.exists(cluster_dir
):
1026 msg
= 'Base cluster dir {} does not exist'.format(cluster_dir
)
1028 raise K8sException(msg
)
1031 kube_dir
= cluster_dir
+ '/' + '.kube'
1032 if create_if_not_exist
and not os
.path
.exists(kube_dir
):
1033 self
.debug('Creating dir {}'.format(kube_dir
))
1034 os
.makedirs(kube_dir
)
1035 if not os
.path
.exists(kube_dir
):
1036 msg
= 'Kube config dir {} does not exist'.format(kube_dir
)
1038 raise K8sException(msg
)
1041 helm_dir
= cluster_dir
+ '/' + '.helm'
1042 if create_if_not_exist
and not os
.path
.exists(helm_dir
):
1043 self
.debug('Creating dir {}'.format(helm_dir
))
1044 os
.makedirs(helm_dir
)
1045 if not os
.path
.exists(helm_dir
):
1046 msg
= 'Helm config dir {} does not exist'.format(helm_dir
)
1048 raise K8sException(msg
)
1050 config_filename
= kube_dir
+ '/config'
1051 return kube_dir
, helm_dir
, config_filename
, cluster_dir
1054 def _remove_multiple_spaces(str):
1057 str = str.replace(' ', ' ')
1064 command
= K8sHelmConnector
._remove
_multiple
_spaces
(command
)
1065 self
.debug('Executing sync local command: {}'.format(command
))
1066 # raise exception if fails
1069 output
= subprocess
.check_output(command
, shell
=True, universal_newlines
=True)
1072 except Exception as e
:
1075 return output
, return_code
1077 async def _local_async_exec(
1080 raise_exception_on_error
: bool = False,
1081 show_error_log
: bool = True,
1082 encode_utf8
: bool = False
1085 command
= K8sHelmConnector
._remove
_multiple
_spaces
(command
)
1086 self
.debug('Executing async local command: {}'.format(command
))
1089 command
= command
.split(sep
=' ')
1092 process
= await asyncio
.create_subprocess_exec(
1094 stdout
=asyncio
.subprocess
.PIPE
,
1095 stderr
=asyncio
.subprocess
.PIPE
1098 # wait for command terminate
1099 stdout
, stderr
= await process
.communicate()
1101 return_code
= process
.returncode
1105 output
= stdout
.decode('utf-8').strip()
1106 # output = stdout.decode()
1108 output
= stderr
.decode('utf-8').strip()
1109 # output = stderr.decode()
1111 if return_code
!= 0 and show_error_log
:
1112 self
.debug('Return code (FAIL): {}\nOutput:\n{}'.format(return_code
, output
))
1114 self
.debug('Return code: {}'.format(return_code
))
1116 if raise_exception_on_error
and return_code
!= 0:
1117 raise K8sException(output
)
1120 output
= output
.encode('utf-8').strip()
1121 output
= str(output
).replace('\\n', '\n')
1123 return output
, return_code
1125 except K8sException
:
1127 except Exception as e
:
1128 msg
= 'Exception executing command: {} -> {}'.format(command
, e
)
1130 if raise_exception_on_error
:
1131 raise K8sException(e
) from e
1144 command
= K8sHelmConnector
._remove
_multiple
_spaces
(command
)
1145 self
.debug('Executing sync remote ssh command: {}'.format(command
))
1147 ssh
= paramiko
.SSHClient()
1148 ssh
.set_missing_host_key_policy(paramiko
.AutoAddPolicy())
1149 ssh
.connect(hostname
=hostname
, username
=username
, password
=password
)
1150 ssh_stdin
, ssh_stdout
, ssh_stderr
= ssh
.exec_command(command
=command
, timeout
=timeout
)
1151 output
= ssh_stdout
.read().decode('utf-8')
1152 error
= ssh_stderr
.read().decode('utf-8')
1154 self
.error('ERROR: {}'.format(error
))
1158 output
= output
.replace('\\n', '\n')
1159 self
.debug('OUTPUT: {}'.format(output
))
1161 return output
, return_code
1163 def _check_file_exists(self
, filename
: str, exception_if_not_exists
: bool = False):
1164 self
.debug('Checking if file {} exists...'.format(filename
))
1165 if os
.path
.exists(filename
):
1168 msg
= 'File {} does not exist'.format(filename
)
1169 if exception_if_not_exists
:
1171 raise K8sException(msg
)