aboutsummaryrefslogtreecommitdiffstats
path: root/moon_manager/moon_manager/api/slave.py
blob: a0201bdb08bfe5a41457e70f6541d66d10818547 (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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# Software Name: MOON

# Version: 5.4

# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors
# SPDX-License-Identifier: Apache-2.0

# This software is distributed under the 'Apache License 2.0',
# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt'
# or see the "LICENSE" file for more details.

"""
Slaves are endpoint for external connectors like OpenStack

"""

import logging
import hug
import os
import requests
from moon_manager.api import ERROR_CODE
from moon_manager import db_driver
from moon_manager import orchestration_driver
from moon_manager.api import configuration
from moon_utilities import exceptions
from moon_utilities.auth_functions import init_db, api_key_authentication, connect_from_env

LOGGER = logging.getLogger("moon.manager.api." + __name__)


class Slaves(object):
    """
    Endpoint for slave requests
    """

    @staticmethod
    @hug.local()
    @hug.get("/slaves/", requires=api_key_authentication)
    @hug.get("/slaves/{uuid}", requires=api_key_authentication)
    def get(uuid: hug.types.uuid = None, authed_user: hug.directives.user = None):
        """Retrieve all slaves

        :param uuid: uuid of the pdp
        :return: {
            "slaves": {
                "XXX": {
                    "name": "...",
                    "address": "..."
                },
                "YYY": {
                    "name": "...",
                    "address": "..."
                }
            }
        }
        """
        if uuid:
            uuid = str(uuid).replace("-", "")
        data = db_driver.SlaveManager.get_slaves(moon_user_id=authed_user)

        return {"slaves": data}

    @staticmethod
    @hug.local()
    @hug.post("/slave/", requires=api_key_authentication)
    def post(body, response, authed_user: hug.directives.user = None):
        """Create a slave.

        :request body: {
            "name": "name of the slave (mandatory)",
            "address": "local_or_ssh://a.b.c.d",
            "description": "description of the slave (optional)",
        }
        :return: {
            "slaves": {
                "XXX": {
                    "name": "...",
                    "address": "..."
                },
                "YYY": {
                    "name": "...",
                    "address": "..."
                }
            }
        }
        """
        try:
            # Create the DB item
            data = db_driver.SlaveManager.add_slave(
                moon_user_id=authed_user, slave_id=None, value=body)

            uuid = list(data.keys())[0]
            # Build and run the process
            new_data = orchestration_driver.SlaveManager.add_slave(moon_user_id=authed_user,
                                                                   slave_id=uuid, data=data[uuid])

            # Update the DB item with the information from the process (port, ...)
            data = db_driver.SlaveManager.update_slave(
                moon_user_id=authed_user, slave_id=uuid, value=new_data)

        except AttributeError as e:
            response.status = ERROR_CODE[400]
            LOGGER.exception(e)
        except exceptions.MoonError as e:
            response.status = ERROR_CODE[e.code]
        return {"slaves": data}

    @staticmethod
    @hug.local()
    @hug.delete("/slave/{uuid}", requires=api_key_authentication)
    def delete(uuid: hug.types.uuid, response=None, authed_user: hug.directives.user = None):
        """Delete a slave

        :param uuid: uuid of the slave to delete
        :param authed_user: authenticated user name
        :param response: response initialized by Hug
        :return: {
            "result": "True or False",
            "message": "optional message (optional)"
        }
        """
        uuid = str(uuid).replace("-", "")
        try:
            db_driver.SlaveManager.delete_slave(
                moon_user_id=authed_user, slave_id=uuid)

            orchestration_driver.SlaveManager.delete_slave(
                moon_user_id=authed_user, slave_id=uuid)

        except exceptions.MoonError as e:
            response.status = ERROR_CODE[e.code]
            return {"result": False, "description": str(e)}
        except Exception as e:
            LOGGER.exception(e)
            return {"result": False, "description": str(e)}
        return {"result": True}

    @staticmethod
    @hug.local()
    @hug.patch("/slave/{uuid}", requires=api_key_authentication)
    def patch(uuid: hug.types.uuid, body, response, authed_user: hug.directives.user = None):
        """Update a slave

        :param uuid: uuid of the slave to delete
        :param body: body content of the Hug request
        :param authed_user: authenticated user name
        :param response: response initialized by Hug
        :return: {
            "pdp_id1": {
                "name": "name of the PDP",
                "address": "local_or_ssh://a.b.c.d",
                "description": "description of the slave (optional)",
            }
        }
        """

        uuid = str(uuid).replace("-", "")
        prev_data = db_driver.SlaveManager.get_slaves(moon_user_id=authed_user, slave_id=uuid)
        if not prev_data:
            response.status = ERROR_CODE[400]
            return {"message": "The slave is unknown."}
        try:
            data = db_driver.SlaveManager.update_slave(
                moon_user_id=authed_user, slave_id=uuid, value=body)


            #TODO  kill the server using orchestration_driver

        except AttributeError as e:
            response.status = ERROR_CODE[400]
            LOGGER.exception(e)
            return {"message": str(e)}
        except exceptions.MoonError as e:
            response.status = ERROR_CODE[e.code]
            return {"message": str(e)}

        orchestration_driver.SlaveManager.update_slave(moon_user_id=authed_user, slave_id=uuid, value=body)

        return {
            "slaves": db_driver.SlaveManager.get_slaves(moon_user_id=authed_user, slave_id=uuid)
        }


SlavesAPI = hug.API(name='slaves', doc=Slaves.__doc__)
db_conf = configuration.get_configuration(key='management')
init_db(db_conf.get("token_file"))


@hug.object(name='slaves', version='1.0.0', api=SlavesAPI)
class SlavesCLI(object):
    """An example of command like calls via an Object"""

    @staticmethod
    @hug.object.cli
    def list(human: bool = False):
        """
        List slaves from the database
        :return: JSON status output
        """
        db_conf = configuration.get_configuration(key='management')

        manager_api_key = connect_from_env()
        _slaves = requests.get("{}/slaves".format(db_conf.get("url")),
                               headers={"x-api-key": manager_api_key}
                               )
        if _slaves.status_code == 200:
            result = _slaves.json()

            if human:
                return SlavesCLI.human_display(result)
            else:
                return result
        LOGGER.error('Cannot list Slave Data {}'.format(_slaves.status_code))

    @staticmethod
    @hug.object.cli
    def add(name='default', address="local", description="", grant_if_unknown_project: bool = False, human: bool = False):
        """
        Add slave in the database
        :return: JSON status output
        """
        db_conf = configuration.get_configuration(key='management')
        manager_api_key = connect_from_env()
        _slaves = requests.post(
            "{}/slave".format(db_conf.get("url")),
            json={
                "name": name,
                "address": address,
                "description": description,
                "grant_if_unknown_project": grant_if_unknown_project
            },
            headers={
                "x-api-key": manager_api_key,
                "Content-Type": "application/json"
            }
        )
        if _slaves.status_code == 200:
            LOGGER.warning('Create {}'.format(_slaves.content))
            if human:
                return SlavesCLI.human_display(_slaves.json())
            else:
                return _slaves.json()
        LOGGER.error('Cannot create {}'.format(name, _slaves.content))

    @staticmethod
    @hug.object.cli
    def delete(name='default'):
        db_conf = configuration.get_configuration(key='management')
        manager_api_key = connect_from_env()
        _slaves = SlavesCLI.list()
        for _slave_id, _slave_value in _slaves.get("slaves").items():
            if _slave_value.get("name") == name:
                req = requests.delete(
                    "{}/slave/{}".format(db_conf.get("url"), _slave_id),
                    headers={"x-api-key": manager_api_key}
                )
                break
        else:
            LOGGER.error("Cannot find slave with name {}".format(name))
            return False
        if req.status_code == 200:
            LOGGER.warning('Deleted {}'.format(name))
            return True
        LOGGER.error("Cannot delete slave with name {}".format(name))
        return False

    @staticmethod
    @hug.object.cli
    def update(name='default', address=None, description=None,
               grant_if_unknown_project: hug.types.one_of(("y", "n")) = None):
        db_conf = configuration.get_configuration(key='management')
        manager_api_key = connect_from_env()
        _slaves = SlavesCLI.list()

        for _slave_id, _slave_value in _slaves.get("slaves").items():
            if _slave_value.get("name") == name:
                address_updated = _slave_value.get("address")
                description_updated = _slave_value.get("description")
                grant_if_unknown_project_updated = _slave_value.get("grant_if_unknown_project")

                if address is not None:
                    address_updated = address
                if description is not None:
                    description_updated = description
                if grant_if_unknown_project is not None:
                    grant_if_unknown_project_updated = True if grant_if_unknown_project in ("y", "true", "1") else False

                req = requests.patch(
                    "{}/slave/{}".format(db_conf.get("url"), _slave_id),
                    json={
                        "name": name,
                        "address": address_updated,
                        "description": description_updated,
                        "grant_if_unknown_project": grant_if_unknown_project_updated,
                    },
                    headers={
                        "x-api-key": manager_api_key,
                        "Content-Type": "application/json"
                    }
                )
                if req.status_code == 200:
                    LOGGER.warning('Updated {}'.format(name))
                    return True
                else:
                    LOGGER.error('Cannot update {}'.format(name))
                    return False

        LOGGER.error('Cannot find {}'.format(name))
        return False

    @staticmethod
    def human_display(slaves_json):
        human_result = "Slaves"
        for slave in slaves_json.get("slaves"):
            human_result += "\n" + slaves_json.get("slaves").get(slave).get("name") + " : \n"
            human_result += "\tname : " + slaves_json.get("slaves").get(slave).get("name") + "\n"
            human_result += "\tid : " + slave + "\n"
            human_result += "\tdescription : " + slaves_json.get("slaves").get(slave).get("description") + "\n"
            human_result += "\taddress : " + slaves_json.get("slaves").get(slave).get("address") + "\n"
            human_result += "\tgrant_if_unknown_project : " + str(slaves_json.get("slaves").get(slave).get("grant_if_unknown_project")) + "\n"
            human_result += "\tprocess : " + slaves_json.get("slaves").get(slave).get("process") + "\n"
            human_result += "\tlog : " + slaves_json.get("slaves").get(slave).get("log") + "\n"
            human_result += "\tapi_key : " + slaves_json.get("slaves").get(slave).get("api_key") + "\n"
            human_result += SlavesCLI.human_display_extra(slaves_json.get("slaves").get(slave).get("extra"))
        return human_result

    @staticmethod
    def human_display_extra(extra_json):
        human_result = "\textra"
        human_result += "\n"
        human_result += "\t\tdescription : " + extra_json.get("description") + "\n"
        human_result += "\t\tstarttime : " + str(extra_json.get("starttime")) + "\n"
        human_result += "\t\tport : " + str(extra_json.get("port")) + "\n"
        human_result += "\t\tserver_ip : " + str(extra_json.get("server_ip")) + "\n"
        human_result += "\t\tstatus : " + extra_json.get("status") + "\n"
        human_result += "\t\tprocess : " + extra_json.get("process") + "\n"
        human_result += "\t\tlog : " + extra_json.get("log") + "\n"
        human_result += "\t\tapi_key : " + extra_json.get("api_key") + "\n"
        return human_result