03d0827e64ebfbc91d4c82290509bcf31137a6e2
[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
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         status = xApp.install_chart_package(xapp_chart_name=xapp_chart_name, version=version, namespace=namespace,overridefile=overridefile)
99         if status == 1:
100            return {"status": "OK"}
101         else:
102            return {"status": "NOT_OK"} 
103
104     def uninstall(self, xapp_chart_name ,namespace):
105         """Uninstalling the xapp using the charts name"""
106         status = xApp.uninstall_chart_package(xapp_chart_name=xapp_chart_name, namespace=namespace)
107         if status == 1:
108            return {"status": "OK"}
109         else:
110            print("No Xapp to uninstall")
111            return {"status": "NOT_OK"}
112
113     def upgrade(self, xapp_chart_name, old_version , new_version, namespace):
114         """Upgrading the xapp to the new version specified"""
115         resp = self.uninstall(xapp_chart_name, namespace) 
116         if resp["status"] == "OK":
117            status = self.install(xapp_chart_name, new_version, namespace)
118            if status["status"] == "OK":
119               return {"status": "OK"}
120            else:
121               self.uninstall(xapp_chart_name, namespace)
122               self.install(xapp_chart_name, old_version, namespace)
123               return {"status": "NOT_OK"}
124         else:
125            return {"status": "NOT_OK"}
126
127     def rollback(self, xapp_chart_name, new_version , old_version, namespace):
128         """Rollback the xapp to the version specified"""
129
130         resp = self.upgrade(xapp_chart_name, new_version, old_version, namespace) 
131
132         if resp["status"] == "OK":
133             return {"status": "OK"}
134         else:
135             return {"status": "NOT_OK"}
136
137     def onboard(self, config_file_path, shcema_file_path="../../../docs/xapp_onboarder/guide/embedded-schema.json"):
138         """Onboard an xApp with local descriptor files. Use --config_file_path to specify the path to
139         config-file.json file, --shcema_file_path to specify the path to schema.json file. """
140         try:
141             with open(config_file_path, 'r') as inputfile:
142                 config_file = json.load(inputfile)
143
144             with open(shcema_file_path, 'r') as inputfile:
145                 schema_file = json.load(inputfile)
146
147         except Exception as err:
148             return err
149
150         message, status = onboard(config_file, schema_file)
151         return json.dumps(message, indent=4, sort_keys=True)
152
153     def download_and_onboard(self, config_file_url, schema_file_url):
154         """Onboard an xApp with URLs pointing to the xApp descriptor files. Use --config_file_url to specify the
155         config-file.json URL, --schema_file_url to specify the schema.json URL. """
156         message, status = download_config_and_schema_and_onboard(config_file_url, schema_file_url)
157         return json.dumps(message, indent=4, sort_keys=True)
158     
159     def health_check(self, xapp_chart_name ,namespace):
160         """status check of the xapp using the charts name"""
161         xApp.health_check_xapp(xapp_chart_name=xapp_chart_name, namespace=namespace)
162
163
164 def run():
165     logger_config = pkg_resources.resource_filename("xapp_onboarder", 'logging.conf')
166     logging.config.fileConfig(logger_config)
167     fire.Fire(cli(), name='xapp_onboarder')
168
169 if __name__ == "__main__":
170
171     run()