summaryrefslogtreecommitdiff
path: root/ick2/client.py
blob: 39e10f8cc07ef7a1400a9048fede9ad5e3b1b454 (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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# Copyright (C) 2018  Lars Wirzenius
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import base64
import json
import logging
import time
import urllib


import requests


class HttpError(Exception):

    pass


class HttpAPI:

    # Make requests to an HTTP API.

    json_type = 'application/json'

    def __init__(self):
        self._session = requests.Session()
        self._token = None
        self._verify = None

    def set_session(self, session):
        self._session = session

    def set_verify_tls(self, verify):  # pragma: no cover
        self._verify = verify

    def set_token(self, token):
        self._token = token

    def get_dict(self, url, headers=None):
        r = self._request(self._session.get, url, headers=headers)
        ct = r.headers.get('Content-Type')
        if ct != self.json_type:
            raise HttpError('Not JSON response')
        try:
            return r.json()
        except json.decoder.JSONDecodeError:
            raise HttpError('JSON parsing error')

    def get_blob(self, url, headers=None):
        r = self._request(self._session.get, url, headers=headers)
        return r.content

    def delete(self, url, headers=None):  # pragma: no cover
        r = self._request(self._session.delete, url, headers=headers)
        return r.content

    def post(self, url, headers=None, body=None):
        self._send_request(self._session.post, url, headers=headers, body=body)
        return None

    def post_auth(self, url, headers=None, body=None, auth=None):
        assert auth is not None
        if headers is None:
            headers = {}
        headers['Authorization'] = self._basic_auth(auth)
        return self._send_request(
            self._session.post, url, headers=headers, body=body, auth=auth)

    def _basic_auth(self, auth):
        username, password = auth
        cleartext = '{}:{}'.format(username, password).encode('UTF-8')
        encoded = base64.b64encode(cleartext)
        return 'Basic {}'.format(encoded.decode('UTF-8'))

    def put(self, url, headers=None, body=None):
        self._send_request(self._session.put, url, headers=headers, body=body)
        return None

    def _send_request(self, func, url, headers=None, body=None, auth=None):
        if headers is None:
            headers = {}
        headers = dict(headers)
        if not headers.get('Content-Type'):
            h, body = self._get_content_type_header(body)
            headers.update(h)
        return self._request(func, url, headers=headers, data=body, auth=auth)

    def _get_content_type_header(self, body):
        if isinstance(body, dict):
            header = {
                'Content-Type': 'application/json',
            }
            body = json.dumps(body)
            return header, body
        return {}, body

    def _get_authorization_headers(self):
        return {
            'Authorization': 'Bearer {}'.format(self._token),
        }

    def _request(self, func, url, headers=None, **kwargs):
        if headers is None:
            headers = {}

        auth = kwargs.get('auth')
        if auth is None:
            headers.update(self._get_authorization_headers())
            if 'auth' in kwargs:
                del kwargs['auth']

        r = func(url, headers=headers, verify=self._verify, **kwargs)
        if not r.ok:
            raise HttpError('{}: {}'.format(r.status_code, r.text))
        return r


class ControllerClient:

    def __init__(self):
        self._name = None
        self._api = HttpAPI()
        self._url = None
        self._auth_url = None

    def set_client_name(self, name):
        self._name = name

    def set_verify_tls(self, verify):  # pragma: no cover
        self._api.set_verify_tls(verify)

    def set_http_api(self, api):
        self._api = api

    def get_http_api(self):  # pragma: no cover
        return self._api

    def set_controller_url(self, url):
        self._url = url

    def get_controller_url(self):  # pragma: no cover
        return self._url

    def set_token(self, token):
        self._api.set_token(token)

    def url(self, path):
        return '{}{}'.format(self._url, path)

    def get_version(self):
        url = self.url('/version')
        return self._api.get_dict(url)

    def get_apt_server(self):
        version = self.get_version()
        logging.debug('get_apt_server: version: %s', version)
        server = version.get('apt_server')
        logging.info('APT server: %r', server)
        return server

    def get_artifact_store_url(self):
        version = self.get_version()
        url = version.get('artifact_store')
        logging.info('Artifact store URL: %r', url)
        return url

    def get_auth_url(self):
        version = self.get_version()
        url = version.get('auth_url')
        logging.info('Authentication URL: %r', url)
        return url

    def get_notify_url(self):  # pragma: no cover
        version = self.get_version()
        url = version.get('notify_url')
        logging.info('Notification URL: %r', url)
        return url

    def get_auth_client(self):
        url = self.get_auth_url()
        ac = AuthClient()
        ac.set_auth_url(url)
        ac.set_http_api(self._api)
        return ac

    def get_blob_client(self):
        url = self.get_artifact_store_url()
        blobs = BlobClient()
        blobs.set_url(url)
        blobs.set_http_api(self._api)
        return blobs

    def register(self):
        assert self._url is not None
        url = self.url('/workers')
        logging.info('Registering worker %s to %s', self._name, url)
        body = {
            'worker': self._name,
        }
        try:
            self._api.post(url, body=body)
        except HttpError:
            pass

    def get_work(self):
        url = self.url('/work')
        work = self._api.get_dict(url)
        logging.info('Requested work, got: %r', work)
        return work

    def report_work(self, work):
        logging.info('Reporting work: %r', work)
        url = self.url('/work')
        headers = {
            'Content-Type': self._api.json_type,
        }
        body = json.dumps(work)
        self._api.post(url, headers=headers, body=body)

    def show(self, path):  # pragma: no cover
        url = self.url(path)
        return self._api.get_dict(url)

    def show_blob(self, path):  # pragma: no cover
        url = self.url(path)
        return self._api.get_blob(url)

    def delete(self, path):  # pragma: no cover
        url = self.url(path)
        return self._api.delete(url)

    def create(self, path, obj):  # pragma: no cover
        url = self.url(path)
        return self._api.post(url, body=obj)

    def update(self, path, obj):  # pragma: no cover
        url = self.url(path)
        return self._api.put(url, body=obj)

    def trigger(self, project_name):  # pragma: no cover
        path = '/projects/{}/+trigger'.format(project_name)
        url = self.url(path)
        return self._api.get_dict(url)

    def get_log(self, build_id):  # pragma: no cover
        path = '/logs/{}'.format(build_id)
        url = self.url(path)
        return self._api.get_blob(url)

    def notify(self, notify):  # pragma: no cover
        url = self.get_notify_url()
        self._api.post(url, body=notify)


class AuthClient:

    def __init__(self):
        self._auth_url = None
        self._http_api = HttpAPI()
        self._client_id = None
        self._client_secret = None

    def set_auth_url(self, url):
        self._auth_url = url

    def set_http_api(self, api):
        self._http_api = api

    def set_client_creds(self, client_id, client_secret):
        self._client_id = client_id
        self._client_secret = client_secret

    def get_token(self, scope):
        auth = (self._client_id, self._client_secret)
        params = {
            'grant_type': 'client_credentials',
            'scope': scope,
        }
        body = urllib.parse.urlencode(params)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        r = self._http_api.post_auth(
            self._auth_url, headers=headers, body=body, auth=auth)
        obj = r.json()
        return obj['access_token']


class Reporter:  # pragma: no cover

    def __init__(self, api, work):
        self._api = api
        self._work = dict(work)

    def report(self, exit_code, stdout, stderr):
        result = dict(self._work)
        result['exit_code'] = exit_code
        result['stdout'] = self.make_string(stdout)
        result['stderr'] = self.make_string(stderr)
        self._api.report_work(result)

    def make_string(self, thing):
        if isinstance(thing, bytes):
            return thing.decode('UTF-8')
        if isinstance(thing, str):
            return thing
        if thing is None:
            return thing
        return repr(thing)

    def get_work_result(self, work):
        return {
            'build_id': work['build_id'],
            'worker': work['worker'],
            'project': work['project'],
            'pipeline': work['pipeline'],
            'stdout': '',
            'stderr': '',
            'exit_code': None,
            'timestamp': self.now(),
        }

    def now(self):
        return time.strftime('%Y-%m-%dT%H:%M:%S')


class BlobClient:

    def __init__(self):
        self._url = None
        self._api = None

    def set_url(self, url):
        self._url = url

    def set_http_api(self, api):
        self._api = api

    def url(self, blob_name):
        assert self._url is not None
        return '{}/blobs/{}'.format(self._url, blob_name)

    def download(self, blob_name):
        logging.info('Download blob %s', blob_name)
        url = self.url(blob_name)
        return self._api.get_blob(url)

    def upload(self, blob_name, blob):
        logging.info('Upload blob %s', blob_name)
        url = self.url(blob_name)
        return self._api.put(url, body=blob)