Add explicit CM dependencies
[ta/config-manager.git] / cmdatahandlers / src / cmdatahandlers / api / configmanager.py
1 # Copyright 2019 Nokia
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 json
16 import os
17 import sys
18 import inspect
19 import imp
20 import types
21 import argparse
22
23 from cmdatahandlers.api import configerror
24
25 class ConfigManager(object):
26     #This needs to be updated when new domain are introduced, a getter function
27     #should be added to the domain config handler
28     """
29     def __init__(self, schema, configjson):
30         #validate according to schema
31         try:
32             self.configjson = configjson
33             builder = pjo.ObjectBuilder(schema)
34             ns = builder.build_classes()
35             self.config = ns.Config(**configjson)
36             self._load_config_handlers()
37         except Exception as exp:
38             raise configerror.ConfigError(str(exp))
39     """
40
41     def __init__(self, configjson):
42         #validate according to schema
43         self.configmap = {}
44         try:
45             self.configjson = configjson
46             self._load_config_handlers()
47         except Exception as exp:
48             raise configerror.ConfigError(str(exp))
49
50     def get_config(self):
51         return self.configjson
52
53     def get_cloud_name(self):
54         if 'cloud.name' not in self.configjson:
55             raise configerror.ConfigError('Cloud name not defined')
56
57         return self.configjson['cloud.name']
58
59     def get_cloud_description(self):
60         if 'cloud.description' not in self.configjson:
61             raise configerror.ConfigError('Cloud description not defined')
62         return self.configjson['cloud.description']
63
64     def get_cloud_installation_date(self):
65         if 'cloud.installation_date' not in self.configjson:
66             raise configerror.ConfigError('Cloud installation date is not defined')
67         return self.configjson['cloud.installation_date']
68
69     def get_cloud_installation_phase(self):
70         if 'cloud.installation_phase' not in self.configjson:
71             raise configerror.ConfigError('Cloud installation phase is not defined')
72         return self.configjson['cloud.installation_phase']
73
74     def _load_config_handlers(self):
75         myfolder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
76         dirn = os.path.dirname(myfolder)
77         basen = os.path.basename(myfolder)
78
79         for d in os.listdir(dirn):
80             if d == basen:
81                 continue
82             if not os.path.isdir(dirn + '/' + d):
83                 continue
84
85             configmodule = dirn + '/' + d + '/config.py'
86
87
88             if not os.path.isfile(configmodule):
89                 continue
90
91             mod = imp.load_source(d, configmodule)
92
93             config = mod.Config(self)
94
95             domain = config.get_domain()
96
97             self.configmap[domain] = config
98
99             domhandlerfunc = 'get_' + domain + '_config_handler'
100
101             setattr(self, domhandlerfunc, types.MethodType(self._get_domain_config_handler, domain))
102
103
104         #finalize initialization after objects are created
105         #this is needed to handle inter-handler dependencies
106         for domain, handler in self.configmap.iteritems():
107             handler.init()
108
109
110
111     def _get_domain_config_handler(self, domain):
112         if domain not in self.configmap:
113             raise configerror.ConfigError('Invalid domain')
114
115         return self.configmap[domain]
116
117
118     def mask_sensitive_data(self):
119         for handler in self.configmap.values():
120             try:
121                 handler.validate_root()
122             except configerror.ConfigError:
123                 continue
124
125             handler.mask_sensitive_data()
126
127 if __name__ == '__main__':
128     parser = argparse.ArgumentParser(description='Config Manager', prog=sys.argv[0])
129
130     parser.add_argument('--domain',
131                         required=True,
132                         dest='domain',
133                         metavar='DOMAIN',
134                         help='The configuration domain',
135                         type=str,
136                         action='store')
137
138     parser.add_argument('--json',
139                         required=True,
140                         dest='jsonfile',
141                         metavar='JSONFILE',
142                         help='The json file containing the configuration',
143                         type=str,
144                         action='store')
145
146     parser.add_argument('--api',
147                         required=True,
148                         dest='api',
149                         metavar='API',
150                         help='The API to call in the domain',
151                         type=str,
152                         action='store')
153
154     parser.add_argument('--dump',
155                         required=False,
156                         dest='dump',
157                         help='Dump the configuration',
158                         action='store_true')
159
160     args, unknownargs = parser.parse_known_args(sys.argv[1:])
161     print("args = %r" % args)
162     print("unknownargs = %r" % unknownargs)
163     f = open(args.jsonfile)
164     data = json.load(f)
165     f.close()
166     manager = ConfigManager(data)
167     #domain handler func
168     funcname = 'get_'+args.domain+'_config_handler'
169     objfunc = getattr(manager, funcname)
170     obj = objfunc()
171     print('Got handler for %s' % obj.get_domain())
172
173     domainfunc = getattr(obj, args.api)
174     result = None
175     if unknownargs:
176         result = domainfunc(*unknownargs)
177     else:
178         result = domainfunc()
179     print("result is %r" % result)
180
181     if args.dump:
182         import pprint
183         pp = pprint.PrettyPrinter(indent=4)
184         pp.pprint(data)