Enhance: Enable O2 DMS by exposing k8s API endpoint
[pti/o2.git] / o2dms / api / dms_lcm_view.py
1 # Copyright (C) 2021 Wind River Systems, Inc.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain 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,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14
15 import string
16 import random
17 import yaml
18 from datetime import datetime
19
20 # from sqlalchemy import select
21 from o2common.service import unit_of_work
22 # from o2ims.adapter.orm import deploymentmanager
23 from o2common.helper import o2logging
24 from o2common.config import config
25 logger = o2logging.get_logger(__name__)
26
27
28 def deployment_managers(uow: unit_of_work.AbstractUnitOfWork):
29     # with uow:
30     # res = uow.session.execute(select(deploymentmanager))
31     # return [dict(r) for r in res]
32     with uow:
33         li = uow.deployment_managers.list()
34     return [r.serialize() for r in li]
35
36
37 def deployment_manager_one(deploymentManagerId: str,
38                            uow: unit_of_work.AbstractUnitOfWork,
39                            profile: str = 'params'):
40     # with uow:
41     #     res = uow.session.execute(select(deploymentmanager).where(
42     #         deploymentmanager.c.deploymentManagerId == deploymentManagerId))
43     #     first = res.first()
44     # return None if first is None else dict(first)
45     # with uow:
46     # first = uow.deployment_managers.get(deploymentManagerId)
47     # return first.serialize() if first is not None else None
48     with uow:
49         first = uow.deployment_managers.get(deploymentManagerId)
50         if first is None:
51             return first
52         result = first.serialize()
53
54     if "params" == profile:
55         pass
56     elif "file" == profile and result.hasattr("profile"):
57         p = result.pop("profile", None)
58         result["profile"] = _gen_kube_config(deploymentManagerId, p)
59     else:
60         result.pop("profile", None)
61
62     return result
63
64
65 def _gen_kube_config(dmId: str, kubeconfig: dict) -> dict:
66
67     # KUBECONFIG environment variable
68     # reference:
69     # https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/
70     data = {
71         'apiVersion': 'v1',
72         'clusters': [
73             {
74                 'cluster': {
75                     'server':
76                     kubeconfig.pop('cluster_api_endpoint', None),
77                     'certificate-authority-data':
78                     kubeconfig.pop('cluster_ca_cert', None),
79                 },
80                 'name': 'inf-cluster'
81             }],
82         'contexts': [
83             {
84                 'context': {
85                     'cluster': 'inf-cluster',
86                     'user': 'kubernetes-admin'
87                 },
88                 'name': 'kubernetes-admin@inf-cluster'
89             }
90         ],
91         'current-context': 'kubernetes-admin@inf-cluster',
92         'kind': 'Config',
93         'preferences': {},
94         'users': [
95             {
96                 'name': kubeconfig.pop('admin_user', None),
97                 'user': {
98                     'client-certificate-data':
99                     kubeconfig.pop('admin_client_cert', None),
100                     'client-key-data':
101                     kubeconfig.pop('admin_client_key', None),
102                 }
103             }]
104     }
105
106     # Generate a random key for tmp kube config file
107     letters = string.ascii_uppercase
108     random_key = ''.join(random.choice(letters) for i in range(10))
109
110     # Get datetime of now as tag of the tmp file
111     current_time = datetime.now().strftime("%Y%m%d%H%M%S")
112     tmp_file_name = random_key + "_" + current_time
113
114     # write down the yaml file of kubectl into tmp folder
115     with open('/tmp/kubeconfig_' + tmp_file_name, 'w') as file:
116         yaml.dump(data, file)
117
118     kubeconfig["kube_config_file"] = config.get_api_url() + \
119         config.get_o2dms_api_base() + "/" + dmId + "/download/" + tmp_file_name
120
121     return kubeconfig