forked from yugabyte/yugabyte-db
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyugabyted
executable file
·7628 lines (6552 loc) · 345 KB
/
yugabyted
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
from __future__ import unicode_literals
import argparse
import atexit
import json
import logging
import multiprocessing
import os
import re
import resource
import shutil
from distutils.spawn import find_executable
import subprocess
import sys
import time
import traceback
import uuid
import tempfile
import socket
import tarfile
import operator
import string
import glob
import tarfile
from datetime import datetime
from signal import SIGABRT, SIGINT, SIGKILL, SIGTERM, SIG_DFL, SIG_IGN, signal
from threading import Thread
# Version-dependent imports
PY_VERSION = sys.version_info[0]
if PY_VERSION < 3:
import Queue as queue
from urllib2 import Request, urlopen, URLError, HTTPError
from urllib import urlencode
from random import SystemRandom
_sysrand = SystemRandom()
PASSWORD_GENNERATOR = _sysrand.choice
else:
import queue
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from urllib.parse import urlencode
import secrets
PASSWORD_GENNERATOR = secrets.choice
"""
Run `yugabyted` to start a single-node YugabyteDB process. If no options are specified,
`yugabyted` will assume the following default directory tree:
yugabyte
+-- var
|
+-- conf
| +-- yugabyted.conf
+-- logs
| +-- master & tserver & yugaware
+-- data
+-- bin
| | +-- yugabyted
| | +-- yb-master
| | +-- yb-tserver
| | +-- ...
+-- ui
| | +-- bin...
| | +-- ...
"""
# OS constants
OS_DETAILS = os.uname()
OS_NAME = OS_DETAILS[0]
# Script constants.
SCRIPT_NAME = os.path.basename(__file__)
YUGABYTE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
TRUE_CHOICES = ["true", "True", "t", "T", "yes", "Yes", "y", "Y", "1"]
FALSE_CHOICES = ["false", "False", "f", "F", "no", "No", "n", "N", "0"]
BOOL_CHOICES = TRUE_CHOICES + FALSE_CHOICES
FAULT_TOLERANCE_CHOICES = ["zone", "region", "cloud"]
START_FAULT_TOLERANCE_CHOICES = ["none", "zone", "region", "cloud"]
SLACK_LINK = "https://www.yugabyte.com/slack"
COMMUNITY_REWARDS_LINK = "https://www.yugabyte.com/community-rewards/"
HELP_LINK = "https://docs.yugabyte.com/latest/faq/"
YUGABYTED_LINK = "https://docs.yugabyte.com/preview/reference/configuration/yugabyted/"
YUGABYTED_START = "https://docs.yugabyte.com/preview/reference/configuration/yugabyted/#start"
GENERATE_SERVER_CERTS = "https://docs.yugabyte.com/preview/secure/tls-encryption/\
server-certificates/#create-the-server-certificates"
YBC_DOWNLOAD_LINK = "https://s3.us-west-2.amazonaws.com/downloads.yugabyte.com/ybc/" + \
"2.0.0.0-b20/ybc-2.0.0.0-b20-linux-x86_64.tar.gz"
DEFAULT_DEMO_DATABASE = "northwind"
DEFAULT_FAULT_TOLERANCE = "zone"
DEFAULT_START_FAULT_TOLERANCE = "none"
SAMPLE_DATA_LINKS = {
"retail": "https://docs.yugabyte.com/latest/quick-start/explore-ysql/",
"chinook": "https://docs.yugabyte.com/latest/sample-data/chinook/",
"sports": "https://docs.yugabyte.com/latest/sample-data/sportsdb/",
"northwind": "https://docs.yugabyte.com/latest/sample-data/northwind/"
}
EXIT_SIGNALS = (SIGABRT, SIGINT, SIGTERM)
REQUIRED_LOOPBACK_ADDRESSES = [
'127\.0\.0\.2',
'127\.0\.0\.3',
'127\.0\.0\.4',
'127\.0\.0\.5',
'127\.0\.0\.6',
'127\.0\.0\.7'
]
MAX_PROC = {
'Linux' : 12000,
'Darwin' : 2500,
}
PREREQS_ERROR_MSGS = {
'open_files' :'open files ulimits value set low. Please set soft and hard limits to 1048576.',
'max_user_processes' :'max user processes ulimits value set low.' \
' Please set soft and hard limits to {}.'.format(MAX_PROC[OS_NAME]),
'transparent_hugepages' :'Transparent hugepages disabled. Please enable transparent_hugepages.',
'ntp/chrony' :'ntp/chrony package is missing for clock synchronization. For centos 7, ' +
'we recommend installing either ntp or chrony package and for centos 8, ' +
'we recommend installing chrony package.',
'mandatory_ports': 'YugabyteDB processes cannot start as the default port(s) {} already' \
' in use. Please free the port(s) and rerun the {} command.',
'yugabyted_ui_port': 'Yugabyted UI cannot start as the default port {} is already in use.' \
' Please free the port and restart with --ui=true.',
'ysql_metric_port': 'YSQL metrics port {} is already in use. For accessing the YSQL metrics,' \
' please free the port and restart the node.',
'ycql_metric_port': 'YCQL metrics port {} is already in use. For accessing the YCQL metrics,' \
' please free the port and restart the node.',
}
QUICK_START_LINKS = {
'mac' : 'https://docs.yugabyte.com/preview/quick-start/',
'linux' : 'https://docs.yugabyte.com/preview/quick-start/linux/',
}
CONFIG_LINK = "https://docs.yugabyte.com/latest/deploy/manual-deployment/system-config"
DEFAULT_PORTS_LINK = "https://docs.yugabyte.com/preview/reference/configuration/default-ports/"
# Help Message Constants
PREFIX = {
'yugabyted' : "YugabyteDB command-line interface for creating" +
" and configuring YugabyteDB cluster.",
'start' : "Install YugabyteDB and start a single node cluster.\n\n" +
"Use --join flag to join other nodes that are part of the same cluster.",
'stop' : "",
'destroy' : "",
'status' : "",
'version' : "",
'collect_logs' : "",
'configure' : "",
'configure data_placement': "",
'configure encrypt_at_rest': "",
'configure admin_operation': "",
'configure_read_replica' : "",
'configure_read_replica new': "",
'configure_read_replica modify': "",
'configure_read_replica delete': "",
'backup': "",
'restore': "",
'connect' : "",
'connect ycql' : "",
'connect ysql' : "",
'demo' : "",
'demo connect' : "",
'demo destroy' : "",
'cert' : "",
'cert generate_server_certs' : "",
}
USAGE = {
'yugabyted' : "yugabyted [command] [flags]",
'start' : "yugabyted start [flags]",
'stop' : "yugabyted stop [flags]",
'destroy' : "yugabyted destroy [flags]",
'status' : "yugabyted status [flags]",
'version' : "yugabyted version [flags]",
'collect_logs' : "yugabyted collect_logs [flags]",
'configure' : "yugabyted configure [command] [flags]",
'configure data_placement': "yugabyted configure data_placement [flags]",
'configure encrypt_at_rest': "yugabyted configure encrypt_at_rest [flags]",
'configure admin_operation' : "yugabyted configure admin_operation [flags]",
'configure_read_replica' : "yugabyted configure_read_replica [command] [flags]",
'configure_read_replica new': "yugabyted configure_read_replica new [flags]",
'configure_read_replica modify': "yugabyted configure_read_replica modify [flags]",
'configure_read_replica delete' : "yugabyted configure_read_replica delete",
'backup' : "yugabyted backup [flags]",
'restore' : "yugabyted restore [flags]",
'connect' : "yugabyted connect [command] [flags]",
'connect ycql' : "yugabyted connect ycql [flags]",
'connect ysql' : "yugabyted connect ysql [flags]",
'demo' : "yugabyted demo [command] [flags]",
'demo connect' : "yugabyted demo connect [flags]",
'demo destroy' : "yugabyted demo destroy [flags]",
'cert' : "yugabyted cert [command] [flags]",
'cert generate_server_certs' : "yugabyted cert generate_server_certs [flag]",
}
EXAMPLE = {
'start' : "# Create a single-node local cluster:\n" +
"yugabyted start\n\n"+
"# Create a single-node locally and join other nodes " +
"that are part of the same cluster:\n" +
"yugabyted start --join=host:port,[host:port]\n\n" +
"# Create a secure cluster:\n" +
"yugabyted start --secure --certs_dir=<path_to_certs_dir>\n\n",
'stop' : "",
'destroy' : "",
'status' : "",
'version' : "",
'collect_logs' : "",
'cert' : "# Create node sever certificates:\n" +
"yugabyted cert generate_server_certs --hostnames=<comma_seperated_hostnames>\n\n",
'backup' : "# Backup a YSQL Database into AWS S3 Bucket: \n" +
"yugabyted backup --database=northwind --cloud_storage_uri=s3://\n\n" +
"# Backup a YCQL namespace into AWS S3 Bucket: \n" +
"yugabyted backup --namespace=default --cloud_storage_uri=s3://\n\n",
'restore' : "# Restore a YSQL Database into AWS S3 Bucket: \n" +
"yugabyted restore --database=northwind --cloud_storage_uri=s3://\n\n",
'configure_read_replica' : "# Configure a new read replica cluster:\n" +
"yugabyted configure_read_replica new --rf=<replication_factor> " +
"--data_placement_constraint=<placement_policy_for_rr_cluster>\n\n" +
"# Modify an existing read replica cluster:\n" +
"yugabyted configure_read_replica modify --rf=<new_replication_factor> " +
"--data_placement_constraint=<new_placement_policy_for_rr_cluster>\n\n" +
"# Delete an existing read replica cluster:\n" +
"yugabyted configure_read_replica delete\n\n",
"new" : "# Configure a new read replica cluster:\n" +
"yugabyted configure_read_replica new --rf=<replication_factor> " +
"--data_placement_constraint=<placement_policy_for_rr_cluster>",
"modify" : "# Modify an existing read replica cluster:\n" +
"yugabyted configure_read_replica modify --rf=<new_replication_factor> " +
"--data_placement_constraint=<new_placement_policy_for_rr_cluster>",
"delete" : "# Delete an existing read replica cluster:\n" +
"yugabyted configure_read_replica delete",
'configure' : "# Configure a multi-zone cluster:\n" +
"yugabyted configure data_placement --fault_tolerance=zone\n\n" +
"# Enable encryption at rest:\n" +
"yugabyted configure encrypt_at_rest --enable\n\n" +
"For more examples use 'yugabyted configure [command] -h'\n\n" +
"# Execute yb-admin command on the YugabyteDB cluster:\n" +
"yugabyted configure admin_operation --command <yb-admin_coomand>",
'data_placement' : "# Configure a multi-zone cluster:\n" +
"yugabyted configure data_placement --fault_tolerance=zone\n\n" +
"# Configure a multi-region cluster:\n" +
"yugabyted configure data_placement --fault_tolerance=region\n\n" +
"# Configure a multi-zone cluster with the specified placement info and " + \
"rf:\n" + "yugabyted configure data_placement --fault_tolerance=zone " +
"--constraint_value=cloud1.region1.zone1,cloud2.region2.zone2," +
"cloud3.region3.zone3 --rf=3\n\n" +
"# Configure a multi-zone cluster with the order of preference" \
" to place the primary copy of the data:\n" +
"yugabyted configure data_placement --constraint_value=" +
"cloud1.region1.zone1:<preference_number>," +
"cloud2.region2.zone2:<preference_number>," +
"cloud3.region3.zone3:<preference_number>\n\n",
'encrypt_at_rest' : "# Enable encryption at rest for a cluster:\n" +
"yugabyted configure encrypt_at_rest --enable\n\n" +
"# Disable encryption at rest for a cluster:\n" +
"yugabyted configure encrypt_at_rest --disable\n\n",
'admin_operation' : "# Execute yb-admin command on the YugabyteDB cluster:\n" +
"yugabyted configure admin_operation --command 'get_universe_config'\n\n",
}
EPILOG_COMMON = "Run '{} [command] -h' for help with specific commands.".format(SCRIPT_NAME)
EPILOG_SPECIFIC = {
'start' : "Use conf file to configure advanced flags. Learn more about advanced flags " +
"refer to the docs page: {}.\n\n".format(YUGABYTED_START),
'stop' : "",
'destroy' : "",
'status' : "",
'version' : "",
'collect_logs' : "",
'configure' : "",
'cert' : "",
"backup" : "",
"restore" : "",
}
# YugabyteDB configs.
IP_ANY = "0.0.0.0"
IP_LOCALHOST = "127.0.0.1"
DEFAULT_BIND_IP = IP_ANY
DEFAULT_MASTER_RPC_PORT = 7100
DEFAULT_TSERVER_RPC_PORT = 9100
DEFAULT_MASTER_WEBSERVER_PORT = 7000
DEFAULT_TSERVER_WEBSERVER_PORT = 9000
DEFAULT_YSQL_PORT = 5433
DEFAULT_YCQL_PORT = 9042
DEFAULT_YSQL_METRIC_PORT = 13000
DEFAULT_YCQL_METRIC_PORT = 12000
DEFAULT_WEBSERVER_PORT = 7200
DEFAULT_YUGABYTED_UI_PORT = 15433
DEFAULT_CALLHOME = True
DEFAULT_YSQL_USER = "yugabyte"
DEFAULT_YSQL_PASSWORD = "yugabyte"
DEFAULT_YSQL_DB = "yugabyte"
DEFAULT_CLOUD_PROVIDER = "cloud1"
DEFAULT_CLOUD_REGION = "datacenter1"
DEFAULT_CLOUD_ZONE = "rack1"
YSQL_PASSWORD_LENGTH_WARNING = "Warning: Your 'YSQL_PASSWORD' length is greater than 99 characters.\
Please set 'PGPASSWORD' in environment variables to use 'bin/ysqlsh'."
DEFAULT_YCQL_USER = "cassandra"
DEFAULT_YCQL_PASSWORD = "cassandra"
DEFAULT_YCQL_KEYSPACE = None
VERSION_METADATA_PATH = os.path.join(YUGABYTE_DIR, "version_metadata.json")
YUGABYTE_API_CLIENT_PROGRAMS = {
"ysql": "ysqlsh",
"ycql": "ycqlsh",
}
YB_NUM_SHARDS_PER_TSERVER = 1
YSQL_NUM_SHARDS_PER_TSERVER = 1
METRICS_SNAPSHOT_LIST = [
"handler_latency_yb_tserver_TabletServerService_Read_count",
"handler_latency_yb_tserver_TabletServerService_Write_count",
"handler_latency_yb_tserver_TabletServerService_Read_sum",
"handler_latency_yb_tserver_TabletServerService_Write_sum",
"disk_usage", "cpu_usage", "node_up"
]
# YugaWare configs. These have their own separate subdirectory to preserve our itest flow.
YUGAWARE_DIR = os.path.join(YUGABYTE_DIR, "ui")
YUGAWARE_BIN_DIR = os.path.join(YUGAWARE_DIR, "bin")
YUGAWARE_CONF = os.path.join(YUGAWARE_DIR, "conf/application.yugabyted.conf")
WEBSERVER_DB = "system_platform"
DEMO_DB_PREFIX = "yb_demo_"
YBC_NFS_DIR = "/tmp/nfs"
BREW_CONF_FILE = "/usr/local/etc/yugabyted.conf"
ALERT_WARNING = "Warning"
ULIMIT_ERR_CODE = "LOW_ULIMITS"
TS_MASTER_ADDRS_FLAG = "tserver_master_addrs"
start_time_sec = time.time()
# Finds the path where a particular file is present from
# amongst the supplied paths.
def search_file_in_paths(dir_candidates, file_name):
for candidate in dir_candidates:
if os.path.exists(os.path.join(candidate, file_name)):
Output.log("Found directory {} for"
" file {}".format(candidate, file_name))
return os.path.join(candidate, file_name)
# If post_install.sh script isn't found then don't error out
# The caller assumes that the environment is dev and skips
# performing the post installation steps
if(file_name == "post_install.sh"):
return None
# If yugabyted-ui is not found, don't error out
# Caller should set self.configs.saved_data.get("ui") to false if needed
if(file_name == "yugabyted-ui"):
Output.log(
"Yugabyte {} file not found in paths {}. Please check "
"the paths.".format(file_name, dir_candidates),
logging.WARN
)
return None
Output.log_error_and_exit(
"Yugabyte {} file not found in paths {}. Please check "
"the paths.".format(file_name, dir_candidates)
)
# Checks if all given files exist in the given path
def check_files_in_path(path, files):
has_error = False
for file in files:
if not os.path.exists(os.path.join(path, file)):
has_error = True
Output.log("{} file not found.".format(os.path.join(path, file)))
return not has_error
# Finds the path of a particular YB binary
def find_binary_location(binary_name):
# Default if tar is downloaded
dir_candidates = [
os.path.join(YUGABYTE_DIR, "bin")
]
# Development environment
dir_candidates += [
os.path.join(YUGABYTE_DIR, "build", "latest", "bin"),
]
# Development environment for UI
dir_candidates += [
os.path.join(YUGABYTE_DIR, "build", "latest", "gobin"),
]
return search_file_in_paths(dir_candidates, binary_name)
# Extract or Download YBC package
def download_extract_ybc_binary():
# Check for existence of YBC package
ybc_file_pattern = "ybc-*.tar.gz"
matching_files = glob.glob(ybc_file_pattern)
result = True
if len(matching_files) == 0:
Output.log(
"YBC binary archive file not found in {}.".
format(YUGABYTE_DIR), logging.WARN
)
# check if Development environment
if os.path.exists(os.path.join(YUGABYTE_DIR, "build", "latest", "bin")):
Output.log(
"Downloading YBC binary from {}.".
format(YBC_DOWNLOAD_LINK), logging.INFO)
result = download_ybc_package()
if result:
matching_files = glob.glob(ybc_file_pattern)
else:
result = False
return result
else:
# YBC binary not found in the YugabyteDB release package.
result = False
return result
if len(matching_files) > 1:
Output.log(
"More than one YBC archive file found. Extracting the following {}.".
format(matching_files[0], logging.WARN)
)
# Extract the YBC package into /ybc folder
ybc_archive_path = YUGABYTE_DIR + "/" + matching_files[0]
ybc_untar_path = YUGABYTE_DIR + "/ybc"
with tarfile.open(ybc_archive_path, 'r:gz') as tar:
for member in tar.getmembers():
# Check if the member is a file (not a directory)
if member.isfile():
path_components = member.path.split(os.path.sep)
# Remove the first folder path
member.path = os.path.sep.join(path_components[1:])
tar.extract(member, path=ybc_untar_path)
return result
# Download YBC release from S3 bucket in dev environment
def download_ybc_package():
try:
response = urlopen(YBC_DOWNLOAD_LINK)
CHUNK_SIZE = 1 << 20
fileName = 'ybc-2.0.0.0-b20-linux-x86_64.tar.gz'
Output.log('Downloading YBC Package: {}', YBC_DOWNLOAD_LINK)
with open(fileName, 'wb') as f:
while True:
chunk = response.read(CHUNK_SIZE)
if not chunk:
break
f.write(chunk)
except HTTPError as http_err:
Output.log('HTTP error occurred while downloading YBC package: {}', http_err)
return False
except Exception as err:
Output.log('Other error occurred while downloading YBC package current: {}', err)
return False
return True
# Find the yb controller binary
def find_ybc_binary_location(binary_name):
# Default if tar is downloaded
dir_candidates = [
os.path.join(YUGABYTE_DIR, "ybc", "bin")
]
return search_file_in_paths(dir_candidates, binary_name)
# Find the path of a particular postgres binary
def find_postgres_binary_location(binary_name):
# Default if tar is downloaded
dir_candidates = [
os.path.join(YUGABYTE_DIR, "postgres", "bin"),
]
# Development environment
dir_candidates += [
os.path.join(YUGABYTE_DIR, "build", "latest", "postgres", "bin"),
]
return search_file_in_paths(dir_candidates, binary_name)
# Finds the path of the sample data
def find_sample_data_location(data_file):
# Default if tar is downloaded
dir_candidates = [
os.path.join(YUGABYTE_DIR, "share")
]
# Development environment
dir_candidates += [
os.path.join(YUGABYTE_DIR, "sample")
]
return search_file_in_paths(dir_candidates, data_file)
# Finds the path of the version_metadata.json file
def find_version_metadata_location(version_file):
# Default if tar is downloaded
dir_candidates = [
os.path.join(YUGABYTE_DIR)
]
# Development environment
dir_candidates += [
os.path.join(YUGABYTE_DIR, "build", "latest")
]
return search_file_in_paths(dir_candidates, version_file)
# Creates the Head Title for yugabyted CLI
def get_cli_title():
title = Output.make_green(Output.make_green("Yugabyted CLI") + ": YugabyteDB command line")
extra_len = len(Output.make_green(""))
div_line = "+" + "-" * 98 + "+" + "\n"
cli_title = div_line
cli_title += ("| {:^" + str(105 + extra_len) + "} |\n").format(title)
cli_title += div_line
return cli_title
class ControlScript(object):
def __init__(self):
self.configs = None
self.processes = {}
self.stop_callhome = False
self.alerts = []
self.script = None
self.setup_env_init = EnvBasedCredentials()
# Starts YugabyteDB node.
def start(self):
if self.script.is_running():
Output.print_out("{} is already running!".format(SCRIPT_NAME))
sys.exit(1)
Output.print_and_log("Starting {}...".format(SCRIPT_NAME))
self.set_env_vars()
if self.configs.temp_data.get("background"):
# In daemon mode, self.daemonize() forks. The child process then executes
# normal control flow. The parent process waits for the child process until
# a status message can be printed to the terminal and then exits within daemonize.
self.daemonize()
self.script.write_pid(os.getpid())
self.set_signals(self.kill_children)
atexit.register(self.kill_children)
Output.script_exit_func = self.kill_children
if self.configs.saved_data.get("read_replica"):
self.start_rr_process()
else:
self.start_processes()
# Kills all processes related to yugabyted
def kill_all_procs(self):
pid = self.script.get_pid()
if pid:
pgid = os.getpgid(pid)
if not pgid:
Output.log("PGID could not be found for {} process".format(SCRIPT_NAME) +
"with PID {}. Is {} running?".format(pid, SCRIPT_NAME))
return ("No PGID", pid)
else:
try:
os.killpg(pgid, SIGTERM)
except OSError as err:
return (err, pid)
self.script.delete_pidfile()
return (None, pid)
# Kills currently running yugabyted process if it exists.
def stop(self, *args):
(err, pid) = self.kill_all_procs()
if err:
Output.log_error_and_exit(
"Failed to shut down {}: {}. Please check PID in {}".format(
SCRIPT_NAME, err, self.script.pidfile))
elif pid:
self.script.wait_until_stop(pid)
Output.print_out("Stopped {} using config {}.".format(SCRIPT_NAME, self.conf_file))
sys.exit(0)
# Back up a database.
def backup(self):
status_details = []
status_display_info = {}
if not self.configs.saved_data.get("backup_daemon"):
final_status = "Backup daemon process not found. " + \
"Please restart the node with --backup_daemon=true."
status_details = [
(Output.make_red("Error"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
else:
YBControllerCLIProxy.init()
ybc_server_dir = "{}/yb-data/ybc".format(self.configs.saved_data.get("data_dir"))
ybc_task_type = "backup"
backup_args = dict()
backup_args["cloud_type"] = self.configs.temp_data.get("ybc_cloud_type")
backup_args["bucket"] = self.configs.temp_data.get("ybc_cloud_storage_bucket")
backup_args["cloud_dir"] = self.configs.temp_data.get("ybc_cloud_storage_dir")
backup_args["ybc_task"] = ybc_task_type
if self.configs.temp_data.get("database_name_backup_restore"):
backup_args["ns"] = self.configs.temp_data.get("database_name_backup_restore")
backup_args["ns_type"] = "ysql"
if self.configs.temp_data.get("keyspace_name_backup_restore"):
backup_args["ns"] = self.configs.temp_data.get("keyspace_name_backup_restore")
backup_args["ns_type"] = "ycql"
if OS_NAME != "Linux":
final_status = "Backup command is not supported in {} enviroments.".format(OS_NAME)
status_details = [
(Output.make_yellow("Status"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
if self.configs.temp_data.get("ybc_status"):
final_status = ""
backup_status = YBControllerCLIProxy.check_for_ongoing_ybc_task(
backup_args, ybc_server_dir)
if backup_status is not None:
if backup_status == "OK":
final_status = "Backup is complete."
elif backup_status == "COMMAND_FAILED":
final_status = "Backup has failed. " + \
"Check the logs for more details."
status_display_info[final_status] = Output.make_red
elif len(backup_status) == 0:
final_status = "Backup is in Progress. Check the logs for more details."
else:
final_status = "Backup status: {}".format(backup_status)
else:
if YBControllerCLIProxy.check_for_existing_backup(backup_args):
final_status = "Backup is complete."
else:
final_status = "Backup not found in the given cloud location."
status_display_info[final_status] = Output.make_red
status_details = [
(Output.make_yellow("Status"), final_status)
]
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
# Check if there is a currently running backup task on the local node.
backup_status = YBControllerCLIProxy.check_for_ongoing_ybc_task(
backup_args, ybc_server_dir)
if backup_status is not None:
if backup_status in ["OK", "NOT_FOUND", "COMMAND_FAILED"]:
YBControllerCLIProxy.rename_ybc_lock_file(backup_args, ybc_server_dir)
else:
final_status = "Backup is in progress."
status_details = [
(Output.make_yellow("Status"), final_status)
]
Output.print_out(self.get_status_string_common(status_details))
return
# Todo: check if there is any ongoing backup tasks on other nodes.
# Check if the cloud location has any other previous backup.
if YBControllerCLIProxy.check_for_existing_backup(backup_args):
final_status = "Already a backup is present " + \
"in the cloud location {}. Abort!!".format( backup_args["cloud_dir"])
status_details = [
(Output.make_yellow("Status"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
advertise_ip = self.advertise_ip()
backup_task_id = YBControllerCLIProxy.backup_to_cloud(
advertise_ip, backup_args
)
if not backup_task_id:
final_status = "Backup failed. Check the logs."
status_details = [
(Output.make_yellow("Status"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
YBControllerCLIProxy.write_ybc_lock_file(
backup_args, backup_task_id, ybc_server_dir, advertise_ip
)
final_status = "Backup started successfully."
Output.log("Backup started successfully with Task UUID: {}".format(backup_task_id))
status_details = [
(Output.make_yellow("Status"), final_status)
]
Output.print_out(self.get_status_string_common(status_details))
# Restore a database.
def restore(self):
status_details = []
status_display_info = {}
if not self.configs.saved_data.get("backup_daemon"):
final_status = "Backup daemon process not found. " + \
"Please restart the node with --backup_daemon=true."
status_details = [
(Output.make_red("Error"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
else:
YBControllerCLIProxy.init()
ybc_server_dir = "{}/yb-data/ybc".format(self.configs.saved_data.get("data_dir"))
ybc_task_type = "restore"
restore_args = dict()
restore_args["cloud_type"] = self.configs.temp_data.get("ybc_cloud_type")
restore_args["bucket"] = self.configs.temp_data.get("ybc_cloud_storage_bucket")
restore_args["cloud_dir"] = self.configs.temp_data.get("ybc_cloud_storage_dir")
restore_args["ybc_task"] = ybc_task_type
if self.configs.temp_data.get("database_name_backup_restore"):
restore_args["ns"] = self.configs.temp_data.get("database_name_backup_restore")
restore_args["ns_type"] = "ysql"
if self.configs.temp_data.get("keyspace_name_backup_restore"):
restore_args["ns"] = self.configs.temp_data.get("keyspace_name_backup_restore")
restore_args["ns_type"] = "ycql"
if OS_NAME != "Linux":
final_status = "Restore command is not supported in {} enviroments.".format(OS_NAME)
status_details = [
(Output.make_yellow("Status"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
if self.configs.temp_data.get("ybc_status"):
final_status = ""
restore_status = YBControllerCLIProxy.check_for_ongoing_ybc_task(
restore_args, ybc_server_dir)
if restore_status is not None:
if restore_status == "OK":
final_status = "Restore is complete."
elif restore_status == "COMMAND_FAILED":
final_status = "Restore has failed. Check the logs for more details."
status_display_info[final_status] = Output.make_red
elif not restore_status:
final_status = "Restore is in progress."
else:
final_status = "Restore status: {}".format(restore_status)
else:
final_status = "No restore task found for {}".format(restore_args["ns"])
status_display_info[final_status] = Output.make_red
status_details = [
(Output.make_yellow("Status"), final_status)
]
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
# Check if the cloud location has a backup.
if not YBControllerCLIProxy.check_for_existing_backup(restore_args):
final_status = "Backup not present in the given " + \
"cloud location {}. Abort!!".format(restore_args["cloud_dir"])
status_details = [
(Output.make_yellow("Status"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details, status_display_info))
return
# Check if there is a currently running backup task on the local node.
ybc_task_status = YBControllerCLIProxy.check_for_ongoing_ybc_task(
restore_args, ybc_server_dir)
if ybc_task_status is not None:
if ybc_task_status in ["OK"]:
YBControllerCLIProxy.rename_ybc_lock_file(restore_args, ybc_server_dir)
else:
final_status = "backup/restore operation is in progress. " + \
"Check the logs for more details."
status_details = [
(Output.make_yellow("Status"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details,
status_display_info))
return
advertise_ip = self.advertise_ip()
restore_task_id = YBControllerCLIProxy.restore_from_cloud(
advertise_ip, restore_args
)
if not restore_task_id:
final_status = "Restore has failed. Check the logs for more details."
status_details = [
(Output.make_yellow("Status"), final_status)
]
status_display_info[final_status] = Output.make_red
Output.print_out(self.get_status_string_common(status_details,
status_display_info))
return
YBControllerCLIProxy.write_ybc_lock_file(
restore_args, restore_task_id, ybc_server_dir, advertise_ip
)
final_status = "Restore started successfully."
Output.log("Restore started successfully with Task UUID: {}".format(restore_task_id))
status_details = [
(Output.make_yellow("Status"), final_status)
]
Output.print_out(self.get_status_string_common(status_details))
# Prints status of YugabyteDB.
def status(self):
if len(os.listdir(self.configs.saved_data.get("data_dir"))) != 0:
Output.print_out(self.get_status_string())
else:
Output.print_out("{} is not running.".format(SCRIPT_NAME))
# Destroy the YugabyteDB cluster.
def destroy(self):
(err, pid) = self.kill_all_procs()
if err:
Output.log_error_and_exit(
"Failed to shut down {}: {}. Please check PID in {}".format(
SCRIPT_NAME, err, self.script.pidfile))
elif pid:
self.script.wait_until_stop(pid)
Output.print_out("Stopped {} using config {}.".format(SCRIPT_NAME, self.conf_file))
logpath = self.configs.saved_data.get("log_dir")
datapath = self.configs.saved_data.get("data_dir")
gen_certs_dir = self.configs.saved_data.get("gen_certs_dir")
certs_dir = self.configs.saved_data.get("certs_dir")
config_path = os.path.dirname(self.conf_file)
is_config_passed=False
for arg in sys.argv[1:]:
if (arg.startswith("--config")):
is_config_passed=True
break
if (self.conf_file == BREW_CONF_FILE):
Output.print_out("{} destroy is not supported for brew installations.".format(
SCRIPT_NAME))
return
if os.path.isdir(logpath):
shutil.rmtree(logpath)
Output.print_out("Deleted logs at {}.".format(logpath))
if os.path.isdir(datapath):
shutil.rmtree(datapath)
Output.print_out("Deleted data at {}.".format(datapath))
if os.path.isdir(gen_certs_dir):
shutil.rmtree(gen_certs_dir)
Output.print_out("Deleted generated certs at {}.".format(gen_certs_dir))
if os.path.isdir(certs_dir):
shutil.rmtree(certs_dir)
Output.print_out("Deleted certs at {}.".format(certs_dir))
if is_config_passed:
if os.path.exists(self.conf_file):
os.remove(self.conf_file)
Output.print_out("Deleted conf file at {}.".format(self.conf_file))
else:
if os.path.isdir(config_path):
shutil.rmtree(config_path)
Output.print_out("Deleted conf at {}.".format(config_path))
sys.exit(0)
# Prints YugabyteDB version.
def version(self):
VERSION_METADATA_PATH = find_version_metadata_location("version_metadata.json")
with open(VERSION_METADATA_PATH) as metadata:
data = json.load(metadata)
title = "Version".format(SCRIPT_NAME)
output = "\n" + "-" * 70 + "\n"
output += ("| {:^66} |\n").format(title)
output += "-" * 70 + "\n"
build = data.get("build_number")
try:
version = "{}-b{}".format(data.get("version_number"), int(build))
except ValueError as e:
version = "{} ({})".format(data.get("version_number"), build)
for k, v in [
("Version", version),
("Build Time", data.get("build_timestamp")),
("Build Hash", data.get("git_hash"))]:
output_k = Output.make_yellow(k)
extra_len = len(Output.make_yellow(""))
output += ("| {:" + str(15 + extra_len) + "}: {:<49} |\n").format(output_k, v)
output += "-" * 70 + "\n"
Output.print_out(output)
# Starts an interactive YSQL shell.
def connect_ysql(self):
if self.get_failed_node_processes():
Output.log_error_and_exit(
"{} is not running. Cannot connect to YSQL.".format(SCRIPT_NAME))
ysql_proxy = YsqlProxy(self.advertise_ip(), self.configs.saved_data.get("ysql_port"))
is_password_passed=False
for arg in sys.argv[1:]:
if arg.startswith("--password"):
is_password_passed = True
break
if self.configs.saved_data.get("secure") and is_password_passed:
ysql_proxy.connect_with_password()
else:
ysql_proxy.connect_without_password()
# Starts an interactive YCQL shell.
def connect_ycql(self):
if self.get_failed_node_processes():
Output.log_error_and_exit(
"{} is not running. Cannot connect to YCQL.".format(SCRIPT_NAME))
if self.configs.saved_data.get("secure"):
self.setup_env_init.setup_cert_file_path(self.configs.
saved_data.get("ca_cert_file_path"))
ycql_proxy = YcqlProxy(ip=self.advertise_ip(),
port=self.configs.saved_data.get("ycql_port"),
secure=self.configs.saved_data.get("secure"))
is_password_passed=False
for arg in sys.argv[1:]:
if arg.startswith("--password"):
is_password_passed = True
break
if self.configs.saved_data.get("secure") and is_password_passed:
ycql_proxy.connect_with_password()
else:
ycql_proxy.connect_without_password()
# Creates demo database and starts an interactive shell into it. Destroys the sample database
# after shell quits.
def demo(self):
if self.get_failed_node_processes():
Output.log_error_and_exit(
"{0} is not running. Please run `{0} start` before starting a demo.".format(
SCRIPT_NAME))
if self.configs.saved_data.get("read_replica"):
Output.log_error_and_exit(Output.make_red("ERROR") + ": Cannot use demo commands " +
"from a read replica node.")
db_name = DEMO_DB_PREFIX + self.configs.temp_data.get("demo_db")
ysql_proxy = YsqlProxy(self.advertise_ip(), self.configs.saved_data.get("ysql_port"))
if ysql_proxy.db_exists(db_name):
Output.log_error_and_exit(
"Demo is already running. Concurrent demos are currently unsupported.")
# TODO: Race condition currently exists when running demo too close to each other. This
# will be solved when concurrent isolated demos are implemented.
Output.print_out("Now creating demo database")
self.create_demo()
# Ignore kill SIGINT to match normal ysqlsh and psql behavior.
signal(SIGINT, SIG_IGN)
signal(SIGABRT, self.destroy_demo)
signal(SIGTERM, self.destroy_demo)
atexit.register(self.destroy_demo)
self.connect_demo()
self.set_signals(SIG_DFL)
# Create target demo database if it does not exist.
def create_demo(self):
if self.get_failed_node_processes():
Output.log_error_and_exit(
"{0} is not running. Please run `{0} start` before starting a demo.".format(
SCRIPT_NAME))
if self.configs.saved_data.get("read_replica"):
Output.log_error_and_exit(Output.make_red("ERROR") + ": Cannot use demo commands " +
"from a read replica node.")
demo_db = self.configs.temp_data.get("demo_db")
db_name = DEMO_DB_PREFIX + demo_db
ysql_proxy = YsqlProxy(self.advertise_ip(), self.configs.saved_data.get("ysql_port"))
if ysql_proxy.db_exists(db_name):
Output.print_out("Demo database {} already exists.".format(demo_db))
return
Output.print_out(