-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathyugabyted
executable file
·2751 lines (2373 loc) · 114 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
import subprocess
import sys
import time
import traceback
import uuid
import tempfile
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
else:
import queue
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from urllib.parse import urlencode
"""
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...
| | +-- ...
"""
# 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
SLACK_LINK = "https://www.yugabyte.com/slack"
COMMUNITY_REWARDS_LINK = "https://www.yugabyte.com/community-rewards/"
HELP_LINK = "https://docs.yugabyte.com/latest/faq/"
DEFAULT_DEMO_DATABASE = "northwind"
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)
# 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_WEBSERVER_PORT = 7200
DEFAULT_CALLHOME = True
DEFAULT_YSQL_USER = "yugabyte"
DEFAULT_YSQL_PASSWORD = "yugabyte"
DEFAULT_YSQL_DB = "yugabyte"
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_"
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
Output.log_error_and_exit(
"Yugabyte {} file not found in paths {}. Please check "
"the paths.".format(file_name, dir_candidates)
)
# 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"),
]
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)
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("daemon"):
# 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())
errors = self.script.set_rlimits(print_info=True)
if errors:
self.alerts.append((ALERT_WARNING, ULIMIT_ERR_CODE, errors))
self.set_signals(self.kill_children)
atexit.register(self.kill_children)
Output.script_exit_func = self.kill_children
self.start_processes()
# Kills currently running yugabyted process if it exists.
def stop(self, *args):
(err, pid) = self.script.kill()
if err:
Output.print_out(
"Failed to shut down {}: {}. Please check PID in {}".format(
SCRIPT_NAME, err, self.script.pidfile))
sys.exit(1)
elif pid:
self.script.wait_until_stop(pid)
Output.print_out("Stopped {} using config {}.".format(SCRIPT_NAME, self.conf_file))
sys.exit(0)
# Prints status of YugabyteDB.
def status(self):
if os.path.isdir(self.configs.saved_data.get("data_dir")):
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.script.kill()
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")
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.exists(self.conf_file):
os.remove(self.conf_file)
Output.print_out("Deleted conf file at {}.".format(self.conf_file))
sys.exit(0)
# Prints YugabyteDB version.
def version(self):
VERSION_METADATA_PATH = find_version_metadata_location("version_metadata.json")
print(VERSION_METADATA_PATH)
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"))
ysql_proxy.connect()
# 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))
ycql_proxy = YcqlProxy(ip=self.advertise_ip(),
port=self.configs.saved_data.get("ycql_port"))
ycql_proxy.connect()
# 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))
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))
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(
"Initializing {} demo database. This may take up to a minute...".format(demo_db))
# Create demo database.
Output.log("Creating database {}...".format(db_name))
ysql_proxy.create_db(db_name)
# Populate demo database.
Output.log("Populating {} with sample data...".format(db_name))
files = []
for name in Configs.get_demo_info()[demo_db]["files"]:
files.append(os.path.join(find_sample_data_location(name)))
ysql_proxy.load_files(files, db=db_name)
msg = "Successfully loaded sample database!"
Output.print_and_log(msg)
# Run YSQL shell in target demo database.
def connect_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))
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 not ysql_proxy.db_exists(db_name):
self.create_demo()
# Ignore kill SIGINT to match normal ysqlsh and psql behavior.
signal(SIGINT, SIG_IGN)
website = Output.make_underline(SAMPLE_DATA_LINKS[demo_db])
Output.print_out(Configs.get_demo_info()[demo_db]["examples"])
Output.print_out(
"For more, go to {}\n".format(website)
)
ysql_proxy.connect(db=db_name)
# Destroy target demo database if it exists.
def destroy_demo(self, signum=None, frame=None):
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))
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):
ysql_proxy.drop_db(db_name)
msg = "Deleted demo database {}.".format(demo_db)
Output.print_and_log(msg)
def collect_logs(self):
logpath = self.configs.saved_data.get("log_dir")
if not os.path.exists(logpath):
Output.print_and_log("No logs directory at {}".format(logpath))
return
tmpprefix = "yugabyted-{}.tar.gz".format(str(datetime.now()).replace(" ", "-"))
tarpath = os.path.join(os.path.expanduser('~'), tmpprefix)
with tarfile.open(name=tarpath, mode='w:gz', dereference=True) as archive:
archive.add(logpath)
if self.configs.temp_data.get("collect_logs_stdout"):
Output.log("Logs are packaged into {}".format(tarpath))
if tarfile.is_tarfile(tarpath):
with open(tarpath, 'rb') as tar_fd:
if sys.version_info[0] == 3:
sys.stdout.buffer.write(tar_fd.read())
else:
sys.stdout.write(tar_fd.read())
else:
Output.print_and_log("Logs are packaged into {}".format(tarpath))
# Checks yb-master and yb-tserver are running. Returns failed processes.
# TODO: Check postmaster.pid.
def get_failed_node_processes(self):
failed_processes = []
for process in ("master", "tserver"):
if not ProcessManager.is_process_running(
process, self.configs.saved_data.get("data_dir")):
failed_processes.append("yb-{}".format(process))
return failed_processes
# Called after receiving certain signals or on exit. Kills all subprocesses.
def kill_children(self, signum=None, frame=None):
if signum:
Output.log("Received signal: {}".format(signum), logging.DEBUG)
Output.print_and_log("Shutting down...")
Output.console_access = False
self.script.daemon_success.put(-1)
cur_pid = os.getpid()
pgid = os.getpgid(cur_pid)
if not pgid:
Output.log(
"PGID could not be found for PID {}. Is {} running?".format(cur_pid, SCRIPT_NAME))
os._exit(os.EX_OK)
self.set_signals(SIG_DFL)
for p in self.processes.values():
p.delete_pidfile()
self.script.delete_pidfile()
try:
# Kill process group instead of self.processes to ensure
# any spawned child processes are killed. Use SIGKILL because YugaWare
# requires KILL signal to terminate and nodes currently do not gracefully terminate.
os.killpg(pgid, SIGKILL)
Output.log(
"{} may not have terminated properly... "
"Please check PGID {}.".format(SCRIPT_NAME, pgid))
except OSError as err:
Output.log(
"Failed to kill PGID {}... Is {} running?\n{}".format(pgid, SCRIPT_NAME, str(err)))
# exit no matter what
os._exit(os.EX_OK)
def start_first_master_tserver(self, master_addresses):
self.processes.get("master").start()
was_already_setup = self.configs.saved_data.get("cluster_member", False)
if was_already_setup:
Output.log("Node was a member of some cluster before. "
"Skipping master setup")
elif not self.setup_master():
# TODO(sanketh): Make these all throw exceptions instead of excns + return values
return "Failed to start master {}".format(SCRIPT_NAME)
self.update_tserver_master_addrs()
self.processes.get("tserver").start()
if was_already_setup:
Output.log("Node was a member of some cluster before. "
"Skipping tserver setup")
elif not self.wait_tserver():
return "Failed to start tserver {}".format(SCRIPT_NAME)
universe_uuid = YBAdminProxy.get_cluster_uuid(master_addresses)
if universe_uuid and universe_uuid != self.configs.saved_data["universe_uuid"]:
self.configs.saved_data["universe_uuid"] = universe_uuid
self.configs.save_configs()
return None
# Starts yb-master, yb-tserver, and yugaware processes.
# After initializing, creates a callhome thread.
def start_processes(self):
bind_ip = self.configs.saved_data.get("listen")
advertise_ip = bind_ip if bind_ip != IP_ANY else IP_LOCALHOST
master_rpc_port = self.configs.saved_data.get("master_rpc_port")
join_ip = self.configs.saved_data.get("join")
master_addresses = "{}:{}".format(advertise_ip, master_rpc_port)
if join_ip:
master_addresses = "{}:{},{}".format(join_ip, master_rpc_port, master_addresses)
tserver_rpc_port = self.configs.saved_data.get("tserver_rpc_port")
common_gflags = [
"--stop_on_parent_termination",
"--undefok=stop_on_parent_termination",
"--fs_data_dirs={}".format(self.configs.saved_data.get("data_dir")),
"--webserver_interface={}".format(bind_ip),
"--metrics_snapshotter_tserver_metrics_whitelist={}".format(
",".join(METRICS_SNAPSHOT_LIST)),
"--yb_num_shards_per_tserver={}".format(YB_NUM_SHARDS_PER_TSERVER),
"--ysql_num_shards_per_tserver={}".format(YSQL_NUM_SHARDS_PER_TSERVER),
]
if not join_ip:
common_gflags.append("--cluster_uuid={}".format(
self.configs.saved_data.get("universe_uuid")))
yb_master_cmd = [find_binary_location("yb-master")] + \
common_gflags + \
[
"--rpc_bind_addresses={}:{}".format(advertise_ip, master_rpc_port),
"--server_broadcast_addresses={}:{}".format(advertise_ip, master_rpc_port),
"--replication_factor=1",
"--use_initial_sys_catalog_snapshot",
"--server_dump_info_path={}".format(
os.path.join(self.configs.saved_data.get("data_dir"), "master-info")),
"--master_enable_metrics_snapshotter=true",
"--webserver_port={}".format(self.configs.saved_data.get("master_webserver_port")),
"--default_memory_limit_to_ram_ratio=0.35",
"--instance_uuid_override={}".format(self.configs.saved_data.get("master_uuid")),
]
# if a join ip is specified, bring up a shell mode master
if not join_ip:
yb_master_cmd.append("--master_addresses={}".format(master_addresses))
if self.configs.saved_data.get("master_flags"):
yb_master_cmd.extend(
["--{}".format(flag) for flag in \
self.configs.saved_data.get("master_flags").split(",")])
yb_tserver_cmd = [find_binary_location("yb-tserver")] + common_gflags + \
[
"--{}={}".format(TS_MASTER_ADDRS_FLAG, master_addresses),
"--rpc_bind_addresses={}:{}".format(bind_ip, tserver_rpc_port),
"--server_broadcast_addresses={}:{}".format(advertise_ip, tserver_rpc_port),
"--cql_proxy_bind_address={}:{}".format(
bind_ip, self.configs.saved_data.get("ycql_port")),
"--server_dump_info_path={}".format(
os.path.join(self.configs.saved_data.get("data_dir"), "tserver-info")),
"--start_pgsql_proxy", "--pgsql_proxy_bind_address={}:{}".format(
bind_ip, self.configs.saved_data.get("ysql_port")),
"--tserver_enable_metrics_snapshotter=true",
"--metrics_snapshotter_interval_ms=11000",
"--webserver_port={}".format(self.configs.saved_data.get("tserver_webserver_port")),
"--default_memory_limit_to_ram_ratio=0.6",
"--instance_uuid_override={}".format(self.configs.saved_data.get("tserver_uuid")),
"--start_redis_proxy=false",
]
if self.configs.saved_data.get("tserver_flags"):
yb_tserver_cmd.extend(
["--{}".format(flag) for flag in \
self.configs.saved_data.get("tserver_flags").split(",")])
# Add authentication flags in tserver
if self.configs.saved_data.get("ysql_enable_auth"):
yb_tserver_cmd.extend(["--ysql_enable_auth=true"])
if self.configs.saved_data.get("use_cassandra_authentication"):
yb_tserver_cmd.extend(["--use_cassandra_authentication=true"])
yw_cmd = [
os.path.join(YUGAWARE_BIN_DIR, "yugaware"), "-Dconfig.file={}".format(YUGAWARE_CONF),
"-Dplay.evolutions.db.default.autoApply=true",
"-Dhttp.port={}".format(self.configs.saved_data.get("webserver_port")),
"-Dhttp.address={}".format(bind_ip),
"-Dlog.override.path={}".format(self.configs.saved_data.get("log_dir"))
]
self.processes = {
"master": YBProcessManager(
"master", yb_master_cmd, self.configs.saved_data.get("log_dir"),
self.configs.saved_data.get("data_dir")),
"tserver": YBProcessManager(
"tserver", yb_tserver_cmd, self.configs.saved_data.get("log_dir"),
self.configs.saved_data.get("data_dir")),
}
if self.configs.temp_data.get("ui"):
self.processes["yugaware"] = ProcessManager(
"yugaware", yw_cmd, self.configs.saved_data.get("log_dir"),
self.configs.saved_data.get("data_dir"))
for p in self.processes.values():
pid = p.get_pid()
if pid:
Output.print_out(
"{} is already running... Is there an existing {} process?".format(
p.name, SCRIPT_NAME))
# Clear self.processes so kill_children() doesn't kill existing processes.
self.processes = {}
return
is_first_run = True
callhome_thread = None
self.stop_callhome = False
while True:
should_callhome = False
is_first_install = is_first_run and not self.is_yb_initialized()
# Create data directory.
data_dir = self.configs.saved_data.get("data_dir")
if not os.path.exists(data_dir):
Output.log(
"Creating data directory {}.".format(data_dir))
os.makedirs(data_dir)
# Delete corrupted data dirs left from interrupting yb-master and yb-tserver startup.
pid_file_name = os.path.basename(self.script.pidfile)
data_dir_files = [ x for x in os.listdir(data_dir) if x != pid_file_name ]
if is_first_install and data_dir_files:
Output.print_and_log(
("Found files {} in data dir {} from possibly failed initialization."
" Removing...").format(data_dir_files, data_dir))
rmcontents(data_dir, exclude_names=[pid_file_name])
# Start or initialize yb-master and yb-tserver.
if is_first_run:
Output.init_animation("Running system checks...")
self.post_install_yb()
ret = self.start_first_master_tserver(master_addresses)
if ret:
Output.update_animation("Database failed to start",
status=Output.ANIMATION_FAIL)
Output.log_error_and_exit(ret)
# Persist the config after successful start
self.configs.save_configs()
Output.update_animation("System checks")
else:
for name in ("master", "tserver"):
process = self.processes.get(name)
process.remove_error_logs()
if not process.is_running():
Output.log(
"{} died unexpectedly. Restarting...".format(process.name),
logging.ERROR)
if name == "tserver":
self.update_tserver_master_addrs()
process.start()
should_callhome = True
if self.configs.temp_data.get("ui"):
(_, was_started) = self.maybe_start_yw(is_first_run, is_first_install)
should_callhome = should_callhome or was_started
if is_first_install and not join_ip:
self.first_install_init_auth()
if is_first_run:
status = self.get_status_string() + \
"{} {} started successfully! To load a sample dataset, " \
"try '{} demo'.\n" \
"{} Join us on Slack at {}\n" \
"{} Claim your free t-shirt at {}\n".format(
Output.ROCKET, SCRIPT_NAME, SCRIPT_NAME, Output.PARTY,
Output.make_underline(SLACK_LINK), Output.SHIRT,
Output.make_underline(COMMUNITY_REWARDS_LINK))
if len(self.setup_env_init.get_ysql_password()) > 99:
status = status + Output.make_red(YSQL_PASSWORD_LENGTH_WARNING)
Output.print_out(status)
if self.configs.temp_data.get("daemon"):
# Let original process know daemon was successful so it can exit.
# This is to display the initial status message.
self.script.daemon_success.put(1)
# Ignore any console output as important information will be logged.
with open('/dev/null', 'r+') as dev_null:
Output.console_access = False
sys.stderr.flush()
sys.stdout.flush()
os.dup2(dev_null.fileno(), sys.stdin.fileno())
os.dup2(dev_null.fileno(), sys.stderr.fileno())
os.dup2(dev_null.fileno(), sys.stdout.fileno())
Diagnostics.first_run_secs = time.time() - start_time_sec
Diagnostics.first_install = is_first_install
if self.configs.saved_data.get("callhome"):
callhome_thread = Thread(target=self.callhome_loop)
callhome_thread.daemon = True
callhome_thread.start()
is_first_run = False
if should_callhome:
self.callhome()
time.sleep(int(self.configs.saved_data.get("polling_interval")))
# Stop callhome. Useful in future if we do anything after quitting.
self.stop_callhome = True
callhome_thread.join()
# Returns (error string, yw_started).
# yw_started is True if YW was actually started
def maybe_start_yw(self, is_first_run, is_first_install):
was_started = False
err = None
if not self.configs.temp_data.get("ui"):
return (err, was_started)
yw_process = self.processes.get("yugaware")
yw_proxy = YugaWareProxy(self.advertise_ip(),
self.configs.saved_data.get("webserver_port"))
# Setup schema for play framework.
if is_first_run and not self.is_yw_initialized():
Output.log("Setting up admin console schema...")
Output.init_animation("Preparing UI schema...")
if not self.init_yw():
#TODO: make this return to caller
Output.log_error_and_exit("Failed to set up admin console schema...")
Output.update_animation("UI schema ready")
try:
if is_first_run:
Output.init_animation("Bringing up UI...")
# Start YW process.
if not yw_process.is_running():
if not is_first_run:
Output.log(
"Webserver died unexpectedly. Restarting...", logging.ERROR)
yw_process.start()
was_started = True
# After first run, do not attempt any more setup, just return.
if not is_first_run:
return (err, was_started)
# Login with username/pwd, this tells us that YW server is up.
err = self.wait_yw_login(yw_proxy, insecure=False)
if err:
return (err, was_started)
# On first install run, always setup YW.
# On a first run that is not first install,
# check if setup still needs to complete.
needs_setup = is_first_install
if not needs_setup:
# Login insecurely - if this fails, this likely means
# YW wasn't fully setup the first time around.
err = self.wait_yw_login(yw_proxy, insecure=True)
if err:
Output.log("Unable to insecure login to YW: {}".format(err))
needs_setup = True
if not needs_setup:
return (err, was_started)
# Set up login without username and password.
err = yw_proxy.set_security("insecure")
if err:
return (err, was_started)
# Verify login without username and password.
err = yw_proxy.insecure_login()
if err:
return (err, was_started)
yw_logged_in = True
full_master_list = self.wait_get_all_masters(timeout=60)
if not full_master_list:
err = "Unable to find full master list for YW import"
return (err, was_started)
# Import the universe (or re-import it). Re-importing should be harmless.
err = yw_proxy.import_universe(
",".join(full_master_list),
self.master_port(),
self.configs.saved_data.get("universe_uuid"))
if err:
return (err, was_started)
err = yw_proxy.set_landing_page(
self.configs.saved_data.get("universe_uuid"))
if err:
return (err, was_started)
if is_first_run:
Output.update_animation("UI ready")
if is_first_run and yw_process.is_running() and self.alerts:
yw_proxy.send_alerts(self.alerts)
finally:
if is_first_run:
animation_status = Output.ANIMATION_FAIL if err else Output.ANIMATION_SUCCESS
Output.update_animation("UI status", status=animation_status)
return (err, was_started)
# Pushes yugabyted script to background as a daemon. The process is not tied to a shell, but
# it will not survive between machine restarts.
def daemonize(self):
def remove_handlers():
if PY_VERSION < 3:
handlers = [e for e in atexit._exithandlers if e[0] == self.kill_children]
for handler in handlers:
atexit._exithandlers.remove(handler)
else:
atexit.unregister(self.kill_children)
if os.fork():
# Delete any custom exit handlers so daemon has full control.
remove_handlers()
# If parent is interrupted, kill the children as well. Note there is potentially a
# window where the daemon hasn't created its pidfile yet and this will error out before
# it can kill the daemon.
self.set_signals(self.stop)
# Keep the parent process alive until the daemon confirms yugabyted started properly.
try:
self.script.daemon_success.get(timeout=600)
except queue.Empty as e:
Output.print_and_log(
"Timed out trying to start {} daemon.".format(SCRIPT_NAME), logging.ERROR)
self.stop()
sys.exit()
os.chdir(YUGABYTE_DIR)
os.setsid()
os.umask(0)
if os.fork():
remove_handlers()
sys.exit()
Output.log("Daemon grandchild process begins execution.")
# Sets env variables needed for yugabyted start.
def set_env_vars(self):
# Sets YW metrics to use local database.
os.environ["USE_NATIVE_METRICS"] = "true"
# Runs post_install script for linux computers.
def post_install_yb(self):
if not sys.platform.startswith('linux'):
return
post_install_script_path = find_binary_location('post_install.sh')
# If post_install.sh script is not found then we assume that
# we are executing it in development mode, hence skip post_install.sh script
# TODO(Sanket): Refactor the design to have yugabyted a way of knowing whether it
# is an install env v/s dev
if(post_install_script_path is None):
return
Output.log("Running the post-installation script {} (may be a no-op)".format(
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:
Output.log_error_and_exit(
"Failed running {} (exit code: {}). Standard output:\n{}\n. "
"Standard error:\n{}".format(
post_install_script_path, process.returncode, std_out, std_err))
Output.log("Successfully ran the post-installation script.")
# Initialize YW process. Creates all necessary tables. Returns false if init failed.
def init_yw(self):
# Create Play evolutions table. Required for YugaWare to start up properly.
create_play_table = [
os.path.join(YUGAWARE_BIN_DIR, "yugaware"),
"-Dconfig.file=" + YUGAWARE_CONF,
"-Dlog.override.path={}".format(self.configs.saved_data.get("log_dir"))
]
Output.log("Initializing play tables...")
run_process(create_play_table)
Output.log("Done initializing play tables.")
return True
# Returns if yb-master and yb-tserver were properly initialized before.
def is_yb_initialized(self):
for info_file in ("master-info", "tserver-info", "tserver-info-cql"):
if not os.path.exists(os.path.join(self.configs.saved_data.get("data_dir"), info_file)):
return False
return True
# Returns if yugaware was properly initialized before.
def is_yw_initialized(self):
# Check Play evolutions table was created.
Output.log("Checking play_evolutions table")
list_tables_cmd = [find_binary_location("ysqlsh"), "-d", WEBSERVER_DB, "-c", "\d"]
out, err, ret_code = run_process(list_tables_cmd)
Output.log("Finished checking play evolutions table")
return not err and not ret_code and "play_evolutions" in out
# Returns true if this master was found in the current list of masters
def wait_master(self):
join_ip = self.configs.saved_data.get("join")
master_ip = join_ip if join_ip else self.advertise_ip()
master_addr = "{}:{}".format(master_ip,
self.configs.saved_data.get("master_rpc_port"))
if (not self.processes.get("master").is_running()):
Output.log("Failed waiting for yb-master... process died.", logging.ERROR)
raise RuntimeError("process died unexpectedly.")
cur_master_uuids = [ m[0] for m in YBAdminProxy.get_masters(master_addr) ]
master_uuid = self.configs.saved_data.get("master_uuid")
if not cur_master_uuids:
raise RetryableError()
return master_uuid in cur_master_uuids
# Use the masters we know (ourselves and the join target) to discover the full cluster.
# Retry until timeout in case the masters we know are still coming up.
def wait_get_all_masters(self, timeout=180):
Output.log("Waiting to get the full master addrs list from master")
try:
return retry_op(self.get_all_masters, timeout)
except RuntimeError:
Output.log("Failed to query for all masters. Exception: {}".format(
traceback.format_exc()))
return False
# Use the masters we know (ourselves and the join target) to discover the full cluster.
def get_all_masters(self):
join_ip = self.configs.saved_data.get("join")
advertise_ip = self.advertise_ip()
all_masters = None
for master_ip in (join_ip, advertise_ip):
if not master_ip:
continue
master_addr = "{}:{}".format(master_ip,
self.configs.saved_data.get("master_rpc_port"))
all_masters = [ m[1] for m in YBAdminProxy.get_masters(master_addr) ]
Output.log("Got all masters: {}".format(all_masters))
if all_masters:
return all_masters
raise RetryableError()
# Verify that the master is in the current list of masters.
# If not, set it up appropriately.
def setup_master(self, timeout=180):
Output.log("Waiting for master")
join_ip = self.configs.saved_data.get("join")
try:
if retry_op(self.wait_master, timeout):
self.configs.saved_data["cluster_member"] = True
return True
# If wait_master returns False, it means the master is
# not part of the current set of masters. If we have a
# join_ip, let's try to add ourselves to it, otherwise
# it is a hard failure.
if not join_ip:
return False
except RuntimeError:
Output.log_error_and_exit("Failed to setup master. Exception: {}".format(
traceback.format_exc()))
return False
# The master was not in the current list of masters
# and we have a valid join_ip
bind_ip = self.configs.saved_data.get("listen")
master_addrs = "{}:{}".format(join_ip,
self.configs.saved_data.get("master_rpc_port"))
master_uuids = [ m[0] for m in YBAdminProxy.get_masters(master_addrs) ]
if len(master_uuids) >= 3:
# this is going to be a standalone shell master
return True
if not YBAdminProxy.add_master(master_addrs, bind_ip):
Output.log_error_and_exit("Unable to add master {} to existing cluster at {}.".format(
bind_ip, join_ip))
return False
# If we are the third master, set replication factor to 3. This makes the cluster
# automatically expand to rf3 when the third node is added.