-
Notifications
You must be signed in to change notification settings - Fork 29
/
client.py
2587 lines (2290 loc) · 96.5 KB
/
client.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
# Copyright 2015, Aiven, https://aiven.io/
#
# This file is under the Apache License, Version 2.0.
# See the file `LICENSE` for details.
from __future__ import annotations
from .common import UNDEFINED
from .session import get_requests_session
from http import HTTPStatus
from requests import Response
from requests_toolbelt import MultipartEncoder # type: ignore
from typing import Any, BinaryIO, Callable, Collection, Mapping, Sequence, TypedDict
from urllib.parse import quote
import json
import logging
import re
import requests
import time
import warnings
try:
from .version import __version__
except ImportError:
__version__ = "UNKNOWN"
UNCHANGED = object() # used as a sentinel value
class Error(Exception):
"""Request error"""
def __init__(self, response: Response, status: int = 520) -> None:
Exception.__init__(self, response.text)
self.response = response
self.status = status
class ResponseError(Exception):
"""Server returned error message"""
class Tag(TypedDict):
key: str
value: str
class AivenClientBase:
"""Aiven Client with low-level HTTP operations"""
def __init__(self, base_url: str, show_http: bool = False, request_timeout: int | None = None) -> None:
self.log = logging.getLogger("AivenClient")
self.auth_token: str | None = None
self.base_url = base_url
self.log.debug("using %r", self.base_url)
self.session = get_requests_session(timeout=request_timeout)
self.http_log = logging.getLogger("aiven_http")
self.init_http_logging(show_http)
self.api_prefix = "/v1"
def init_http_logging(self, show_http: bool) -> None:
http_handler = logging.StreamHandler()
http_handler.setFormatter(logging.Formatter("%(message)s"))
self.http_log.addHandler(http_handler)
self.http_log.propagate = False
self.http_log.setLevel(logging.INFO)
if show_http:
self.http_log.setLevel(logging.DEBUG)
def set_auth_token(self, token: str) -> None:
self.auth_token = token
def set_ca(self, ca: str) -> None:
self.session.verify = ca
def _execute(self, func: Callable, method: str, path: str, body: Any, params: Any = None) -> Response:
url = self.base_url + path
headers = {}
if isinstance(body, dict):
headers["content-type"] = "application/json"
data = json.dumps(body)
log_data = json.dumps(body, sort_keys=True, indent=4)
elif isinstance(body, MultipartEncoder):
headers["content-type"] = body.content_type
data = body
log_data = data
else:
headers["content-type"] = "application/octet-stream"
data = body
log_data = data or ""
if self.auth_token:
headers["authorization"] = "aivenv1 {token}".format(token=self.auth_token)
self.http_log.debug("-----Request Begin-----")
self.http_log.debug("%s %s %s", method, url, params if params else "")
for header, header_value in headers.items():
self.http_log.debug("%s: %s", header, header_value)
self.http_log.debug("")
self.http_log.debug("%s", log_data)
self.http_log.debug("-----Request End-----")
response = func(url, headers=headers, params=params, data=data)
self.http_log.debug("-----Response Begin-----")
self.http_log.debug("%s %s", response.status_code, response.reason)
for header, header_value in response.headers.items():
self.http_log.debug("%s: %s", header, header_value)
self.http_log.debug("")
if response.headers.get("content-type") == "application/json":
self.http_log.debug("%s", json.dumps(response.json(), sort_keys=True, indent=4))
else:
self.http_log.debug("%s", response.text)
self.http_log.debug("-----Response End-----")
if not str(response.status_code).startswith("2"):
raise Error(response, status=response.status_code)
return response
def get(self, path: str = "", params: Any = None) -> Response:
"""HTTP GET"""
return self._execute(self.session.get, "GET", path, body=None, params=params)
def patch(self, path: str = "", body: Any = None, params: Any = None) -> Response:
"""HTTP PATCH"""
return self._execute(self.session.patch, "PATCH", path, body, params)
def post(self, path: str = "", body: Any = None, params: Any = None) -> Response:
"""HTTP POST"""
return self._execute(self.session.post, "POST", path, body, params)
def put(self, path: str = "", body: Any = None, params: Any = None) -> Response:
"""HTTP PUT"""
return self._execute(self.session.put, "PUT", path, body, params)
def delete(self, path: str = "", body: Any = None, params: Any = None) -> Response:
"""HTTP DELETE"""
return self._execute(self.session.delete, "DELETE", path, body, params)
def verify(
self,
op: Callable[..., Response],
path: str,
body: Any = None,
params: Any = None,
result_key: str | None = None,
retry: int | None = None,
) -> Any:
# Retry GET operations by default
if retry is None and op == self.get:
attempts = 3
else:
attempts = 1 + (retry or 0)
path = self.api_prefix + path
while attempts:
attempts -= 1
try:
if body is not None:
response = op(path=path, body=body, params=params)
else:
response = op(path=path, params=params)
break
except requests.exceptions.ConnectionError as ex:
if attempts <= 0:
raise
self.log.warning(
"%s %s failed: %s: %s; retrying in 0.2 seconds, %s attempts left",
op.__name__.upper(),
path,
ex.__class__.__name__,
ex,
attempts,
)
time.sleep(0.2)
return self._process_response(response=response, op=op, path=path, result_key=result_key)
@staticmethod
def build_path(*parts: str) -> str:
return "/" + "/".join(quote(part, safe="") for part in parts)
def _process_response(
self,
response: Response,
op: Callable[..., Response],
path: str,
result_key: str | None = None,
) -> Mapping | bytes:
# Check API is actually returning data or not
if response.status_code == HTTPStatus.NO_CONTENT or len(response.content) == 0:
return {}
if response.headers.get("Content-Type") == "application/octet-stream":
return response.content
result = response.json()
if result.get("error"):
raise ResponseError(
"server returned error: {op} {base_url}{path} {result}".format(
op=op.__doc__, base_url=self.base_url, path=path, result=result
)
)
if result_key is not None:
return result[result_key]
return result
class AivenClient(AivenClientBase):
"""Aiven Client with high-level operations"""
def get_service_versions(self) -> Sequence[Mapping[str, str]]:
return self.verify(self.get, "/service_versions", result_key="service_versions")
def get_service_indexes(self, project: str, service: str) -> Sequence[dict[str, Any]]:
return self.verify(
self.get,
self.build_path("project", project, "service", service, "index"),
result_key="indexes",
)
def delete_service_index(self, project: str, service: str, index_name: str) -> Mapping:
return self.verify(
self.delete,
self.build_path("project", project, "service", service, "index", index_name),
)
def get_clouds(self, project: str | None) -> Sequence[dict[str, Any]]:
if project is None:
path = "/clouds"
else:
path = self.build_path("project", project, "clouds")
return self.verify(self.get, path, result_key="clouds")
def get_service(self, project: str, service: str) -> dict[str, Any]:
return self.verify(
self.get,
self.build_path("project", project, "service", service),
result_key="service",
)
def get_service_metrics(self, project: str, service: str, period: str) -> Mapping:
path = self.build_path("project", project, "service", service, "metrics")
return self.verify(self.post, path, result_key="metrics", body={"period": period})
def authenticate_user(self, email: str, password: str, otp: str | None = None, tenant_id: str | None = None) -> Mapping:
body = {
"email": email,
"password": password,
}
if otp is not None:
body["otp"] = otp
if tenant_id is not None:
body["tenant"] = tenant_id
return self.verify(self.post, "/userauth", body=body)
def create_service_connection_pool(
self,
project: str,
service: str,
pool_name: str,
dbname: str,
username: str | None = None,
pool_size: int | None = None,
pool_mode: str | None = None,
) -> Mapping:
body: dict[str, Any] = {"database": dbname, "pool_name": pool_name}
if username:
body["username"] = username
if pool_size:
body["pool_size"] = pool_size
if pool_mode:
body["pool_mode"] = pool_mode
return self.verify(
self.post,
self.build_path("project", project, "service", service, "connection_pool"),
body=body,
)
def update_service_connection_pool(
self,
project: str,
service: str,
pool_name: str,
dbname: str | None = None,
username: object | str = UNCHANGED,
pool_size: int | None = None,
pool_mode: str | None = None,
) -> Mapping:
body = {}
if username is not UNCHANGED:
body["username"] = username
if dbname is not None:
body["database"] = dbname
if pool_size is not None:
body["pool_size"] = pool_size
if pool_mode is not None:
body["pool_mode"] = pool_mode
path = self.build_path("project", project, "service", service, "connection_pool", pool_name)
return self.verify(self.put, path, body=body)
def delete_service_connection_pool(self, project: str, service: str, pool_name: str) -> Mapping:
path = self.build_path("project", project, "service", service, "connection_pool", pool_name)
return self.verify(self.delete, path)
def create_service_database(self, project: str, service: str, dbname: str) -> Mapping:
return self.verify(
self.post,
self.build_path("project", project, "service", service, "db"),
body={"database": dbname},
)
def delete_service_database(self, project: str, service: str, dbname: str) -> Mapping:
path = self.build_path("project", project, "service", service, "db", dbname)
return self.verify(self.delete, path)
def list_databases(self, project: str, service: str) -> Mapping:
path = self.build_path("project", project, "service", service, "db")
return self.verify(self.get, path)
def create_service_user(
self, project: str, service: str, username: str, extra_params: Mapping[str, Any] | None = None
) -> Mapping:
body = {"username": username}
if extra_params:
body.update(extra_params)
return self.verify(
self.post,
self.build_path("project", project, "service", service, "user"),
body=body,
result_key="user",
)
def delete_service_user(self, project: str, service: str, username: str) -> Mapping:
path = self.build_path("project", project, "service", service, "user", username)
return self.verify(self.delete, path)
def get_service_user(self, project: str, service: str, username: str) -> Mapping:
path = self.build_path("project", project, "service", service, "user", username)
return self.verify(self.get, path, result_key="user")
def acknowledge_service_user_certificate(self, project: str, service: str, username: str) -> Mapping:
path = self.build_path("project", project, "service", service, "user", username)
body = {"operation": "acknowledge-renewal"}
return self.verify(self.put, path, body=body)
def reset_service_user_password(self, project: str, service: str, username: str, password: str) -> Mapping:
path = self.build_path("project", project, "service", service, "user", username)
body = {"operation": "reset-credentials"}
if password is not None:
body["new_password"] = password
return self.verify(self.put, path, body=body)
def set_service_user_access_control(
self, project: str, service: str, username: str, access_control: Mapping[str, Any]
) -> Mapping:
path = self.build_path("project", project, "service", service, "user", username)
body = {"operation": "set-access-control", "access_control": access_control}
return self.verify(self.put, path, body=body)
def get_service_integration_endpoints(self, project: str) -> Sequence[dict[str, Any]]:
path = self.build_path("project", project, "integration_endpoint")
return self.verify(self.get, path, result_key="service_integration_endpoints")
def get_service_integration_endpoint_types(self, project: str) -> Sequence[dict[str, Any]]:
path = self.build_path("project", project, "integration_endpoint_types")
return self.verify(self.get, path, result_key="endpoint_types")
def create_service_integration_endpoint(
self, project: str, endpoint_name: str, endpoint_type: str, user_config: Mapping[str, Any]
) -> Mapping:
return self.verify(
self.post,
self.build_path("project", project, "integration_endpoint"),
body={
"endpoint_name": endpoint_name,
"endpoint_type": endpoint_type,
"user_config": user_config,
},
)
def update_service_integration_endpoint(self, project: str, endpoint_id: str, user_config: Mapping[str, Any]) -> Mapping:
return self.verify(
self.put,
self.build_path("project", project, "integration_endpoint", endpoint_id),
body={
"user_config": user_config,
},
)
def delete_service_integration_endpoint(self, project: str, endpoint_id: str) -> Mapping:
return self.verify(
self.delete,
self.build_path("project", project, "integration_endpoint", endpoint_id),
)
def get_service_backups(self, project: str, service: str) -> Sequence[dict[str, Any]]:
path = self.build_path("project", project, "service", service, "backups")
return self.verify(self.get, path, result_key="backups")
def get_service_integrations(self, project: str, service: str) -> Sequence[dict[str, Any]]:
path = self.build_path("project", project, "service", service, "integration")
return self.verify(self.get, path, result_key="service_integrations")
def get_service_integration_types(self, project: str) -> Sequence[dict[str, Any]]:
path = self.build_path("project", project, "integration_types")
return self.verify(self.get, path, result_key="integration_types")
def create_service_integration(
self,
project: str,
integration_type: str,
source_service: str | None = None,
dest_service: str | None = None,
source_endpoint_id: str | None = None,
dest_endpoint_id: str | None = None,
user_config: Mapping[str, Any] | None = None,
) -> Mapping:
user_config = user_config or {}
return self.verify(
self.post,
self.build_path("project", project, "integration"),
body={
"source_endpoint_id": source_endpoint_id,
"source_service": source_service,
"dest_endpoint_id": dest_endpoint_id,
"dest_service": dest_service,
"integration_type": integration_type,
"user_config": user_config,
},
)
def update_service_integration(self, project: str, integration_id: str, user_config: Mapping[str, Any]) -> Mapping:
return self.verify(
self.put,
self.build_path("project", project, "integration", integration_id),
body={
"user_config": user_config,
},
result_key="service_integration",
)
def get_service_integration(self, project: str, integration_id: str) -> Mapping:
path = self.build_path("project", project, "integration", integration_id)
return self.verify(self.get, path, result_key="service_integration")
def delete_service_integration(self, project: str, integration_id: str) -> Mapping:
return self.verify(
self.delete,
self.build_path("project", project, "integration", integration_id),
)
def create_service_task(self, project: str, service: str, body: Mapping[str, Any]) -> Mapping:
return self.verify(
self.post,
self.build_path("project", project, "service", service, "task"),
body=body,
)
def get_service_task(self, project: str, service: str, task_id: str) -> Mapping:
path = self.build_path("project", project, "service", service, "task", task_id)
return self.verify(self.get, path, result_key="task")
def get_service_topic(self, project: str, service: str, topic: str) -> Mapping:
path = self.build_path("project", project, "service", service, "topic", topic)
return self.verify(self.get, path, result_key="topic")
def _set_namespace_options(
self,
ns: dict[str, Any],
ns_ret: str | None = None,
ns_res: str | None = None,
ns_blocksize_dur: str | None = None,
ns_block_data_expiry_dur: str | None = None,
ns_buffer_future_dur: str | None = None,
ns_buffer_past_dur: str | None = None,
ns_writes_to_commitlog: bool | None = None,
) -> None:
re_ns_duration = re.compile(r"\d+[smhd]")
def _validate_ns_dur(val: str) -> None:
if not re_ns_duration.match(val):
raise ValueError(f"Invalid namespace duration value '{val}'")
ns["options"] = ns.get("options", {})
ns["options"]["retention_options"] = ns["options"].get("retention_options", {})
if ns_ret:
_validate_ns_dur(ns_ret)
ns["options"]["retention_options"]["retention_period_duration"] = ns_ret
if ns_res:
_validate_ns_dur(ns_res)
ns["resolution"] = ns_res
if ns_blocksize_dur:
_validate_ns_dur(ns_blocksize_dur)
ns["options"]["retention_options"]["blocksize_duration"] = ns_blocksize_dur
if ns_block_data_expiry_dur:
_validate_ns_dur(ns_block_data_expiry_dur)
ns["options"]["retention_options"]["block_data_expiry_duration"] = ns_block_data_expiry_dur
if ns_buffer_future_dur:
_validate_ns_dur(ns_buffer_future_dur)
ns["options"]["retention_options"]["buffer_future_duration"] = ns_buffer_future_dur
if ns_buffer_past_dur:
_validate_ns_dur(ns_buffer_past_dur)
ns["options"]["retention_options"]["buffer_past_duration"] = ns_buffer_past_dur
if ns_writes_to_commitlog is not None:
ns["options"]["writes_to_commitlog"] = bool(ns_writes_to_commitlog)
def list_m3_namespaces(self, project: str, service: str) -> Sequence[dict[str, Any]]:
service_res = self.get_service(project=project, service=service)
return service_res.get("user_config", {}).get("namespaces", [])
def delete_m3_namespace(self, project: str, service: str, ns_name: str) -> Mapping:
service_res = self.get_service(project=project, service=service)
old_namespaces = service_res.get("user_config", {}).get("namespaces", [])
new_namespaces = [ns for ns in old_namespaces if ns["name"] != ns_name]
if len(old_namespaces) == len(new_namespaces):
raise KeyError(f"Namespace '{ns_name}' does not exist")
return self.verify(
self.put,
self.build_path("project", project, "service", service),
body={"user_config": {"namespaces": new_namespaces}},
)
def add_m3_namespace(
self,
project: str,
service: str,
ns_name: str,
ns_type: str,
ns_ret: str,
ns_res: str | None = None,
ns_blocksize_dur: str | None = None,
ns_block_data_expiry_dur: str | None = None,
ns_buffer_future_dur: str | None = None,
ns_buffer_past_dur: str | None = None,
ns_writes_to_commitlog: bool | None = None,
) -> Mapping:
service_res = self.get_service(project=project, service=service)
namespaces = service_res.get("user_config", {}).get("namespaces", [])
valid_namespace_types = {"unaggregated", "aggregated"}
if ns_type not in valid_namespace_types:
raise ValueError(f"Invalid namespace type {ns_type}, valid types {valid_namespace_types}")
new_namespace = {
"name": ns_name,
"type": ns_type,
}
self._set_namespace_options(
ns=new_namespace,
ns_ret=ns_ret,
ns_res=ns_res,
ns_blocksize_dur=ns_blocksize_dur,
ns_block_data_expiry_dur=ns_block_data_expiry_dur,
ns_buffer_future_dur=ns_buffer_future_dur,
ns_buffer_past_dur=ns_buffer_past_dur,
ns_writes_to_commitlog=ns_writes_to_commitlog,
)
namespaces.append(new_namespace)
return self.verify(
self.put,
self.build_path("project", project, "service", service),
body={"user_config": {"namespaces": namespaces}},
)
def update_m3_namespace(
self,
project: str,
service: str,
ns_name: str,
ns_ret: str | None = None,
ns_res: str | None = None,
ns_blocksize_dur: str | None = None,
ns_block_data_expiry_dur: str | None = None,
ns_buffer_future_dur: str | None = None,
ns_buffer_past_dur: str | None = None,
ns_writes_to_commitlog: bool | None = None,
) -> Mapping:
service_res = self.get_service(project=project, service=service)
namespaces = service_res.get("user_config", {}).get("namespaces", [])
namespace = None
for ns in namespaces:
if ns["name"] == ns_name:
namespace = ns
if not namespace:
raise KeyError(f"Namespace '{ns_name}' does not exist")
self._set_namespace_options(
ns=namespace,
ns_ret=ns_ret,
ns_res=ns_res,
ns_blocksize_dur=ns_blocksize_dur,
ns_block_data_expiry_dur=ns_block_data_expiry_dur,
ns_buffer_future_dur=ns_buffer_future_dur,
ns_buffer_past_dur=ns_buffer_past_dur,
ns_writes_to_commitlog=ns_writes_to_commitlog,
)
return self.verify(
self.put,
self.build_path("project", project, "service", service),
body={"user_config": {"namespaces": namespaces}},
)
def list_service_topics(self, project: str, service: str) -> Sequence[dict[str, Any]]:
return self.verify(
self.get,
self.build_path("project", project, "service", service, "topic"),
result_key="topics",
)
def create_service_topic(
self,
project: str,
service: str,
topic: str,
partitions: int,
replication: int,
min_insync_replicas: int,
retention_bytes: int,
retention_hours: int,
cleanup_policy: str,
retention_ms: int | None = None,
remote_storage_enable: bool | None = None,
local_retention_ms: int | None = None,
local_retention_bytes: int | None = None,
tags: Sequence[Tag] | None = None,
) -> Mapping:
body: dict[str, Any] = {
"cleanup_policy": cleanup_policy,
"min_insync_replicas": min_insync_replicas,
"topic_name": topic,
"partitions": partitions,
"replication": replication,
"retention_bytes": retention_bytes,
"retention_hours": retention_hours,
}
config = {}
if retention_ms is not None:
config["retention_ms"] = retention_ms
if remote_storage_enable is not None:
config["remote_storage_enable"] = remote_storage_enable
if local_retention_ms is not None:
config["local_retention_ms"] = local_retention_ms
if local_retention_bytes is not None:
config["local_retention_bytes"] = local_retention_bytes
if config:
body["config"] = config
if tags is not None:
body.update({"tags": tags})
return self.verify(
self.post,
self.build_path("project", project, "service", service, "topic"),
body=body,
)
def update_service_topic(
self,
project: str,
service: str,
topic: str,
partitions: int,
retention_bytes: int,
retention_hours: int,
min_insync_replicas: int,
retention_ms: int | None = None,
remote_storage_enable: bool | None = None,
local_retention_ms: int | None = None,
local_retention_bytes: int | None = None,
replication: int | None = None,
tags: Sequence[str] | None = None,
) -> Mapping:
body: dict[str, Any] = {
"partitions": partitions,
"min_insync_replicas": min_insync_replicas,
"replication": replication,
"retention_bytes": retention_bytes,
"retention_hours": retention_hours,
}
config = {}
if retention_ms is not None:
config["retention_ms"] = retention_ms
if remote_storage_enable is not None:
config["remote_storage_enable"] = remote_storage_enable
if local_retention_ms is not None:
config["local_retention_ms"] = local_retention_ms
if local_retention_bytes is not None:
config["local_retention_bytes"] = local_retention_bytes
if config:
body["config"] = config
if tags is not None:
body.update({"tags": tags})
return self.verify(
self.put,
self.build_path("project", project, "service", service, "topic", topic),
body=body,
)
def delete_service_topic(self, project: str, service: str, topic: str) -> Mapping:
return self.verify(
self.delete,
self.build_path("project", project, "service", service, "topic", topic),
)
def list_service_elasticsearch_acl_config(self, project: str, service: str) -> Mapping:
return self.verify(
self.get,
self.build_path("project", project, "service", service, "elasticsearch", "acl"),
)
@staticmethod
def _add_es_acl_rules(config: dict[str, Any], user: str | None, rules: Mapping[str, Any]) -> None:
user_acl = None
for acl in config["acls"]:
if acl["username"] == user:
user_acl = acl
break
if user_acl is None: # new user
user_acl = {"username": user, "rules": []}
config["acls"].append(user_acl)
patterns = {rule["index"]: rule["permission"] for rule in user_acl["rules"]}
patterns.update(rules)
user_acl["rules"] = [{"index": index, "permission": permission} for index, permission in patterns.items()]
@staticmethod
def _del_es_acl_rules(config: dict[str, Any], user: str | None, rules: set[str]) -> None:
acls = []
user_acl = None
for acl in config["acls"]:
if acl["username"] != user:
acls.append(acl)
if acl["username"] == user:
user_acl = acl
config["acls"] = acls
if user_acl is None: # No rules existed for the user
return
if not rules: # removing all rules
return
# Remove the requested rules
user_acl["rules"] = [rule for rule in user_acl["rules"] if rule["index"] not in rules]
config["acls"].append(user_acl)
def update_service_elasticsearch_acl_config(
self,
project: str,
service: str,
enabled: bool | None = None,
extended_acl: bool | None = None,
username: str | None = None,
add_rules: Sequence[str] | None = None,
del_rules: Sequence[str] | None = None,
) -> Mapping:
acl_config = self.list_service_elasticsearch_acl_config(project, service)["elasticsearch_acl_config"]
if enabled is not None:
acl_config["enabled"] = enabled
if extended_acl is not None:
acl_config["extendedAcl"] = extended_acl
if add_rules is not None:
try:
rules = {index.strip(): permission.strip() for index, permission in [rule.split("/") for rule in add_rules]}
except ValueError as ex:
raise ValueError("Unrecognized index-pattern/permission rule") from ex
self._add_es_acl_rules(config=acl_config, user=username, rules=rules)
if del_rules is not None:
self._del_es_acl_rules(
config=acl_config,
user=username,
rules=set(rule.strip() for rule in del_rules),
)
path = self.build_path("project", project, "service", service, "elasticsearch", "acl")
return self.verify(self.put, path, body={"elasticsearch_acl_config": acl_config})
def add_service_kafka_acl(self, project: str, service: str, permission: str, topic: str, username: str) -> Mapping:
return self.verify(
self.post,
self.build_path("project", project, "service", service, "acl"),
body={
"permission": permission,
"topic": topic,
"username": username,
},
)
def add_service_kafka_schema_registry_acl(
self,
project: str,
service: str,
permission: str,
resource: str,
username: str,
) -> Mapping:
return self.verify(
self.post,
self.build_path("project", project, "service", service, "kafka", "schema-registry", "acl"),
body={
"permission": permission,
"resource": resource,
"username": username,
},
)
def create_connector_config_based_on_current(
self, project: str, service: str, connector_name: str, config_update: Mapping[str, Any]
) -> Mapping:
current_connectors = self.list_kafka_connectors(project, service)
connector = [conn for conn in current_connectors["connectors"] if conn["name"] == connector_name]
if not connector:
raise KeyError("Current configuration for connector '{}' not in connector list".format(connector_name))
assert len(connector) == 1
full_config = connector[0]["config"]
full_config.update(config_update)
return full_config
def delete_service_kafka_acl(self, project: str, service: str, acl_id: str) -> Mapping:
return self.verify(
self.delete,
self.build_path("project", project, "service", service, "acl", acl_id),
)
def delete_service_kafka_schema_registry_acl(self, project: str, service: str, acl_id: str) -> Mapping:
return self.verify(
self.delete,
self.build_path("project", project, "service", service, "kafka", "schema-registry", "acl", acl_id),
)
def get_available_kafka_connectors(self, project: str, service: str) -> Mapping:
return self.verify(
self.get,
self.build_path("project", project, "service", service, "available-connectors"),
)
def list_kafka_connectors(self, project: str, service: str) -> Mapping:
return self.verify(
self.get,
self.build_path("project", project, "service", service, "connectors"),
)
def get_kafka_connector_status(self, project: str, service: str, connector_name: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"connectors",
connector_name,
"status",
)
return self.verify(self.get, path)
def get_kafka_connector_schema(self, project: str, service: str, connector_name: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"connector-plugins",
connector_name,
"configuration",
)
return self.verify(self.get, path)
def create_kafka_connector(self, project: str, service: str, config: Mapping[str, Any]) -> Mapping:
return self.verify(
self.post,
self.build_path("project", project, "service", service, "connectors"),
body=config,
)
def update_kafka_connector(
self, project: str, service: str, connector_name: str, config: Mapping[str, Any], fetch_current: bool = False
) -> Mapping:
path = self.build_path("project", project, "service", service, "connectors", connector_name)
if fetch_current:
config = self.create_connector_config_based_on_current(project, service, connector_name, config)
return self.verify(self.put, path, body=config)
def delete_kafka_connector(self, project: str, service: str, connector_name: str) -> Mapping:
path = self.build_path("project", project, "service", service, "connectors", connector_name)
return self.verify(self.delete, path)
def pause_kafka_connector(self, project: str, service: str, connector_name: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"connectors",
connector_name,
"pause",
)
return self.verify(self.post, path)
def resume_kafka_connector(self, project: str, service: str, connector_name: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"connectors",
connector_name,
"resume",
)
return self.verify(self.post, path)
def restart_kafka_connector(self, project: str, service: str, connector_name: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"connectors",
connector_name,
"restart",
)
return self.verify(self.post, path)
def restart_kafka_connector_task(self, project: str, service: str, connector_name: str, task_id: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"connectors",
connector_name,
"tasks",
task_id,
"restart",
)
return self.verify(self.post, path)
def get_schema(self, project: str, service: str, schema_id: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"kafka",
"schema",
"schemas",
"ids",
schema_id,
)
return self.verify(self.get, path)
def check_schema_compatibility(self, project: str, service: str, subject: str, version: str, schema: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"kafka",
"schema",
"compatibility",
"subjects",
subject,
"versions",
version,
)
return self.verify(self.post, path, body={"schema": schema})
def get_schema_global_configuration(self, project: str, service: str) -> Mapping:
path = self.build_path("project", project, "service", service, "kafka", "schema", "config")
return self.verify(self.get, path)
def update_schema_global_configuration(self, project: str, service: str, compatibility: str) -> Mapping:
path = self.build_path("project", project, "service", service, "kafka", "schema", "config")
return self.verify(self.put, path, body={"compatibility": compatibility})
def get_schema_subject_configuration(self, project: str, service: str, subject: str) -> Mapping:
path = self.build_path("project", project, "service", service, "kafka", "schema", "config", subject)
return self.verify(self.get, path)
def update_schema_subject_configuration(self, project: str, service: str, subject: str, compatibility: str) -> Mapping:
path = self.build_path("project", project, "service", service, "kafka", "schema", "config", subject)
return self.verify(self.put, path, body={"compatibility": compatibility})
def list_schema_subjects(self, project: str, service: str) -> Mapping:
path = self.build_path("project", project, "service", service, "kafka", "schema", "subjects")
return self.verify(self.get, path)
def delete_schema_subject(self, project: str, service: str, subject: str) -> Mapping:
path = self.build_path(
"project",
project,
"service",
service,
"kafka",
"schema",
"subjects",
subject,
)
return self.verify(self.delete, path)