aboutsummaryrefslogtreecommitdiffstats
path: root/moon_manager/moon_manager/plugins/moon_openstack_plugin.py
blob: a4b8a237c5ffa45ef6d9764e32e9adbae37360d2 (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
# 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.

"""
Abstract plugin to request OpenStack infrastructure
"""

import json
import logging
import time
import requests
from moon_manager.pip_driver import InformationDriver
from moon_manager.api.configuration import get_configuration
from moon_utilities.exceptions import MoonError

LOGGER = logging.getLogger("moon.manager.plugins.moon_openstack_plugin")

PLUGIN_TYPE = "information"
_ = str


# Keystone exceptions


class KeystoneError(MoonError):
    description = _("There is an error connecting to Keystone.")
    code = 400
    title = 'Keystone error'
    logger = "ERROR"


class KeystoneProjectError(KeystoneError):
    description = _("There is an error retrieving projects from the Keystone service.")
    code = 400
    title = 'Keystone project error'
    logger = "ERROR"


class KeystoneUserError(KeystoneError):
    description = _("There is an error retrieving users from the Keystone service.")
    code = 400
    title = 'Keystone user error'
    logger = "ERROR"


class KeystoneUserConflict(KeystoneUserError):
    description = _("A user with that name already exist.")
    code = 400
    title = 'Keystone user error'
    logger = "ERROR"


class OpenStackConnector(InformationDriver):

    def __init__(self, driver_name, engine_name, conf):
        self.driver_name = driver_name
        self.engine_name = engine_name
        self.opst_conf = get_configuration("information")

        if not self.opst_conf:
            raise Exception("Cannot find OpenStack configuration in configuration file")

        self.__headers = {}
        self.__user = conf.get("user", self.opst_conf['user'])
        self.__password = conf.get("password", self.opst_conf['password'])
        self.__domain = conf.get("domain", self.opst_conf['domain'])
        self.__project = conf.get("project", self.opst_conf['project'])
        self.__url = conf.get("url", self.opst_conf['url'])

    def set_auth(self, **kwargs):
        start_time = time.time()
        user = kwargs.get("user", self.opst_conf['user'])
        password = kwargs.get("password", self.opst_conf['password'])
        domain = kwargs.get("domain", self.opst_conf['domain'])
        project = kwargs.get("project", self.opst_conf['project'])
        url = kwargs.get("url", self.opst_conf['url'])
        headers = {
            "Content-Type": "application/json"
        }
        data_auth = {
            "auth": {
                "identity": {
                    "methods": [
                        "password"
                    ],
                    "password": {
                        "user": {
                            "domain": {
                                "id": domain
                            },
                            "name": user,
                            "password": password
                        }
                    }
                },
                "scope": {
                    "project": {
                        "domain": {
                            "id": domain
                        },
                        "name": project
                    }
                }
            }
        }

        while True:
            req = requests.post("{}/auth/tokens".format(url),
                                json=data_auth, headers=headers,
                                verify=kwargs.get("certificate", self.opst_conf['certificate']))

            if req.status_code in (200, 201, 204):
                self.__headers['X-Auth-Token'] = req.headers['X-Subject-Token']
                return self.__headers
            LOGGER.warning("Waiting for Keystone...")
            if time.time() - start_time == 100:
                LOGGER.error(req.text)
                raise KeystoneError
            time.sleep(5)

    def unset_auth(self, **kwargs):
        url = kwargs.get("url", self.opst_conf['url'])
        self.__headers['X-Subject-Token'] = self.__headers['X-Auth-Token']
        req = requests.delete("{}/auth/tokens".format(url), headers=self.__headers,
                              verify=kwargs.get("certificate", self.opst_conf['certificate']))
        if req.status_code in (200, 201, 204):
            return
        LOGGER.error(req.text)
        raise KeystoneError

    def _get(self, endpoint, url=None, _exception=KeystoneError):
        if not url:
            if not self.__url:
                LOGGER.warning("Cannot retrieve the URL for the OpenStack endpoint")
                return {'users': []}
            url = self.__url

        req = requests.get("{}{}".format(url, endpoint),
                           headers=self.__headers)
        if req.status_code not in (200, 201):
            LOGGER.error(req.text)
            raise _exception
        data = req.json()
        return data

    def _post(self, endpoint, url=None, data=None, _exception=KeystoneError):
        if not url:
            if not self.__url:
                LOGGER.warning("Cannot retrieve the URL for the OpenStack endpoint")
                return {'users': []}
            url = self.__url

        req = requests.post("{}{}".format(url, endpoint),
                            data=json.dumps(data),
                            headers=self.__headers)
        if req.status_code == 409:
            LOGGER.warning(req.text)
            raise KeystoneUserConflict
        if req.status_code not in (200, 201):
            LOGGER.error(req.text)
            raise _exception
        data = req.json()
        return data

    def create_project(self, **tenant_dict):
        if "name" not in tenant_dict:
            raise KeystoneProjectError("Cannot get the project name.")
        _project = {
            "project": {
                "description": tenant_dict['description'],
                "domain_id": tenant_dict['domain'],
                "enabled": tenant_dict['enabled'],
                "is_domain": tenant_dict['is_domain'],
                "name": tenant_dict['name']
            }
        }
        return self._post(endpoint="/projects/",
                          url=self.opst_conf["url"],
                          data=_project,
                          _exception=KeystoneProjectError)

    def get_projects(self):
        return self._get(endpoint="/projects/", url=self.opst_conf["url"], _exception=KeystoneProjectError)

    def get_items(self, item_id=None, **kwargs):
        raise NotImplementedError()  # pragma: no cover

    def add_item(self, item_id=None, **kwargs):
        raise NotImplementedError()  # pragma: no cover

    def update_item(self, item_id, **kwargs):
        raise NotImplementedError()  # pragma: no cover

    def delete_item(self, item_id, **kwargs):
        raise NotImplementedError()  # pragma: no cover