Merge "Remove Compass from genesis."
[genesis.git] / opensteak / tools / opensteak / foreman_objects / api.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 # @author: David Blaisonneau <david.blaisonneau@orange.com>
17 # @author: Arnaud Morin <arnaud1.morin@orange.com>
18
19 import json
20 import requests
21 from requests_futures.sessions import FuturesSession
22 from pprint import pformat
23
24
25 class Api:
26     """
27     Api class
28     Class to deal with the foreman API v2
29     """
30     def __init__(self, password, login='admin', ip='127.0.0.1', printErrors=False):
31         """ Function __init__
32         Init the API with the connection params
33
34         @param password: authentication password
35         @param password: authentication login - default is admin
36         @param ip: api ip - default is localhost
37         @return RETURN: self
38         """
39         self.base_url = 'http://{}/api/v2/'.format(ip)
40         self.headers = {'Accept': 'version=2',
41                         'Content-Type': 'application/json; charset=UTF-8'}
42         self.auth = (login, password)
43         self.errorMsg = ''
44         self.printErrors = printErrors
45
46     def list(self, obj, filter=False, only_id=False, limit=20):
47         """ Function list
48         Get the list of an object
49
50         @param obj: object name ('hosts', 'puppetclasses'...)
51         @param filter: filter for objects
52         @param only_id: boolean to only return dict with name/id
53         @return RETURN: the list of the object
54         """
55         self.url = '{}{}/?per_page={}'.format(self.base_url, obj, limit)
56         if filter:
57             self.url += '&search={}'.format(filter)
58         self.resp = requests.get(url=self.url, auth=self.auth,
59                                  headers=self.headers)
60         if only_id:
61             if self.__process_resp__(obj) is False:
62                 return False
63             if type(self.res['results']) is list:
64                 return dict((x['name'], x['id']) for x in self.res['results'])
65             elif type(self.res['results']) is dict:
66                 r = {}
67                 for v in self.res['results'].values():
68                     for vv in v:
69                         r[vv['name']] = vv['id']
70                 return r
71             else:
72                 return False
73         else:
74             return self.__process_resp__(obj)
75
76     def get(self, obj, id, sub_object=None):
77         """ Function get
78         Get an object by id
79
80         @param obj: object name ('hosts', 'puppetclasses'...)
81         @param id: the id of the object (name or id)
82         @return RETURN: the targeted object
83         """
84         self.url = '{}{}/{}'.format(self.base_url, obj, id)
85         if sub_object:
86             self.url += '/' + sub_object
87         self.resp = requests.get(url=self.url, auth=self.auth,
88                                  headers=self.headers)
89         if self.__process_resp__(obj):
90             return self.res
91         return False
92
93     def get_id_by_name(self, obj, name):
94         """ Function get_id_by_name
95         Get the id of an object
96
97         @param obj: object name ('hosts', 'puppetclasses'...)
98         @param id: the id of the object (name or id)
99         @return RETURN: the targeted object
100         """
101         list = self.list(obj, filter='name = "{}"'.format(name),
102                          only_id=True, limit=1)
103         return list[name] if name in list.keys() else False
104
105     def set(self, obj, id, payload, action='', async=False):
106         """ Function set
107         Set an object by id
108
109         @param obj: object name ('hosts', 'puppetclasses'...)
110         @param id: the id of the object (name or id)
111         @param action: specific action of an object ('power'...)
112         @param payload: the dict of the payload
113         @param async: should this request be async, if true use
114                         return.result() to get the response
115         @return RETURN: the server response
116         """
117         self.url = '{}{}/{}'.format(self.base_url, obj, id)
118         if action:
119             self.url += '/{}'.format(action)
120         self.payload = json.dumps(payload)
121         if async:
122             session = FuturesSession()
123             return session.put(url=self.url, auth=self.auth,
124                                headers=self.headers, data=self.payload)
125         else:
126             self.resp = requests.put(url=self.url, auth=self.auth,
127                                      headers=self.headers, data=self.payload)
128             if self.__process_resp__(obj):
129                 return self.res
130             return False
131
132     def create(self, obj, payload, async=False):
133         """ Function create
134         Create an new object
135
136         @param obj: object name ('hosts', 'puppetclasses'...)
137         @param payload: the dict of the payload
138         @param async: should this request be async, if true use
139                         return.result() to get the response
140         @return RETURN: the server response
141         """
142         self.url = self.base_url + obj
143         self.payload = json.dumps(payload)
144         if async:
145             session = FuturesSession()
146             return session.post(url=self.url, auth=self.auth,
147                                 headers=self.headers, data=self.payload)
148         else:
149             self.resp = requests.post(url=self.url, auth=self.auth,
150                                       headers=self.headers,
151                                       data=self.payload)
152             return self.__process_resp__(obj)
153
154     def delete(self, obj, id):
155         """ Function delete
156         Delete an object by id
157
158         @param obj: object name ('hosts', 'puppetclasses'...)
159         @param id: the id of the object (name or id)
160         @return RETURN: the server response
161         """
162         self.url = '{}{}/{}'.format(self.base_url, obj, id)
163         self.resp = requests.delete(url=self.url,
164                                     auth=self.auth,
165                                     headers=self.headers, )
166         return self.__process_resp__(obj)
167
168     def __process_resp__(self, obj):
169         """ Function __process_resp__
170         Process the response sent by the server and store the result
171
172         @param obj: object name ('hosts', 'puppetclasses'...)
173         @return RETURN: the server response
174         """
175         self.last_obj = obj
176         if self.resp.status_code > 299:
177             self.errorMsg = ">> Error {} for object '{}'".format(self.resp.status_code,
178                                                                  self.last_obj)
179             try:
180                 self.ret = json.loads(self.resp.text)
181                 self.errorMsg += pformat(self.ret[list(self.ret.keys())[0]])
182             except:
183                 self.ret = self.resp.text
184                 self.errorMsg += self.ret
185             if self.printErrors:
186                 print(self.errorMsg)
187             return False
188         self.res = json.loads(self.resp.text)
189         if 'results' in self.res.keys():
190             return self.res['results']
191         return self.res
192
193     def __str__(self):
194         ret = pformat(self.base_url) + "\n"
195         ret += pformat(self.headers) + "\n"
196         ret += pformat(self.auth) + "\n"
197         return ret