-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathyb-ctl
executable file
·2109 lines (1783 loc) · 88.8 KB
/
yb-ctl
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
#!/usr/bin/env python
# Copyright (c) YugaByte, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations
# under the License.
#
"""A script to manage a local YugaByte cluster.
We will aim to maintain https://docs.yugabyte.com/admin/yb-ctl/ as public facing documentation!
Example use cases:
Creating a cluster with default settings
yb-ctl start (yb-ctl create)
Creating a cluster with replication factor 5
yb-ctl --rf 5 start
Creating a cluster with placement_info
yb-ctl start --placement_info "cloud1.region1.zone1,cloud2.region2.zone2,cloud3.region3.zone3"
Creating a cluster with custom flags
yb-ctl start \\
--master_flags 'flag1=value,flag2=value,flag3=value' \\
--tserver_flags 'flag1=value,"flag2=complex=,=,=,value",flag3=value'
Destroying a cluster
yb-ctl destroy
Restart the cluster
yb-ctl restart
Wipe restart
yb-ctl wipe_restart
Destroying your local cluster and its data
yb-ctl destroy
Add node
yb-ctl add_node (--placement_info "cloud1.region1.zone1")
Stopping node #X from your cluster
yb-ctl remove_node <node_id>
Start node
yb-ctl start_node <node_id> (--placement_info "cloud1.region1.zone1")
Stop node
yb-ctl stop_node <node_id>
Restart node
yb-ctl restart_node <node_id>
"""
from __future__ import print_function
import atexit
import argparse
import errno
import glob
import hashlib
import json
import logging
import os
import random
import re
import shutil
import signal
import subprocess
import sys
import time
import tempfile
import csv
DAEMON_TYPE_MASTER = 'master'
DAEMON_TYPE_TSERVER = 'tserver'
PROTOCOL_TYPE_YSQL = 'ysql'
PROTOCOL_TYPE_YCQL = 'ycql'
PROTOCOL_TYPE_YEDIS = 'yedis'
VERSION_METADATA_JSON = 'version_metadata.json'
DAEMON_TYPES = [
DAEMON_TYPE_MASTER,
DAEMON_TYPE_TSERVER
]
PROTOCOL_TYPES = {
PROTOCOL_TYPE_YSQL,
PROTOCOL_TYPE_YCQL,
PROTOCOL_TYPE_YEDIS
}
YSQL_DEFAULT_PORT = 5433
YCQL_DEFAULT_PORT = 9042
YEDIS_DEFAULT_PORT = 6379
LOCALHOST_IP = '127.0.0.1'
SLEEP_TIME_IN_SEC = 1
MAX_YB_ADMIN_WAIT_SEC = 45
MAX_WAIT_FOR_PROCESSES_RUNNING_SEC = 10
DEFAULT_REPLICATION_FACTOR = 1
DEFAULT_IP_START = 1
# A regex to get data directories out a command line of a running process.
# Needs to match e.g. the following command line snippet:
# --fs_data_dirs /tmp/yb-ctl-test-data-2019-06-05T14_14_12-4841/node-1/disk-1
FS_DATA_DIRS_ARG_RE = re.compile(r'--fs_data_dirs[ =](\S+)')
def is_release_mode():
"""
This script can be located in either a release package or a src package.
Use the VERSION_METADATA_JSON file to determin if it is running in the
release mode.
"""
root_candidate = dirname_n(os.path.realpath(__file__), 2)
return os.path.exists(os.path.join(root_candidate, VERSION_METADATA_JSON))
def call_get_output_maybe_error(cmd_list, should_get_error=False):
"""
Subprocess call the passed in command and on success, return the output.
:param cmd_list: the command to execute
:param should_get_error: if to capture and log the error on failure
:return: the output of the command, on success, else raises a CalledProcessError
"""
with open(os.devnull, "wb") as devnull:
stderr = subprocess.PIPE if should_get_error else devnull
stderr = subprocess.PIPE
proc = subprocess.Popen(
cmd_list, stdout=subprocess.PIPE, stderr=stderr)
output, error = proc.communicate()
if proc.returncode:
raise subprocess.CalledProcessError(
proc.returncode, cmd_list, output="{}\n{}".format(output, error))
return output
def retry_call_with_timeout(fn, timeout_sec=MAX_YB_ADMIN_WAIT_SEC):
"""
This will retry a given function that is supposed to be doing subprocess callouts. Based on
the passed in function behavior, this function will behave accordingly:
- if fn returns True, we return True
- if fn does not return True, we keep retrying
- if fn throws a CalledProcessError, we keep retrying and log errors if the last run
- if we hit the timeout, we just return
Note: the function takes a bool arg to decide if to capture and log stderr on error.
:param fn: the function to retry calling
:param timeout_sec: the amount of time to keep retrying
"""
start_time = time.time()
while True:
time_elapsed = time.time() - start_time
if time_elapsed > timeout_sec:
return
is_last_iteration = time_elapsed + SLEEP_TIME_IN_SEC > timeout_sec
try:
ret = fn(is_last_iteration)
if ret:
return ret
except subprocess.CalledProcessError as e:
if is_last_iteration:
logging.error("Failed too many times. CMDLINE={} RETCODE={} OUTPUT={}".format(
e.cmd, e.returncode, e.output))
time.sleep(SLEEP_TIME_IN_SEC)
def wait_for_proc_report_progress(proc):
"""
Poll process to check if it has terminated and print one . per second.
This is used as a way to indicate to user that process is still running.
:param proc: the process whose status needs to be checked
"""
INITIAL_SECONDS_WITHOUT_PROGRESS_REPORTING = 2
start_time_sec = time.time()
printed_dots = False
while proc.poll() is None:
# Do not add newline at the end, just report one . per second.
if time.time() - start_time_sec > INITIAL_SECONDS_WITHOUT_PROGRESS_REPORTING:
print(".", end="")
sys.stdout.flush()
printed_dots = True
time.sleep(1)
if printed_dots:
# Add a newline, since we did not do so during above printing of dots.
print()
def is_env_var_true(env_var_name):
env_var_value = os.getenv(env_var_name)
return env_var_value and env_var_value.strip().lower() not in ['n', 'no', '0', 'f', 'false']
def format_cmd_line_with_host_port(executable, host, port, default_port):
"""
Adds -h host -p port options if necessary. This works for ysqlsh (psql) and redis-cli.
"""
cmd_line = str(executable)
if host != LOCALHOST_IP:
cmd_line += ' -h %s' % host
if port != default_port:
cmd_line += ' -p %d' % port
return cmd_line
DISABLE_CALLHOME_ENV_VAR_SET = is_env_var_true('YB_DISABLE_CALLHOME')
class ExitWithError(Exception):
pass
def get_local_ip(index):
return "127.0.0.{}".format(index)
def validate_daemon_type(daemon_type):
if daemon_type not in DAEMON_TYPES:
raise RuntimeError("Invalid daemon type: '{}'".format(daemon_type))
def get_binary_name_for_daemon_type(daemon_type):
binary_name = None
# Allow the user to use binaries of their choice for yb-master and/or yb-tserver.
if daemon_type == DAEMON_TYPE_MASTER:
binary_name = os.getenv('YB_CTL_MASTER_DAEMON_FILE_NAME')
elif daemon_type == DAEMON_TYPE_TSERVER:
binary_name = os.getenv('YB_CTL_TSERVER_DAEMON_FILE_NAME')
if binary_name is not None:
return binary_name
return "yb-{}".format(daemon_type)
def adjust_env_for_ysql():
# TODO: we should not need to do this if Linuxbrew's glibc bundled with the YB package has
# proper access to locale data.
for k in os.environ.keys():
if k == 'LANG' or k.startswith('LC_'):
del os.environ[k]
def get_home_dir():
return os.path.expanduser('~')
def get_default_data_dir():
return os.path.join(get_home_dir(), 'yugabyte-data')
def get_os_family():
if sys.platform.startswith('linux'):
return 'linux'
if sys.platform.startswith('darwin'):
return 'darwin'
raise ValueError("Unsupported operating system: sys.platform=%s" % sys.platform)
def is_linux():
return get_os_family() == 'linux'
def get_file_sha256_sum(file_path):
"""
Compute a SHA256 checksum of a file. Based on http://bit.ly/2uGHL8N
"""
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(1048576), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def download_file(url, dest_path):
"""
Download a file and return its SHA256 sum.
"""
try:
with open(dest_path, 'wb') as dest_file:
if sys.version_info[0] >= 3:
import urllib.request
req = urllib.request.Request(url, headers={'user-agent': 'Mozilla'})
remote_file = urllib.request.urlopen(req)
else:
import urllib2
req = urllib2.Request(url)
req.add_header('user-agent', 'Mozilla')
remote_file = urllib2.urlopen(req)
try:
sha256_hash = hashlib.sha256()
for byte_block in iter(lambda: remote_file.read(1048576), b""):
sha256_hash.update(byte_block)
dest_file.write(byte_block)
return sha256_hash.hexdigest()
finally:
remote_file.close()
except: # noqa
if os.path.exists(dest_path):
logging.warn("Deleting the unfinished download: %s", dest_path)
os.remove(dest_path)
raise
def mkdir_p(dir_path):
try:
if not os.path.exists(dir_path):
os.makedirs(dir_path)
except IOError as ex:
if os.path.isdir(dir_path):
# Concurrent directory creation.
return
raise
def has_rel_paths(top_dir, rel_paths):
for rel_path in rel_paths:
if not os.path.exists(os.path.join(top_dir, rel_path)):
return False
return True
def dirname_n(dir_path, n):
"""
Call N times of dirname(...) on the input dir_path.
"""
for _ in range(n):
dir_path = os.path.dirname(dir_path)
return dir_path
def is_yugabyte_db_installation_dir(top_dir):
"""
Checks if the given directory is a viable YugaByte DB installation directory. A build directory
with master/tserver/postgres binaries already built would match this definition.
"""
if top_dir is None:
return False
return has_rel_paths(
top_dir, [
'bin/' + get_binary_name_for_daemon_type(DAEMON_TYPE_MASTER),
'bin/' + get_binary_name_for_daemon_type(DAEMON_TYPE_TSERVER),
'postgres/bin/postgres'
])
def remove_surrounding_quotes(s):
if len(s) >= 2:
for quote in ['"', "'"]:
if s.startswith(quote) and s.endswith(quote):
return s[1:-1]
return s
def is_flag_true(flags, name):
value = flags.get(name, '').lower()
return value == '1' or value == 'true'
class Installer:
YUGABYTE_DB_VERSION = '2.1.8.2'
DOWNLOAD_URL_PATTERN = 'https://downloads.yugabyte.com/yugabyte-{version}-{os}.tar.gz'
SHA256_SUM_BY_OS = {
'darwin': 'dd6cbd63ad4dd150c9707ed5dc8f3696adf9828dff941bae2255bc04eff7e924',
'linux': 'e4709b75bc6f180d91281b1c898b0dbe9ef7ea81ed7c9a5ee2368d78c66a664e'
}
def __init__(self, only_find_existing=False):
self.installation_dir = None
self.only_find_existing = only_find_existing
def get_download_cache_dir(self):
return os.path.join(get_home_dir(), '.cache', 'yugabyte', 'downloads')
def get_software_installation_top_dir(self):
return os.path.join(get_home_dir(), 'yugabyte-db')
def install_or_find_existing(self):
"""
Downloads/installs YugaByte DB, or only finds an existing installation, if
"only_find_existing" was set during this installer's creation.
Returns True in case YugaByte DB was installed or an existing installation was found.
Returns False only if only_find_existing is specified and no existing installation found.
Errors are still handled by raising exceptions.
"""
installation_top_dir = self.get_software_installation_top_dir()
self.installation_dir = os.path.join(
installation_top_dir, 'yugabyte-' + Installer.YUGABYTE_DB_VERSION)
if os.path.exists(self.installation_dir):
if not is_yugabyte_db_installation_dir(self.installation_dir):
logging.error(
"Directory %s exists but does not appear to be a valid YugaByte DB "
"installation directory. Remove that directory and re-run the script "
"to re-install YugaByte DB.", self.installation_dir)
sys.exit(1)
# Already installed.
logging.info("Found existing YugaByte DB installation at %s", self.installation_dir)
# This will re-run the post-install script if it did not complete initially.
return self.run_post_install_script()
if self.only_find_existing:
# No installation found, and we're not allowed to make any changes.
return False
cache_dir = self.get_download_cache_dir()
mkdir_p(cache_dir)
os_family = get_os_family()
download_url = Installer.DOWNLOAD_URL_PATTERN.format(
version=self.YUGABYTE_DB_VERSION,
os=os_family)
download_name = download_url.rsplit('/', 1)[-1]
download_dest_path = os.path.join(cache_dir, download_name)
expected_sha256_sum = Installer.SHA256_SUM_BY_OS[os_family]
need_to_download = True
if os.path.exists(download_dest_path):
logging.info("File %s already exists, validating the checksum", download_dest_path)
existing_sha256_sum = get_file_sha256_sum(download_dest_path)
if existing_sha256_sum == expected_sha256_sum:
logging.info("Checksum is valid for %s", download_dest_path)
need_to_download = False
else:
logging.info(
"Existing file %s has an SHA-256 sum %s, different from the expected sum %s. "
"Removing the existing file and re-downloading.",
download_dest_path, existing_sha256_sum, expected_sha256_sum)
os.remove(download_dest_path)
if need_to_download:
print("Downloading %s to %s", download_url, download_dest_path)
downloaded_sha256_sum = download_file(download_url, download_dest_path)
if downloaded_sha256_sum != expected_sha256_sum:
raise IOError(
"Downloaded file %s has SHA-256 sum %s, different from expected: %s" % (
download_dest_path, downloaded_sha256_sum, expected_sha256_sum))
mkdir_p(installation_top_dir)
logging.info("Extracting %s in directory %s", download_dest_path, installation_top_dir)
subprocess.check_call(
['tar',
'xf',
download_dest_path],
cwd=installation_top_dir)
if not os.path.isdir(self.installation_dir):
raise RuntimeError(
"Extracting %s in directory %s failed to produce directory %s" % (
download_dest_path, installation_top_dir, self.installation_dir))
self.run_post_install_script()
def run_post_install_script(self):
if not is_linux():
# No post_install.sh script on macOS.
return True
post_install_script_path = os.path.join(
self.installation_dir, 'bin', 'post_install.sh')
post_install_completion_flag_path = post_install_script_path + '.completed'
if os.path.exists(post_install_completion_flag_path):
logging.debug(
"File %s already exists, meaning the post_install.sh script has already run.",
post_install_completion_flag_path)
return True
if self.only_find_existing:
logging.warning(
"The post-install script did not complete successfully earlier in %s. Specify "
"--install-if-needed to re-run it.",
self.installation_dir)
return False
logging.info("Running the post-installation script %s", post_install_script_path)
process = subprocess.Popen(
post_install_script_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
std_out, std_err = process.communicate()
if process.returncode != 0:
logging.error(
"Failed running %s (exit code: %d). Standard output:\n%s\n. Standard error:\n%s",
post_install_script_path, process.returncode, std_out, std_err)
raise RuntimeError("Failed running %s" % post_install_script_path)
logging.info("Successfully ran the post-installation script")
with open(post_install_completion_flag_path, 'w'):
# Write an empty file.
pass
class SetAndRestoreEnv:
"""A utility class to save environment variables, and optionally set new environment. """
def __init__(self, new_env=None):
self.old_env = {}
self.new_env = new_env
def __enter__(self):
for k in os.environ:
self.old_env[k] = os.environ[k]
if self.new_env:
for k in self.new_env:
v = self.new_env[k]
if v is None:
del os.environ[k]
else:
os.environ[k] = v
def __exit__(self, type, value, traceback):
for k in os.environ.keys():
if k not in self.old_env:
del os.environ[k]
for k in self.old_env:
os.environ[k] = self.old_env[k]
class DaemonId:
def __init__(self, daemon_type, index):
validate_daemon_type(daemon_type)
self.daemon_type = daemon_type
self.index = index
def __str__(self):
return "{}-{}".format(self.daemon_type, self.index)
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
return self.daemon_type == other.daemon_type and self.index == other.index
def is_master(self):
return self.daemon_type == DAEMON_TYPE_MASTER
def is_tserver(self):
return self.daemon_type == DAEMON_TYPE_TSERVER
def supports_placement(self):
return self.daemon_type in [DAEMON_TYPE_MASTER, DAEMON_TYPE_TSERVER]
def get_default_base_ports_dict():
return {
DAEMON_TYPE_MASTER: {
"http": 7000,
"rpc": 7100
},
DAEMON_TYPE_TSERVER: {
"http": 9000,
"rpc": 9100,
},
PROTOCOL_TYPE_YSQL: {
"http": 13000,
"rpc": YSQL_DEFAULT_PORT
},
PROTOCOL_TYPE_YCQL: {
"http": 12000,
"rpc": YCQL_DEFAULT_PORT,
},
PROTOCOL_TYPE_YEDIS: {
"http": 11000,
"rpc": YEDIS_DEFAULT_PORT
}
}
class ClusterOptions:
def __init__(self):
self.max_daemon_index = 20
self.num_shards_per_tserver = None
self.ysql_num_shards_per_tserver = None
self.timeout_yb_admin_sec = None
self.timeout_processes_running_sec = None
self.master_memory_limit_ratio = 0.35
self.tserver_memory_limit_ratio = 0.65
self.cluster_base_dir = None
self.custom_binary_dir = None
self.script_dir = os.path.dirname(os.path.realpath(__file__))
self.installation_dir = None
self.placement_cloud = "cloud"
self.placement_region = "region"
self.placement_zone = "zone"
self.master_addresses = ""
self.base_ports = get_default_base_ports_dict()
self.master_flags = []
self.tserver_flags = []
self.placement_info_raw = ""
self.placement_info = []
self.verbose_level = 0
self.force = False
self.use_cassandra_authentication = False
self.ysql_hba_conf_csv = None
self.ysql_ident_conf_csv = None
self.ysql_pg_conf_csv = None
self.node_type = DAEMON_TYPE_TSERVER
self.is_shell_master = False
self.is_startup_command = False
self.install_if_needed = False
self.yb_ctl_verbose = False
self.cluster_config = None
# These fields are saved into the cluster configuration.
self.enable_ysql = None
self.num_drives = None
self.replication_factor = DEFAULT_REPLICATION_FACTOR
self.ip_start = DEFAULT_IP_START
self.listen_ip = ''
def parse_flag_args(self, flag_args):
flags = [] if flag_args is None else next(csv.reader([flag_args]), [])
return [item.strip() for item in flags]
def _find_installation_dir(self):
yb_src_root_candidate = os.path.dirname(os.path.dirname(os.path.dirname(self.script_dir)))
# For development, assume $PARENT_DIR/yugabyte-installation/bin/yb-ctl will have sibling
# directories $PARENT_DIR/yugabyte or $PARENT_DIR/yugabyte-db.
installation_parent_dir = os.path.dirname(os.path.dirname(self.script_dir))
self.installation_dirs_considered = [
# yb-ctl being run from the "bin" directory of an installation.
os.path.dirname(self.script_dir),
]
if os.environ.get('YB_CTL_NO_DEV_MODE') != '1':
# "YB_USE_EXTERNAL_BUILD_ROOT" is a special way to place the build directory. This is
# only relevant when running yb-ctl from the yugabyte-db source tree.
use_external_build_root = os.environ.get('YB_USE_EXTERNAL_BUILD_ROOT') == '1'
self.installation_dirs_considered += [
os.path.join(yb_src_root_candidate + '__build', 'latest') if use_external_build_root
else os.path.join(yb_src_root_candidate, 'build', 'latest'),
os.path.join(installation_parent_dir, 'yugabyte', 'build', 'latest'),
os.path.join(installation_parent_dir, 'yugabyte-db', 'build', 'latest')
]
for installation_dir_candidate in self.installation_dirs_considered:
if self.yb_ctl_verbose:
logging.info(
"Considering YugaByte DB installation directory candidate: %s",
installation_dir_candidate)
if is_yugabyte_db_installation_dir(installation_dir_candidate):
self.installation_dir = installation_dir_candidate
if self.yb_ctl_verbose:
logging.info(
"Found YugaByte DB installation directory: %s",
self.installation_dir)
break
def update_options_from_args(self, args, fallback_installation_dir=None):
self.yb_ctl_verbose = args.verbose
self._find_installation_dir()
self.replication_factor = args.replication_factor
self.custom_binary_dir = args.binary_dir
self.cluster_base_dir = args.data_dir
self.num_shards_per_tserver = args.num_shards_per_tserver
self.ysql_num_shards_per_tserver = args.ysql_num_shards_per_tserver
self.timeout_yb_admin_sec = args.timeout_yb_admin_sec
self.timeout_processes_running_sec = args.timeout_processes_running_sec
if hasattr(args, "force"):
self.force = args.force
if hasattr(args, "master_memory_limit_ratio"):
self.master_memory_limit_ratio = args.master_memory_limit_ratio
if hasattr(args, "tserver_memory_limit_ratio"):
self.tserver_memory_limit_ratio = args.tserver_memory_limit_ratio
if hasattr(args, "v"):
self.verbose_level = args.v
if hasattr(args, "use_cassandra_authentication"):
self.use_cassandra_authentication = args.use_cassandra_authentication
if hasattr(args, "ysql_hba_conf_csv"):
self.ysql_hba_conf_csv = args.ysql_hba_conf_csv
if hasattr(args, "ysql_ident_conf_csv"):
self.ysql_ident_conf_csv = args.ysql_ident_conf_csv
if hasattr(args, "ysql_pg_conf_csv"):
self.ysql_pg_conf_csv = args.ysql_pg_conf_csv
if hasattr(args, "ip_start"):
self.ip_start = args.ip_start
if hasattr(args, "listen_ip"):
self.listen_ip = args.listen_ip
if self.listen_ip and self.replication_factor > 1:
raise RuntimeError("Invalid argument: listen_ip is only compatible with rf=1")
for arg in ["master_flags", "tserver_flags"]:
try:
parser_arg = getattr(args, arg)
except AttributeError:
parser_arg = None
setattr(self, arg, self.parse_flag_args(parser_arg))
try:
self.placement_info_raw = getattr(args, "placement_info")
placement_list = self.placement_info_raw.split(",")
except AttributeError:
placement_list = []
for items in placement_list:
t_item = tuple(items.split("."))
if len(t_item) != 3:
raise RuntimeError("Invalid argument: Each entry in placement info should "
"specify cloud, region and zone as cloud.region.zone, "
"separated by commas.")
self.placement_info.append(t_item)
self.num_drives = getattr(args, "num_drives", None)
if self.num_drives is not None and self.num_drives <= 0:
raise ExitWithError("Invalid number of drives: {}".format(self.num_drives))
if hasattr(args, "master") and args.master:
self.node_type = DAEMON_TYPE_MASTER
# -----------------------------------------------------------------------------------------
# Controlling whether to enable or disable YSQL
# -----------------------------------------------------------------------------------------
ysql_explicitly_enabled = False
ysql_explicitly_disabled = False
if hasattr(args, "disable_ysql") and args.disable_ysql:
self.enable_ysql = False
ysql_explicitly_disabled = True
if args.verbose:
logging.info("Found --disable_ysql command-line option, setting enable_ysql=%s",
self.enable_ysql)
if hasattr(args, "enable_ysql") and args.enable_ysql:
self.enable_ysql = True
ysql_explicitly_enabled = True
if args.verbose:
logging.info("Found --enable_ysql command-line option, setting enable_ysql=%s",
self.enable_ysql)
if ysql_explicitly_enabled and ysql_explicitly_disabled:
raise ExitWithError("--disable_ysql and --enable_ysql cannot both be specified")
if self.enable_ysql is None:
self.enable_ysql = True
# -----------------------------------------------------------------------------------------
# Client protocol ports
# -----------------------------------------------------------------------------------------
for protocol_type in PROTOCOL_TYPES:
port_option_str = protocol_type + '_port'
port = getattr(args, port_option_str, None)
if port is not None:
if port < 1 or port > 65535:
raise ExitWithError("Invalid port specified for option --%s: %d" % (
port_option_str, port))
self.base_ports[protocol_type]['rpc'] = port
# -----------------------------------------------------------------------------------------
# Automatic YugaByte DB installation
# -----------------------------------------------------------------------------------------
if args.install_if_needed and not self.installation_dir:
installer = Installer()
if installer.install_or_find_existing():
self.installation_dir = installer.installation_dir
if not self.installation_dir:
self.installation_dir = fallback_installation_dir
if not self.installation_dir:
installation_finder = Installer(only_find_existing=True)
if installation_finder.install_or_find_existing():
self.installation_dir = installation_finder.installation_dir
if not self.installation_dir:
raise ExitWithError(
"Failed to determine YugaByte DB installation directory. Directories "
"considered:\n%s\nPlease specify --install-if-needed to download and "
"install YugaByte DB automatically." %
(" " + "\n ".join(self.installation_dirs_considered)))
def validate_daemon_type(self, daemon_type):
if daemon_type not in DAEMON_TYPES:
raise RuntimeError("Invalid daemon type: {}".format(daemon_type))
# Validate the binary.
self.get_server_binary_path(daemon_type)
def validate_daemon_index(self, daemon_index):
if daemon_index < 1 or daemon_index > self.max_daemon_index:
raise RuntimeError("Invalid daemon node_id: {}".format(daemon_index))
def get_server_binary_path(self, daemon_type):
binary_path = self.get_binary_path(get_binary_name_for_daemon_type(daemon_type))
if self.yb_ctl_verbose:
logging.info("Found binary path for daemon type %s: %s", daemon_type, binary_path)
return binary_path
def get_binary_path(self, binary_name):
base_dir = self.custom_binary_dir if self.custom_binary_dir else self.installation_dir
binary_dirs = [
os.path.join(base_dir, 'bin'),
os.path.join(base_dir, 'postgres', 'bin')
]
logging.info("Using binaries path: {}".format(base_dir))
for binary_dir in binary_dirs:
path = os.path.join(binary_dir, binary_name)
if not os.path.isfile(path) or not os.access(path, os.X_OK):
logging.debug("No binary found at {}".format(path))
else:
return path
raise RuntimeError("No binary found for {}. Considered binary directories: {}".format(
binary_name, binary_dirs))
def get_ip_start(self):
return self.cluster_config.get("ip_start") or self.ip_start
def get_ip_address(self, daemon_id):
# Subtract 1 because daemon_id.index starts from 1.
return get_local_ip(self.get_ip_start() + daemon_id.index - 1)
def get_client_protocol_port(self, protocol_type):
return self.base_ports[protocol_type]['rpc']
def get_port_str(self, daemon_id, port_type):
if port_type in PROTOCOL_TYPES:
return str(self.get_client_protocol_port(port_type))
else:
return str(self.base_ports[daemon_id.daemon_type][port_type])
def get_host_port(self, daemon_id, port_type):
base_local_url = self.get_ip_address(daemon_id)
return "{}:{}".format(base_local_url, self.get_port_str(daemon_id, port_type))
def get_client_listen_host_port(self, daemon_id, port_type=None):
base_local_url = self.listen_ip if self.listen_ip else self.get_ip_address(daemon_id)
if port_type is None:
return base_local_url
else:
return "{}:{}".format(base_local_url, self.get_port_str(daemon_id, port_type))
def get_client_advertise_host_port(self, daemon_id, port_type=None):
base_ip = self.get_ip_address(daemon_id)
if self.listen_ip and self.listen_ip != "0.0.0.0":
base_ip = self.listen_ip
if port_type is None:
return base_ip
else:
return "{}:{}".format(base_ip, self.get_port_str(daemon_id, port_type))
def set_cluster_config(self, cluster_config):
self.cluster_config = cluster_config
base_ports_from_config = cluster_config.get('ports')
if base_ports_from_config is not None:
self.base_ports = base_ports_from_config
def get_bin_parent_dir(self):
# Use the installation dir if it is called in release mode.
# Otherwise use the source root dir in development mode.
return self.installation_dir if is_release_mode() \
else dirname_n(os.path.realpath(__file__), 4)
def get_client_tool_path(self, client_tool_name):
bin_parent_dir = self.get_bin_parent_dir()
tool_abs_path = os.path.abspath(os.path.join(bin_parent_dir, 'bin', client_tool_name))
cur_dir_abs_path = os.path.abspath(os.getcwd())
home_dir_abs_path = os.path.abspath(os.path.expanduser('~'))
path_rel_to_cur = os.path.relpath(tool_abs_path, cur_dir_abs_path)
path_rel_to_home = '~/' + os.path.relpath(tool_abs_path, home_dir_abs_path)
candidates = [tool_abs_path, path_rel_to_cur, path_rel_to_home]
min_len = None
for i in range(len(candidates)):
cur_len = len(candidates[i])
if min_len is None or cur_len < min_len:
min_len = cur_len
shortest_path = candidates[i]
return shortest_path
# End of ClusterOptions
# -------------------------------------------------------------------------------------------------
class ClusterControl:
def __init__(self):
self.options = ClusterOptions()
self.args = None
# Parent subparser holding all common flags.
self.parent_parser = argparse.ArgumentParser(add_help=False)
self.setup_parent_parser()
self.parser = argparse.ArgumentParser()
self.subparsers = self.parser.add_subparsers(dest='command')
self.subparsers.required = True
# This is a dictionary serialized into JSON and written to a configuration file in the data
# directory.
self.cluster_config = None
# This is true only for the "create" command.
self.creating_cluster = False
self.setup_parsing()
self.log_file = None
self.already_running_daemons = set()
def setup_base_parser(self, command, help=None):
subparser = self.subparsers.add_parser(command, help=help, parents=[self.parent_parser])
func = getattr(self, "%s_cmd_impl" % command, None)
if not func:
raise RuntimeError("Invalid command: {}".format(command))
subparser.set_defaults(func=func)
return subparser
# TODO: Combine this with setup_parsing when we drop support for `yb-ctl --rf 3 create` so
# self.parser doesn't require a parent parser.
def setup_parent_parser(self):
self.parent_parser.add_argument(
"--binary_dir", default=None,
help="Specify a custom directory in which to find the yugabyte binaries.")
self.parent_parser.add_argument(
"--data_dir", default=None,
help="Specify a custom directory where to store data.")
self.parent_parser.add_argument(
"--replication_factor", "--rf", type=int, default=None,
help="Replication factor for the cluster as well as default number of masters. ")
self.parent_parser.add_argument(
"--num_shards_per_tserver", type=int, default=None,
help="Number of shards (tablets) to start per tablet server for each non-YSQL table.")
self.parent_parser.add_argument(
"--ysql_num_shards_per_tserver", type=int, default=None,
help="Number of shards (tablets) to start per tablet server for each YSQL table.")
self.parent_parser.add_argument(
"--timeout-yb-admin-sec", type=float, default=None,
help="Timeout in seconds for operations that call yb-admin and wait on the cluster.")
self.parent_parser.add_argument(
"--timeout-processes-running-sec",
type=float, default=None,
help="Timeout in seconds for operations that wait on the master and tserver processes "
"to come up and start running.")
self.parent_parser.add_argument(
"--verbose", action="store_true", default=None,
help="If specified, will log internal debug messages to stderr. Note --verbose "
"affects yb-ctl and --v affects server processes.")
self.parent_parser.add_argument(
"--install-if-needed", action='store_true', default=None,
help="With this option, if YugaByte DB is not yet installed on the system, the latest "
"version will be downloaded and installed automatically.")
def get_cluster_config_file_path(self):
"""
:return: the path to a "cluster configuration file" that holds various options specified
at cluster creation time, e.g. whether YSQL is enabled.
"""
return os.path.join(self.args.data_dir, 'cluster_config.json')
def load_cluster_config(self):
config_file_path = self.get_cluster_config_file_path()
if os.path.exists(config_file_path):
with open(config_file_path) as config_file:
self.cluster_config = json.load(config_file)
else:
# No configuration file -- let's create an empty one.
self.cluster_config = {}
loaded_cluster_config = json.loads(json.dumps(self.cluster_config, sort_keys=True))
if 'enable_postgres' in self.cluster_config:
# Migrate the deprecated "enable_postgres" cluster config option to the new format.
self.cluster_config['enable_ysql'] = (
self.cluster_config.get('enable_ysql', False) or
self.cluster_config['enable_postgres'])
del self.cluster_config['enable_postgres']
if self.cluster_config != loaded_cluster_config:
self.save_cluster_config()
self.options.set_cluster_config(self.cluster_config)
def save_cluster_config(self):
cluster_config_path = self.get_cluster_config_file_path()
with open(cluster_config_path, 'w') as config_file:
json.dump(self.cluster_config, config_file, indent=2)
def is_ysql_enabled(self):
ysql_enabled = self.cluster_config.get("enable_ysql", self.options.enable_ysql)
if self.args.verbose:
logging.info("is_ysql_enabled returning %s", ysql_enabled)
return ysql_enabled
def get_replication_factor(self):
return self.cluster_config.get("replication_factor") or self.options.replication_factor