forked from couchbase/couchbase-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbmgr.py
4566 lines (3791 loc) · 209 KB
/
cbmgr.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
"""A Couchbase CLI subcommand"""
import getpass
import inspect
import ipaddress
import json
import os
import platform
import random
import re
import string
import subprocess
import sys
import urllib.parse
import time
from argparse import ArgumentError, ArgumentParser, HelpFormatter, Action, SUPPRESS
from cluster_manager import ClusterManager
from pbar import TopologyProgressBar
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"
CB_BIN_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "bin"))
CB_ETC_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "etc", "couchbase"))
CB_LIB_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "lib"))
# On MacOS the config is store in the users home directory
if platform.system() == "Darwin":
CB_CFG_PATH = os.path.expanduser("~/Library/Application Support/Couchbase/var/lib/couchbase")
else:
CB_CFG_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "var", "lib", "couchbase"))
CB_MAN_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "share"))
if os.name == "nt":
CB_MAN_PATH = os.path.join(CB_MAN_PATH, "html")
else:
CB_MAN_PATH = os.path.join(CB_MAN_PATH, "man", "man1")
def check_cluster_initialized(rest):
"""Checks to see if the cluster is initialized"""
initialized, errors = rest.is_cluster_initialized()
if errors:
_exitIfErrors(errors)
if not initialized:
_exitIfErrors(["Cluster is not initialized, use cluster-init to initialize the cluster"])
def index_storage_mode_to_param(value, default="plasma"):
"""Converts the index storage mode to what Couchbase understands"""
if value == "default":
return default
elif value == "memopt":
return "memory_optimized"
else:
return value
def process_services(services, enterprise):
"""Converts services to a format Couchbase understands"""
sep = ","
if services.find(sep) < 0:
#backward compatible when using ";" as separator
sep = ";"
svc_set = set([w.strip() for w in services.split(sep)])
svc_candidate = ["data", "index", "query", "fts", "eventing", "analytics"]
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"]:
return None, [f'{svc} service is only available on Enterprise Edition']
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"]]:
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 _exitIfErrors(errors):
if errors:
for error in errors:
print(f'ERROR: {error}')
sys.exit(1)
def _exit_on_file_write_failure(fname, to_write):
try:
wfile = open(fname, 'w')
wfile.write(to_write)
wfile.close()
except IOError as error:
_exitIfErrors([error])
def _exit_on_file_read_failure(fname, toReport = None):
try:
rfile = open(fname, 'r')
read_bytes = rfile.read()
rfile.close()
return read_bytes
except IOError as error:
if toReport is None:
_exitIfErrors([f'{error.strerror} `{fname}`'])
else:
_exitIfErrors([toReport])
def apply_default_port(nodes):
"""
Adds the default port if the port is missing.
@type nodes: string
@param nodes: A comma seprated 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('.*:\d+$', node):
return node
return f'{node}:8091'
return [append_port(x) for x in nodes]
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}')
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("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([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:
raise ArgumentError(self, f"{values} is not an accepted hostname")
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=True, default=None, **kwargs):
if not default and envvar:
if 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=True, 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 == 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"""
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)
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):
exe_path = os.path.abspath(sys.argv[0])
base_path = os.path.dirname(exe_path)
if os.name == "nt":
try:
subprocess.call(["rundll32.exe", "url.dll,FileProtocolHandler", os.path.join(CB_MAN_PATH, page)])
except OSError as e:
_exitIfErrors(["Unable to open man page using your browser, %s" % e])
else:
try:
subprocess.call(["man", os.path.join(CB_MAN_PATH, page)])
except OSError:
_exitIfErrors(["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("-"):
_exitIfErrors([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 "couchbase-cli" + ".1" if os.name != "nt" else ".html"
@staticmethod
def get_description():
return "A Couchbase cluster administration utility"
class Subcommand(Command):
"""
A Couchbase CLI Subcommand: This is for subcommand that interact 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__()
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==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", required=True,
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", required=True,
action=CBNonEchoedAction, envvar='CB_REST_PASSWORD',
metavar="<password>", help="The password for the 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,
help="Prints the short or long help message")
def execute(self, opts):
super(Subcommand, self).execute(opts)
@staticmethod
def get_man_page_name():
return Command.get_man_page_name()
@staticmethod
def get_description():
return Command.get_description()
@staticmethod
def is_hidden():
"""Whether or not the subcommand should be hidden from the help message"""
return False
class LocalSubcommand(Command):
"""
A Couchbase CLI Localcommand: This is for subcommands that interact with the local Couchbase Server via the
filesystem or a local socket.
"""
def __init__(self):
super(LocalSubcommand, self).__init__()
self.parser = CliParser(formatter_class=CLIHelpFormatter, add_help=False, allow_abbrev=False)
group = self.parser.add_argument_group(title="Local command options",
description="This command has to be execute on the locally running" +
" Couchbase Server.")
group.add_argument("-h", "--help", action=CBHelpAction, klass=self,
help="Prints the short or long help message")
group.add_argument("--config-path", dest="config_path", metavar="<path>",
default=CB_CFG_PATH, help=SUPPRESS)
def execute(self, opts):
super(LocalSubcommand, self).execute(opts)
@staticmethod
def get_man_page_name():
return Command.get_man_page_name()
@staticmethod
def get_description():
return Command.get_description()
@staticmethod
def is_hidden():
"""Whether or not the subcommand should be hidden from the help message"""
return False
class ClusterInit(Subcommand):
"""The cluster initialization subcommand"""
def __init__(self):
super(ClusterInit, self).__init__(True, True, "http://127.0.0.1:8091")
self.parser.prog = "couchbase-cli cluster-init"
group = self.parser.add_argument_group("Cluster initialization options")
group.add_argument("--cluster-username", dest="username", required=True,
metavar="<username>", help="The cluster administrator username")
group.add_argument("--cluster-password", dest="password", required=True,
metavar="<password>", help="Only compact the data files")
group.add_argument("--cluster-port", dest="port", type=(int),
metavar="<port>", help="The cluster administration console port")
group.add_argument("--cluster-ramsize", dest="data_mem_quota", type=(int),
metavar="<quota>", help="The data service memory quota in megabytes")
group.add_argument("--cluster-index-ramsize", dest="index_mem_quota", type=(int),
metavar="<quota>", help="The index service memory quota in megabytes")
group.add_argument("--cluster-fts-ramsize", dest="fts_mem_quota", type=(int),
metavar="<quota>",
help="The full-text service memory quota in Megabytes")
group.add_argument("--cluster-eventing-ramsize", dest="eventing_mem_quota", type=(int),
metavar="<quota>",
help="The Eventing service memory quota in Megabytes")
group.add_argument("--cluster-analytics-ramsize", dest="cbas_mem_quota", type=(int),
metavar="<quota>",
help="The analytics service memory quota in Megabytes")
group.add_argument("--cluster-name", dest="name", metavar="<name>", help="The cluster name")
group.add_argument("--index-storage-setting", dest="index_storage_mode",
choices=["default", "memopt"], metavar="<mode>",
help="The index storage backend (Defaults to \"default)\"")
group.add_argument("--services", dest="services", default="data", metavar="<service_list>",
help="The services to run on this server")
def execute(self, opts):
# We need to ensure that creating the REST username/password is the
# last REST API that is called because once that API succeeds the
# cluster is initialized and cluster-init cannot be run again.
rest = ClusterManager(opts.cluster, opts.username, opts.password, opts.ssl, opts.ssl_verify,
opts.cacert, opts.debug)
initialized, errors = rest.is_cluster_initialized()
_exitIfErrors(errors)
if initialized:
_exitIfErrors(["Cluster is already initialized, use setting-cluster to change settings"])
enterprise, errors = rest.is_enterprise()
_exitIfErrors(errors)
if not enterprise and opts.index_storage_mode == 'memopt':
_exitIfErrors(["memopt option for --index-storage-setting can only be configured on enterprise edition"])
services, errors = process_services(opts.services, enterprise)
_exitIfErrors(errors)
if 'kv' not in services.split(','):
_exitIfErrors(["Cannot set up first cluster node without the data service"])
if opts.data_mem_quota or opts.index_mem_quota or opts.fts_mem_quota or opts.cbas_mem_quota \
or opts.eventing_mem_quota or opts.name is not None:
_, errors = rest.set_pools_default(opts.data_mem_quota, opts.index_mem_quota, opts.fts_mem_quota,
opts.cbas_mem_quota, opts.eventing_mem_quota, opts.name)
_exitIfErrors(errors)
# Set the index storage mode
if not opts.index_storage_mode and 'index' in services.split(','):
opts.index_storage_mode = "default"
default = "plasma"
if not enterprise:
default = "forestdb"
if opts.index_storage_mode:
param = index_storage_mode_to_param(opts.index_storage_mode, default)
_, errors = rest.set_index_settings(param, None, None, None, None, None)
_exitIfErrors(errors)
# Setup services
_, errors = rest.setup_services(services)
_exitIfErrors(errors)
# Enable notifications
_, errors = rest.enable_notifications(True)
_exitIfErrors(errors)
# Setup Administrator credentials and Admin Console port
_, errors = rest.set_admin_credentials(opts.username, opts.password,
opts.port)
_exitIfErrors(errors)
_success("Cluster initialized")
@staticmethod
def get_man_page_name():
return "couchbase-cli-cluster-init" + ".1" if os.name != "nt" else ".html"
@staticmethod
def get_description():
return "Initialize a Couchbase cluster"
class BucketCompact(Subcommand):
"""The bucket compact subcommand"""
def __init__(self):
super(BucketCompact, self).__init__()
self.parser.prog = "couchbase-cli bucket-compact"
group = self.parser.add_argument_group("Bucket compaction options")
group.add_argument("--bucket", dest="bucket_name", metavar="<name>",
help="The name of bucket to compact")
group.add_argument("--data-only", dest="data_only", action="store_true",
help="Only compact the data files")
group.add_argument("--view-only", dest="view_only", action="store_true",
help="Only compact the view files")
def execute(self, opts):
rest = ClusterManager(opts.cluster, opts.username, opts.password, opts.ssl, opts.ssl_verify,
opts.cacert, opts.debug)
check_cluster_initialized(rest)
check_versions(rest)
bucket, errors = rest.get_bucket(opts.bucket_name)
_exitIfErrors(errors)
if bucket["bucketType"] != BUCKET_TYPE_COUCHBASE:
_exitIfErrors(["Cannot compact memcached buckets"])
_, errors = rest.compact_bucket(opts.bucket_name, opts.data_only, opts.view_only)
_exitIfErrors(errors)
_success("Bucket compaction started")
@staticmethod
def get_man_page_name():
return "couchbase-cli-bucket-compact" + ".1" if os.name != "nt" else ".html"
@staticmethod
def get_description():
return "Compact database and view data"
class BucketCreate(Subcommand):
"""The bucket create subcommand"""
def __init__(self):
super(BucketCreate, self).__init__()
self.parser.prog = "couchbase-cli bucket-create"
group = self.parser.add_argument_group("Bucket create options")
group.add_argument("--bucket", dest="bucket_name", metavar="<name>", required=True,
help="The name of bucket to create")
group.add_argument("--bucket-type", dest="type", metavar="<type>", required=True,
choices=["couchbase", "ephemeral", "memcached"],
help="The bucket type (couchbase, ephemeral, or memcached)")
group.add_argument("--bucket-ramsize", dest="memory_quota", metavar="<quota>", type=(int),
required=True, help="The amount of memory to allocate the bucket")
group.add_argument("--bucket-replica", dest="replica_count", metavar="<num>",
choices=["0", "1", "2", "3"],
help="The replica count for the bucket")
group.add_argument("--bucket-priority", dest="priority", metavar="<priority>",
choices=[BUCKET_PRIORITY_LOW_STR, BUCKET_PRIORITY_HIGH_STR],
help="The bucket disk io priority (low or high)")
group.add_argument("--bucket-eviction-policy", dest="eviction_policy", metavar="<policy>",
choices=["valueOnly", "fullEviction", "noEviction", "nruEviction"],
help="The bucket eviction policy")
group.add_argument("--conflict-resolution", dest="conflict_resolution", default=None,
choices=["sequence", "timestamp"], metavar="<type>",
help="The XDCR conflict resolution type (timestamp or sequence)")
group.add_argument("--max-ttl", dest="max_ttl", default=None, type=(int), metavar="<seconds>",
help="Set the maximum TTL the bucket will accept. Couchbase server Enterprise Edition only.")
group.add_argument("--compression-mode", dest="compression_mode",
choices=["off", "passive", "active"], metavar="<mode>",
help="Set the compression mode of the bucket")
group.add_argument("--enable-flush", dest="enable_flush", metavar="<0|1>",
choices=["0", "1"], help="Enable bucket flush on this bucket (0 or 1)")
group.add_argument("--enable-index-replica", dest="replica_indexes", metavar="<0|1>",
choices=["0", "1"], help="Enable replica indexes (0 or 1)")
group.add_argument("--wait", dest="wait", action="store_true",
help="Wait for bucket creation to complete")
group.add_argument("--database-fragmentation-threshold-percentage", dest="db_frag_perc",
metavar="<perc>", type=(int), help="Set Database Fragmentation level percent")
group.add_argument("--database-fragmentation-threshold-size", dest="db_frag_size",
metavar="<megabytes>", type=(int), help="Set Database Fragmentation level")
group.add_argument("--view-fragmentation-threshold-percentage", dest="view_frag_perc",
metavar="<perc>", type=(int), help="Set View Fragmentation level percent")
group.add_argument("--view-fragmentation-threshold-size", dest="view_frag_size",
metavar="<megabytes>", type=(int), help="Set View Fragmentation level size")
group.add_argument("--from-hour", dest="from_hour",
metavar="<quota>", type=(int), help="Set start time hour")
group.add_argument("--from-minute", dest="from_min",
metavar="<quota>", type=(int), help="Set start time minutes")
group.add_argument("--to-hour", dest="to_hour",
metavar="<quota>", type=(int), help="Set end time hour")
group.add_argument("--to-minute", dest="to_min",
metavar="<quota>", type=(int), help="Set end time minutes")
group.add_argument("--abort-outside", dest="abort_outside",
metavar="<0|1>", choices=["0", "1"], help="Allow Time period")
group.add_argument("--parallel-db-view-compaction", dest="paralleldb_and_view_compact",
metavar="<0|1>", choices=["0", "1"], help="Set parallel DB and View Compaction")
group.add_argument("--purge-interval", dest="purge_interval", type=(float),
metavar="<float>", help="Set parallel DB and View Compaction")
def execute(self, opts):
rest = ClusterManager(opts.cluster, opts.username, opts.password, opts.ssl, opts.ssl_verify,
opts.cacert, opts.debug)
check_cluster_initialized(rest)
check_versions(rest)
enterprise, errors = rest.is_enterprise()
_exitIfErrors(errors)
if opts.max_ttl and not enterprise:
_exitIfErrors(["Maximum TTL can only be configured on enterprise edition"])
if opts.compression_mode and not enterprise:
_exitIfErrors(["Compression mode can only be configured on enterprise edition"])
if opts.type == "memcached":
if opts.replica_count is not None:
_exitIfErrors(["--bucket-replica cannot be specified for a memcached bucket"])
if opts.conflict_resolution is not None:
_exitIfErrors(["--conflict-resolution cannot be specified for a memcached bucket"])
if opts.replica_indexes is not None:
_exitIfErrors(["--enable-index-replica cannot be specified for a memcached bucket"])
if opts.priority is not None:
_exitIfErrors(["--bucket-priority cannot be specified for a memcached bucket"])
if opts.eviction_policy is not None:
_exitIfErrors(["--bucket-eviction-policy cannot be specified for a memcached bucket"])
if opts.max_ttl is not None:
_exitIfErrors(["--max-ttl cannot be specified for a memcached bucket"])
if opts.compression_mode is not None:
_exitIfErrors(["--compression-mode cannot be specified for a memcached bucket"])
elif opts.type == "ephemeral":
if opts.eviction_policy in ["valueOnly", "fullEviction"]:
_exitIfErrors(["--bucket-eviction-policy must either be noEviction or nruEviction"])
elif opts.type == "couchbase":
if opts.eviction_policy in ["noEviction", "nruEviction"]:
_exitIfErrors(["--bucket-eviction-policy must either be valueOnly or fullEviction"])
if ((opts.type == "memcached" or opts.type == "ephemeral") and (opts.db_frag_perc is not None or
opts.db_frag_size is not None or opts.view_frag_perc is not None or
opts.view_frag_size is not None or opts.from_hour is not None or opts.from_min is not None or
opts.to_hour is not None or opts.to_min is not None or opts.abort_outside is not None or
opts.paralleldb_and_view_compact is not None)):
_warning(f'ignoring compaction settings as bucket type {opts.type} does not accept it')
priority = None
if opts.priority is not None:
if opts.priority == BUCKET_PRIORITY_HIGH_STR:
priority = BUCKET_PRIORITY_HIGH_INT
elif opts.priority == BUCKET_PRIORITY_LOW_STR:
priority = BUCKET_PRIORITY_LOW_INT
conflict_resolution_type = None
if opts.conflict_resolution is not None:
if opts.conflict_resolution == "sequence":
conflict_resolution_type = "seqno"
elif opts.conflict_resolution == "timestamp":
conflict_resolution_type = "lww"
_, errors = rest.create_bucket(opts.bucket_name, opts.type, opts.memory_quota, opts.eviction_policy,
opts.replica_count, opts.replica_indexes, priority, conflict_resolution_type,
opts.enable_flush, opts.max_ttl, opts.compression_mode, opts.wait,
opts.db_frag_perc, opts.db_frag_size, opts.view_frag_perc, opts.view_frag_size,
opts.from_hour, opts.from_min, opts.to_hour, opts.to_min, opts.abort_outside,
opts.paralleldb_and_view_compact, opts.purge_interval)
_exitIfErrors(errors)
_success("Bucket created")
@staticmethod
def get_man_page_name():
return "couchbase-cli-bucket-create" + ".1" if os.name != "nt" else ".html"
@staticmethod
def get_description():
return "Add a new bucket to the cluster"
class BucketDelete(Subcommand):
"""The bucket delete subcommand"""
def __init__(self):
super(BucketDelete, self).__init__()
self.parser.prog = "couchbase-cli bucket-delete"
group = self.parser.add_argument_group("Bucket delete options")
group.add_argument("--bucket", dest="bucket_name", metavar="<name>", required=True,
help="The name of bucket to delete")
def execute(self, opts):
rest = ClusterManager(opts.cluster, opts.username, opts.password, opts.ssl, opts.ssl_verify,
opts.cacert, opts.debug)
check_cluster_initialized(rest)
check_versions(rest)
_, errors = rest.get_bucket(opts.bucket_name)
_exitIfErrors(errors)
_, errors = rest.delete_bucket(opts.bucket_name)
_exitIfErrors(errors)
_success("Bucket deleted")
@staticmethod
def get_man_page_name():
return "couchbase-cli-bucket-delete" + ".1" if os.name != "nt" else ".html"
@staticmethod
def get_description():
return "Delete an existing bucket"
class BucketEdit(Subcommand):
"""The bucket edit subcommand"""
def __init__(self):
super(BucketEdit, self).__init__()
self.parser.prog = "couchbase-cli bucket-edit"
group = self.parser.add_argument_group("Bucket edit options")
group.add_argument("--bucket", dest="bucket_name", metavar="<name>", required=True,
help="The name of bucket to create")
group.add_argument("--bucket-ramsize", dest="memory_quota", metavar="<quota>",
type=(int), help="The amount of memory to allocate the bucket")
group.add_argument("--bucket-replica", dest="replica_count", metavar="<num>",
choices=["0", "1", "2", "3"],
help="The replica count for the bucket")
group.add_argument("--bucket-priority", dest="priority", metavar="<priority>",
choices=["low", "high"], help="The bucket disk io priority (low or high)")
group.add_argument("--bucket-eviction-policy", dest="eviction_policy", metavar="<policy>",
choices=["valueOnly", "fullEviction"],
help="The bucket eviction policy (valueOnly or fullEviction)")
group.add_argument("--max-ttl", dest="max_ttl", default=None, type=(int), metavar="<seconds>",
help="Set the maximum TTL the bucket will accept")
group.add_argument("--compression-mode", dest="compression_mode",
choices=["off", "passive", "active"], metavar="<mode>",
help="Set the compression mode of the bucket")
group.add_argument("--enable-flush", dest="enable_flush", metavar="<0|1>",
choices=["0", "1"], help="Enable bucket flush on this bucket (0 or 1)")
group.add_argument("--remove-bucket-port", dest="remove_port", metavar="<0|1>",
choices=["0", "1"], help="Removes the bucket-port setting")
group.add_argument("--database-fragmentation-threshold-percentage", dest="db_frag_perc",
metavar="<perc>", type=(int), help="Set Database Fragmentation level percent")
group.add_argument("--database-fragmentation-threshold-size", dest="db_frag_size",
metavar="<megabytes>", type=(int), help="Set Database Fragmentation level")
group.add_argument("--view-fragmentation-threshold-percentage", dest="view_frag_perc",
metavar="<perc>", type=(int), help="Set View Fragmentation level percent")
group.add_argument("--view-fragmentation-threshold-size", dest="view_frag_size",
metavar="<megabytes>", type=(int), help="Set View Fragmentation level size")
group.add_argument("--from-hour", dest="from_hour",
metavar="<hour>", type=(int), help="Set start time hour")
group.add_argument("--from-minute", dest="from_min",
metavar="<min>", type=(int), help="Set start time minutes")
group.add_argument("--to-hour", dest="to_hour",
metavar="<hour>", type=(int), help="Set end time hour")
group.add_argument("--to-minute", dest="to_min",
metavar="<min>", type=(int), help="Set end time minutes")
group.add_argument("--abort-outside", dest="abort_outside",
metavar="<0|1>", choices=["0", "1"], help="Allow Time period")
group.add_argument("--parallel-db-view-compaction", dest="paralleldb_and_view_compact",
metavar="<0|1>", choices=["0", "1"], help="Set parallel DB and View Compaction")
group.add_argument("--purge-interval", dest="purge_interval", type=(float),
metavar="<num>", help="Set parallel DB and View Compaction")
def execute(self, opts):
rest = ClusterManager(opts.cluster, opts.username, opts.password, opts.ssl, opts.ssl_verify,
opts.cacert, opts.debug)
check_cluster_initialized(rest)
check_versions(rest)
enterprise, errors = rest.is_enterprise()
_exitIfErrors(errors)
if opts.max_ttl and not enterprise:
_exitIfErrors(["Maximum TTL can only be configured on enterprise edition"])
if opts.compression_mode and not enterprise:
_exitIfErrors(["Compression mode can only be configured on enterprise edition"])
bucket, errors = rest.get_bucket(opts.bucket_name)
_exitIfErrors(errors)
if "bucketType" in bucket and bucket["bucketType"] == "memcached":
if opts.memory_quota is not None:
_exitIfErrors(["--bucket-ramsize cannot be specified for a memcached bucket"])
if opts.replica_count is not None:
_exitIfErrors(["--bucket-replica cannot be specified for a memcached bucket"])
if opts.priority is not None:
_exitIfErrors(["--bucket-priority cannot be specified for a memcached bucket"])
if opts.eviction_policy is not None:
_exitIfErrors(["--bucket-eviction-policy cannot be specified for a memcached bucket"])
if opts.max_ttl is not None:
_exitIfErrors(["--max-ttl cannot be specified for a memcached bucket"])
if opts.compression_mode is not None:
_exitIfErrors(["--compression-mode cannot be specified for a memcached bucket"])
if (("bucketType" in bucket and (bucket["bucketType"] == "memcached" or bucket["bucketType"] == "ephemeral"))
and (opts.db_frag_perc is not None or opts.db_frag_size is not None or
opts.view_frag_perc is not None or opts.view_frag_size is not None or opts.from_hour is not None or
opts.from_min is not None or opts.to_hour is not None or opts.to_min is not None or
opts.abort_outside is not None or opts.paralleldb_and_view_compact is not None)):
_exitIfErrors([f'compaction settings can not be specified for a {bucket["bucketType"]} bucket'])
priority = None
if opts.priority is not None:
if opts.priority == BUCKET_PRIORITY_HIGH_STR:
priority = BUCKET_PRIORITY_HIGH_INT
elif opts.priority == BUCKET_PRIORITY_LOW_STR:
priority = BUCKET_PRIORITY_LOW_INT
if opts.remove_port:
if opts.remove_port == '1':
opts.remove_port = True
else:
opts.remove_port = False
_, errors = rest.edit_bucket(opts.bucket_name, opts.memory_quota, opts.eviction_policy, opts.replica_count,
priority, opts.enable_flush, opts.max_ttl, opts.compression_mode, opts.remove_port,
opts.db_frag_perc, opts.db_frag_size, opts.view_frag_perc, opts.view_frag_size,
opts.from_hour, opts.from_min, opts.to_hour, opts.to_min, opts.abort_outside,
opts.paralleldb_and_view_compact, opts.purge_interval)
_exitIfErrors(errors)
_success("Bucket edited")
@staticmethod
def get_man_page_name():
return "couchbase-cli-bucket-edit" + ".1" if os.name != "nt" else ".html"
@staticmethod
def get_description():
return "Modify settings for an existing bucket"
class BucketFlush(Subcommand):
"""The bucket edit subcommand"""
def __init__(self):
super(BucketFlush, self).__init__()
self.parser.prog = "couchbase-cli bucket-flush"
group = self.parser.add_argument_group("Bucket flush options")
group.add_argument("--bucket", dest="bucket_name", metavar="<name>", required=True,
help="The name of bucket to delete")
group.add_argument("--force", dest="force", action="store_true",
help="Execute the command without asking to confirm")
def execute(self, opts):
rest = ClusterManager(opts.cluster, opts.username, opts.password, opts.ssl, opts.ssl_verify,
opts.cacert, opts.debug)
check_cluster_initialized(rest)
check_versions(rest)
_, errors = rest.get_bucket(opts.bucket_name)
_exitIfErrors(errors)