Merge "Remove Compass from genesis."
[genesis.git] / opensteak / tools / opensteak / foreman_objects / item.py
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #    not use this file except in compliance with the License. You may obtain
5 #    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, WITHOUT
11 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #    License for the specific language governing permissions and limitations
13 #    under the License.
14 #
15 #    Authors:
16 #     David Blaisonneau <david.blaisonneau@orange.com>
17 #     Arnaud Morin <arnaud1.morin@orange.com>
18
19 from pprint import pprint as pp
20
21
22 class ForemanItem(dict):
23     """
24     Item class
25     Represent the content of a foreman object as a dict
26     """
27
28     def __init__(self, api, key,
29                  objName, payloadObj,
30                  *args, **kwargs):
31         """ Function __init__
32         Represent the content of a foreman object as a dict
33
34         @param api: The foreman api
35         @param key: The object Key
36         @param *args, **kwargs: the dict representation
37         @return RETURN: Itself
38         """
39         self.api = api
40         self.key = key
41         if objName:
42             self.objName = objName
43         if payloadObj:
44             self.payloadObj = payloadObj
45         self.store = dict()
46         if args[0]:
47             self.update(dict(*args, **kwargs))
48         # We get the smart class parameters for the good items
49         if objName in ['hosts', 'hostgroups',
50                        'puppet_classes', 'environments']:
51             from opensteak.foreman_objects.itemSmartClassParameter\
52                 import ItemSmartClassParameter
53             scp_ids = map(lambda x: x['id'],
54                           self.api.list('{}/{}/smart_class_parameters'
55                                         .format(self.objName, key)))
56             scp_items = list(map(lambda x: ItemSmartClassParameter(self.api, x,
57                                  self.api.get('smart_class_parameters', x)),
58                                  scp_ids))
59             scp = {'{}::{}'.format(x['puppetclass']['name'],
60                                    x['parameter']): x
61                    for x in scp_items}
62             self.update({'smart_class_parameters_dict': scp})
63
64     def __setitem__(self, key, attributes):
65         """ Function __setitem__
66         Set a parameter of a foreman object as a dict
67
68         @param key: The key to modify
69         @param attribute: The data
70         @return RETURN: The API result
71         """
72         if key is 'puppetclass_ids':
73             payload = {"puppetclass_id": attributes,
74                        self.payloadObj + "_class":
75                            {"puppetclass_id": attributes}}
76             return self.api.create("{}/{}/{}"
77                                    .format(self.objName,
78                                            self.key,
79                                            "puppetclass_ids"),
80                                    payload)
81         elif key is 'parameters':
82             payload = {"parameter": attributes}
83             return self.api.create("{}/{}/{}"
84                                    .format(self.objName,
85                                            self.key,
86                                            "parameters"),
87                                    payload)
88         else:
89             payload = {self.payloadObj: {key: attributes}}
90             return self.api.set(self.objName, self.key, payload)
91
92     def getParam(self, name=None):
93         """ Function getParam
94         Return a dict of parameters or a parameter value
95
96         @param key: The parameter name
97         @return RETURN: dict of parameters or a parameter value
98         """
99         if 'parameters' in self.keys():
100             l = {x['name']: x['value'] for x in self['parameters']}
101             if name:
102                 if name in l.keys():
103                     return l[name]
104                 else:
105                     return False
106             else:
107                 return l
108
109     def checkAndCreateClasses(self, classes):
110         """ Function checkAndCreateClasses
111         Check and add puppet classe
112
113         @param key: The parameter name
114         @param classes: The classes ids list
115         @return RETURN: boolean
116         """
117         actual_classes = self['puppetclass_ids']
118         for v in classes:
119             if v not in actual_classes:
120                 self['puppetclass_ids'] = v
121         return list(classes).sort() is list(self['puppetclass_ids']).sort()
122
123     def checkAndCreateParams(self, params):
124         """ Function checkAndCreateParams
125         Check and add global parameters
126
127         @param key: The parameter name
128         @param params: The params dict
129         @return RETURN: boolean
130         """
131         actual_params = self['param_ids']
132         for k, v in params.items():
133             if k not in actual_params:
134                 self['parameters'] = {"name": k, "value": v}
135         return self['param_ids'].sort() == list(params.values()).sort()