-
Notifications
You must be signed in to change notification settings - Fork 29
/
cli.py
5783 lines (5257 loc) · 223 KB
/
cli.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 . import argx, client, units
from aiven.client import AivenClient, envdefault
from aiven.client.cliarg import arg
from aiven.client.client import Tag
from aiven.client.common import UNDEFINED
from aiven.client.connection_info.common import Store
from aiven.client.connection_info.kafka import KafkaCertificateConnectionInfo, KafkaSASLConnectionInfo
from aiven.client.connection_info.pg import PGConnectionInfo
from aiven.client.connection_info.redis import RedisConnectionInfo
from aiven.client.speller import suggest
from argparse import ArgumentParser
from ast import literal_eval
from collections import Counter
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from http import HTTPStatus
from typing import Any, Callable, Final, IO, Mapping, Protocol, Sequence
from urllib.parse import urlparse
import errno
import getpass
import json as jsonlib
import os
import re
import requests
import subprocess
import sys
import time
USER_GROUP_COLUMNS = [
"user_group_name",
"user_group_id",
"description",
]
EOL_ADVANCE_WARNING_TIME = timedelta(weeks=26) # Give 6 months advance notice for EOL services
def convert_str_to_value(schema: Mapping[str, Any], value: Any | None) -> Any:
if value is not None:
if "string" in schema["type"] or "object" in schema["type"]:
return value
elif "integer" in schema["type"]:
return int(value, 0) # automatically convert from '123', '0x123', '0o644', etc.
elif "number" in schema["type"]:
return float(value)
elif "boolean" in schema["type"]:
values = {
"1": True,
"0": False,
"true": True,
"false": False,
}
try:
return values[value]
except KeyError as ex:
raise argx.UserError(
"Invalid boolean value {!r}: expected one of {}".format(value, ", ".join(values))
) from ex
elif "array" in schema["type"]:
evaluated_array = literal_eval(value)
values_array = []
for item in evaluated_array:
values_array.append(convert_str_to_value(schema["items"], item))
return values_array
else:
raise argx.UserError("Support for option value type(s) {!r} not implemented".format(schema["type"]))
if "null" in schema["type"]:
return None
raise argx.UserError("Support for option value type(s) {!r} not implemented".format(schema["type"]))
tag_key_re = re.compile(r"[\w\-]+")
tag_value_re = re.compile(r"[\w\-,. ]*")
def parse_tag_str(kv: str) -> Tag:
k, v = (kv.split(sep="=", maxsplit=1) + [""])[:2]
if not tag_key_re.fullmatch(k):
raise argx.UserError(f"Tag key '{k}' must consist of alpha-numeric characters, underscores or dashes")
if not tag_value_re.fullmatch(v):
raise argx.UserError(
f"Tag value '{k}={v}' must consist of alpha-numeric characters, underscores, dashes, commas or dots"
)
return {"key": k, "value": v}
def parse_untag_str(k: str) -> str:
if not tag_key_re.match(k):
raise argx.UserError(f"Tag key {k} must consist of alpha-numeric characters, underscores or dashes")
return k
def no_auth(fun: Callable) -> Callable:
fun.no_auth = True # type: ignore
return fun
def optional_auth(fun: Callable) -> Callable:
fun.optional_auth = True # type: ignore
return fun
def is_truthy(value: str) -> bool:
return value.lower() in {"y", "yes", "t", "true", "1", "ok"}
def parse_iso8601(value: str) -> datetime:
# Python 3.6 doesn't support fromisoformat()
# or 'Z' as valid for '%z' format string
if value[-1] == "Z":
value = value[:-1] + "+0000"
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S%z")
def get_current_date() -> datetime:
return datetime.now(timezone.utc)
class ClientFactory(Protocol):
def __call__(self, base_url: str, show_http: bool, request_timeout: int | None) -> client.AivenClient:
...
class AivenCLI(argx.CommandLineTool):
client: AivenClient
def __init__(self, client_factory: ClientFactory = AivenClient):
argx.CommandLineTool.__init__(self, "avn")
self.client_factory = client_factory
def add_args(self, parser: ArgumentParser) -> None:
parser.add_argument(
"--auth-ca",
help="CA certificate to use [AIVEN_CA_CERT], default %(default)r",
default=envdefault.AIVEN_CA_CERT,
metavar="FILE",
)
parser.add_argument(
"--auth-token",
help="Client auth token to use [AIVEN_AUTH_TOKEN], [AIVEN_CREDENTIALS_FILE]",
default=envdefault.AIVEN_AUTH_TOKEN,
)
parser.add_argument("--show-http", help="Show HTTP requests and responses", action="store_true")
parser.add_argument(
"--url",
help="Server base url default %(default)r",
default=envdefault.AIVEN_WEB_URL,
)
parser.add_argument(
"--request-timeout",
type=int,
default=None,
help="Wait for up to N seconds for a response to a request (default: infinite)",
)
def collect_user_config_options(self, obj_def: Mapping[str, Any], prefixes: list[str] | None = None) -> dict[str, Any]:
opts = {}
for prop, spec in sorted(obj_def.get("properties", {}).items()):
full_prop = prefixes + [prop] if prefixes else [prop]
full_name = ".".join(full_prop)
types = spec["type"]
if not isinstance(types, list):
types = [types]
# "object" or ["object", "null"]
if "object" in types:
opts.update(self.collect_user_config_options(spec, prefixes=full_prop))
if "null" in types:
# allow removing user config option
opts[full_name] = {
"property_parts": full_prop,
"title": "Remove {}".format(prop),
"type": "null",
}
else:
opts[full_name] = dict(spec, property_parts=full_prop)
for spec in sorted(obj_def.get("patternProperties", {}).values()):
full_prop = prefixes + ["KEY"] if prefixes else ["KEY"]
full_name = ".".join(full_prop)
if spec["type"] == "object":
opts.update(self.collect_user_config_options(spec, prefixes=full_prop))
else:
title = ": ".join([obj_def["title"], spec["title"]]) if "title" in spec else obj_def["title"]
opts[full_name] = dict(spec, property_parts=full_prop, title=title)
return opts
def create_user_config(self, user_config_schema: Mapping[str, Any]) -> dict[str, Any]:
"""Convert a list of ["foo.bar='baz'"] to {"foo": {"bar": "baz"}}"""
user_option_remove = []
if hasattr(self.args, "user_option_remove"):
user_option_remove = self.args.user_option_remove
if not self.args.user_config and not user_option_remove:
return {}
options = self.collect_user_config_options(user_config_schema)
user_config: dict[str, Any] = {}
for key_value in self.args.user_config:
try:
key, value = key_value.split("=", 1)
except ValueError as ex:
raise argx.UserError(
"Invalid config value: {!r}, expected '<KEY>[.<SUBKEY>]=<JSON_VALUE>'".format(key_value)
) from ex
opt_schema = options.get(key)
if not opt_schema:
# Exact key not found, try generic one
generic_key = ".".join(key.split(".")[:-1] + ["KEY"])
opt_schema = options.get(generic_key)
if not opt_schema:
raise argx.UserError(
"Unsupported option {!r}, available options: {}".format(key, ", ".join(options) or "none")
)
try:
value = convert_str_to_value(opt_schema, value)
except ValueError as ex:
raise argx.UserError("Invalid value {!r}: {}".format(key_value, ex))
leaf_config, leaf_key = self.get_leaf_config_and_key(config=user_config, key=key, opt_schema=opt_schema)
leaf_config[leaf_key] = value
for opt in user_option_remove:
opt_schema = options.get(opt)
if not opt_schema:
raise argx.UserError(
"Unsupported option {!r}, available options: {}".format(opt, ", ".join(options) or "none")
)
if "null" not in opt_schema["type"]:
raise argx.UserError("Removing option {!r} is not supported".format(opt))
leaf_config, leaf_key = self.get_leaf_config_and_key(config=user_config, key=opt, opt_schema=opt_schema)
leaf_config[leaf_key] = None
return user_config
@classmethod
def get_leaf_config_and_key(
cls, *, config: dict[str, Any], key: str, opt_schema: Mapping[str, Any]
) -> tuple[dict[str, Any], str]:
key_suffix = key
for part in opt_schema["property_parts"][:-1]:
prefix = "{}.".format(part)
if not key_suffix.startswith(prefix):
raise argx.UserError("Expected {} to start with {} (full key {})".format(key_suffix, prefix, key))
key_suffix = key_suffix[len(prefix) :]
config = config.setdefault(part, {})
return config, key_suffix
def enter_password(self, prompt: str, var: str = "AIVEN_PASSWORD", confirm: bool = False) -> str:
"""Prompt user for a password"""
password = os.environ.get(var)
if password:
return password
password = getpass.getpass(prompt)
if confirm:
again = getpass.getpass("Confirm password again: ")
if password != again:
raise argx.UserError("Passwords do not match")
return password
def print_boxed(self, lines: list[str]) -> None:
longest = max(len(line) for line in lines)
print("*" * longest)
for line in lines:
print(line)
print("*" * longest)
def confirm(self, prompt: str = "confirm (y/N)? ") -> bool:
if self.args.force or is_truthy(os.environ.get("AIVEN_FORCE", "no")):
return True
answer = input(prompt)
return is_truthy(answer)
def get_project(self, raise_if_none: bool = True) -> str:
"""Return project given as cmdline argument or the default project from config file"""
if getattr(self.args, "project", None) and self.args.project:
return self.args.project
default_project = self.config.get("default_project", "")
if raise_if_none and not default_project:
raise argx.UserError(
"Specify project: use --project in the command line or the default_project item in the config file."
)
return default_project
@no_auth
@arg("pattern", nargs="*", help="command search pattern")
def help(self) -> None:
"""List commands"""
output = []
patterns = [re.compile(p, re.I) for p in self.args.pattern]
for plugin in self._extensions:
for prop_name in dir(plugin):
if prop_name.startswith("_"):
continue
prop = getattr(plugin, prop_name)
arg_list = getattr(prop, argx.ARG_LIST_PROP, None)
if arg_list is not None:
cmd = prop_name.replace("__", " ").replace("_", "-")
if patterns and not all((p.search(cmd) or p.search(prop.__doc__)) for p in patterns):
continue
output.append({"command": cmd, "help": " ".join(prop.__doc__.split())})
layout = ["command", "help"]
self.print_response(output, json=False, table_layout=layout)
@no_auth
@arg()
def crab(self) -> None:
"""Aiven crab"""
output = """
`'+;` `'+;`
'@@@#@@@` '@@@#@@@`
#@. #@. @@. #@.
@: ,@@ @@ @: ,@@ @@
,@ @@@@@ :@ :@ @@@@@ .@
@ #@@@. #@ @` #@@@` @@
@@ `@# @@ `@#
@@#. :@@+ @@#. :@@#
`+@@@' `#@@@'
,;:` ,;;.
@@@@@@# .+@@@@@@@@@@@@@'. `@@@@@@@
@@@@@# @@@@@@@@@@@@@@@@@@@@@@+ @@@@@@
@@@ ;@@@@@@@@@@@@@@@@@@@@@@@@@@@` `@@;
` `@@@@@@@@@@@ ;@@@@@@@@@@@
`@@@ '@@@@@@@@@@@@@ @@@@@@@@@@@@@` @@@
'@@@` .@@@@@@@@@@@@@@@ `@@@@@@@@@@@@@@@ @@@@`
@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@
'@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@
,:::; @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,:::
:@ ,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #@
@@@ +@#+#@@@@@@@@@@@@@@@@@@@@@@@@@#+#@. @@@
@@@@ '@@@@@@@@@@@@@@@@@@@. @@@@
@@@ @@@@@@+ @@@@@@@@@@@@@@@@@ @@@@@@; @@@
@@ @@@@@@@@@ @@@@@@@@@@@@@@@ `@@@@@@@@@ @+
@@@@@@@@@@@ :@@@@@@@@@@@@@ @@@@@@@@@@@ '
`@@@@@@@@@@@ ``` ,@@@@@@@@@@@
`@@@@@@ '@ :@: @@@@@@
@@@@@: @@@@@@
@@@@@ @@@@@
@@@@# @@@@'
"""
print(output)
@no_auth
@arg("email", nargs="?", help="User email address")
@arg("--tenant", help="Login under a different tenant")
@arg("--token", action="store_true", help="Provide an access token instead of password")
def user__login(self) -> None:
"""Login as a user"""
email = self.args.email
if not email:
email = input("Username (email): ")
if self.args.token:
token = self.enter_password(f"{email}'s Aiven access token: ", var="AIVEN_AUTH_TOKEN")
else:
password = self.enter_password(f"{email}'s Aiven password: ", var="AIVEN_PASSWORD")
try:
result = self.client.authenticate_user(email=email, password=password, tenant_id=self.args.tenant)
except client.Error as ex:
if ex.status == HTTPStatus.NOT_EXTENDED:
# Two-factor auth OTP required
otp = input("Two-factor authentication OTP: ")
result = self.client.authenticate_user(email=email, password=password, otp=otp)
else:
raise
token = result["token"]
self._write_auth_token_file(token=token, email=email)
# ensure that there is a working default project
auth_token = self._get_auth_token()
if auth_token:
self.client.set_auth_token(auth_token)
project = self.get_project(raise_if_none=False)
projects = self.client.get_projects()
if project and any(p["project_name"] == project for p in projects):
# default project exists
return
if projects:
default_project = projects[0]["project_name"]
self.config["default_project"] = default_project
self.config.save()
self.log.info(
"Default project set as '%s' (change with 'avn project switch <project>')",
default_project,
)
else:
self.log.info("No projects exists. You should probably create one with 'avn project create <name>'")
@arg("--no-token-revoke", action="store_true", help="Do not revoke token")
def user__logout(self) -> None:
"""Logout from current session"""
if not self.args.no_token_revoke:
auth_token = self._get_auth_token()
if auth_token:
self.client.access_token_revoke(token_prefix=auth_token)
self._remove_auth_token_file()
@arg.verbose
def user__tokens_expire(self) -> None:
"""Expire all authorization tokens"""
message = self.client.expire_user_tokens()["message"]
print(message)
@arg.verbose
def user__password_change(self) -> None:
"""Change the password of the currently logged in user"""
current_password = getpass.getpass("Current password: ")
new_password = self.enter_password("New password: ", confirm=True)
self.client.change_user_password(current_password, new_password)
print("Password changed. Next, use 'avn user login' to log in again using your new password.")
@arg("--description", required=True, help="Description of how the token will be used")
@arg("--max-age-seconds", type=int, help="Maximum age of the token, if any")
@arg(
"--extend-when-used",
action="store_true",
help="Extend token's expiry time when used (only applicable if token is set to expire)",
)
@arg.json
def user__access_token__create(self) -> None:
"""Creates new access token"""
token_info = self.client.access_token_create(
description=self.args.description,
extend_when_used=self.args.extend_when_used,
max_age_seconds=self.args.max_age_seconds,
)
layout = [
"expiry_time",
"description",
"max_age_seconds",
"extend_when_used",
"full_token",
]
self.print_response([token_info], json=self.args.json, table_layout=layout)
@arg(
"token_prefix",
help="The full token or token prefix identifying the token to update",
)
@arg("--description", required=True, help="Description of how the token will be used")
@arg.json
def user__access_token__update(self) -> None:
"""Updates an existing access token"""
token_info = self.client.access_token_update(token_prefix=self.args.token_prefix, description=self.args.description)
layout = [
"expiry_time",
"token_prefix",
"description",
"max_age_seconds",
"extend_when_used",
"last_used_time",
"last_ip",
"last_user_agent",
]
self.print_response([token_info], json=self.args.json, table_layout=layout)
@arg(
"token_prefix",
help="The full token or token prefix identifying the token to revoke",
)
def user__access_token__revoke(self) -> None:
"""Revokes an access token"""
self.client.access_token_revoke(token_prefix=self.args.token_prefix)
print("Revoked")
@arg.json
def user__access_token__list(self) -> None:
"""List all of your access tokens"""
tokens = self.client.access_tokens_list()
layout = [
"expiry_time",
"token_prefix",
"description",
"max_age_seconds",
"extend_when_used",
"last_used_time",
"last_ip",
"last_user_agent",
]
self.print_response(tokens, json=self.args.json, table_layout=layout)
def _show_logs(self, msgs: Mapping[str, Any]) -> str:
if self.args.json:
print(jsonlib.dumps(msgs["logs"], indent=4, sort_keys=True))
else:
for log_msg in msgs["logs"]:
print("{time:<27}{hostname} {unit} {msg}".format(**log_msg))
return msgs["offset"]
@arg.project
@arg.service_name
@arg.json
@arg(
"-S",
"--sort-order",
type=str,
default="asc",
choices=["desc", "asc"],
help="Sort direction for log fetching",
)
@arg("-n", "--limit", type=int, default=100, help="Get up to N rows of logs")
@arg("-f", "--follow", action="store_true", default=False)
def service__logs(self) -> None:
"""View project logs"""
previous_offset: str | None = None
consecutive_errors_limit: Final = 10
consecutive_errors = 0
while True:
try:
msgs = self.client.get_service_logs(
project=self.get_project(),
limit=self.args.limit,
offset=previous_offset,
service=self.args.service_name,
sort_order=self.args.sort_order,
)
except requests.RequestException as ex:
if not self.args.follow:
raise ex
consecutive_errors += 1
if consecutive_errors > consecutive_errors_limit:
raise argx.UserError("Fetching logs failed repeatedly, aborting.")
sys.stderr.write("Fetching log messages failed with {}. Retrying after 10s\n".format(ex))
time.sleep(10.0)
continue
consecutive_errors = 0
new_offset = self._show_logs(msgs)
if not msgs["logs"] and previous_offset is not None and self.args.sort_order == "desc":
# Quit because since we didn't find older messages than this, we'll never find any.
break
if not self.args.follow:
break
if previous_offset == new_offset:
# No new msgs, sleep for a while
time.sleep(10.0)
previous_offset = new_offset
@arg.project
@arg.json
@arg("-n", "--limit", type=int, default=100, help="Get up to N rows of logs")
def events(self) -> None:
"""View project event logs"""
events = self.client.get_events(project=self.get_project(), limit=self.args.limit)
if self.args.json:
print(jsonlib.dumps(events, indent=4, sort_keys=True))
return
for msg in events:
if not msg["service_name"]:
msg["service_name"] = ""
layout = ["time", "actor", "event_type", "service_name", "event_desc"]
self.print_response(events, json=self.args.json, table_layout=layout)
@optional_auth
@arg.project
@arg.json
def cloud__list(self) -> None:
"""List cloud types"""
project = self.get_project(raise_if_none=False)
if project and not self.client.auth_token:
raise argx.UserError("authentication is required to list clouds for a specific project")
self.print_response(self.client.get_clouds(project=project), json=self.args.json)
@staticmethod
def describe_plan(plan: Mapping[str, Any], node_count: int, service_plan: str) -> str:
"""Describe a plan based on their specs as published in the api, returning strings like:
"Basic-0 (4 CPU, 123 MB RAM) "
"Basic-1 (4 CPU, 1 GB RAM, 9 GB disk) "
"Dual-1 (4 CPU, 1 GB RAM, 9 GB disk) high availability pair"
"Quad-2 (4 CPU, 2 GB RAM, 9 GB disk) 4-node high availability set"
"""
if plan["node_memory_mb"] < units.MIB_IN_GIB:
ram_amount = "{} MB".format(plan["node_memory_mb"])
else:
ram_amount = "{:.0f} GB".format(units.convert_mib_to_gib(plan["node_memory_mb"]))
if plan["disk_space_mb"]:
if plan.get("disk_space_cap_mb"):
disk_desc = ", {:.0f}-{:.0f} GB disk".format(
units.convert_mib_to_gib(plan["disk_space_mb"]), units.convert_mib_to_gib(plan["disk_space_cap_mb"])
)
else:
disk_desc = ", {:.0f} GB disk".format(units.convert_mib_to_gib(plan["disk_space_mb"]))
else:
disk_desc = ""
if node_count == 2: # noqa: PLR2004
plan_qual = " high availability pair"
elif node_count > 2: # noqa: PLR2004
plan_qual = " {}-node high availability set".format(node_count)
else:
plan_qual = ""
return "{name} ({cpu_count} CPU, {ram_amount} RAM{disk_desc}){qual}".format(
name=service_plan.title(),
cpu_count=plan["node_cpu_count"],
ram_amount=ram_amount,
disk_desc=disk_desc,
qual=plan_qual,
)
@arg.json
@arg("-n", "--name", required=True, help="Name of the account to create")
def account__create(self) -> None:
"""Create new account"""
account = self.client.create_account(self.args.name)
self.print_response(account, json=self.args.json, single_item=True)
@arg.json
@arg.account_id
@arg("-n", "--name", required=True, help="New name for the account")
def account__update(self) -> None:
"""Update an account"""
account = self.client.update_account(self.args.account_id, self.args.name)
self.print_response(account, json=self.args.json, single_item=True)
@arg.account_id
def account__delete(self) -> None:
"""Delete an account"""
self.client.delete_account(self.args.account_id)
print("Deleted")
@arg.json
def account__list(self) -> None:
"""Lists all current accounts"""
accounts = self.client.get_accounts()
self.print_response(accounts, json=self.args.json)
@staticmethod
def _parse_auth_config_options(config_cmdline: Sequence[str], config_file: Sequence[str]) -> Mapping[str, str]:
options = {}
for name_and_value in config_cmdline:
if "=" not in name_and_value:
raise argx.UserError("Invalid custom value, missing '=': {}".format(name_and_value))
name, value = name_and_value.split("=", 1)
options[name] = value
for name_and_value in config_file:
if "=" not in name_and_value:
raise argx.UserError("Invalid custom value, missing '=': {}".format(name_and_value))
name, filename = name_and_value.split("=", 1)
if not os.path.isfile(filename):
raise argx.UserError("No such file {!r}".format(filename))
with open(filename, encoding="utf-8") as fob:
value = fob.read()
options[name] = value
return options
@arg.json
@arg.account_id
def account__team__list(self) -> None:
"""List account teams"""
self.print_response(self.client.list_teams(self.args.account_id), json=self.args.json)
@arg.json
@arg.account_id
@arg.team_name
def account__team__create(self) -> None:
"""Create a team within an account"""
self.client.create_team(self.args.account_id, self.args.team_name)
@arg.json
@arg.account_id
@arg.team_id
def account__team__delete(self) -> None:
"""Delete a team"""
self.client.delete_team(self.args.account_id, self.args.team_id)
@arg.json
@arg.account_id
@arg.team_id
def account__team__user_list(self) -> None:
"""List team members"""
self.print_response(
self.client.list_team_members(self.args.account_id, self.args.team_id),
json=self.args.json,
)
@arg.json
@arg.account_id
@arg.team_id
@arg.email
def account__team__user_invite(self) -> None:
"""Invite user to join a team"""
self.client.add_team_member(self.args.account_id, self.args.team_id, self.args.email)
@arg.json
@arg.account_id
@arg.team_id
def account__team__user_list_pending(self) -> None:
"""List pending invitations to a team"""
self.print_response(
self.client.list_team_invites(self.args.account_id, self.args.team_id),
json=self.args.json,
)
@arg.json
@arg.account_id
@arg.team_id
@arg.email
def account__team__invite_delete(self) -> None:
"""Delete pending invite from a team"""
self.client.delete_team_invite(self.args.account_id, self.args.team_id, self.args.email)
@arg.json
@arg.account_id
@arg.team_id
@arg.user_id
def account__team__user_delete(self) -> None:
"""Delete user from a team"""
self.client.delete_team_member(self.args.account_id, self.args.team_id, self.args.user_id)
@arg.json
@arg.account_id
@arg.team_id
def account__team__project_list(self) -> None:
"""List projects associated to a team"""
self.print_response(
self.client.list_team_projects(self.args.account_id, self.args.team_id),
json=self.args.json,
)
@arg.json
@arg.account_id
@arg.team_id
@arg.project
@arg(
"--team-type",
required=True,
choices=["admin", "developer", "operator", "read_only"],
help="Team type (permission level)",
)
def account__team__project_attach(self) -> None:
"""Attach team to a project"""
self.client.attach_team_to_project(
self.args.account_id,
self.args.team_id,
self.args.project,
self.args.team_type,
)
@arg.json
@arg.account_id
@arg.team_id
@arg.project
def account__team__project_detach(self) -> None:
"""Detach team from a project"""
self.client.detach_team_from_project(self.args.account_id, self.args.team_id, self.args.project)
@optional_auth
@arg.project
@arg.cloud
@arg.json
@arg.service_type
@arg("--monthly", help="Show monthly price estimates", action="store_true")
def service__plans(self) -> None:
"""List service plans"""
project = self.get_project()
if project and not self.client.auth_token:
raise argx.UserError("authentication is required to list service plans for a specific project")
if not self.args.cloud:
print("Used cloud not defined, only showing service types!\n")
service_types = self.client.get_service_types(project=project)
if self.args.json:
print(jsonlib.dumps(service_types, indent=4, sort_keys=True))
return
output = []
for service_type, prop in service_types.items():
if self.args.service_type and service_type != self.args.service_type:
continue
entry = prop.copy()
entry["service_type"] = service_type
output.append(entry)
dformat = Decimal("0") if self.args.monthly else Decimal("0.000")
for info in sorted(output, key=lambda s: s["description"]):
print("{} Plans:\n".format(info["description"]))
for plan in info["service_plans"]:
if self.args.cloud not in plan["regions"]:
continue
args = "{}:{}".format(plan["service_type"], plan["service_plan"])
price_dec = Decimal(plan["regions"][self.args.cloud]["price_usd"])
if self.args.monthly:
price_str = (price_dec * 730).quantize(dformat)
price = "${}/mo".format(price_str)
else:
price_str = price_dec.quantize(dformat)
price = "${}/h".format(price_str)
description = self.describe_plan(
plan["regions"][self.args.cloud],
plan["node_count"],
plan["service_plan"],
)
print(" {:<28} {:>10} {}".format(args, price, description))
if not info["service_plans"]:
print(" (no plans available)")
print()
@arg.project
@arg.json
@arg.verbose
def service__types(self) -> None:
"""List service types"""
service_types = self.client.get_service_types(project=self.get_project())
if self.args.json:
self.print_response(service_types, json=self.args.json)
return
output = []
for service_type, prop in sorted(service_types.items()):
entry = prop.copy()
entry["service_type"] = service_type
output.append(entry)
self.print_response(output, json=self.args.json, table_layout=[["service_type", "description"]])
if not self.args.json and self.args.verbose:
for service_type, service_def in sorted(service_types.items()):
print("\nService type {!r} options:".format(service_type))
options = self.collect_user_config_options(service_def["user_config_schema"])
if not options:
print(" (No configurable options)")
else:
for name, spec in sorted(options.items()):
default = spec.get("default")
default_desc = "(default={!r})".format(default) if default is not None else ""
description = ": {}".format(spec["description"]) if "description" in spec else ""
types = spec["type"]
if isinstance(types, str) and types == "null":
print(
" {title}{description}\n"
" => --remove-option {name}".format(
name=name,
title=spec["title"],
description=description,
)
)
else:
if not isinstance(types, list):
types = [types]
type_str = " or ".join(t for t in types if t != "null")
print(
" {title}{description}\n"
" => -c {name}=<{type}> {default}".format(
name=name,
type=type_str,
default=default_desc,
title=spec["title"],
description=description,
)
)
SERVICE_LAYOUT = [
[
"service_name",
"service_type",
"state",
"cloud_name",
"plan",
"create_time",
"update_time",
"notifications",
]
]
EXT_SERVICE_LAYOUT = ["service_uri", "disk_space_mb", "user_config.*", "databases", "users"]
@arg.project
@arg("service_name", nargs="*", default=[], help="Service name")
@arg.service_type
@arg("--format", help="Format string for output, e.g. '{service_name} {service_uri}'")
@arg.verbose
@arg.json
def service__list(self) -> None:
"""List services"""
services = self.client.get_services(project=self.get_project())
if self.args.service_type is not None:
services = [s for s in services if s["service_type"] == self.args.service_type]
if self.args.service_name:
services = [s for s in services if s["service_name"] in self.args.service_name]
layout: list[Any] = self.SERVICE_LAYOUT[:]
if self.args.verbose:
layout.extend(self.EXT_SERVICE_LAYOUT)
# Format service notifications
for service in services:
service["notifications"] = self._format_service_notifications(service)
self.print_response(services, format=self.args.format, json=self.args.json, table_layout=layout)
def _format_service_notifications(self, service: Mapping[str, Any]) -> Sequence[str]:
"""Format service notifications as list of short text elements suitable for table view."""
if "service_notifications" in service:
notifications = []
for notification in service["service_notifications"]:
if notification["type"] == "service_end_of_life":
eol_time = parse_iso8601(notification["metadata"]["service_end_of_life_time"])
eol_date = eol_time.date().isoformat()
is_urgent = notification["level"] == "warning"
upgrade_urgency = "required" if is_urgent else "available"
notifications.append(f"EOL: {eol_date} Upgrade {upgrade_urgency}")
return notifications
else:
return []
def print_service_notifications(self, service_notifications: Sequence[Mapping[str, Any]]) -> None:
def make_bold(text: str) -> str:
bold = "\033[1m"
normal = "\033[0m"
return bold + text + normal
for service_notification in service_notifications:
text = service_notification["message"]
if service_notification["type"] == "service_end_of_life":
text += "\nRead more: " + service_notification["metadata"]["end_of_life_help_article_url"]
print(make_bold(text) if service_notification["level"] == "warning" else text)
print()
_aws_privatelink_principal_help = "AWS IAM principals allowed to connect to the Privatelink VPC endpoint service"
@arg.project
@arg.service_name
@arg("--format", help="Format string for output")
@arg.json
@arg("--principal", dest="principals", action="append", metavar="PRINCIPAL", help=_aws_privatelink_principal_help)
def service__privatelink__aws__create(self) -> None:
"""Create PrivateLink for a service"""
resp = self.client.create_service_privatelink_aws(
project=self.get_project(), service=self.args.service_name, principals=self.args.principals
)
self.print_response([resp], format=self.args.format, json=self.args.json)
@arg.project
@arg.service_name
@arg("--format", help="Format string for output")
@arg.json
@arg("--principal", dest="principals", action="append", metavar="PRINCIPAL", help=_aws_privatelink_principal_help)
def service__privatelink__aws__update(self) -> None:
"""Update PrivateLink for a service"""
resp = self.client.update_service_privatelink_aws(
project=self.get_project(), service=self.args.service_name, principals=self.args.principals
)
self.print_response([resp], format=self.args.format, json=self.args.json)
@arg.project
@arg.service_name
@arg("--format", help="Format string for output")
@arg.json
def service__privatelink__aws__get(self) -> None:
"""Get PrivateLink information for a service"""
resp = self.client.get_service_privatelink_aws(project=self.get_project(), service=self.args.service_name)
self.print_response([resp], format=self.args.format, json=self.args.json)
@arg.project
@arg.service_name
@arg("--format", help="Format string for output")
@arg.json
def service__privatelink__aws__delete(self) -> None:
"""Delete PrivateLink for a service"""
resp = self.client.delete_service_privatelink_aws(project=self.get_project(), service=self.args.service_name)
self.print_response([resp], format=self.args.format, json=self.args.json)
@arg.project
@arg.service_name
@arg("--format", help="Format string for output")
@arg.json
def service__privatelink__aws__connection__list(self) -> None:
"""List PrivateLink connections for a service"""
resp = self.client.list_service_privatelink_aws_connections(