Initial commit
[ta/config-manager.git] / serviceprofiles / python / serviceprofiles / profiles.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 os
16 import re
17
18 class Profile(object):
19     def __init__(self):
20         self.name = None
21         self.description = None
22         self.inherits = []
23         self.included_profiles = []
24     def __str__(self):
25         return 'name:{}\ndescription:{}\ninherits:{}\nincluded_profiles:{}\n'.format(self.name, self.description, self.inherits, self.included_profiles)
26
27 class Profiles(object):
28     def __init__(self, location='/etc/service-profiles/'):
29         self.location = location
30         self.profiles = {}
31         self._load_profiles()
32
33     def _load_profiles(self):
34         files = self._get_profiles_files()
35         for f in files:
36             self._profile_from_file(f)
37
38         #update the included profiles
39         for name, profile in self.profiles.iteritems():
40             included_profiles = []
41             self._update_included_profiles(profile, included_profiles)
42             profile.included_profiles = included_profiles
43
44     def _update_included_profiles(self, profile, included_profiles):
45         included_profiles.append(profile.name)
46         for b in profile.inherits:
47             self._update_included_profiles(self.profiles[b], included_profiles)
48             
49     def _get_profiles_files(self):
50         files = os.listdir(self.location)
51         pattern = re.compile('.*[.]profile$')
52         result = []
53         for f in files:
54             fullpath = self.location + '/' + f
55             if os.path.isfile(fullpath) and pattern.match(f):
56                 result.append(fullpath)
57         return result
58
59     def _profile_from_file(self, filename):
60         profile = Profile()
61         with open(filename) as f:
62             lines=f.read().splitlines()
63             for l in lines:
64                 data = l.split(':')
65                 if len(data) != 2:
66                     raise Exception('Invalid line %s in file %s' % (l, filename))
67                 elif data[0] == 'name':
68                     profile.name = data[1]
69                 elif data[0] == 'description':
70                     profile.description = data[1]
71                 elif data[0] == 'inherits':
72                     profile.inherits = data[1].split(',')
73                 else:
74                     raise Exception('Invalid line %s in file %s' % (l, filename))
75         self.profiles[profile.name] = profile
76
77     def get_included_profiles(self, name):
78         return self.profiles[name].included_profiles
79
80     def get_profiles(self):
81         return self.profiles
82
83     def get_children_profiles(self, name):
84         ret = []
85         for pfname, profile in self.profiles.iteritems():
86             if name in profile.inherits:
87                 ret.append(pfname)
88         return ret
89
90     def get_service_profiles(self):
91         #profiles_files = self._get_profiles_files()
92         #profiles_names = [profile_file[:-len('.profile')] for profile_file in profiles_files]
93         profiles_names = self.profiles.keys()
94
95         return profiles_names
96
97     def get_node_service_profiles(self, name):
98         path = '/etc/service-profiles/config.ini'
99         profiles = []
100         with open(path) as f:
101             content = f.readlines()
102             for line in content:
103                 tmp = line.strip()
104                 node = tmp.split(':')[0]
105                 if node == name:
106                     profiles = tmp.split(':')[1].split(',')
107                     break
108         return profiles
109
110     @staticmethod
111     def get_management_service_profile():
112         return 'management'
113
114     @staticmethod
115     def get_base_service_profile():
116         return 'base'
117
118     @staticmethod
119     def get_controller_service_profile():
120         return 'controller'
121
122     @staticmethod
123     def get_caasmaster_service_profile():
124         return 'caas_master'
125
126     @staticmethod
127     def get_caasworker_service_profile():
128         return 'caas_worker'
129
130     @staticmethod
131     def get_compute_service_profile():
132         return 'compute'
133
134     @staticmethod
135     def get_storage_service_profile():
136         return 'storage'
137
138
139 if __name__ == '__main__':
140     import sys
141     import traceback
142     import argparse
143
144     parser = argparse.ArgumentParser(description='Test service profiles',
145             prog=sys.argv[0])
146
147     parser.add_argument('--location',
148             required=True,
149             metavar='LOCATION',
150             dest='location',
151             help='The location for service profile files',
152             type=str,
153             action='store')
154
155     parser.add_argument('--get-included-profiles',
156             dest='get_included_profiles',
157             help='Get the profiles included in some profile name',
158             action='store_true')
159
160     parser.add_argument('--get-all-profiles',
161             help='Get the profiles list',
162             dest='get_all_profiles',
163             action='store_true')
164
165     parser.add_argument('--get-children-profiles',
166             dest='get_children_profiles',
167             help='Get the children of a profile',
168             action='store_true')
169
170     parser.add_argument('--name',
171             metavar='NAME',
172             dest='name',
173             help='The name of the profile',
174             type=str,
175             action='store')
176     try:
177         args = parser.parse_args(sys.argv[1:])
178         location = args.location
179         profiles = Profiles(location)
180         if args.get_included_profiles or args.get_children_profiles:
181             if not args.name:
182                 raise Exception('Missing profile name')
183            
184             if args.get_included_profiles:
185                 included_profiles = profiles.get_included_profiles(args.name)
186                 print('Included profiles')
187                 for p in included_profiles:
188                     print(p)
189             if args.get_children_profiles:
190                 children_profiles = profiles.get_children_profiles(args.name)
191                 print('Children profiles')
192                 for p in children_profiles:
193                     print(p)
194         elif args.get_all_profiles:
195             all = profiles.get_profiles()
196             for name, p in all.iteritems():
197                 print(p)
198     except Exception as exp:
199         print('Failed with error %s' % exp)
200         traceback.print_exc()
201         sys.exit(1)