-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcbmgr.py
More file actions
8489 lines (7042 loc) · 401 KB
/
cbmgr.py
File metadata and controls
8489 lines (7042 loc) · 401 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
"""A Couchbase CLI subcommand"""
import argparse
import dataclasses
import getpass
import inspect
import ipaddress
import json
import os
import platform
import random
import re
import socket
import string
import subprocess
import sys
import tempfile
import time
import traceback
import urllib.parse
from argparse import SUPPRESS, Action, ArgumentError, ArgumentParser, HelpFormatter
from operator import itemgetter
from typing import Any, Dict, List, Optional
import couchbaseConstants
from cluster_manager import ClusterManager
from pbar import TopologyProgressBar
from x509_adapter import X509AdapterError
try:
from cb_version import VERSION # pylint: disable=import-error
except ImportError:
VERSION = "0.0.0-0000-community"
print(f'WARNING: Could not import cb_version, setting VERSION to {VERSION}')
COUCHBASE_DEFAULT_PORT = 8091
BUCKET_PRIORITY_HIGH_INT = 8
BUCKET_PRIORITY_HIGH_STR = "high"
BUCKET_PRIORITY_LOW_INT = 3
BUCKET_PRIORITY_LOW_STR = "low"
BUCKET_TYPE_COUCHBASE = "membase"
BUCKET_TYPE_MEMCACHED = "memcached"
VERSION_UNKNOWN = "0.0.0"
LATEST_VERSION = "8.0.0"
def check_base_path(base_path):
required_dirs = ["bin", "etc", "lib"]
return all(os.path.exists(os.path.join(base_path, d)) for d in required_dirs)
def get_base_cb_path():
# Check if relative path exists
base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if os.path.exists(base_path) and check_base_path(base_path):
return base_path
# If the base path is not at the relative path, then check the default path, which is platform dependent
system = platform.system()
if system == "Darwin":
base_path = os.path.join(os.sep, "Applications", "Couchbase Server.app", "Contents", "Resources",
"couchbase-core")
elif system == "Windows":
base_path = os.path.join("C:" + os.sep, "Program Files", "couchbase", "server")
elif system == "Linux":
base_path = os.path.join(os.sep, "opt", "couchbase")
else:
base_path = None
if base_path and check_base_path(base_path):
return base_path
return None
def get_bin_path():
base_path = get_base_cb_path()
if not base_path:
return None
return os.path.join(base_path, "bin")
def get_hosts_path():
base_path = get_base_cb_path()
if not base_path:
return None
hosts_path = os.path.join(base_path, "etc", "couchbase", "hosts.cfg")
if os.path.isfile(hosts_path):
return hosts_path
return None
def get_inetrc(hosts_path):
inetrc_file = hosts_path.encode('unicode-escape').decode()
return ['inetrc', f'"{inetrc_file}"']
def get_cfg_path():
base_path = get_base_cb_path()
if not base_path:
return None
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Couchbase/var/lib/couchbase")
return os.path.join(base_path, "var", "lib", "couchbase")
def get_lib_path():
base_path = get_base_cb_path()
if not base_path:
return None
return os.path.join(base_path, "lib")
def get_ns_ebin_path():
lib_path = get_lib_path()
if not lib_path:
return None
if platform.system() == "Windows":
return os.path.join(lib_path, "ns_server", "ebin")
return os.path.join(lib_path, "ns_server", "erlang", "lib", "ns_server", "ebin")
def get_man_path():
base_path = get_base_cb_path()
if not base_path:
return None
share_path = os.path.join(base_path, "share")
if platform.system() == "Windows":
return os.path.join(share_path, "doc", "couchbase-cli")
return os.path.join(share_path, "man", "man1")
def get_doc_page_name(command: str) -> str:
return f'{command}.{"1" if os.name != "nt" else "html"}'
def remove_prefix(val: str, prefix: str) -> str:
"""This function removes a prefix from a string.
Note this is a built-in function in Python 3.9 once we upgrade to it we should use it instead.
"""
return val[len(prefix):] if val.startswith(prefix) else val
def force_communicate_tls(rest: ClusterManager) -> bool:
"""force_communicate_tls returns a boolean indicating whether we should communicate with other nodes using the TLS
ports.
When communicating with a cluster which has 'clusterEncryptionLevel' set to 'strict' the non-tls ports will only be
open to 'localhost' meaning we must communicate via the non-tls ports.
"""
settings, err = rest.get_security_settings()
_exit_if_errors(err)
# The cluster isn't using 'strict' cluster encryption, we shouldn't need to force enable TLS
if 'clusterEncryptionLevel' not in settings or settings['clusterEncryptionLevel'] != 'strict':
return False
# The user might not have used a 'https://' scheme prefix, so communicating to other nodes via the secure ports may
# lead to interesting/surprising errors; let them know beforehand.
_warning("sub-command requires multi-node communication via TLS enabled ports, '--cacert' or "
"'--no-ssl-verify' may need to be supplied")
return True
def rest_initialiser(cluster_init_check=False, version_check=False, enterprise_check=None, credentials_required=True,
enterprise_analytics_check=None):
"""rest_initialiser is a decorator that does common subcommand tasks.
The decorator will always creates a cluster manager and assign it to the subcommand variable rest
:param cluster_init_check: if true it will check if the cluster is initialized before executing the subcommand
:param version_check: if true it will check if the cluster and CLI version match if they do not it prints a warning
:param enterprise_check: if true it will check if the cluster is enterprise and fail if not. If it is false it does
the check but it does not fail if not enterprise. If none it does not perform the check. The result of the
check is stored on the instance parameter enterprise
:param enterprise_analytics_check: if true it will check if the cluster supports Enterprise Analytics and fail if
not. If it is false it does the check but it does not fail if not Enterprise Analytics. If none it does not
perform the check. The result of the check is stored on the instance parameter enterprise_analytics
"""
def inner(fn):
def decorator(self, opts):
_exit_if_errors(validate_credential_flags(opts.cluster, opts.username, opts.password, opts.auth_token,
opts.client_ca, opts.client_ca_password, opts.client_pk,
opts.client_pk_password, credentials_required))
try:
self.rest = ClusterManager(opts.cluster, opts.username, opts.password, opts.auth_token,
opts.ssl, opts.ssl_verify, opts.cacert, opts.debug,
client_ca=opts.client_ca, client_ca_password=opts.client_ca_password,
client_pk=opts.client_pk, client_pk_password=opts.client_pk_password)
except X509AdapterError as error:
_exit_if_errors([f"failed to setup client certificate encryption, {error}"])
if cluster_init_check:
check_cluster_initialized(self.rest)
if version_check:
check_versions(self.rest)
if enterprise_check is not None or enterprise_analytics_check is not None:
# check Enterprise Analytics when we check enterprise to avoid a duplicate fetch on pools
enterprise, enterprise_analytics, errors = self.rest.get_cluster_type()
_exit_if_errors(errors)
if enterprise_check and not enterprise:
_exit_if_errors(['Command only available in enterprise edition'])
if enterprise_analytics_check and not enterprise_analytics:
_exit_if_errors(['Command only available for Enterprise Analytics'])
if enterprise_check is not None:
self.enterprise = enterprise
if enterprise_analytics_check is not None:
self.enterprise_analytics = enterprise_analytics
return fn(self, opts)
return decorator
return inner
def validate_credential_flags(host, username, password, token, client_ca, client_ca_password,
client_pk, client_pk_password, credentials_required: bool = True):
"""ValidateCredentialFlags - Performs validation to ensure the user has provided the flags required to connect to
their cluster.
"""
using_cert_auth = not (client_ca is None and
client_ca_password is None and
client_pk is None and
client_pk_password is None)
if using_cert_auth:
return validate_certificate_flags(
host,
username,
password,
token,
client_ca,
client_ca_password,
client_pk,
client_pk_password)
if (username is None and password is None and token is None):
if credentials_required is False:
return None
return ["cluster credentials required, expected --username/--password, --client-cert/--client-key or "
"--auth-token"]
if token:
if username is not None or password is not None:
return ["expected either --username and --password or --auth-token but not both"]
return None
if (username is None or password is None):
return ["the --username/--password flags must be supplied together"]
return None
def validate_certificate_flags(host, username, password, token, client_ca, client_ca_password, client_pk,
client_pk_password):
"""Validate that the user is correctly using certificate authentication.
"""
if username is not None or password is not None:
return ["expected either --username and --password or --client-cert and --client-key but not both"]
if token is not None:
return ["expected either --auth-token or --client-cert and --client-key but not both"]
if not (host.startswith("https://") or host.startswith("couchbases://")):
return ["certificate authentication requires a secure connection, use https:// or couchbases://"]
if client_ca is None:
return ["certificate authentication requires a certificate to be supplied with the --client-cert flag"]
if client_ca_password is not None and client_pk_password is not None:
return ["--client-cert-password and --client-key-password can't be supplied together"]
unencrypted = client_ca_password is None and client_pk_password is None
if unencrypted and (client_ca is None or client_pk is None):
return ["when no cert/key password is provided, the --client-cert/--client-key flags must be supplied together"]
if client_pk_password is not None and client_pk is None:
return ["--client-key-password provided without --client-key"]
return None
def check_cluster_initialized(rest):
initialized, errors = rest.is_cluster_initialized()
if errors:
_exit_if_errors(errors)
if not initialized:
_exit_if_errors(["Cluster is not initialized, use cluster-init to initialize the cluster"])
def check_versions(rest):
result, errors = rest.pools()
if errors:
return
server_version = result['implementationVersion']
if server_version is None or VERSION is None:
return
major_couch = server_version[: server_version.index('.')]
minor_couch = server_version[server_version.index('.') + 1: server_version.index('.', len(major_couch) + 1)]
major_cli = VERSION[: VERSION.index('.')]
minor_cli = VERSION[VERSION.index('.') + 1: VERSION.index('.', len(major_cli) + 1)]
if major_cli != major_couch or minor_cli != minor_couch:
_warning(f'couchbase-cli version {VERSION} does not match couchbase server version {server_version}')
def index_storage_mode_to_param(value, default="plasma"):
"""Converts the index storage mode to what Couchbase understands"""
if value == "default":
return default
if value == "memopt":
return "memory_optimized"
return value
def process_services(services, enterprise, enterprise_analytics, cluster_version="0.0.0"):
"""Converts services to a format Couchbase understands"""
if not services and not enterprise_analytics:
services = "data"
elif services and enterprise_analytics:
return None, ["--services cannot be specified on Enterprise Analytics"]
elif enterprise_analytics:
return None, None
sep = ","
if services.find(sep) < 0:
# backward compatible when using ";" as separator
sep = ";"
svc_set = set([w.strip() for w in services.split(sep)])
manager_only = "manager-only"
svc_candidate = ["data", "index", "query", "fts", "eventing", "analytics", "backup", manager_only]
for svc in svc_set:
if svc not in svc_candidate:
return None, [f'`{svc}` is not a valid service']
if not enterprise and svc in ["eventing", "analytics", "backup"]:
return None, [f'{svc} service is only available on Enterprise Edition']
if len(svc_set) > 1 and manager_only in svc_set:
return None, ["Invalid service configuration. A manager only node cannot run any other services."]
versionCheck = compare_versions(cluster_version, "7.6.0")
if manager_only in svc_set and versionCheck == -1:
return None, ["The manager only service can only be used with >= 7.6.0 clusters"]
if not enterprise:
# Valid CE node service configuration
ce_svc_30 = set(["data"])
ce_svc_40 = set(["data", "index", "query"])
ce_svc_45 = set(["data", "index", "query", "fts"])
if svc_set not in [ce_svc_30, ce_svc_40, ce_svc_45]:
return None, [f"Invalid service configuration. Community Edition only supports nodes with the following"
f" combinations of services: '{''.join(ce_svc_30)}', '{','.join(ce_svc_40)}' or "
f"'{','.join(ce_svc_45)}'"]
services = ",".join(svc_set)
for old, new in [[";", ","], ["data", "kv"], ["query", "n1ql"], ["analytics", "cbas"], ["manager-only", ""]]:
services = services.replace(old, new)
return services, None
def find_subcommands():
"""Finds all subcommand classes"""
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
subclasses = [cls for cls in clsmembers if issubclass(cls[1], (Subcommand, LocalSubcommand))
and cls[1] not in [Subcommand, LocalSubcommand]]
subcommands = []
for subclass in subclasses:
name = '-'.join([part.lower() for part in re.findall('[A-Z][a-z]*', subclass[0])])
subcommands.append((name, subclass[1]))
return subcommands
def _success(msg):
print(f'SUCCESS: {msg}')
def _deprecated(msg):
print(f'DEPRECATED: {msg}')
def _warning(msg):
print(f'WARNING: {msg}')
def _error(msg):
print(f"ERROR: {msg}")
def _exit_if_errors(errors):
if not errors:
return
for error in errors:
# Some endpoints return errors prefixed with '_ -' this has to be stripped out. For more information see
# MB-42801.
_error(remove_prefix(str(error), "_ -").strip())
sys.exit(1)
def _exit_on_file_write_failure(fname, to_write):
try:
wfile = open(fname, 'w', encoding="utf-8")
wfile.write(to_write)
wfile.close()
except IOError as error:
_exit_if_errors([error])
def _exit_on_encrypted_file_read_failure(fname, password, config_path):
cbcat_path = os.path.join(get_bin_path(), 'cbcat')
if not os.path.isfile(cbcat_path):
_exit_if_errors([f'`{cbcat_path}` does not exist'])
gosecrets_cfg_path = os.path.join(config_path, 'config', 'gosecrets.cfg')
args = [cbcat_path, '--with-gosecrets', gosecrets_cfg_path,
'--password', '-', fname]
r = subprocess.run(args, input=password, text=True, capture_output=True,
check=False)
if r.returncode == 2: # cbcat returns 2 if and only it is incorrect password
_exit_if_errors(['Invalid master password'])
if r.returncode != 0:
_exit_if_errors([f'cbcat returned non zero return code: {r.stderr}'])
return r.stdout
def _exit_on_file_read_failure(fname, to_report=None):
try:
rfile = open(fname, 'r', encoding="utf-8")
read_bytes = rfile.read()
rfile.close()
return read_bytes
except IOError as error:
if to_report is None:
_exit_if_errors([f'{error.strerror} `{fname}`'])
else:
_exit_if_errors([to_report])
def _exit_on_json_file_read_failure(fname, to_report=None):
raw = _exit_on_file_read_failure(fname, to_report)
try:
decoded = json.loads(raw)
except ValueError as error:
if to_report is None:
_exit_if_errors([f'`{fname}` does not contain valid JSON data: {error}'])
else:
_exit_if_errors([to_report])
return decoded
def _read_json_file_if_provided(fname, to_report=None):
if fname is None or fname == "":
return None
return _exit_on_json_file_read_failure(fname, to_report)
def apply_default_port(nodes):
"""
Adds the default port if the port is missing.
@type nodes: string
@param nodes: A comma separated list of nodes
@rtype: array of strings
@return: The nodes with the port postfixed on each one
"""
nodes = nodes.split(',')
def append_port(node):
if re.match(r'.*:\d+$', node):
return node
return f'{node}:8091'
return [append_port(x) for x in nodes]
def prompt_for_confirmation(question, default=None):
confirm = 'Are you sure? '
if default is None:
confirm += 'Y/N'
elif default:
confirm += '[Y]/N'
else:
confirm += 'Y/[N]'
while True:
answer = input(question + ' ' + confirm + ' ')
if not answer:
if default is None:
continue
return default
if answer.lower() in ('y', 'yes'):
return True
if answer.lower() in ('n', 'no'):
return False
print(f'Unrecognised option "{answer}"')
if confirm not in ('y', 'Y', 'yes', 'Yes'):
return
class CollectionStringParser:
def __init__(self, inp):
self.inp = inp
self.pos = 0
def pop(self):
if self.pos == len(self.inp):
return None
self.pos += 1
return self.inp[self.pos - 1]
def peek(self):
if self.pos == len(self.inp):
return None
return self.inp[self.pos]
def expect(self, c):
if self.inp[self.pos] != c:
raise ValueError(f"unexpected char {self.inp[self.pos]}, was expecting {c}")
self.pos += 1
def take_until(self, c, accept_eof=False):
s = ''
while True:
got = self.peek()
if got is None:
if accept_eof:
return s
raise ValueError(f"unexpected end, was waiting for a {c} character")
if got == c:
return s
s += self.pop()
def item(self):
start = self.pop()
if start is None:
raise ValueError("unexpected end")
if start in "'\"":
item = self.take_until(start)
self.pop()
return item
return start + self.take_until(".", accept_eof=True)
def run(self):
items = []
for _ in range(3):
item = self.item()
items.append(item)
if self.peek() is None:
return items
self.expect('.')
raise ValueError(f"extra input left: {self.inp[self.pos:]}")
def parse(self, start_at="bucket"):
items = []
try:
items = self.run()
except ValueError as e:
return None, [str(e)]
keys = ["bucket", "scope", "collection"]
if start_at == "scope":
keys = keys[1:]
if len(keys) < len(items):
return None, ["too many items in collection string"]
d = dict(zip(keys, items))
cs = CollectionString(
bucket=d.get("bucket", None),
scope=d.get("scope", None),
collection=d.get("collection", None))
errors = cs.valid()
if errors:
return None, errors
return cs, []
@dataclasses.dataclass
class CollectionString:
bucket: str = None
scope: str = None
collection: str = None
def scope_collection_string(self):
if not self.scope:
return ""
s = self.scope
if self.collection:
s += "." + self.collection
return s
def levels(self):
if not self.bucket:
return 0
if not self.scope:
return 1
if not self.collection:
return 2
return 3
def _valid_name(self, field, name, allowed, disallowed_starting_chars='', max_len=0):
if max_len != 0 and len(name) > max_len:
return [f"{field} is too long"]
for i, c in enumerate(name.lower()):
if i == 0 and c in disallowed_starting_chars:
return [f"{field} names cannot start with {c}"]
if c not in allowed:
return [f"{field} names cannot have {c} in them"]
return []
def valid(self):
errors = []
if self.bucket:
e = self._valid_name("bucket", self.bucket, "abcdefghijklmnopqrstuvwxyz0123456789.%_-", max_len=100)
if e:
errors += e
valid_scope_collection_chars = "abcdefghijklmnopqrstuvwxyz0123456789%_-"
if self.scope:
e = self._valid_name(
"scope", self.scope, valid_scope_collection_chars, disallowed_starting_chars='%_', max_len=251)
if e:
errors += e
if self.collection:
e = self._valid_name(
"collection", self.collection, valid_scope_collection_chars, disallowed_starting_chars='%_',
max_len=251)
if e:
errors += e
return errors
class CLIHelpFormatter(HelpFormatter):
"""Format help with indented section bodies"""
def __init__(self, prog, indent_increment=2, max_help_position=30, width=None):
HelpFormatter.__init__(self, prog, indent_increment, max_help_position, width)
def add_argument(self, action):
if action.help is not SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
for subaction in self._iter_indented_subactions(action):
invocations.append(get_invocation(subaction))
# update the maximum item length
invocation_length = max([len(s) for s in invocations])
action_length = invocation_length + self._current_indent + 2
self._action_max_length = max(self._action_max_length,
action_length)
# add the item to the list
self._add_item(self._format_action, [action])
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
if action.nargs == 0:
parts.extend(action.option_strings)
return ','.join(parts)
else:
default = action.dest
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append(option_string)
return ','.join(parts) + ' ' + args_string
class CBDeprecatedAction(Action):
"""Indicates that a specific option is deprecated"""
def __call__(self, parser, namespace, values, option_string=None):
_deprecated('Specifying ' + '/'.join(self.option_strings) + ' is deprecated')
if self.nargs == 0:
setattr(namespace, self.dest, self.const)
else:
setattr(namespace, self.dest, values)
class CBHostAction(Action):
"""Allows the handling of hostnames on the command line"""
def __call__(self, parser, namespace, values, option_string=None):
parsed = urllib.parse.urlparse(values)
# If the netloc is empty then it means that there was no scheme added
# to the URI and we are parsing it as a path. In this case no scheme
# means HTTP so we can add that scheme to the hostname provided.
if parsed.netloc == "":
parsed = urllib.parse.urlparse("http://" + values)
if parsed.scheme == "":
parsed = urllib.parse.urlparse("http://" + values)
if parsed.path != "" or parsed.params != "" or parsed.query != "" or parsed.fragment != "":
raise ArgumentError(self, f"{values} is not an accepted hostname")
if not parsed.hostname:
raise ArgumentError(self, f"{values} is not an accepted hostname")
hostname_regex = re.compile(r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*'
+ r'([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$')
if not hostname_regex.match(parsed.hostname):
try:
ipaddress.ip_address(parsed.hostname)
except ValueError as val_error:
raise ArgumentError(self, f"{values} is not an accepted hostname") from val_error
scheme = parsed.scheme
port = None
if scheme in ["http", "couchbase"]:
if not parsed.port:
port = 8091
if scheme == "couchbase":
scheme = "http"
elif scheme in ["https", "couchbases"]:
if not parsed.port:
port = 18091
if scheme == "couchbases":
scheme = "https"
else:
raise ArgumentError(self, "%s is not an accepted scheme" % scheme)
if parsed.port:
setattr(namespace, self.dest, (scheme + "://" + parsed.netloc))
else:
setattr(namespace, self.dest, (scheme + "://" + parsed.netloc + ":" + str(port)))
class CBEnvAction(Action):
"""Allows the custom handling of environment variables for command line options"""
def __init__(self, envvar, required=False, default=None, **kwargs):
if not default and envvar and envvar in os.environ:
default = os.environ[envvar]
if required and default:
required = False
super(CBEnvAction, self).__init__(default=default, required=required,
**kwargs)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
class CBNonEchoedAction(CBEnvAction):
"""Allows an argument to be specified by use of a non-echoed value passed through
stdin, through an environment variable, or as a value to the argument"""
def __init__(self, envvar, prompt_text="Enter password: ", confirm_text=None,
required=False, default=None, nargs='?', **kwargs):
self.prompt_text = prompt_text
self.confirm_text = confirm_text
super(CBNonEchoedAction, self).__init__(envvar, required=required, default=default,
nargs=nargs, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if values is None:
values = getpass.getpass(self.prompt_text)
if self.confirm_text is not None:
confirm = getpass.getpass(self.prompt_text)
if values != confirm:
raise ArgumentError(self, "Passwords entered do not match, please retry")
super(CBNonEchoedAction, self).__call__(parser, namespace, values, option_string=None)
class CBHelpAction(Action):
"""Allows the custom handling of the help command line argument"""
# pylint: disable=redefined-builtin
def __init__(self, option_strings, klass, dest=SUPPRESS, default=SUPPRESS, help=None):
super(CBHelpAction, self).__init__(option_strings=option_strings, dest=dest,
default=default, nargs=0, help=help) # pylint: disable=redefined-builtin
self.klass = klass
def __call__(self, parser, namespace, values, option_string=None):
if option_string == "-h":
parser.print_help()
else:
CBHelpAction._show_man_page(self.klass.get_man_page_name())
parser.exit()
@staticmethod
def _show_man_page(page):
man_path = get_man_path()
if os.name == "nt":
try:
subprocess.call(["rundll32.exe", "url.dll,FileProtocolHandler", os.path.join(man_path, page)])
except OSError as e:
_exit_if_errors(["Unable to open man page using your browser, %s" % e])
else:
try:
subprocess.call(["man", os.path.join(man_path, page)])
except OSError:
_exit_if_errors(["Unable to open man page using the 'man' command, ensure it is on your path or"
+ "install a manual reader"])
class CliParser(ArgumentParser):
def __init__(self, *args, **kwargs):
super(CliParser, self).__init__(*args, **kwargs)
def error(self, message):
self.exit(2, f'ERROR: {message}\n')
class Command(object):
"""A Couchbase CLI Command"""
def __init__(self):
self.parser = CliParser(formatter_class=CLIHelpFormatter, add_help=False, allow_abbrev=False)
def parse(self, args):
"""Parses the subcommand"""
if len(args) == 0:
self.short_help()
return self.parser.parse_args(args)
def short_help(self, code=0):
"""Prints the short help message and exits"""
self.parser.print_help()
self.parser.exit(code)
def execute(self, opts):
"""Executes the subcommand"""
raise NotImplementedError
@staticmethod
def get_man_page_name():
"""Returns the man page name"""
raise NotImplementedError
@staticmethod
def get_description():
"""Returns the command description"""
raise NotImplementedError
class CouchbaseCLI(Command):
"""A Couchbase CLI command"""
def __init__(self):
super(CouchbaseCLI, self).__init__()
self.parser.prog = "couchbase-cli"
subparser = self.parser.add_subparsers(title="Commands", metavar="")
for (name, klass) in find_subcommands():
if klass.is_hidden():
subcommand = subparser.add_parser(name)
else:
subcommand = subparser.add_parser(name, help=klass.get_description())
subcommand.set_defaults(klass=klass)
group = self.parser.add_argument_group("Options")
group.add_argument("-h", "--help", action=CBHelpAction, klass=self,
help="Prints the short or long help message")
group.add_argument("--version", help="Get couchbase-cli version")
def parse(self, args):
if len(sys.argv) == 1:
self.parser.print_help()
self.parser.exit(1)
if args[1] == "--version":
print(VERSION)
sys.exit(0)
if not args[1] in ["-h", "--help", "--version"] and args[1].startswith("-"):
_exit_if_errors([f"Unknown subcommand: '{args[1]}'. The first argument has to be a subcommand like"
f" 'bucket-list' or 'rebalance', please see couchbase-cli -h for the full list of commands"
f" and options"])
l1_args = self.parser.parse_args(args[1:2])
l2_args = l1_args.klass().parse(args[2:])
setattr(l2_args, 'klass', l1_args.klass)
return l2_args
def execute(self, opts):
opts.klass().execute(opts)
@staticmethod
def get_man_page_name():
"""Returns the man page name"""
return get_doc_page_name("couchbase-cli")
@staticmethod
def get_description():
return "A Couchbase cluster administration utility"
class Subcommand(Command):
"""
A Couchbase CLI Subcommand: This is for subcommand that interacts with a remote Couchbase Server over the REST API.
"""
def __init__(self, deprecate_username=False, deprecate_password=False, cluster_default=None):
super(Subcommand, self).__init__()
# Filled by the decorators
self.rest = None
self.enterprise = None
self.enterprise_analytics = None
self.parser = CliParser(formatter_class=CLIHelpFormatter, add_help=False, allow_abbrev=False)
group = self.parser.add_argument_group("Cluster options")
group.add_argument("-c", "--cluster", dest="cluster", required=(cluster_default is None),
metavar="<cluster>", action=CBHostAction, default=cluster_default,
help="The hostname of the Couchbase cluster")
if deprecate_username:
group.add_argument("-u", "--username", dest="username",
action=CBDeprecatedAction, help=SUPPRESS)
else:
group.add_argument("-u", "--username", dest="username",
action=CBEnvAction, envvar='CB_REST_USERNAME',
metavar="<username>", help="The username for the Couchbase cluster")
if deprecate_password:
group.add_argument("-p", "--password", dest="password",
action=CBDeprecatedAction, help=SUPPRESS)
else:
group.add_argument("-p", "--password", dest="password",
action=CBNonEchoedAction, envvar='CB_REST_PASSWORD',
metavar="<password>", help="The password for the Couchbase cluster")
group.add_argument("--auth-token", dest="auth_token",
action=CBNonEchoedAction, envvar="CB_REST_AUTH_TOKEN", metavar="<auth-token>",
help="The JWT to authenticate with this Couchbase cluster")
group.add_argument("-o", "--output", dest="output", default="standard", metavar="<output>",
choices=["json", "standard"], help="The output type (json or standard)")
group.add_argument("-d", "--debug", dest="debug", action="store_true",
help="Run the command with extra logging")
group.add_argument("-s", "--ssl", dest="ssl", const=True, default=False,
nargs=0, action=CBDeprecatedAction,
help="Use ssl when connecting to Couchbase (Deprecated)")
group.add_argument("--no-ssl-verify", dest="ssl_verify", action="store_false", default=True,
help="Skips SSL verification of certificates against the CA")
group.add_argument("--cacert", dest="cacert", default=True,
help="Verifies the cluster identity with this certificate")
group.add_argument("-h", "--help", action=CBHelpAction, klass=self,