aa582672f3ccaa6e47b3a4856ce85c077e08f306
[ric-plt/appmgr.git] / xapp_orchestrater / dev / xapp_onboarder / xapp_onboarder / server / cli.py
1 ################################################################################
2 #   Copyright (c) 2020 AT&T Intellectual Property.                             #
3 #                                                                              #
4 #   Licensed under the Apache License, Version 2.0 (the "License");            #
5 #   you may not use this file except in compliance with the License.           #
6 #   You may obtain a copy of the License at                                    #
7 #                                                                              #
8 #       http://www.apache.org/licenses/LICENSE-2.0                             #
9 #                                                                              #
10 #   Unless required by applicable law or agreed to in writing, software        #
11 #   distributed under the License is distributed on an "AS IS" BASIS,          #
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
13 #   See the License for the specific language governing permissions and        #
14 #   limitations under the License.                                             #
15 ################################################################################
16
17
18 import fire
19 import json
20 import os
21 import pkg_resources
22 import logging.config
23 import operator
24
25 from xapp_onboarder.api.charts import get_charts_list, download_chart_package, download_values_yaml
26 from xapp_onboarder.repo_manager.repo_manager import repo_manager
27 from xapp_onboarder.api.onboard import onboard, download_config_and_schema_and_onboard
28 from xapp_onboarder.helm_controller.xApp_builder import xApp, xAppError
29
30 log = logging.getLogger(__name__)
31
32
33 class cli():
34     """This is the cli tool for xapp_onboarder."""
35
36     def get_charts_list(self, xapp_chart_name=''):
37         """Get the list of all onboarded xApps. To show all version of an xApp, use --xapp_chart_name to
38         specify the name."""
39         message, status = get_charts_list(xapp_chart_name=xapp_chart_name)
40
41         return json.dumps(message, indent=4, sort_keys=True)
42
43     def download_helm_chart(self, xapp_chart_name, version, output_path="."):
44         """Download the helm chart package of an xApp. Specify xApp name with --xapp_chart_name, version with
45         --version. Optionally use --output_path to specify the path to save the file."""
46         content, status = download_chart_package(xapp_chart_name=xapp_chart_name, version=version)
47
48         if status != 200:
49             #return json.dumps(content, indent=4, sort_keys=True)
50             return {"status": "NOT_OK"}
51         try:
52             if os.path.isabs(output_path):
53                 path = output_path + '/' + xapp_chart_name + '-' + version + '.tgz'
54             else:
55                 path = os.getcwd() + '/' + output_path + '/' + xapp_chart_name + '-' + version + '.tgz'
56
57             if not os.path.exists(os.path.dirname(path)):
58                 os.makedirs(os.path.dirname(path))
59
60             with open(path, 'wb') as outputfile:
61                 outputfile.write(content)
62         except Exception as err:
63             return err
64         return {"status": "OK"}
65
66     def download_values_yaml(self, xapp_chart_name, version, output_path="."):
67         """Download the values.yaml file that can be used to override parameters at runtime. Specify xApp name with
68         --xapp_chart_name, version with --version. Optionally use --output_path to specify the path to save the file.
69         """
70         content, status = download_values_yaml(xapp_chart_name=xapp_chart_name, version=version)
71
72         if status != 200:
73             return json.dumps(content, indent=4, sort_keys=True)
74
75         try:
76             if os.path.isabs(output_path):
77                 path = output_path + '/values.yaml'
78             else:
79                 path = os.getcwd() + '/' + output_path + '/values.yaml'
80
81             if not os.path.exists(os.path.dirname(path)):
82                 os.makedirs(os.path.dirname(path))
83
84             with open(path, 'wb') as outputfile:
85                 outputfile.write(content)
86         except Exception as err:
87             return err
88         return {"status": "OK"}
89
90     def health(self):
91         """Health check. If xapp onboarder is not ready, it return false."""
92         return repo_manager.is_repo_ready()
93
94     def install(self, xapp_chart_name, version, namespace,overridefile="" ):
95         """Installing the xapp using the charts name and version,optionally can provide the yaml file to override"""
96         resp = self.download_helm_chart(xapp_chart_name, version)
97
98         if resp['status'] == "NOT_OK":
99             return {"status": "Not OK"}
100         status = xApp.install_chart_package(xapp_chart_name=xapp_chart_name, version=version, namespace=namespace,overridefile=overridefile)
101         if status == 1:
102            return {"status": "OK"}
103         else:
104            return {"status": "NOT_OK"} 
105
106     def uninstall(self, xapp_chart_name, namespace, version=""):
107         """Uninstalling the xapp using the charts name, --version can be provided optionally"""
108         status = xApp.uninstall_chart_package(xapp_chart_name=xapp_chart_name, namespace=namespace, version=version)
109         if status == 1:
110            return {"status": "OK"}
111         else:
112            print("No Xapp to uninstall")
113            return {"status": "NOT_OK"}
114
115     def upgrade(self, xapp_chart_name, old_version , new_version, namespace):
116         """Upgrading the xapp to the new version specified"""
117         resp = self.uninstall(xapp_chart_name, namespace,old_version) 
118         if resp["status"] == "OK":
119            status = self.install(xapp_chart_name, new_version, namespace)
120            if status["status"] == "OK":
121               return {"status": "OK"}
122            else:
123               self.uninstall(xapp_chart_name, namespace,new_version)
124               self.install(xapp_chart_name, old_version, namespace)
125               return {"status": "NOT_OK"}
126         else:
127            return {"status": "NOT_OK"}
128
129     def rollback(self, xapp_chart_name, new_version , old_version, namespace):
130         """Rollback the xapp to the version specified"""
131
132         resp = self.upgrade(xapp_chart_name, new_version, old_version, namespace) 
133
134         if resp["status"] == "OK":
135             return {"status": "OK"}
136         else:
137             return {"status": "NOT_OK"}
138
139     def onboard(self, config_file_path, shcema_file_path="../../../docs/xapp_onboarder/guide/embedded-schema.json"):
140         """Onboard an xApp with local descriptor files. Use --config_file_path to specify the path to
141         config-file.json file, --shcema_file_path to specify the path to schema.json file. """
142         try:
143             with open(config_file_path, 'r') as inputfile:
144                 config_file = json.load(inputfile)
145
146             with open(shcema_file_path, 'r') as inputfile:
147                 schema_file = json.load(inputfile)
148
149         except Exception as err:
150             return err
151
152         message, status = onboard(config_file, schema_file)
153         return json.dumps(message, indent=4, sort_keys=True)
154
155     def download_and_onboard(self, config_file_url, schema_file_url):
156         """Onboard an xApp with URLs pointing to the xApp descriptor files. Use --config_file_url to specify the
157         config-file.json URL, --schema_file_url to specify the schema.json URL. """
158         message, status = download_config_and_schema_and_onboard(config_file_url, schema_file_url)
159         return json.dumps(message, indent=4, sort_keys=True)
160     
161     def health_check(self, xapp_chart_name ,namespace):
162         """status check of the xapp using the charts name"""
163         xApp.health_check_xapp(xapp_chart_name=xapp_chart_name, namespace=namespace)
164
165
166 def run():
167     logger_config = pkg_resources.resource_filename("xapp_onboarder", 'logging.conf')
168     logging.config.fileConfig(logger_config)
169     fire.Fire(cli(), name='xapp_onboarder')
170
171 if __name__ == "__main__":
172
173     run()