Initial commit
[ta/config-manager.git] / cmdatahandlers / tests / mocked_dependencies / 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 import inspect
18
19 class Profile(object):
20     def __init__(self):
21         self.name = None
22         self.description = None
23         self.inherits = []
24         self.included_profiles = []
25     def __str__(self):
26         return 'name:{}\ndescription:{}\ninherits:{}\nincluded_profiles:{}\n'.format(self.name, self.description, self.inherits, self.included_profiles)
27
28 class Profiles(object):
29     def __init__(self, location=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))):
30         self.location = location
31         self.profiles = {}
32         try:
33             self._load_profiles()
34         except:
35             pass
36
37     def _load_profiles(self):
38         files = self._get_profiles_files()
39         for f in files:
40             self._profile_from_file(f)
41
42         #update the included profiles
43         for name, profile in self.profiles.iteritems():
44             included_profiles = []
45             self._update_included_profiles(profile, included_profiles)
46             profile.included_profiles = included_profiles
47
48
49     def _update_included_profiles(self, profile, included_profiles):
50         included_profiles.append(profile.name)
51         for b in profile.inherits:
52             self._update_included_profiles(self.profiles[b], included_profiles)
53             
54     def _get_profiles_files(self):
55         files = os.listdir(self.location)
56         pattern = re.compile('.*[.]profile$')
57         result = []
58         for f in files:
59             fullpath = self.location + '/' + f
60             if os.path.isfile(fullpath) and pattern.match(f):
61                 result.append(fullpath)
62         return result
63
64
65
66     def _profile_from_file(self, filename):
67         profile = Profile()
68         with open(filename) as f:
69             lines=f.read().splitlines()
70             for l in lines:
71                 data = l.split(':')
72                 if len(data) != 2:
73                     raise Exception('Invalid line %s in file %s' % (l, filename))
74                 elif data[0] == 'name':
75                     profile.name = data[1]
76                 elif data[0] == 'description':
77                     profile.description = data[1]
78                 elif data[0] == 'inherits':
79                     profile.inherits = data[1].split(',')
80                 else:
81                     raise Exception('Invalid line %s in file %s' % (l, filename))
82         self.profiles[profile.name] = profile
83
84     def get_included_profiles(self, name):
85         return self.profiles[name].included_profiles
86
87     def get_profiles(self):
88         return self.profiles
89
90     def get_children_profiles(self, name):
91         ret = []
92         for pfname, profile in self.profiles.iteritems():
93             if name in profile.inherits:
94                 ret.append(pfname)
95         return ret
96
97
98 if __name__ == '__main__':
99     import sys
100     import traceback
101     import argparse
102
103     parser = argparse.ArgumentParser(description='Test service profiles',
104             prog=sys.argv[0])
105
106
107     parser.add_argument('--get-included-profiles',
108             dest='get_included_profiles',
109             help='Get the profiles included in some profile name',
110             action='store_true')
111
112     parser.add_argument('--get-all-profiles',
113             help='Get the profiles list',
114             dest='get_all_profiles',
115             action='store_true')
116
117     parser.add_argument('--get-children-profiles',
118             dest='get_children_profiles',
119             help='Get the children of a profile',
120             action='store_true')
121
122     parser.add_argument('--name',
123             metavar='NAME',
124             dest='name',
125             help='The name of the profile',
126             type=str,
127             action='store')
128     try:
129         args = parser.parse_args(sys.argv[1:])
130         profiles = Profiles()
131         if args.get_included_profiles or args.get_children_profiles:
132             if not args.name:
133                 raise Exception('Missing profile name')
134            
135             if args.get_included_profiles:
136                 included_profiles = profiles.get_included_profiles(args.name)
137                 print('Included profiles')
138                 for p in included_profiles:
139                     print(p)
140             if args.get_children_profiles:
141                 children_profiles = profiles.get_children_profiles(args.name)
142                 print('Children profiles')
143                 for p in children_profiles:
144                     print(p)
145         elif args.get_all_profiles:
146             all = profiles.get_profiles()
147             for name, p in all.iteritems():
148                 print(p)
149     except Exception as exp:
150         print('Failed with error %s' % exp)
151         traceback.print_exc()
152         sys.exit(1)