aboutsummaryrefslogtreecommitdiffstats
path: root/moonclient/moonclient/shell.py
blob: f3d87ba32d20440eb2c6e395122dac5d559bf0a6 (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
# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
# This software is distributed under the terms and conditions of the 'Apache-2.0'
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.

import logging
import sys
import json
import httplib
import os

from cliff.app import App
from cliff.commandmanager import CommandManager
from cliff.formatters.base import ListFormatter, SingleFormatter


class _JSONFormatter(ListFormatter, SingleFormatter):

    def add_argument_group(self, parser):
        group = parser.add_argument_group(title='json formatter')
        group.add_argument(
            '--noindent',
            action='store_true',
            dest='noindent',
            help='whether to disable indenting the JSON'
        )
        group.add_argument(
            '--projectname',
            help='Set the project name'
        )

    def emit_list(self, column_names, data, stdout, parsed_args):
        items = []
        import time
        for item in data:
            element = dict(zip(column_names, item))
            element["project_name"] = parsed_args.projectname
            element["name"] = element.pop("test_name")
            element["url"] = ""
            element["_id"] = ""
            element["creation_date"] = time.strftime("%Y-%m-%d %H:%M:%S")
            items.append(element)
        indent = None if parsed_args.noindent else 2
        json.dump({"testcases": items}, stdout, indent=indent)

    def emit_one(self, column_names, data, stdout, parsed_args):
        one = dict(zip(column_names, data))
        indent = None if parsed_args.noindent else 2
        json.dump(one, stdout, indent=indent)


def get_env_creds(admin_token=False):
    d = dict()
    if 'OS_SERVICE_ENDPOINT' in os.environ.keys() or 'OS_USERNAME' in os.environ.keys():
        if admin_token:
            d['endpoint'] = os.environ['OS_SERVICE_ENDPOINT']
            d['token'] = os.environ['OS_SERVICE_TOKEN']
        else:
            d['username'] = os.environ['OS_USERNAME']
            d['password'] = os.environ['OS_PASSWORD']
            d['auth_url'] = os.environ['OS_AUTH_URL']
            d['tenant_name'] = os.environ['OS_TENANT_NAME']
    return d


class MoonClient(App):

    log = logging.getLogger(__name__)
    x_subject_token = None
    host = "localhost"
    port = "35358"
    tenant = None
    _intraextension = None
    _tenant_id = None
    _tenant_name = None
    secureprotocol = False
    user_saving_file = ".moonclient"
    url_prefix = "/moon"
    post = {
        "auth": {
            "identity": {
                "methods": [
                    "password"
                ],
                "password": {
                    "user": {
                        "domain": {
                            "id": "Default"
                        },
                        "name": "admin",
                        "password": "nomoresecrete"
                    }
                }
            },
            "scope": {
                "project": {
                    "domain": {
                        "id": "Default"
                    },
                    "name": "demo"
                }
            }
        }
    }

    def __init__(self):
        super(MoonClient, self).__init__(
            description='Moon Python Client',
            version='0.2.0',
            command_manager=CommandManager('moon.client'),
            )
        creds = get_env_creds()
        self.post["auth"]["identity"]["password"]["user"]["password"] = creds["password"]
        self.post["auth"]["identity"]["password"]["user"]["name"] = creds["username"]
        self.post["auth"]["scope"]["project"]["name"] = creds["tenant_name"]
        self.host = creds["auth_url"].replace("https://", "").replace("http://", "").split("/")[0].split(":")[0]
        self.port = creds["auth_url"].replace("https://", "").replace("http://", "").split("/")[0].split(":")[1]
        if "https" in creds["auth_url"]:
            self.secureprotocol = True
        else:
            self.secureprotocol = False
        self._tenant_name = creds["tenant_name"]
        self.parser.add_argument(
            '--username',
            metavar='<username-str>',
            help='Force OpenStack username',
            default=None
        )
        self.parser.add_argument(
            '--tenant',
            metavar='<tenantname-str>',
            help='Force OpenStack tenant',
            default=None
        )
        self.parser.add_argument(
            '--password',
            metavar='<password-str>',
            help='Force OpenStack password',
            default=None
        )
        self.parser.add_argument(
            '--authurl',
            metavar='<authurl-str>',
            help='Force OpenStack authentication URL',
            default=None
        )

    @property
    def tenant_id(self):
        if not self._tenant_id:
            self._tenant_id = self.get_url("/v3/projects?name={}".format(self._tenant_name),
                                           authtoken=True, port=5000)["projects"][0]["id"]
        return self._tenant_id

    @property
    def tenant_name(self):
        return self._tenant_name

    @property
    def intraextension(self):
        return open(os.path.join(os.getenv('HOME'), self.user_saving_file)).read().strip()

    @intraextension.setter
    def intraextension(self, value):
        self._intraextension = value
        open(os.path.join(os.getenv('HOME'), self.user_saving_file), "w").write(value)

    def get_tenant_uuid(self, tenant_name):
        return self.get_url("/v3/projects?name={}".format(tenant_name), authtoken=True, port=5000)["projects"][0]["id"]

    def get_url(self, url, post_data=None, delete_data=None, method="GET", authtoken=None, port=None):
        if post_data:
            method = "POST"
        if delete_data:
            method = "DELETE"
        self.log.debug("\033[32m{} {}\033[m".format(method, url))
        # TODO: we must manage authentication and requests with secure protocol (ie. HTTPS)
        if not port:
            port = self.port
        conn = httplib.HTTPConnection(self.host, int(port))
        self.log.debug("Host: {}:{}".format(self.host, self.port))
        headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        }
        if authtoken:
            if self.x_subject_token:
                headers["X-Auth-Token"] = self.x_subject_token
        if post_data:
            method = "POST"
            headers["Content-type"] = "application/json"
            post_data = json.dumps(post_data)
            conn.request(method, url, post_data, headers=headers)
        elif delete_data:
            method = "DELETE"
            conn.request(method, url, json.dumps(delete_data), headers=headers)
        else:
            conn.request(method, url, headers=headers)
        resp = conn.getresponse()
        headers = resp.getheaders()
        try:
            self.x_subject_token = dict(headers)["x-subject-token"]
        except KeyError:
            pass
        content = resp.read()
        conn.close()
        if len(content) == 0:
            return {}
        try:
            content = json.loads(content)
            if "error" in content:
                try:
                    raise Exception("Getting an error while requiring {} ({}: {}, {})".format(
                        url,
                        content['error']['code'],
                        content['error']['title'],
                        content['error']['message'],
                    ))
                except ValueError:
                    raise Exception("Bad error format while requiring {} ({})".format(url, content))
            return content
        except ValueError:
            raise Exception("Getting an error while requiring {} ({})".format(url, content))
        finally:
            self.log.debug(str(content))

    def auth_keystone(self, username=None, password=None, host=None, port=None, tenant=None):
        """Send a new authentication request to Keystone

        :param username: user identification name
        :return:
        """
        if username:
            self.post["auth"]["identity"]["password"]["user"]["name"] = username
        if password:
            self.post["auth"]["identity"]["password"]["user"]["password"] = password
        if tenant:
            self.post["auth"]["scope"]["project"]["name"] = tenant
        if host:
            self.host = host
        if port:
            self.port = port
        data = self.get_url("/v3/auth/tokens", post_data=self.post)
        if "token" not in data:
            raise Exception("Authentication problem ({})".format(data))

    def initialize_app(self, argv):
        self.log.debug('initialize_app: {}'.format(argv))
        if self.options.username:
            self.post["auth"]["identity"]["password"]["user"]["name"] = self.options.username
            self.log.debug("change username {}".format(self.options.username))
        if self.options.password:
            self.post["auth"]["identity"]["password"]["user"]["password"] = self.options.password
            self.log.debug("change password")
        if self.options.tenant:
            self.post["auth"]["scope"]["project"]["name"] = self.options.tenant
            self._tenant_name = self.options.tenant
            self.log.debug("change tenant {}".format(self.options.tenant))
        if self.options.authurl:
            self.host = self.options.authurl.replace("https://", "").replace("http://", "").split("/")[0].split(":")[0]
            self.port = self.options.authurl.replace("https://", "").replace("http://", "").split("/")[0].split(":")[1]
            if "https" in self.options.authurl:
                self.secureprotocol = True
            else:
                self.secureprotocol = False
        data = self.get_url("/v3/auth/tokens", post_data=self.post)
        if "token" not in data:
            raise Exception("Authentication problem ({})".format(data))
        from cliff.formatters.json_format import JSONFormatter
        JSONFormatter = _JSONFormatter

    def prepare_to_run_command(self, cmd):
        self.log.debug('prepare_to_run_command %s', cmd.__class__.__name__)

    def clean_up(self, cmd, result, err):
        self.log.debug('clean_up %s', cmd.__class__.__name__)
        if err:
            self.log.debug('got an error: %s', err)
        self.log.debug("result: {}".format(result))


def main(argv=sys.argv[1:]):
    myapp = MoonClient()
    return myapp.run(argv)


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))