summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/ansible/ansible_runner_svc.py
blob: 636e20b0fdcde5b42c9e8e3a76d9ee13deab59a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""
Client module to interact with the Ansible Runner Service
"""
import requests
import json
import re
from functools import wraps

# Ansible Runner service API endpoints
API_URL = "api"
LOGIN_URL = "api/v1/login"
PLAYBOOK_EXEC_URL = "api/v1/playbooks"
PLAYBOOK_EVENTS = "api/v1/jobs/%s/events"
EVENT_DATA_URL = "api/v1/jobs/%s/events/%s"

class AnsibleRunnerServiceError(Exception):
    pass

def handle_requests_exceptions(func):
    """Decorator to manage errors raised by requests library
    """
    @wraps(func)
    def inner(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except requests.exceptions.RequestException as ex:
               raise AnsibleRunnerServiceError(str(ex))
    return inner

class ExecutionStatusCode(object):
    """Execution status of playbooks ( 'msg' field in playbook status request)
    """

    SUCCESS = 0   # Playbook has been executed succesfully" msg = successful
    ERROR = 1     # Playbook has finished with error        msg = failed
    ON_GOING = 2  # Playbook is being executed              msg = running
    NOT_LAUNCHED = 3  # Not initialized

class PlayBookExecution(object):
    """Object to provide all the results of a Playbook execution
    """

    def __init__(self, rest_client, playbook, logger, result_pattern="",
                 the_params=None,
                 querystr_dict=None):

        self.rest_client = rest_client

        # Identifier of the playbook execution
        self.play_uuid = "-"

        # Pattern used to extract the result from the events
        self.result_task_pattern = result_pattern

        # Playbook name
        self.playbook = playbook

        # Parameters used in the playbook
        self.params = the_params

        # Query string used in the "launch" request
        self.querystr_dict = querystr_dict

        # Logger
        self.log = logger

    def launch(self):
        """ Launch the playbook execution
        """

        response = None
        endpoint = "%s/%s" % (PLAYBOOK_EXEC_URL, self.playbook)

        try:
            response = self.rest_client.http_post(endpoint,
                                                    self.params,
                                                    self.querystr_dict)
        except AnsibleRunnerServiceError:
            self.log.exception("Error launching playbook <%s>", self.playbook)
            raise

        # Here we have a server response, but an error trying
        # to launch the playbook is also posible (ex. 404, playbook not found)
        # Error already logged by rest_client, but an error should be raised
        # to the orchestrator (via completion object)
        if response.ok:
            self.play_uuid = json.loads(response.text)["data"]["play_uuid"]
            self.log.info("Playbook execution launched succesfuly")
        else:
            raise AnsibleRunnerServiceError(response.reason)

    def get_status(self):
        """ Return the status of the execution

        In the msg field of the respons we can find:
            "msg": "successful"
            "msg": "running"
            "msg": "failed"
        """

        status_value = ExecutionStatusCode.NOT_LAUNCHED
        response = None

        if self.play_uuid == '-': # Initialized
            status_value = ExecutionStatusCode.NOT_LAUNCHED
        elif self.play_uuid == '': # Error launching playbook
            status_value = ExecutionStatusCode.ERROR
        else:
            endpoint = "%s/%s" % (PLAYBOOK_EXEC_URL, self.play_uuid)

            try:
                response = self.rest_client.http_get(endpoint)
            except AnsibleRunnerServiceError:
                self.log.exception("Error getting playbook <%s> status",
                                   self.playbook)

            if response:
                the_status = json.loads(response.text)["msg"]
                if the_status == 'successful':
                    status_value = ExecutionStatusCode.SUCCESS
                elif the_status == 'failed':
                    status_value = ExecutionStatusCode.ERROR
                else:
                    status_value = ExecutionStatusCode.ON_GOING
            else:
                status_value = ExecutionStatusCode.ERROR

        self.log.info("Requested playbook execution status is: %s", status_value)
        return status_value

    def get_result(self, event_filter=""):
        """Get the data of the events filtered by a task pattern and
        a event filter

        @returns: the events that matches with the patterns provided
        """
        response = None
        if not self.play_uuid:
            return {}

        try:
            response = self.rest_client.http_get(PLAYBOOK_EVENTS % self.play_uuid)
        except AnsibleRunnerServiceError:
            self.log.exception("Error getting playbook <%s> result", self.playbook)

        if not response:
            result_events = {}
        else:
            events = json.loads(response.text)["data"]["events"]

            if self.result_task_pattern:
                result_events = {event:data for event,data in events.items()
                                if "task" in data and
                                re.match(self.result_task_pattern, data["task"])}
            else:
                result_events = events

            if event_filter:
                result_events = {event:data for event,data in result_events.items()
                                if re.match(event_filter, data['event'])}

        self.log.info("Requested playbook result is: %s", json.dumps(result_events))
        return result_events

class Client(object):
    """An utility object that allows to connect with the Ansible runner service
    and execute easily playbooks
    """

    def __init__(self, server_url, user, password, verify_server, logger):
        """Provide an https client to make easy interact with the Ansible
        Runner Service"

        :param servers_url: The base URL >server>:<port> of the Ansible Runner Service
        :param user: Username of the authorized user
        :param password: Password of the authorized user
        :param verify_server: Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
        :param logger: Log file
        """
        self.server_url = server_url
        self.user = user
        self.password = password
        self.log = logger
        self.auth = (self.user, self.password)
        if not verify_server:
            self.verify_server = True
        elif verify_server.lower().strip() == 'false':
            self.verify_server = False
        else:
            self.verify_server = verify_server

        # Once authenticated this token will be used in all the requests
        self.token = ""

        self.server_url = "https://{0}".format(self.server_url)

        # Log in the server and get a token
        self.login()

    @handle_requests_exceptions
    def login(self):
        """ Login with user credentials to obtain a valid token
        """

        the_url = "%s/%s" % (self.server_url, LOGIN_URL)
        response = requests.get(the_url,
                                auth = self.auth,
                                verify = self.verify_server)

        if response.status_code != requests.codes.ok:
            self.log.error("login error <<%s>> (%s):%s",
                            the_url, response.status_code, response.text)
        else:
            self.log.info("login succesful <<%s>> (%s):%s",
                            the_url, response.status_code, response.text)

        if response:
            self.token = json.loads(response.text)["data"]["token"]
            self.log.info("Connection with Ansible Runner Service is operative")

    @handle_requests_exceptions
    def is_operative(self):
        """Indicates if the connection with the Ansible runner Server is ok
        """

        # No Token... this means we haven't used yet the service.
        if not self.token:
            return False

        # Check the service
        response = self.http_get(API_URL)

        if response:
            return response.status_code == requests.codes.ok
        else:
            return False

    @handle_requests_exceptions
    def http_get(self, endpoint):
        """Execute an http get request

        :param endpoint: Ansible Runner service RESTful API endpoint

        :returns: A requests object
        """

        the_url = "%s/%s" % (self.server_url, endpoint)
        response = requests.get(the_url,
                            verify = self.verify_server,
                            headers = {"Authorization": self.token})

        if response.status_code != requests.codes.ok:
            self.log.error("http GET %s <--> (%s - %s)\n%s",
                            the_url, response.status_code, response.reason,
                            response.text)
        else:
            self.log.info("http GET %s <--> (%s - %s)",
                            the_url, response.status_code, response.text)

        return response

    @handle_requests_exceptions
    def http_post(self, endpoint, payload, params_dict):
        """Execute an http post request

        :param endpoint: Ansible Runner service RESTful API endpoint
        :param payload: Dictionary with the data used in the post request
        :param params_dict: A dict used to build a query string

        :returns: A requests object
        """

        the_url = "%s/%s" % (self.server_url, endpoint)
        response = requests.post(the_url,
                            verify = self.verify_server,
                            headers = {"Authorization": self.token,
                                        "Content-type": "application/json"},
                            json = payload,
                            params = params_dict)

        if response.status_code != requests.codes.ok:
            self.log.error("http POST %s [%s] <--> (%s - %s:%s)\n",
                            the_url, payload, response.status_code,
                            response.reason, response.text)
        else:
            self.log.info("http POST %s <--> (%s - %s)",
                            the_url, response.status_code, response.text)

        return response

    @handle_requests_exceptions
    def http_delete(self, endpoint):
        """Execute an http delete request

        :param endpoint: Ansible Runner service RESTful API endpoint

        :returns: A requests object
        """

        the_url = "%s/%s" % (self.server_url, endpoint)
        response = requests.delete(the_url,
                            verify = self.verify_server,
                            headers = {"Authorization": self.token})

        if response.status_code != requests.codes.ok:
            self.log.error("http DELETE %s <--> (%s - %s)\n%s",
                            the_url, response.status_code, response.reason,
                            response.text)
        else:
            self.log.info("http DELETE %s <--> (%s - %s)",
                            the_url, response.status_code, response.text)

        return response

    def http_put(self, endpoint, payload):
        """Execute an http put request

        :param endpoint: Ansible Runner service RESTful API endpoint
        :param payload: Dictionary with the data used in the put request

        :returns: A requests object
        """
        # TODO
        raise NotImplementedError("TODO")