-
Notifications
You must be signed in to change notification settings - Fork 736
Expand file tree
/
Copy pathadmin.py
More file actions
2205 lines (1872 loc) · 75.8 KB
/
admin.py
File metadata and controls
2205 lines (1872 loc) · 75.8 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
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 2021 Redpanda Data, Inc.
#
# Use of this software is governed by the Business Source License
# included in the file licenses/BSL.md
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software will be governed
# by the Apache License, Version 2.0
import json
import random
import time
import urllib.parse
from dataclasses import dataclass
from enum import Enum
from json.decoder import JSONDecodeError
from logging import Logger
from typing import Any, Callable, NamedTuple, Optional, Protocol, overload
from uuid import UUID
import requests
from ducktape.cluster.cluster import ClusterNode
from ducktape.utils.util import wait_until
from requests import Response
from requests.adapters import HTTPAdapter
from requests.exceptions import HTTPError, RequestException
from urllib3.util.retry import Retry
from rptest.services.redpanda_types import OAuthBearerCredentials, SaslCredentials
from rptest.util import not_none, wait_until_result
from rptest.utils.mode_checks import is_debug_mode
DEFAULT_TIMEOUT = 30
MaybeNode = ClusterNode | None
# The Admin class is used by RedpandaService and we also pass
# a RedpandaService to Admin instances which use it for logging
# among other things. So a circular dependency though not at the
# runtime level (only RedpandaService imports Admin, Admin just uses
# service objects passed in from outside and doesn't need to import
# them). However, from a type checking point of view this circular
# dependency is real. There a few workarounds, but mine is just to use
# a small protocol to stand-in for RedpandaService with the properties
# we actually use.
class RedpandaServiceProto(Protocol):
nodes: list[ClusterNode]
@property
def logger(self) -> Logger: ...
def node_id(
self, node: ClusterNode, force_refresh: bool = False, timeout_sec: int = 30
) -> int: ...
def get_node(self, idx: int) -> ClusterNode: ...
def started_nodes(self) -> list[ClusterNode]: ...
class AuthPreservingSession(requests.Session):
"""
Override `requests` default behaviour of dropping Authorization
headers when redirecting. This makes sense as a general default,
but in the case of the redpanda admin API, we trust the server to
only redirect us to other equally privileged servers within
the same cluster.
"""
def should_strip_auth(self, old_url: str, new_url: str) -> bool:
return False
class Replica:
node_id: int
core: int
def __init__(self, replica_dict: dict[str, Any]) -> None:
self.node_id = replica_dict["node_id"]
self.core = replica_dict["core"]
def __getitem__(self, item_type: str) -> int | None:
if item_type == "node_id":
return self.node_id
elif item_type == "core":
return self.core
return None
class PartitionDetails:
replicas: list[Replica]
leader: int | None
status: str | None
def __init__(self) -> None:
self.replicas = []
self.leader = None
self.status = None
class RedpandaNode(NamedTuple):
# host or ip address
ip: str
# node id in redpanda.yaml
id: int
class CommittedWasmOffset(NamedTuple):
name: str
partition: int
offset: int
class RoleErrorCode(Enum):
MALFORMED_DEF = 40001
INVALID_NAME = 40002
UNRECOGNIZED_FIELD = 40003
MEMBER_LIST_CONFLICT = 40004
ROLE_NOT_FOUND = 40401
ROLE_ALERADY_EXISTS = 40901
ROLE_NAME_CONFLICT = 40902
class RoleError:
def __init__(self, code: RoleErrorCode, message: str):
self.code = code
self.message = message
@classmethod
def from_json(cls, body: str):
data = json.loads(body)
return cls(RoleErrorCode(data["code"]), data["message"])
@classmethod
def from_http_error(cls, e: HTTPError):
data = e.response.json()
return cls.from_json(data["message"])
class RoleUpdate(NamedTuple):
role: str
class RoleDescription(NamedTuple):
name: str
class RolesList:
def __init__(self, roles: list[RoleDescription]):
self.roles = roles
def __getitem__(self, i: int) -> RoleDescription:
return self.roles[i]
def __len__(self) -> int:
return len(self.roles)
def __str__(self) -> str:
return json.dumps(self.roles)
@classmethod
def from_json(cls, body: bytes) -> "RolesList":
d = json.loads(body)
for k in d:
assert k == "roles", f"Unexpected key {k}"
return cls([RoleDescription(**r) for r in d.get("roles", [])])
@classmethod
def from_response(cls, rsp: Response) -> "RolesList":
return cls.from_json(rsp.content)
class RoleMember(NamedTuple):
class PrincipalType(str, Enum):
USER = "User"
principal_type: PrincipalType
name: str
@classmethod
def User(cls, name: str) -> "RoleMember":
return cls(cls.PrincipalType.USER, name)
class RoleMemberList:
members: list[RoleMember]
def __init__(self, mems: list[dict[str, Any]] | None = None) -> None:
if mems is None:
mems = []
self.members = [RoleMember(**m) for m in mems]
def __getitem__(self, i: int) -> RoleMember:
return self.members[i]
def __len__(self) -> int:
return len(self.members)
def __str__(self) -> str:
return str(self.members)
@classmethod
def from_json(cls, body: bytes) -> "RoleMemberList":
d = json.loads(body)
for k in d:
assert k == "members", f"Unexpected key {k}"
return cls(d["members"])
# TODO(oren): factor this out to a base class maybe
@classmethod
def from_response(cls, rsp: Response) -> "RoleMemberList":
return cls.from_json(rsp.content)
class Role:
name: str
members: RoleMemberList
def __init__(self, name: str, members: RoleMemberList | None = None) -> None:
self.name = name
self.members = members if members is not None else RoleMemberList()
@classmethod
def from_json(cls, body: bytes) -> "Role":
d = json.loads(body)
expected_keys = set(["name", "members"])
assert all(k in expected_keys for k in d), f"Unexpected key(s): {d.keys()}"
assert "name" in d, "Expected 'name' key"
name = d["name"]
members = RoleMemberList(d.get("members", []))
return cls(name, members=members)
@classmethod
def from_response(cls, rsp: Response) -> "Role":
return cls.from_json(rsp.content)
class RoleMemberUpdateResponse:
role: str
added: RoleMemberList
removed: RoleMemberList
created: bool
def __init__(
self,
role: str,
added: RoleMemberList | None = None,
removed: RoleMemberList | None = None,
created: bool = False,
) -> None:
self.role = role
self.added = added if added is not None else RoleMemberList()
self.removed = removed if removed is not None else RoleMemberList()
self.created = created
def __str__(self) -> str:
return json.dumps(
{
"role": self.role,
"added": [a for a in self.added],
"removed": [r for r in self.removed],
"created": self.created,
}
)
@classmethod
def from_json(cls, body: bytes) -> "RoleMemberUpdateResponse":
d = json.loads(body)
expected_keys = set(["role", "added", "removed", "created"])
assert all(k in expected_keys for k in d), f"Unexpected key(s): {d.keys()}"
assert "role" in d, "Expected 'role' key"
role = d["role"]
kwargs: dict[str, Any] = {}
kwargs["added"] = RoleMemberList(d.get("added", []))
kwargs["removed"] = RoleMemberList(d.get("removed", []))
kwargs["created"] = d.get("created", False)
return cls(role, **kwargs)
@classmethod
def from_response(cls, rsp: Response) -> "RoleMemberUpdateResponse":
return cls.from_json(rsp.content)
class NamespacedTopic:
def __init__(self, topic: str, namespace: str | None = "kafka") -> None:
self.ns = namespace
self.topic = topic
def as_dict(self) -> dict[str, str]:
ret: dict[str, str] = {"topic": self.topic}
if self.ns is not None:
ret["ns"] = self.ns
return ret
@classmethod
def from_json(cls, body: bytes) -> "NamespacedTopic":
d = json.loads(body)
expected_keys = set(["ns", "topic"])
assert all(k in expected_keys for k in d), f"Unexpected key(s): {d.keys()}"
assert "topic" in d, "Expected 'topic' key"
topic = d["topic"]
namespace = "kafka"
if "ns" in d:
namespace = d["ns"]
return cls(topic, namespace)
class OutboundDataMigration:
migration_type: str
topics: list[NamespacedTopic]
consumer_groups: list[str]
def __init__(
self, topics: list[NamespacedTopic], consumer_groups: list[str]
) -> None:
self.migration_type = "outbound"
self.topics = topics
self.consumer_groups = consumer_groups
@classmethod
def from_json(cls, body: bytes) -> "OutboundDataMigration":
d = json.loads(body)
expected_keys = set(["type", "topics", "consumer_groups"])
assert all(k in expected_keys for k in d), f"Unexpected key(s): {d.keys()}"
assert all(k in d for k in expected_keys), (
f"Missing keys: {expected_keys - set(d)}"
)
return cls(d["topics"], d["consumer_groups"])
def as_dict(self) -> dict[str, Any]:
return {
"migration_type": self.migration_type,
"topics": [t.as_dict() for t in self.topics],
"consumer_groups": self.consumer_groups,
}
class InboundTopic:
def __init__(
self,
source_topic_reference: NamespacedTopic,
alias: NamespacedTopic | None = None,
) -> None:
"""
source_topic_reference is the topic location in cloud storage.
source_topic_reference.topic can be just a topic name (if there is just one instance
of topic data in cloud storage), or a full location of the form
"<original topic name>/<original cluster uuid>/<original revision>".
alias is the name of the topic that will be created in the cluster
(if None, name from source_topic_reference is used).
"""
self.source_topic_reference = source_topic_reference
self.alias = alias
def as_dict(self) -> dict[str, Any]:
d: dict[str, Any] = {
"source_topic_reference": self.source_topic_reference.as_dict(),
}
if self.alias:
d["alias"] = self.alias.as_dict()
return d
class InboundDataMigration:
migration_type: str
topics: list[InboundTopic]
consumer_groups: list[str]
def __init__(self, topics: list[InboundTopic], consumer_groups: list[str]) -> None:
self.migration_type = "inbound"
self.topics = topics
self.consumer_groups = consumer_groups
def as_dict(self) -> dict[str, Any]:
return {
"migration_type": self.migration_type,
"topics": [t.as_dict() for t in self.topics],
"consumer_groups": self.consumer_groups,
}
class MigrationAction(Enum):
prepare = "prepare"
execute = "execute"
finish = "finish"
cancel = "cancel"
class EnterpriseLicenseStatus(Enum):
valid = "valid"
expired = "expired"
not_present = "not_present"
class DebugBundleEncoder(json.JSONEncoder):
"""
DebugBundleEncoder is a custom JSON encoder that extends the default JSONEncoder
to handle named tuples and UUIDs.
Attributes:
ignore_none (bool): If True, fields with None values are ignored during encoding.
Methods:
default(o):
Overrides the default method to provide custom serialization for named tuples
and UUIDs. Named tuples are converted to dictionaries, and UUIDs are converted
to strings. Other types are handled by the superclass method.
encode(o: Any) -> str:
Overrides the encode method to ensure that the custom default method is used
during encoding.
Usage:
encoder = DebugBundleEncoder(ignore_none=True)
json_str = encoder.encode(your_object)
"""
def __init__(self, *args: Any, ignore_none: bool = False, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.ignore_none = ignore_none
def default(
self, o: Any
) -> dict[str, Any] | str | list[Any] | tuple[Any, ...] | int | float | bool | None:
if hasattr(o, "_fields") and isinstance(o, tuple):
return {
k: self.default(v)
for k, v in o._asdict().items() # type: ignore[attr-defined]
if not (self.ignore_none and v is None)
}
if isinstance(o, UUID):
return str(o)
if isinstance(o, (dict, list, tuple, str, int, float, bool)) or o is None:
return o # type: ignore[reportUnknownVariableType]
if hasattr(o, "__dataclass_fields__"): # assume SaslCredentials
creds: dict[str, Any] = o.__dict__
if isinstance(o, SaslCredentials):
# Swap algorithm for mechansim
creds["mechanism"] = creds.pop("algorithm")
return creds
return super().default(o)
def encode(self, o: Any) -> str:
return super().encode(self.default(o))
@dataclass
class DebugBundleLabelSelection:
key: str
value: str
class DebugBundleStartConfigParams(NamedTuple):
authentication: Optional[SaslCredentials | OAuthBearerCredentials] = None
controller_logs_size_limit_bytes: Optional[int] = None
cpu_profiler_wait_seconds: Optional[int] = None
logs_since: Optional[str] = None
logs_size_limit_bytes: Optional[int] = None
logs_until: Optional[str] = None
metrics_interval_seconds: Optional[int] = None
metrics_samples: Optional[int] = None
partition: Optional[list[str]] = None
tls_enabled: Optional[bool] = None
tls_insecure_skip_verify: Optional[bool] = None
namespace: Optional[str] = None
label_selector: Optional[list[DebugBundleLabelSelection]] = None
class DebugBundleStartConfig(NamedTuple):
job_id: UUID
config: Optional[DebugBundleStartConfigParams] = None
class CrashType(Enum):
SEGFAULT = "segfault"
ABORT = "abort"
ASSERT = "assert"
ASAN_CRASH = "asan_crash"
UBSAN_CRASH = "ubsan_crash"
class Admin:
"""
Wrapper for Redpanda admin REST API.
All methods on this class will raise on errors. For GETs the return
value is a decoded dict of the JSON payload, for other requests
the successful HTTP response object is returned.
"""
def __init__(
self,
redpanda: RedpandaServiceProto,
default_node: ClusterNode | None = None,
retry_codes: list[int] | None = None,
auth: tuple[str, str] | None = None,
retries_amount: int = 5,
timeout_seconds: float = DEFAULT_TIMEOUT,
) -> None:
self.redpanda = redpanda
self._session = AuthPreservingSession()
if auth is not None:
self._session.auth = auth
self._default_node: ClusterNode | None = default_node
# - We retry on 503s because at any time a POST to a leader-redirected
# request will return 503 if the partition is leaderless -- this is common
# at the very start of a test when working with the controller partition to
# e.g. create users.
# - We do not let urllib retry on connection errors, because we need to do our
# own logic in _request for trying a different node in that case.
# - If the caller wants to handle 503s directly, they can set retry_codes to []
if retry_codes is None:
retry_codes = [503]
retries = Retry(
status=retries_amount,
connect=0,
read=0,
backoff_factor=1,
status_forcelist=retry_codes,
respect_retry_after_header=True,
allowed_methods=None, # Retry all methods
remove_headers_on_redirect=[],
)
self._session.mount("http://", HTTPAdapter(max_retries=retries))
self._timeout_seconds = timeout_seconds
@staticmethod
def ready(node: ClusterNode) -> dict[str, Any]:
url = f"http://{node.account.hostname}:9644/v1/status/ready"
return requests.get(url).json()
@staticmethod
def _url(node: ClusterNode, path: str) -> str:
return f"http://{node.account.hostname}:9644/v1/{path}"
@staticmethod
def _equal_assignments(r0: list[dict[str, Any]], r1: list[dict[str, Any]]) -> bool:
def to_tuple(a: dict[str, Any]) -> tuple[int, int]:
return a["node_id"], a["core"]
r0_tuples = [to_tuple(a) for a in r0]
r1_tuples = [to_tuple(a) for a in r1]
return set(r0_tuples) == set(r1_tuples)
def _get_configuration(
self, host: str, namespace: str, topic: str, partition: int
) -> dict[str, Any] | None:
url = f"http://{host}:9644/v1/partitions/{namespace}/{topic}/{partition}"
self.redpanda.logger.debug(f"Dispatching GET {url}")
r = self._session.request("GET", url)
if r.status_code != 200:
self.redpanda.logger.warning(f"Response {r.status_code}: {r.text}")
return None
else:
try:
json = r.json()
self.redpanda.logger.debug(f"Response OK, JSON: {json}")
return json
except JSONDecodeError as e:
self.redpanda.logger.debug(
f"Response OK, Malformed JSON: '{r.text}' ({e})"
)
return None
def _get_stable_configuration(
self,
hosts: list[str],
topic: str,
partition: int = 0,
namespace: str = "kafka",
replication: Optional[int] = None,
) -> Optional[PartitionDetails]:
"""
Method iterates through hosts and checks that the configuration of
namespace/topic/partition is the same on all hosts and that all
hosts see the same leader.
When replication is provided the method also checks that the confi-
guration has exactly that amout of nodes.
When the configuration isn't stable the method returns None
"""
last_leader = -1
replicas = None
status = None
for host in hosts:
self.redpanda.logger.debug(
f'requesting "{namespace}/{topic}/{partition}" details from {host})'
)
meta = self._get_configuration(host, namespace, topic, partition)
if meta is None:
return None
if "replicas" not in meta:
self.redpanda.logger.debug("replicas are missing")
return None
if "status" not in meta:
self.redpanda.logger.debug("status is missing")
return None
if status is None:
status = meta["status"]
self.redpanda.logger.debug(f"get status:{status}")
if status != meta["status"]:
self.redpanda.logger.debug(
f"get status:{meta['status']} while already observed:{status} before"
)
return None
read_replicas = meta["replicas"]
if replicas is None:
replicas = read_replicas
self.redpanda.logger.debug(f"get replicas:{read_replicas} from {host}")
elif not self._equal_assignments(replicas, read_replicas):
self.redpanda.logger.debug(
f"get conflicting replicas:{read_replicas} from {host}"
)
return None
if replication is not None:
if len(meta["replicas"]) != replication:
self.redpanda.logger.debug(
f"expected replication:{replication} got:{len(meta['replicas'])}"
)
return None
if meta["leader_id"] < 0:
self.redpanda.logger.debug("doesn't have leader")
return None
if last_leader < 0:
last_leader = int(meta["leader_id"])
self.redpanda.logger.debug(f"get leader:{last_leader}")
if last_leader not in [n["node_id"] for n in replicas]:
self.redpanda.logger.debug(
f"leader:{last_leader} isn't in the replica set"
)
return None
if last_leader != meta["leader_id"]:
self.redpanda.logger.debug(
f"got leader:{meta['leader_id']} but observed {last_leader} before"
)
return None
assert replicas is not None, "replicas must be set at this point"
info = PartitionDetails()
info.status = status
info.leader = int(last_leader)
info.replicas = [Replica(r) for r in replicas]
return info
def wait_stable_configuration(
self,
topic: str,
*,
partition: int = 0,
namespace: str = "kafka",
replication: int | None = None,
timeout_s: int = 10,
backoff_s: int = 1,
hosts: Optional[list[str]] = None,
) -> PartitionDetails:
"""
Method waits for timeout_s until the configuration is stable and returns it.
When the timeout is exhaust it throws TimeoutException
"""
if hosts is None:
hosts = [n.account.hostname for n in self.redpanda.started_nodes()]
hosts = list(hosts)
def get_stable_configuration():
random.shuffle(hosts)
msg = ",".join(hosts)
self.redpanda.logger.debug(
f"wait details for {namespace}/{topic}/{partition} from nodes: {msg}"
)
try:
info = self._get_stable_configuration(
hosts,
topic,
partition=partition,
namespace=namespace,
replication=replication,
)
if info is None:
return False
return True, info
except RequestException:
self.redpanda.logger.exception(
"an error on getting stable configuration, retrying"
)
return False
return wait_until_result(
get_stable_configuration,
timeout_sec=timeout_s,
backoff_sec=backoff_s,
err_msg=f"can't fetch stable replicas for {namespace}/{topic}/{partition} within {timeout_s} sec",
)
def await_stable_leader(
self,
topic: str,
partition: int = 0,
namespace: str = "kafka",
replication: int | None = None,
timeout_s: int = 10,
backoff_s: int = 1,
hosts: Optional[list[str]] = None,
check: Callable[[int], bool] = lambda node_id: True,
) -> int:
"""
Method waits for timeout_s until the configuration is stable and check
predicate returns true when invoked on the configuration's leader.
When the timeout is exhaust it throws TimeoutException
"""
def is_leader_stable():
info = self.wait_stable_configuration(
topic,
partition=partition,
namespace=namespace,
replication=replication,
timeout_s=timeout_s,
hosts=hosts,
backoff_s=backoff_s,
)
if info.leader is not None and check(info.leader):
return True, info.leader
self.redpanda.logger.debug(f"check failed (leader id: {info.leader})")
return False
return wait_until_result(
is_leader_stable,
timeout_sec=timeout_s,
backoff_sec=backoff_s,
err_msg=f"can't get stable leader of {namespace}/{topic}/{partition} within {timeout_s} sec",
)
def _request(
self,
verb: str,
path: str,
node: MaybeNode = None,
params: dict[str, Any] | None = None,
**kwargs: Any,
) -> Response:
if node is None and self._default_node is not None:
# We were constructed with an explicit default node: use that one
# and do not retry on others.
node = self._default_node
retry_connection = False
elif node is None:
# Pick a random node to run this request on. If that node gives
# connection errors we will retry on other nodes.
node = random.choice(self.redpanda.started_nodes())
retry_connection = True
else:
# We were called with a specific node to run on -- do no retry on
# other nodes.
retry_connection = False
assert node is not None, "node must be set at this point"
if kwargs.get("timeout", None) is None:
kwargs["timeout"] = self._timeout_seconds
# We will have to handle redirects ourselves (always set kwargs['allow_redirects'] = False),
# see comment after _session.request() below.
# If kwargs was passed with "allow_redirects:False", it is assumed that the user intends
# to handle the redirect case at the call site. Otherwise, it will be retried in the
# request loop below.
handle_retry_backoff = kwargs.get("allow_redirects", True)
kwargs["allow_redirects"] = False
num_redirects = 0
fallback_nodes: list[ClusterNode] = self.redpanda.nodes
fallback_nodes = list(filter(lambda n: n != node, fallback_nodes))
params_e = f"?{urllib.parse.urlencode(params)}" if params is not None else ""
url = self._url(node, path + params_e)
# On connection errors, retry until we run out of alternative nodes to try
# (fall through on first successful request)
while True:
self.redpanda.logger.debug(f"Dispatching {verb} {url}")
try:
r = self._session.request(verb, url, **kwargs)
except requests.ConnectionError:
if retry_connection and fallback_nodes:
node = random.choice(fallback_nodes)
fallback_nodes = list(filter(lambda n: n != node, fallback_nodes))
self.redpanda.logger.info(
f"Connection error, retrying on node {node.account.hostname} (remaining {[n.account.hostname for n in fallback_nodes]})"
)
url = self._url(node, path + params_e)
else:
raise
else:
# Requests library does NOT respect Retry-After with a redirect
# error code (see https://github.com/psf/requests/pull/4562).
# There is logic that respects Retry-After within urllib3,
# but since the Requests library handles 30# error codes
# internally, a Retry-After attached to a redirect response
# will not be respected. We will have to handle this ourselves.
if (
handle_retry_backoff
and r.is_redirect
and num_redirects < self._session.max_redirects
):
url = not_none(r.headers.get("Location"))
retry_after = r.headers.get("Retry-After")
if retry_after is not None:
self.redpanda.logger.info(
f"Retry-After: {retry_after} on redirect {url}"
)
time.sleep(int(retry_after))
num_redirects += 1
else:
break
# Log the response
if r.status_code != 200:
self.redpanda.logger.warning(f"Response {r.status_code}: {r.text}")
else:
if "application/json" in (not_none(r.headers.get("Content-Type"))) and len(
r.text
):
try:
self.redpanda.logger.debug(f"Response OK, JSON: {r.json()}")
except json.decoder.JSONDecodeError as e:
self.redpanda.logger.debug(
f"Response OK, Malformed JSON: '{r.text}' ({e})"
)
else:
self.redpanda.logger.debug("Response OK")
r.raise_for_status()
return r
@staticmethod
def _bool_param(value: bool) -> str:
"""
Converts a boolean value to a string representation for use in query parameters.
"""
return "true" if value else "false"
def get_status_ready(self, node: MaybeNode = None) -> dict[str, Any]:
return self._request("GET", "status/ready", node=node).json()
def get_cluster_config(
self,
node: MaybeNode = None,
include_defaults: bool | None = None,
key: str | None = None,
suppress_pending: bool | None = None,
) -> dict[str, Any]:
params: dict[str, Any] = {}
if key is not None:
params["key"] = key
if include_defaults is not None:
params["include_defaults"] = include_defaults
if suppress_pending is not None:
params["suppress_pending"] = suppress_pending
kwargs = {"params": params} if params else {}
return self._request("GET", "cluster_config", node=node, **kwargs).json()
def get_cluster_config_schema(self, node: MaybeNode = None) -> dict[str, Any]:
return self._request("GET", "cluster_config/schema", node=node).json()
def patch_cluster_config(
self,
upsert: dict[str, str | int | None] = {},
remove: list[str] = [],
force: bool = False,
dry_run: bool = False,
node: MaybeNode = None,
) -> Any:
path = "cluster_config"
params: dict[str, str] = {}
if force:
params["force"] = "true"
if dry_run:
params["dry_run"] = "true"
if params:
joined = "&".join([f"{k}={v}" for k, v in params.items()])
path = path + f"?{joined}"
return self._request(
"PUT", path, json={"upsert": upsert, "remove": remove}, node=node
).json()
def get_cluster_config_status(self, node: MaybeNode = None):
return self._request("GET", "cluster_config/status", node=node).json()
def get_node_config(self, node: MaybeNode = None):
return self._request("GET", "node_config", node).json()
def get_features(self, node: MaybeNode = None):
return self._request("GET", "features", node=node).json()
def get_cloud_storage_lifecycle_markers(self, node: MaybeNode = None):
return self._request("GET", "cloud_storage/lifecycle", node=node).json()
def delete_cloud_storage_lifecycle_marker(
self, topic: str, revision: str, node: MaybeNode = None
):
return self._request(
"DELETE", f"cloud_storage/lifecycle/{topic}/{revision}", node=node
)
def cloud_storage_trim(
self,
*,
byte_limit: Optional[int],
object_limit: Optional[int],
node: ClusterNode,
):
path = "cloud_storage/cache/trim"
params: dict[str, str] = {}
if byte_limit is not None:
params["bytes"] = str(byte_limit)
if object_limit is not None:
params["objects"] = str(object_limit)
if params:
joined = "&".join([f"{k}={v}" for k, v in params.items()])
path = path + f"?{joined}"
return self._request("POST", path, node=node)
def supports_feature(
self, feature_name: str, nodes: list[ClusterNode] | None = None
):
"""
Returns true whether all nodes in 'nodes' support the given feature. If
no nodes are supplied, uses all nodes in the cluster.
"""
if not nodes:
nodes = self.redpanda.nodes
def node_supports_feature(node: ClusterNode):
features_resp = None
try:
features_resp = self.get_features(node=node)
except RequestException as e:
self.redpanda.logger.debug(
f"Could not get features on {node.account.hostname}: {e}"
)
return False
features_dict = dict((f["name"], f) for f in features_resp["features"])
return features_dict[feature_name]["state"] == "active"
for node in nodes:
if not node_supports_feature(node):
return False
return True
def unsafe_reset_cloud_metadata(
self, topic: str, partition: str, manifest: dict[str, Any]
):
return self._request(
"POST", f"debug/unsafe_reset_metadata/{topic}/{partition}", json=manifest
)
def unsafe_reset_metadata_from_cloud(
self, namespace: str, topic: str, partition: int
):
return self._request(
"POST",
f"cloud_storage/unsafe_reset_metadata_from_cloud/{namespace}/{topic}/{partition}",
)
def put_feature(self, feature_name: str, body: dict[str, Any]) -> Response:
return self._request("PUT", f"features/{feature_name}", json=body)
def get_license(self, node: MaybeNode = None, timeout: int | None = None):
return self._request(
"GET", "features/license", node=node, timeout=timeout
).json()
@staticmethod
def is_sample_license(resp: dict[str, Any]) -> bool:
"""
Returns true if the given response to a `get_license` request returned the same license as the sample license
configured in `sample_license` ("REDPANDA_SAMPLE_LICENSE" env var). Returns false for the built in evaluation
period license and the second sample license 'REDPANDA_SECOND_SAMPLE_LICENSE'.
"""
# NOTE: the initial implementation of the get license endpoint (before v22.3) didn't return the sha256.
# We could remove those old tests, but it's simpler to use the type and the org to detect the installed
# license instead.