-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathlaunchpad_client.py
More file actions
616 lines (504 loc) · 20.4 KB
/
launchpad_client.py
File metadata and controls
616 lines (504 loc) · 20.4 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
import json
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
import requests
from requests.adapters import HTTPAdapter
from requests.auth import HTTPBasicAuth
from urllib3.util.retry import Retry
from .launchpad.exceptions import (
DataikuBadRequestException,
DataikuException,
DataikuForbiddenException,
DataikuResourceNotFoundException,
DataikuResponseException,
DataikuUnauthorizedException,
)
from .launchpad.group import LaunchpadGroup
from .launchpad.node import LaunchpadNode
from .launchpad.profile import LaunchpadProfile
from .launchpad.response import LaunchpadBulkResponse
from .launchpad.user import LaunchpadInvite, LaunchpadUser
API_VERSION = "v1"
DEFAULT_LAUNCHPAD_URL = f"https://api.launchpad-dku.app.dataiku.io/{API_VERSION}"
class LaunchpadClient:
"""Entry point for the Launchpad API client"""
def __init__(
self,
space_id: str,
api_key_id: str,
api_key_secret: str,
host=DEFAULT_LAUNCHPAD_URL,
extra_headers: Optional[dict] = None,
):
"""
Instantiate a new Launchpad API client
.. note::
Credentials are managed in the Launchpad
The client credentials will define which operations are allowed
"""
self.space_id = space_id
self.api_key_id = api_key_id
self.api_key_secret = api_key_secret
self.host = host
self._session = requests.Session()
self._session.auth = HTTPBasicAuth(self.api_key_id, self.api_key_secret)
retry_strategy = Retry(
total=1,
read=1,
allowed_methods=None,
raise_on_status=False,
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self._session.mount("https://", adapter)
self._session.mount("http://", adapter)
if extra_headers is not None:
self._session.headers.update(extra_headers)
########################################################
# Invites
########################################################
def build_invite(
self,
email: str,
profile: str,
groups: Optional[List[str]] = None,
) -> LaunchpadInvite:
"""
Get a handle for a new invite
.. note::
This does not create the invite on the Launchpad, it simply returns an object.
See usage example to create the invite on the Launchpad.
Usage example:
.. code-block:: python
# Invite a user
invite = client.build_invite("[email protected]", "designer", ["designers"])
client.create_invites([invite])
:param email: the email of the invitee to create
:type email: str
:param profile: the profile of the invitee across Dataiku & Govern nodes
:type profile: str
:param groups: the groups of the invitee across Dataiku & Govern nodes. Defaults to ``[]``
:type groups: Optional[List[str]]
:return: An invite object
:rtype: LaunchpadInvite
"""
invite = LaunchpadInvite(self, email=email)
invite.set_profile(profile)
invite.add_groups(groups or [])
return invite
def get_invite(self, email: str) -> LaunchpadInvite:
"""
Get a handle to interact with an existing invite on the Cloud space
.. important::
``read_users`` scope is required
:param email: the email of the desired invite
:type email: str
:return: An invite object
:rtype: LaunchpadInvite
"""
if not email:
raise DataikuException("email_required: Email cannot be empty")
return LaunchpadInvite._get_by(self, email=email)
def list_invites(self, emails: Optional[List[str]] = None) -> List[LaunchpadInvite]:
"""
List invites on the Cloud space
.. important::
``read_users`` scope is required
:param emails: the emails of the desired users. Defaults to ``None`` (no filter)
:type emails: Optional[List[str]]
:return: A list of invite objects
:rtype: List[LaunchpadInvite]
"""
invites = self._perform_json(
"POST",
f"/spaces/{self.space_id}/invites/search",
raw_body={"emails": emails},
)
return [LaunchpadInvite(self, **invite) for invite in invites]
def create_invites(
self, invites: List[LaunchpadInvite], fail_all_on_error: bool = False
) -> Tuple[List[LaunchpadInvite], List[dict]]:
"""
Create invites on the Cloud space
.. important::
``write_users`` scope is required
Usage example:
.. code-block:: python
# Create multiple invites
invite_1 = client.build_invite(email_1, "reader")
invite_2 = client.build_invite(email_2, "designer", ["designers"])
successes, failures = client.create_invites([invite_1, invite_2])
:param invites: the list of invite objects to create
:type invites: List[LaunchpadInvite]
:param fail_all_on_error: whether to perform the operation atomically, i.e. if one invite fails, all invites fail. Defaults to ``False``
:type fail_all_on_error: bool
:return: A Tuple of successes (invite objects) and errors (dicts) objects
:rtype: Tuple[List[LaunchpadInvite], List[dict]]
"""
multi_response = self._perform_json(
"POST",
f"/spaces/{self.space_id}/invites",
raw_body=[invite._data for invite in invites],
params={"failAllOnError": fail_all_on_error},
)
response = LaunchpadBulkResponse(self, **multi_response)
email_to_invite = {invite.email: invite for invite in invites}
successes = []
for item in response.successes:
invite = email_to_invite[item["email"]]
invite._data["id"] = item["id"]
successes.append(invite)
return successes, response.errors
def update_invites(
self,
invites: List[LaunchpadInvite],
fail_all_on_error=False,
) -> Tuple[List[LaunchpadInvite], List[dict]]:
"""
Update invites on the Cloud space
.. important::
``write_users`` scope is required
Usage example:
.. code-block:: python
# Update invites based on a group
invites = client.list_invites()
invites_to_update = [
invite
for invite in invites
if "my-group" in invite.groups
]
for invite in invites_to_update:
invite.set_profile("designer")
successes, failures = client.update_invites(invites_to_update)
:param invites: the list of invite objects to update
:type invites: List[LaunchpadInvite]
:param fail_all_on_error: whether to perform the operation atomically, i.e. if one update fails, all updates fail. Defaults to ``False``
:type fail_all_on_error: bool
:return: A Tuple of successes (invite objects) and errors (dicts) objects
:rtype: Tuple[List[LaunchpadInvite], List[dict]]
"""
multi_response = self._perform_json(
"PUT",
f"/spaces/{self.space_id}/invites",
raw_body=[invite._data for invite in invites],
params={"failAllOnError": fail_all_on_error},
)
response = LaunchpadBulkResponse(self, **multi_response)
id_to_invite = {invite.id: invite for invite in invites}
successes = []
for item in response.successes:
invite = id_to_invite[item["id"]]
invite._data.update(item)
successes.append(invite)
return successes, response.errors
def delete_invites(
self, emails: List[str], fail_all_on_error=False
) -> Tuple[List[dict], List[dict]]:
"""
Delete invites on the Cloud space
.. important::
``write_users`` scope is required
Usage example:
.. code-block:: python
# Delete invites older than 7 days
invites = client.list_invites()
invites_to_delete = [
invite.email
for invite in invites
if invite.created_on <= datetime.now(timezone.utc) - timedelta(days=7)
]
successes, failures = client.delete_invites(invites_to_delete)
:param emails: the list of emails to delete
:type emails: List[str]
:param fail_all_on_error: whether to perform the operation atomically, i.e. if one deletion fails, all deletions fail. Defaults to ``False``
:type fail_all_on_error: bool
:return: A Tuple of successes (dicts) and errors (dicts) objects
:rtype: Tuple[List[dict], List[dict]]
"""
multi_response = self._perform_json(
"DELETE",
f"/spaces/{self.space_id}/invites",
raw_body={"emails": emails},
params={"failAllOnError": fail_all_on_error},
)
response = LaunchpadBulkResponse(self, **multi_response)
return response.successes, response.errors
########################################################
# Users
########################################################
def get_user(self, email: str) -> LaunchpadUser:
"""
Get a handle to interact with an existing user on the Cloud space
.. important::
``read_users`` scope is required
:param str email: the email of the desired user
:return: A user object
:rtype: LaunchpadUser
"""
if not email:
raise DataikuException("email_required: Email cannot be empty")
return LaunchpadUser._get_by(self, email=email)
def list_users(self, emails: Optional[List[str]] = None) -> List[LaunchpadUser]:
"""
List users on the Cloud space
.. important::
``read_users`` scope is required
:param emails: the emails of the desired users. Defaults to ``None`` (no filter)
:type emails: Optional[List[str]]
:return: A list of user objects
:rtype: List[LaunchpadUser]
"""
users = self._perform_json(
"POST", f"/spaces/{self.space_id}/users/search", raw_body={"emails": emails}
)
return [LaunchpadUser(self, **user) for user in users]
def update_users(
self,
users: List[LaunchpadUser],
fail_all_on_error=False,
wait_for_propagation=False,
) -> Tuple[List[LaunchpadUser], List[dict]]:
"""
Update users on the Cloud space
.. important::
``write_users`` scope is required
Usage example:
.. code-block:: python
# Update users based on a group
users = client.list_users()
users_to_update = [
user
for user in users
if "my-group" in user.groups
]
for user in users_to_update:
user.set_profile("designer")
successes, failures = client.update_users(users_to_update)
:param users: the list of user objects to update
:type users: List[LaunchpadUser]
:param fail_all_on_error: whether to perform the operation atomically, i.e. if one update fails, all updates fail. Defaults to ``False``
:type fail_all_on_error: bool
:param wait_for_propagation: whether to wait for the changes to propagate to all Dataiku & Govern running nodes. Defaults to ``False``
:type wait_for_propagation: bool
:return: A Tuple of successes (user objects) and errors (dicts) objects
:rtype: Tuple[List[LaunchpadUser], List[dict]]
"""
multi_response = self._perform_json(
"PUT",
f"/spaces/{self.space_id}/users",
raw_body=[user._data for user in users],
params={"failAllOnError": fail_all_on_error},
)
response = LaunchpadBulkResponse(self, **multi_response)
id_to_user = {user.id: user for user in users}
successes = []
for item in response.successes:
user = id_to_user[item["id"]]
user._data.update(item)
successes.append(user)
if wait_for_propagation and response.has_task:
response.task.wait_for_result()
return successes, response.errors
def delete_users(
self,
emails: List[str],
fail_all_on_error=False,
wait_for_propagation=False,
) -> Tuple[List[dict], List[dict]]:
"""
Delete multiple users on the Cloud space
.. important::
``write_users`` scope is required
Usage example:
.. code-block:: python
# Delete users based on a group
my_group = client.get_group("my-group")
successes, failures = client.delete_users(my_group.users)
:param emails: the list of user emails to delete
:type emails: List[str]
:param fail_all_on_error: whether to perform the operation atomically, i.e. if one deletion fails, all deletions fail. Defaults to ``False``
:type fail_all_on_error: bool
:param wait_for_propagation: whether to wait for the changes to propagate to all Dataiku & Govern running nodes. Defaults to ``False``
:type wait_for_propagation: bool
:return: A Tuple of successes (dicts) and errors (dicts) objects
:rtype: Tuple[List[dict], List[dict]]
"""
multi_response = self._perform_json(
"DELETE",
f"/spaces/{self.space_id}/users",
raw_body={"emails": emails},
params={"failAllOnError": fail_all_on_error},
)
response = LaunchpadBulkResponse(self, **multi_response)
if wait_for_propagation and response.has_task:
response.task.wait_for_result()
return response.successes, response.errors
########################################################
# Groups
########################################################
def build_group(
self,
name: str,
description: Optional[str] = None,
emails: Optional[List[str]] = None,
launchpad_permissions: Optional[Dict[str, bool]] = None,
dataiku_permissions: Optional[Dict[str, Dict[str, Any]]] = None,
govern_permissions: Optional[Dict[str, Dict[str, bool]]] = None,
) -> LaunchpadGroup:
"""
Get a handle for a new group
.. note::
This does not create the group on the Launchpad, it simply returns an object.
See usage example to create the group on the Launchpad.
Usage example:
.. code-block:: python
# Create a group
group = client.build_group("Designers", "Designer group", ["[email protected]"])
group.launchpad_permissions = {"mayTurnOnSpace": True}
group.update_permissions({"mayCreateProjects": True}, node_name="design-0")
group.save()
:param name: the name of the group to create
:type name: str
:param description: the description of the group to create. Defaults to ``None``
:type description: Optional[str]
:param emails: the emails of the group to create. Defaults to ``[]``
:type emails: Optional[List[str]]
:param launchpad_permissions: the launchpad permissions of the group. Defaults to ``{}``
:type launchpad_permissions: Optional[Dict[str, bool]]
:param dataiku_permissions: the permissions of the group across Dataiku nodes. Defaults to ``{}``
:type dataiku_permissions: Optional[Dict[str, Dict[str, Any]]]
:param govern_permissions: the govern permissions of the group across Govern nodes. Defaults to ``{}``
:type govern_permissions: Optional[Dict[str, Dict[str, bool]]]
:return: A group object
:rtype: LaunchpadGroup
"""
group = LaunchpadGroup(self, name=name)
group.description = description
if emails:
group.add_users(emails)
if launchpad_permissions:
group.launchpad_permissions = deepcopy(launchpad_permissions)
if dataiku_permissions:
group._data["dataikuPermissions"] = deepcopy(dataiku_permissions)
if govern_permissions:
group._data["governPermissions"] = deepcopy(govern_permissions)
return group
def get_group(self, name: str) -> LaunchpadGroup:
"""
Get a handle to interact with an existing group on the Cloud space
.. important::
``read_groups`` scope is required
:param name: the name of the desired group
:type name: str
:return: A group object
:rtype: LaunchpadGroup
"""
if not name:
raise DataikuException("name_required: Name cannot be empty")
return LaunchpadGroup._get_by(self, name=name)
def list_groups(self, names: Optional[List[str]] = None) -> List[LaunchpadGroup]:
"""
List groups setup on the Cloud space
.. important::
``read_groups`` scope is required
:param names: the names of the desired groups. Defaults to ``None`` (no filter)
:type names: Optional[List[str]]
:return: A list of group objects
:rtype: List[LaunchpadGroup]
"""
groups = self._perform_json(
"POST", f"/spaces/{self.space_id}/groups/search", raw_body={"names": names}
)
return [LaunchpadGroup(self, **group) for group in groups]
########################################################
# Profiles
########################################################
def list_profiles(self) -> List[LaunchpadProfile]:
"""
List profiles on the Cloud space
.. important::
``read_users`` scope is required
:return: A list of profile objects
:rtype: List[LaunchpadProfile]
"""
user_seats = self._perform_json("GET", f"/spaces/{self.space_id}/profiles")
return [LaunchpadProfile(self, **profile) for profile in user_seats]
########################################################
# Nodes
########################################################
def list_nodes(self, type: Optional[str] = None) -> List[LaunchpadNode]:
"""
List nodes on the Cloud space
:param type: the type of nodes to list. Defaults to ``None`` (no filter)
:type type: Optional[str]
:return: A list of node objects
:rtype: List[LaunchpadNode]
"""
nodes = self._perform_json(
"POST",
f"/spaces/{self.space_id}/nodes/search",
raw_body={"type": type},
)
return [LaunchpadNode(self, **node) for node in nodes]
########################################################
# Internal Request handling
########################################################
def _perform_http(
self,
method,
path,
params=None,
body=None,
stream=False,
files=None,
raw_body=None,
headers=None,
):
if body is not None:
body = json.dumps(body)
elif raw_body is not None:
body = raw_body
return self._session.request(
method,
f"{self.host}{path}",
params=params,
json=body,
files=files,
stream=stream,
headers=headers,
)
def _perform_json(
self,
method,
path,
params=None,
body=None,
files=None,
raw_body=None,
headers=None,
) -> dict:
try:
response = self._perform_http(
method=method,
path=path,
params=params,
body=body,
files=files,
stream=False,
raw_body=raw_body,
headers=headers,
)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
exception_class_mapping = {
401: DataikuUnauthorizedException,
403: DataikuForbiddenException,
404: DataikuResourceNotFoundException,
422: DataikuBadRequestException,
}
exc = exception_class_mapping.get(
err.response.status_code, DataikuResponseException
)
raise exc(err.response) from err
if response.status_code == 204:
return {}
return response.json()