-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_server.py
1432 lines (1264 loc) · 54.8 KB
/
api_server.py
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=C0302
"""
Specifies the API server and its endpoints for SkyShift.
"""
import asyncio
import json
import os
import secrets
import signal
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from functools import partial
from pathlib import Path
from typing import Dict, List, Optional, cast
from urllib.parse import unquote
import jsonpatch
import jwt
import yaml
from fastapi import (APIRouter, Body, Depends, FastAPI, HTTPException, Query,
Request, WebSocket)
from fastapi.responses import StreamingResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from passlib.context import CryptContext
from pydantic import ValidationError
from skyshift.cluster_manager.kubernetes.kubernetes_manager import \
K8ConnectionError
from skyshift.cluster_manager.manager_utils import setup_cluster_manager
from skyshift.etcd_client.etcd_client import (ETCD_PORT, ConflictError,
ETCDClient, KeyNotFoundError)
from skyshift.globals import (API_SERVER_CONFIG_PATH, DEFAULT_NAMESPACE,
SKYCONF_DIR)
from skyshift.globals_object import (ALL_OBJECTS, NAMESPACED_OBJECTS,
NON_NAMESPACED_OBJECTS)
from skyshift.templates import Namespace, NamespaceMeta, ObjectException
from skyshift.templates.cluster_template import Cluster, ClusterStatusEnum
from skyshift.templates.event_template import WatchEvent
from skyshift.templates.job_template import ContainerStatusEnum, TaskStatusEnum
from skyshift.templates.rbac_template import ActionEnum, Role, RoleMeta, Rule
from skyshift.templates.user_template import User, UserList
from skyshift.utils import load_object, sanitize_cluster_name
### Utility functions for the API server.
# Assumes authentication tokens are JWT tokens
OAUTH2_SCHEME = OAuth2PasswordBearer(tokenUrl="token")
CACHED_SECRET_KEY = None
CONF_FLAG_DIR = '/.tmp/'
WORKER_LOCK_FILE = SKYCONF_DIR + CONF_FLAG_DIR + 'api_server_init.lock'
WORKER_DONE_FLAG = SKYCONF_DIR + CONF_FLAG_DIR + 'api_server_init_done.flag'
def create_jwt(data: dict,
secret_key: str,
expires_delta: Optional[timedelta] = None):
"""Creates jwt of DATA based on SECRET_KEY."""
to_encode = data.copy()
if expires_delta:
expire = datetime.now(timezone.utc) + expires_delta
else:
# 10 years
expire = datetime.now(timezone.utc) + timedelta(minutes=315360000)
to_encode.update({"exp": expire})
encoded_jwt: str = jwt.encode(to_encode, secret_key, algorithm='HS512')
return encoded_jwt
def authenticate_jwt(token: str = Depends(OAUTH2_SCHEME)) -> dict:
"""Authenticates if the token is signed by API Server."""
global CACHED_SECRET_KEY # pylint: disable=global-statement
if CACHED_SECRET_KEY is None:
secret_key = load_manager_config()["api_server"]["secret"]
CACHED_SECRET_KEY = secret_key
else:
secret_key = CACHED_SECRET_KEY
try:
payload = jwt.decode(token, secret_key, algorithms=['HS512'])
except jwt.PyJWTError as error:
raise error
return payload
def authenticate_request(token: str = Depends(OAUTH2_SCHEME)) -> str:
"""Authenticates the request using the provided token.
If the token is valid, the username is returned. Otherwise, an HTTPException is raised."""
credentials_exception = HTTPException(
status_code=401,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = authenticate_jwt(token=token)
username: str = payload.get("sub", None)
if username is None:
raise credentials_exception
# Check if time out
if datetime.now(timezone.utc) >= datetime.fromtimestamp(
payload.get("exp"), tz=timezone.utc): #type: ignore
raise HTTPException(
status_code=401,
detail="Token expired. Please log in again.",
headers={"WWW-Authenticate": "Bearer"},
)
except jwt.PyJWTError as error:
raise credentials_exception from error
return username
def load_manager_config():
"""Loads the API server config file."""
try:
with open(os.path.expanduser(API_SERVER_CONFIG_PATH),
"r") as config_file:
config_dict = yaml.safe_load(config_file)
except FileNotFoundError as error:
raise Exception(
f"API server config file not found at {API_SERVER_CONFIG_PATH}."
) from error
return config_dict
def update_manager_config(config: dict):
"""Updates the API server config file."""
with open(os.path.expanduser(API_SERVER_CONFIG_PATH), "w") as config_file:
yaml.dump(config, config_file)
def generate_nonce(length=32):
"""Generates a secure nonce."""
return secrets.token_hex(length)
CONF_FLAG_DIR = '/.tmp/'
WORKER_LOCK_FILE = SKYCONF_DIR + CONF_FLAG_DIR + 'api_server_init.lock'
WORKER_DONE_FLAG = SKYCONF_DIR + CONF_FLAG_DIR + 'api_server_init_done.flag'
def check_or_wait_initialization():
"""Creates the necessary configuration files"""
absolute_done_flag = Path(WORKER_DONE_FLAG)
absolute_lock_file = Path(WORKER_LOCK_FILE)
if os.path.exists(absolute_done_flag):
return
while os.path.exists(absolute_lock_file):
# Initialization in progress by another worker, wait...
time.sleep(1)
if not os.path.exists(absolute_done_flag):
# This worker is responsible for initialization
open(absolute_lock_file, 'a').close()
try:
api_server.installation_hook()
open(absolute_done_flag,
'a').close() # Mark initialization as complete
finally:
os.remove(absolute_lock_file)
def remove_flag_file():
"""Removes the flag file to indicate that the API server has been shut down."""
absolute_done_flag = Path(WORKER_DONE_FLAG)
if os.path.exists(absolute_done_flag):
os.remove(absolute_done_flag)
# ==============================================================================
### API Server Code.
# Hashing password
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
ADMIN_USER = os.getenv("SKYSHIFT_ADMIN_USR", "admin")
ADMIN_PWD = os.getenv("SKYSHIFT_ADMIN_PASS", "admin")
class APIServer:
"""
Defines the API server for the SkyShift.
It maintains a connection to the ETCD server and provides a REST API for
interacting with SkyShift objects. Supports CRUD operations on all objects.
"""
def __init__(self, app, etcd_port=ETCD_PORT): # pylint: disable=redefined-outer-name
self.app = app
self.etcd_client = ETCDClient(port=etcd_port)
self.router = APIRouter()
self.create_endpoints()
def installation_hook(self):
"""Primes the API server with default objects and roles."""
all_namespaces = self.etcd_client.read_prefix("namespaces")
# Hack: Create Default Namespace if it does not exist.
if DEFAULT_NAMESPACE not in all_namespaces:
self.etcd_client.write(
"namespaces/default",
Namespace(metadata=NamespaceMeta(name="default")).model_dump(
mode="json"),
)
# Create admin role.
admin_role = Role(metadata=RoleMeta(name="admin-role",
namespaces=["*"]),
rules=[Rule(resources=["*"], actions=["*"])],
users=[ADMIN_USER])
self.etcd_client.write(
"roles/admin-role",
admin_role.dict(),
)
# Create reader role (can only read objects).
reader_role = Role(
metadata=RoleMeta(name="reader-role", namespaces=["*"]),
rules=[Rule(resources=["*"], actions=["get", "list"])],
users=[ADMIN_USER])
self.etcd_client.write(
"roles/reader-role",
reader_role.dict(),
)
# Create inviter role.
inviter_role = Role(
metadata=RoleMeta(name="inviter-role", namespaces=["*"]),
rules=[Rule(resources=["user"], actions=["create"])
], #Create user actually means can create invite to user.
users=[])
self.etcd_client.write(
"roles/inviter-role",
inviter_role.dict(),
)
# Create system admin user and create authentication token.
admin_invite_nonce = generate_nonce()
self.etcd_client.write(
f"invites/{admin_invite_nonce}",
{
"used": False,
"revoked": False,
"owner": "",
},
)
admin_invite_jwt = create_jwt(
data={
"granted_roles":
[admin_role.get_name(),
inviter_role.get_name()],
"nonce": admin_invite_nonce,
"inviter": ""
},
secret_key=load_manager_config()['api_server']['secret'],
)
admin_user = User(username=ADMIN_USER,
password=ADMIN_PWD,
email='[email protected]')
try:
self.register_user(admin_user, admin_invite_jwt)
except HTTPException: # pylint: disable=broad-except
pass
self._login_user(ADMIN_USER, ADMIN_PWD)
# Create current context if it not populated yet.
admin_config = load_manager_config()
current_context = admin_config.get('current_context', None)
if not current_context:
admin_config[
"current_context"] = f'{ADMIN_USER}-{DEFAULT_NAMESPACE}'
update_manager_config(admin_config)
def _authenticate_action(self, action: str, user: str, object_type: str,
namespace: str) -> bool:
"""Authenticates the role of a user based on intended action."""
roles = self.etcd_client.read_prefix("roles")
for role in roles:
if self._authenticate_action_with_role(action, user, object_type,
namespace, role):
return True
raise HTTPException(
status_code=401,
detail="Unauthorized access. User does not have the required role."
)
# pylint: disable=too-many-arguments
@staticmethod
def _authenticate_action_with_role(action: str, user: str,
object_type: str, namespace: str,
role: Dict) -> bool:
"""Return if USER on perform ACTION based on ROLE."""
def _verify_subset(key: str, values: List[str]) -> bool:
return "*" in values or key in values
if user not in role['users']:
return False
is_namespace = object_type in NAMESPACED_OBJECTS
if is_namespace and not _verify_subset(namespace,
role['metadata']['namespaces']):
return False
rules = role['rules']
for rule in rules:
if _verify_subset(action, rule['actions']) and _verify_subset(
object_type, rule['resources']):
return True
return False
def _authenticate_by_role_name(self, user: str, role_name: str) -> bool:
"""Authenticates the role of a user based on the Role object name. """
try:
role = self._fetch_etcd_object(f"roles/{role_name}")
return self._authenticate_by_role(user, role)
except Exception as error: # Catch-all for other exceptions such as network issues
raise HTTPException(
status_code=503,
detail='An error occured while authenticating user') from error
def _authenticate_by_role(
self,
user: str,
role: Dict,
assumed_roles: Optional[List[Dict]] = None) -> bool:
"""Authenticates USER have superset of access of the ROLE. """
if user in role['users']:
return True
if not assumed_roles:
assumed_roles = self._get_all_roles(user)
rules = role['rules']
namespaces = role["metadata"]["namespaces"]
for namespace in namespaces:
for rule in rules:
# Check if all actions permitted by RULE is also permitted for USER
resources = rule["resources"]
actions = rule["actions"]
for rsc in resources:
for act in actions:
if not any(
self._authenticate_action_with_role(
act, user, rsc, namespace, assumed_role)
for assumed_role in assumed_roles):
raise HTTPException(
status_code=401,
detail=
"Unauthorized access. User does not have the required role."
)
return True
def _authenticate_by_role_names(self, user: str,
role_names: List[str]) -> bool:
"""Authenticates USER have superset of access of the ROLE_NAMES. """
assumed_roles = self._get_all_roles(user)
roles = []
try:
for role_name in role_names:
roles.append(self._fetch_etcd_object(f"roles/{role_name}"))
except Exception as error: # Catch-all for other exceptions such as network issues
raise HTTPException(
status_code=503,
detail='An error occured while authenticating user') from error
return all(
self._authenticate_by_role(user, role, assumed_roles)
for role in roles)
def _get_all_roles(self, user: str) -> List[Dict]:
all_roles = []
roles = self.etcd_client.read_prefix("roles")
for role in roles:
if user in role['users']:
all_roles.append(role)
return all_roles
def _check_cluster_connectivity(self, cluster: Cluster): # pylint: disable=no-self-use
"""Checks if the cluster is accessible."""
try:
cluster_manager = setup_cluster_manager(cluster)
cluster_manager.get_cluster_status()
except K8ConnectionError as error:
raise HTTPException(
status_code=400,
detail=f'Could not load configuration for Kubernetes cluster\
{cluster.get_name()}.') from error
except Exception as error: # Catch-all for other exceptions such as network issues
raise HTTPException(
status_code=400,
detail=f'An error occurred while trying to connect to cluster\
{cluster.get_name()}.') from error
def _fetch_etcd_object(self, link_header: str):
"""Fetches an object from the ETCD server."""
obj_dict = self.etcd_client.read(link_header)
if obj_dict is None or obj_dict == {}:
raise HTTPException(
status_code=404,
detail=f"Object '{link_header}' not found.",
)
return obj_dict
def _login_user(self, username: str, password: str): # pylint: disable=too-many-locals, too-many-branches
"""Helper method that logs in a user."""
try:
user_dict = self._fetch_etcd_object(f"users/{username}")
except HTTPException as error:
raise HTTPException(
status_code=400,
detail="Incorrect username or password",
) from error
if not pwd_context.verify(password, user_dict['password']):
raise HTTPException(
status_code=400,
detail="Incorrect username or password",
)
access_token = create_jwt(
data={
"sub": username,
},
secret_key=load_manager_config()['api_server']['secret'],
)
access_dict = {'name': username, 'access_token': access_token}
# Update access token in admin config.
admin_config = load_manager_config()
found_user = False
if 'users' not in admin_config:
admin_config['users'] = []
for user in admin_config['users']:
if user['name'] == username:
user['access_token'] = access_token
found_user = True
break
if not found_user:
admin_config['users'].append(access_dict)
if 'contexts' not in admin_config:
admin_config['contexts'] = []
all_namespaces = self.etcd_client.read_prefix("namespaces")
# Fetch all namespaces that a user is in.
user_roles = self._get_all_roles(username)
allowed_namespaces = set()
for role in user_roles:
role_namespaces = role['metadata']['namespaces']
if '*' in role_namespaces:
allowed_namespaces = {
n['metadata']['name']
for n in all_namespaces
}
break
allowed_namespaces.update(role_namespaces)
# Populate config contexts with new (username, namespace) tuples
for namespace in allowed_namespaces:
found = False
for context in admin_config['contexts']:
if context['user'] == username and context[
'namespace'] == namespace:
found = True
break
if not found:
context_dict = {
'namespace': namespace,
'user': username,
'name': f'{username}-{namespace}'
}
admin_config['contexts'].append(context_dict)
update_manager_config(admin_config)
return access_dict
# Authentication/RBAC Methods
# pylint: disable=too-many-branches
def register_user(self, user: User, invite_token: str = Body(...)):
"""Registers a user into SkyShift."""
try:
invite = authenticate_jwt(invite_token)
if datetime.now(timezone.utc) >= datetime.fromtimestamp(
cast(float, invite.get("exp")), tz=timezone.utc):
raise HTTPException(
status_code=401,
detail="Invite token expired. Please ask for a new one.",
headers={"WWW-Authenticate": "Bearer"},
)
#Check invite(nonce) exist
invite_store = self._fetch_etcd_object(
f"invites/{invite['nonce']}")
if invite_store["revoked"] or invite_store["used"]:
raise HTTPException(
status_code=404,
detail="Invite is no longer invalid.",
)
inviter = invite['inviter']
# inviter being "" is special user for setting up admin
if inviter:
try:
self._fetch_etcd_object(f"users/{inviter}")
except HTTPException as error:
invite_store["revoked"] = True
self.etcd_client.write(f'invites/{invite.get("nonce")}',
invite_store)
raise HTTPException(
status_code=404,
detail=
"Inviter is no longer invalid. Invalidating the invite.",
) from error
if not self._authenticate_by_role_name(inviter,
'inviter-role'):
raise HTTPException(
status_code=404,
detail=
"Inviter can no longer invite users. Invite status not changed.",
)
invite_store["used"] = True
self.etcd_client.write(f'invites/{invite.get("nonce")}',
invite_store)
except HTTPException as error:
if error.status_code == 404:
raise HTTPException(
status_code=404,
detail="Invite is invalid.",
) from error
raise HTTPException(
status_code=500,
detail="Unusual error occurred.",
) from error
try:
self._fetch_etcd_object(f"users/{user.username}")
except HTTPException as error:
if error.status_code == 404:
user.password = pwd_context.hash(user.password)
self.etcd_client.write(
f"users/{user.username}",
user.model_dump(mode="json"),
)
#Add newly created user to all the granted roles
role_message = ""
assumed_roles = self._get_all_roles(inviter)
for granted_role in invite["granted_roles"]:
try:
role_dict = self._fetch_etcd_object(
f"roles/{granted_role}")
# inviter being "" is special user for setting up admin
if not inviter or self._authenticate_by_role(
inviter, role_dict, assumed_roles):
role_dict["users"].append(user.username)
self.etcd_client.write(
f"roles/{granted_role}",
role_dict,
)
role_message += f"Sucessfully added user to role {granted_role}.\n"
else:
role_message += f"Inviter can no longer added new user to role {granted_role}.\n" # pylint: disable=C0301
except HTTPException as error:
role_message += f"Unusual error has occurred when trying to add user to role {granted_role}.\n" # pylint: disable=C0301
return {
"message":
f"User registered successfully. \n{role_message}",
"user": user
}
raise HTTPException( # pylint: disable=raise-missing-from
status_code=500,
detail="Unusual error occurred.",
)
else:
raise HTTPException(
status_code=400,
detail=f"User '{user.username}' already exists.",
)
def login_for_access_token(
self, form_data: OAuth2PasswordRequestForm = Depends()):
"""Logs in a user and returns an access token."""
username = form_data.username
password = form_data.password
return self._login_user(username, password)
def create_invite(self,
roles: List[str] = Body(..., embed=True),
username: str = Depends(authenticate_request)):
"""Create invite for new user and returns the invite jwt."""
# pylint: disable=too-many-locals
try:
# Check user exist
self._fetch_etcd_object(f"users/{username}")
except HTTPException as error:
raise HTTPException(
status_code=400,
detail="Cannot create invite. User doesn't exist",
) from error
try:
if not self._authenticate_by_role_name(username, 'inviter-role'):
raise HTTPException(
status_code=401,
detail="Not authorized to create invite.",
)
except Exception as error:
raise HTTPException(
status_code=404,
detail="Something went wrong when authenticating the user.",
) from error
#Check if all roles are grantable
#@TODO:(colin): Replace once we introduce group admin
if not self._authenticate_by_role_names(username, roles):
raise HTTPException(
status_code=401,
detail=
"Unauthorized access. User does not have the required role.")
nonce = generate_nonce()
self.etcd_client.write(f"invites/{nonce}", {
"used": False,
"revoked": False,
"owner": username
})
invite_token = create_jwt(
data={
"granted_roles": roles,
"nonce": nonce,
"inviter": username
},
secret_key=load_manager_config()['api_server']['secret'],
)
return {
"message": "invite created successfully",
"invite": invite_token
}
def revoke_invite(self,
invite_token: str = Body(..., embed=True),
username: str = Depends(authenticate_request)):
"""Invoke invite."""
try:
# Check user exist
self._fetch_etcd_object(f"users/{username}")
except HTTPException as error:
raise HTTPException(
status_code=400,
detail="Cannot revoke invite. User doesn't exist",
) from error
try:
invite = authenticate_jwt(invite_token)
# empty invite['inviter'] means the special startup invite
if invite['inviter'] != username and invite['inviter']:
raise HTTPException(
status_code=404,
detail="You cannot revoke invites not from you.",
)
# Check invite(nonce) exist
invite_store = self._fetch_etcd_object(
f"invites/{invite['nonce']}")
used = invite_store["used"]
invite_store["revoked"] = True
self.etcd_client.write(f'invites/{invite.get("nonce")}',
invite_store)
except HTTPException as error:
if error.status_code == 404:
raise HTTPException(
status_code=404,
detail="Revoke request is invalid.",
) from error
raise HTTPException(
status_code=500,
detail="Unusual error occurred.",
) from error
return {
"message":
f"invite {invite_token} revoked" if not used else
f"invite {invite_token} revoked but it's used already",
}
# General methods over objects.
def create_object(self, object_type: str):
"""Creates an object of a given type."""
async def _create_object(request: Request,
namespace: str = DEFAULT_NAMESPACE,
user: str = Depends(authenticate_request)):
self._authenticate_action(ActionEnum.DELETE.value, user,
object_type, namespace)
content_type = request.headers.get("content-type", None)
body = await request.body()
if content_type == "application/json":
object_specs = json.loads(body.decode())
elif content_type == "application/yaml":
object_specs = yaml.safe_load(body.decode())
else:
raise HTTPException(
status_code=400,
detail=f"Unsupported Content-Type: {content_type}")
if object_type not in ALL_OBJECTS:
raise HTTPException(
status_code=400,
detail=f"Invalid object type: {object_type}")
object_class = ALL_OBJECTS[object_type]
try:
object_init = object_class(**object_specs)
except ObjectException as error:
raise HTTPException(
status_code=400,
detail=f"Invalid {object_type} template.") from error
object_name = object_init.get_name()
# Read all objects of the same type and check if the object already exists.
if object_type in NAMESPACED_OBJECTS:
link_header = f"{object_type}/{namespace}"
else:
link_header = object_type
list_response = self.etcd_client.read_prefix(link_header)
for obj_dict in list_response:
temp_name = obj_dict["metadata"]["name"]
if object_name == temp_name:
raise HTTPException(
status_code=409,
detail=
f"Conflict error: Object '{link_header}/{object_name}' already exists.",
)
# Check if object type is cluster and if it is accessible.
if isinstance(
object_init, Cluster
) and object_init.status.status == ClusterStatusEnum.READY.value:
self._check_cluster_connectivity(object_init)
self.etcd_client.write(f"{link_header}/{object_name}",
object_init.model_dump(mode="json"))
return object_init
return _create_object
async def list_objects(
self,
object_type: str,
namespace: str = DEFAULT_NAMESPACE,
watch: bool = Query(False),
user: str = Depends(authenticate_request),
):
"""
Lists all objects of a given type.
"""
self._authenticate_action(ActionEnum.LIST.value, user, object_type,
namespace)
if object_type not in ALL_OBJECTS:
raise HTTPException(status_code=400,
detail=f"Invalid object type: {object_type}")
object_class = ALL_OBJECTS[object_type]
if namespace is not None and object_type in NAMESPACED_OBJECTS:
link_header = f"{object_type}/{namespace}"
else:
link_header = f"{object_type}"
if watch:
return await self._watch_key(link_header)
read_response = self.etcd_client.read_prefix(link_header)
obj_cls = object_class.__name__ + "List"
obj_list = load_object({
'kind': obj_cls,
'objects': read_response,
})
return obj_list
async def get_object(
self,
object_type: str,
object_name: str,
namespace: str = DEFAULT_NAMESPACE,
watch: bool = Query(False),
user: str = Depends(authenticate_request),
): # pylint: disable=too-many-arguments
"""
Gets a specific object, raises Error otherwise.
"""
self._authenticate_action(ActionEnum.GET.value, user, object_type,
namespace)
if object_type not in ALL_OBJECTS:
raise HTTPException(status_code=400,
detail=f"Invalid object type: {object_type}")
object_class = ALL_OBJECTS[object_type]
if object_type in NAMESPACED_OBJECTS:
link_header = f"{object_type}/{namespace}"
else:
link_header = f"{object_type}"
if object_type == "clusters":
object_name = sanitize_cluster_name(object_name)
if watch:
return await self._watch_key(f"{link_header}/{object_name}")
obj_dict = self._fetch_etcd_object(f"{link_header}/{object_name}")
obj = object_class(**obj_dict)
return obj
async def _watch_key(self, key: str):
"""Watches a set of keys (prefixed by key) from Etcd3 Client."""
event_queue: asyncio.Queue = asyncio.Queue()
events_iterator, cancel_watch_fn = self.etcd_client.watch(key)
loop = asyncio.get_event_loop()
def watch_etcd_key():
for event in events_iterator:
asyncio.run_coroutine_threadsafe(event_queue.put(event), loop)
# User cancels the watch, or if the watch errors.
asyncio.run_coroutine_threadsafe(event_queue.put(None), loop)
executor = ThreadPoolExecutor(max_workers=1) # pylint: disable=consider-using-with
loop.run_in_executor(executor, watch_etcd_key)
async def generate_events():
"""Pops events from event queue and returns WatchEvent objects."""
while True:
try:
event = await event_queue.get()
if event is None:
break
event_type, event_value = event
event_value = load_object(event_value)
watch_event = WatchEvent(event_type=event_type.value,
object=event_value)
yield watch_event.model_dump_json() + "\n"
except (ValidationError, Exception): # pylint: disable=broad-except
# If watch errors, cancel watch.
break
cancel_watch_fn()
yield "{}"
return StreamingResponse(generate_events(),
media_type="application/x-ndjson",
status_code=200)
def update_object(
self,
object_type: str,
):
"""Updates an object of a given type."""
async def _update_object(
request: Request,
namespace: str = DEFAULT_NAMESPACE,
user: str = Depends(authenticate_request),
):
"""Processes request to update an object."""
self._authenticate_action(ActionEnum.UPDATE.value, user,
object_type, namespace)
content_type = request.headers.get("content-type", None)
body = await request.body()
if content_type == "application/json":
object_specs = json.loads(body.decode())
elif content_type == "application/yaml":
object_specs = yaml.safe_load(body.decode())
else:
raise HTTPException(
status_code=400,
detail=f"Unsupported Content-Type: {content_type}")
if object_type not in ALL_OBJECTS:
raise HTTPException(
status_code=400,
detail=f"Invalid object type: {object_type}")
object_class = ALL_OBJECTS[object_type]
try:
obj_instance = object_class(**object_specs)
except ObjectException as error:
raise HTTPException(
status_code=400,
detail=f"Invalid {object_type} template.") from error
object_name = obj_instance.get_name()
# Read all objects of the same type and check if the object already exists.
if object_type in NAMESPACED_OBJECTS:
link_header = f"{object_type}/{namespace}"
else:
link_header = object_type
list_response = self.etcd_client.read_prefix(link_header)
for obj_dict in list_response:
temp_name = obj_dict["metadata"]["name"]
if object_name == temp_name:
try:
self.etcd_client.update(
f"{link_header}/{object_name}",
obj_instance.model_dump(mode="json"),
)
except KeyNotFoundError as error:
raise HTTPException(status_code=404,
detail=error.msg) from error
except ConflictError as error:
raise HTTPException(status_code=409,
detail=error.msg) from error
return obj_instance
raise HTTPException(
status_code=400,
detail=f"Object '{link_header}/{object_name}' does not exist.",
)
return _update_object
# Example command:
# curl -X PATCH http://127.0.0.1:50051/clusters/local
# -H 'Content-Type: application/json'
# -d '[{"op": "replace", "path": "/status/status",
# "value": "INIT"}]'
def patch_object(self, object_type: str):
"""Patches an object of a given type."""
async def _patch_object(
request: Request,
object_name: str,
namespace: str = DEFAULT_NAMESPACE,
user: str = Depends(authenticate_request),
):
self._authenticate_action(ActionEnum.PATCH.value, user,
object_type, namespace)
content_type = request.headers.get("content-type", None)
body = await request.body()
if content_type == "application/json":
patch_list = json.loads(body.decode())
elif content_type == "application/yaml":
patch_list = yaml.safe_load(body.decode())
else:
raise HTTPException(
status_code=400,
detail=f"Unsupported Content-Type: {content_type}")
if object_type not in ALL_OBJECTS:
raise HTTPException(
status_code=400,
detail=f"Invalid object type: {object_type}")
# Read all objects of the same type and check if the object already exists.
if object_type in NAMESPACED_OBJECTS:
link_header = f"{object_type}/{namespace}"
else:
link_header = f"{object_type}"
obj_dict = self.etcd_client.read(f"{link_header}/{object_name}")
if obj_dict is None or obj_dict == {}:
raise HTTPException(
status_code=404,
detail=f"Object '{link_header}/{object_name}' not found.",
)
# Support basic JSON patch: https://jsonpatch.com/
try:
patch = jsonpatch.JsonPatch(patch_list)
except Exception as error:
raise HTTPException(status_code=400,
detail="Invalid patch list.") from error
updated_obj_dict = patch.apply(obj_dict)
object_class = ALL_OBJECTS[object_type]
obj = object_class(**updated_obj_dict)
try:
self.etcd_client.update(
f"{link_header}/{object_name}",
obj.model_dump(mode="json"),
)
except KeyNotFoundError as error:
raise HTTPException(status_code=404,
detail=error.msg) from error
except Exception as error:
raise HTTPException(status_code=400, detail=error) from error
return obj
return _patch_object
def job_logs(self,