-
Notifications
You must be signed in to change notification settings - Fork 68
/
scylla_node.py
1559 lines (1351 loc) · 70 KB
/
scylla_node.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ccm node
from datetime import datetime
import errno
import os
import signal
import shutil
import socket
import stat
import subprocess
import time
import threading
from pathlib import Path
from collections import OrderedDict
import psutil
import yaml
import glob
import re
import requests
from ccmlib.common import CASSANDRA_SH, BIN_DIR, wait_for, copy_directory
from ccmlib import common
from ccmlib.node import Node, NodeUpgradeError
from ccmlib.node import Status
from ccmlib.node import NodeError
from ccmlib.node import TimeoutError
from ccmlib.scylla_repository import setup, get_scylla_version
from ccmlib.utils.version import parse_version
class ScyllaNode(Node):
"""
Provides interactions to a Scylla node.
"""
def __init__(self, name, cluster, auto_bootstrap, thrift_interface,
storage_interface, jmx_port, remote_debug_port, initial_token,
save=True, binary_interface=None, scylla_manager=None):
self._node_install_dir = None
self._node_scylla_version = None
self._relative_repos_root = None
super(ScyllaNode, self).__init__(name, cluster, auto_bootstrap,
thrift_interface, storage_interface,
jmx_port, remote_debug_port,
initial_token, save, binary_interface)
self.__global_log_level = 'info'
self.__classes_log_level = {}
self.get_cassandra_version()
self._process_jmx = None
self._process_jmx_waiter = None
self._process_scylla = None
self._process_scylla_waiter = None
self._process_agent = None
self._process_agent_waiter = None
self._smp = 2
self._smp_set_during_test = False
self._mem_mb_per_cpu = 512
self._mem_mb_set_during_test = False
self._memory = None
self.__conf_updated = False
self.scylla_manager = scylla_manager
self.jmx_pid = None
self.agent_pid = None
self.upgraded = False
self.upgrader = NodeUpgrader(node=self)
self._create_directory()
@property
def node_install_dir(self):
if not self._node_install_dir:
self._node_install_dir = self.get_install_dir()
return self._node_install_dir
@node_install_dir.setter
def node_install_dir(self, install_dir):
self._node_install_dir = install_dir
@property
def node_scylla_version(self):
if not self._node_scylla_version:
self._node_scylla_version = self.get_node_scylla_version()
return self._node_scylla_version
@node_scylla_version.setter
def node_scylla_version(self, install_dir):
self._node_scylla_version = self.get_node_scylla_version(install_dir)
@property
def scylla_build_id(self):
return self._run_scylla_executable_with_option(option="--build-id")
def scylla_mode(self):
return self.cluster.get_scylla_mode()
def is_scylla_reloc(self):
return self.cluster.is_scylla_reloc()
def set_smp(self, smp):
self._smp = smp
self._smp_set_during_test = True
def smp(self):
return self._smp
def set_mem_mb_per_cpu(self, mem):
self._mem_mb_per_cpu = mem
self._mem_mb_set_during_test = True
def get_install_cassandra_root(self):
return self.get_tools_java_dir()
def get_node_cassandra_root(self):
return os.path.join(self.get_path())
def get_conf_dir(self):
"""
Returns the path to the directory where Cassandra config are located
"""
return os.path.join(self.get_path(), 'conf')
def get_tool(self, toolname):
candidate_dirs = [
os.path.join(self.node_install_dir, 'share', 'cassandra', BIN_DIR),
os.path.join(self.get_tools_java_dir(), BIN_DIR),
os.path.join(self.get_cqlsh_dir(), BIN_DIR),
]
for candidate_dir in candidate_dirs:
candidate = shutil.which(toolname, path=candidate_dir)
if candidate:
return candidate
raise ValueError(f"tool {toolname} wasn't found in any path: {candidate_dirs}")
def get_tool_args(self, toolname):
raise NotImplementedError('ScyllaNode.get_tool_args')
def get_env(self):
update_conf = not self.__conf_updated
if update_conf:
self.__conf_updated = True
return common.make_cassandra_env(self.get_install_cassandra_root(),
self.get_node_cassandra_root(), update_conf=update_conf)
def get_cassandra_version(self):
# TODO: Handle versioning
return '3.0'
def set_log_level(self, new_level, class_name=None):
known_level = {'TRACE' : 'trace', 'DEBUG' : 'debug', 'INFO' : 'info', 'WARN' : 'warn', 'ERROR' : 'error', 'OFF' : 'info'}
if not new_level in known_level:
raise common.ArgumentError(f"Unknown log level {new_level} (use one of {' '.join(known_level)})")
new_log_level = known_level[new_level]
# TODO class_name can be validated against help-loggers
if class_name:
self.__classes_log_level[class_name] = new_log_level
else:
self.__global_log_level = new_log_level
return self
def set_workload(self, workload):
raise NotImplementedError('ScyllaNode.set_workload')
def cpuset(self, id, count, cluster_id):
# leaving one core for other executables to run
allocated_cpus = psutil.cpu_count() - 1
start_id = (id * count + cluster_id) % allocated_cpus
cpuset = []
for cpuid in range(start_id, start_id + count):
cpuset.append(str(cpuid % allocated_cpus))
return cpuset
def memory(self):
return self._memory
def _wait_for_jmx(self):
if self._process_jmx:
self._process_jmx.wait()
def _wait_for_scylla(self):
if self._process_scylla:
self._process_scylla.wait()
def _wait_for_agent(self):
if self._process_agent:
self._process_agent.wait()
def _start_jmx(self, data):
jmx_jar_dir = os.path.join(self.get_path(), BIN_DIR)
jmx_java_bin = os.path.join(jmx_jar_dir, 'symlinks', 'scylla-jmx')
jmx_jar = os.path.join(jmx_jar_dir, 'scylla-jmx-1.0.jar')
args = [jmx_java_bin,
f"-Dapiaddress={data['listen_address']}",
'-Djavax.management.builder.initial=com.scylladb.jmx.utils.APIBuilder',
f"-Djava.rmi.server.hostname={data['listen_address']}",
'-Dcom.sun.management.jmxremote',
f"-Dcom.sun.management.jmxremote.host={data['listen_address']}",
f'-Dcom.sun.management.jmxremote.port={self.jmx_port}',
f'-Dcom.sun.management.jmxremote.rmi.port={self.jmx_port}',
'-Dcom.sun.management.jmxremote.local.only=false',
'-Xmx256m',
'-XX:+UseSerialGC',
'-Dcom.sun.management.jmxremote.authenticate=false',
'-Dcom.sun.management.jmxremote.ssl=false',
'-jar',
jmx_jar]
log_file = os.path.join(self.get_path(), 'logs', 'system.log.jmx')
env_copy = os.environ
env_copy['SCYLLA_HOME'] = self.get_path()
message = f"Starting scylla-jmx: args={args}"
self.debug(message)
with open(log_file, 'a') as jmx_log:
jmx_log.write(f"{message}\n")
self._process_jmx = subprocess.Popen(args, stdout=jmx_log, stderr=jmx_log, close_fds=True, env=env_copy)
self._process_jmx.poll()
# When running on ccm standalone, the waiter thread would block
# the create commands. Besides in that mode, waiting is unnecessary,
# since the original popen reference is garbage collected.
standalone = os.environ.get('SCYLLA_CCM_STANDALONE', None)
if standalone is None:
self._process_jmx_waiter = threading.Thread(target=self._wait_for_jmx)
# Don't block the main thread on abnormal shutdown
self._process_jmx_waiter.daemon = True
self._process_jmx_waiter.start()
pid_filename = os.path.join(self.get_path(), 'scylla-jmx.pid')
with open(pid_filename, 'w') as pid_file:
pid_file.write(str(self._process_jmx.pid))
# Wait for a starting node until is starts listening for CQL.
# Possibly poll the log for long-running offline processes, like
# bootstrap or resharding.
# Return True iff detected bootstrap or resharding processes in the log
def wait_for_starting(self, from_mark=None, timeout=None):
if from_mark is None:
from_mark = self.mark_log()
if timeout is None:
timeout = 120
process=self._process_scylla
starting_message = 'Starting listening for CQL clients'
bootstrap_message = r'storage_service .* Starting to bootstrap'
resharding_message = r'(compaction|database) -.*Resharding'
if not self.watch_log_for(f"{starting_message}|{bootstrap_message}|{resharding_message}", from_mark=from_mark, timeout=timeout, process=process):
return False
prev_mark = from_mark
prev_mark_time = time.time()
sleep_time = 10 if timeout >= 100 else 1
while not self.grep_log(starting_message, from_mark=from_mark):
process.poll()
if process.returncode is not None:
self.print_process_output(self.name, process, verbose=True)
if process.returncode != 0:
raise RuntimeError(f"The process is dead, returncode={process.returncode}")
pat = '|'.join([
r'repair - Repair \d+ out of \d+ ranges',
r'repair - .*: Started to repair',
r'range_streamer - Bootstrap .* streaming .* ranges',
r'(compaction|database) -.*Resharded',
r'compaction_manager - (Starting|Done with) off-strategy compaction',
r'compaction - .* Reshaped'
])
if self.grep_log(pat, from_mark=prev_mark):
prev_mark = self.mark_log()
prev_mark_time = time.time()
elif time.time() - prev_mark_time >= timeout:
raise TimeoutError(f"{self.name}: Timed out waiting for '{starting_message}'")
time.sleep(sleep_time)
return bool(self.grep_log(f"{bootstrap_message}|{resharding_message}", from_mark=from_mark))
def _start_scylla(self, args, marks, update_pid, wait_other_notice,
wait_for_binary_proto, ext_env, timeout=None):
log_file = os.path.join(self.get_path(), 'logs', 'system.log')
# In case we are restarting a node
# we risk reading the old cassandra.pid file
self._delete_old_pid()
try:
env_copy = self._launch_env
except AttributeError:
env_copy = os.environ
env_copy['SCYLLA_HOME'] = self.get_path()
env_copy.update(ext_env)
with open(log_file, 'a') as scylla_log:
self._process_scylla = \
subprocess.Popen(args, stdout=scylla_log, stderr=scylla_log, close_fds=True, env=env_copy)
self._process_scylla.poll()
# When running on ccm standalone, the waiter thread would block
# the create commands. Besides in that mode, waiting is unnecessary,
# since the original popen reference is garbage collected.
standalone = os.environ.get('SCYLLA_CCM_STANDALONE', None)
if standalone is None:
self._process_scylla_waiter = threading.Thread(target=self._wait_for_scylla)
# Don't block the main thread on abnormal shutdown
self._process_scylla_waiter.daemon = True
self._process_scylla_waiter.start()
pid_filename = os.path.join(self.get_path(), 'cassandra.pid')
with open(pid_filename, 'w') as pid_file:
pid_file.write(str(self._process_scylla.pid))
if update_pid:
self._update_pid(self._process_scylla)
if not self.is_running():
raise NodeError(f"Error starting node {self.name}",
self._process_scylla)
if wait_other_notice:
for node, _ in marks:
t = timeout if timeout is not None else 120 if self.cluster.scylla_mode != 'debug' else 360
node.watch_rest_for_alive(self, timeout=t)
self.watch_rest_for_alive(node, timeout=t)
if wait_for_binary_proto:
t = timeout * 4 if timeout is not None else 420 if self.cluster.scylla_mode != 'debug' else 900
from_mark = self.mark
try:
self.wait_for_binary_interface(from_mark=from_mark, process=self._process_scylla, timeout=timeout or 180)
except TimeoutError as e:
self.wait_for_starting(from_mark=self.mark, timeout=t)
self.wait_for_binary_interface(from_mark=from_mark, process=self._process_scylla, timeout=0)
return self._process_scylla
def _create_agent_config(self):
conf_file = os.path.join(self.get_conf_dir(), 'scylla-manager-agent.yaml')
ssl_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scylla_test_ssl')
data = dict()
data['https'] = f"{self.address()}:10001"
data['auth_token'] = self.scylla_manager.auth_token
data['tls_cert_file'] = os.path.join(ssl_dir, 'scylla-manager-agent.crt')
data['tls_key_file'] = os.path.join(ssl_dir, 'scylla-manager-agent.key')
data['logger'] = dict(level='debug')
data['debug'] = f"{self.address()}:56112"
data['scylla'] = {'api_address': f"{self.address()}",
'api_port': 10000}
data['prometheus'] = f"{self.address()}:56090"
data['s3'] = {"endpoint": os.getenv("AWS_S3_ENDPOINT"), "provider": "Minio"}
with open(conf_file, 'w') as f:
yaml.safe_dump(data, f, default_flow_style=False)
return conf_file
def update_agent_config(self, new_settings, restart_agent_after_change=True):
conf_file = os.path.join(self.get_conf_dir(), 'scylla-manager-agent.yaml')
with open(conf_file, 'r') as f:
current_config = yaml.safe_load(f)
current_config.update(new_settings)
with open(conf_file, 'w') as f:
yaml.safe_dump(current_config, f, default_flow_style=False)
if restart_agent_after_change:
self.restart_scylla_manager_agent(gently=True, recreate_config=False)
def start_scylla_manager_agent(self, create_config=True):
agent_bin = os.path.join(self.scylla_manager._get_path(), BIN_DIR, 'scylla-manager-agent')
log_file = os.path.join(self.get_path(), 'logs', 'system.log.manager_agent')
if create_config:
config_file = self._create_agent_config()
else:
config_file = os.path.join(self.get_conf_dir(), 'scylla-manager-agent.yaml')
args = [agent_bin,
'--config-file', config_file]
with open(log_file, 'a') as agent_log:
self._process_agent = subprocess.Popen(args, stdout=agent_log, stderr=agent_log, close_fds=True)
self._process_agent.poll()
# When running on ccm standalone, the waiter thread would block
# the create commands. Besides in that mode, waiting is unnecessary,
# since the original popen reference is garbage collected.
standalone = os.environ.get('SCYLLA_CCM_STANDALONE', None)
if standalone is None:
self._process_agent_waiter = threading.Thread(target=self._wait_for_agent)
# Don't block the main thread on abnormal shutdown
self._process_agent_waiter.daemon = True
self._process_agent_waiter.start()
pid_filename = os.path.join(self.get_path(), 'scylla-agent.pid')
with open(pid_filename, 'w') as pid_file:
pid_file.write(str(self._process_agent.pid))
with open(config_file, 'r') as f:
current_config = yaml.safe_load(f)
# Extracting currently configured port
current_listening_port = int(current_config['https'].split(":")[1])
api_interface = common.parse_interface(self.address(), current_listening_port)
if not common.check_socket_listening(api_interface, timeout=180):
raise Exception(
"scylla manager agent interface %s:%s is not listening after 180 seconds, scylla manager agent may have failed to start."
% (api_interface[0], api_interface[1]))
def restart_scylla_manager_agent(self, gently, recreate_config=True):
self.stop_scylla_manager_agent(gently=gently)
self.start_scylla_manager_agent(create_config=recreate_config)
def stop_scylla_manager_agent(self, gently):
if gently:
try:
self._process_agent.terminate()
except OSError:
pass
else:
try:
self._process_agent.kill()
except OSError:
pass
def _wait_java_up(self, ip_addr, jmx_port):
def is_java_up():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as _socket:
_socket.settimeout(1.0)
try:
_socket.connect((ip_addr, jmx_port))
return True
except (socket.timeout, ConnectionRefusedError):
return False
return wait_for(func=is_java_up, timeout=30, step=0.05)
def node_install_dir_version(self):
if not self.node_install_dir:
return None
return get_scylla_version(self.node_install_dir)
@staticmethod
def parse_size(s):
iec_prefixes = {'k': 10,
'K': 10,
'M': 20,
'G': 30,
'T': 40}
for prefix, power in list(iec_prefixes.items()):
if s.endswith(prefix):
return int(s[:-1]) * pow(2, power)
return int(s)
# Scylla Overload start
def start(self, join_ring=True, no_wait=False, verbose=False,
update_pid=True, wait_other_notice=None, replace_token=None,
replace_address=None, replace_node_host_id=None, jvm_args=None, wait_for_binary_proto=None,
profile_options=None, use_jna=False, quiet_start=False):
"""
Start the node. Options includes:
- join_ring: if false, start the node with -Dcassandra.join_ring=False
- no_wait: by default, this method returns when the node is started
and listening to clients.
If no_wait=True, the method returns sooner.
- wait_other_notice: if True, this method returns only when all other
live node of the cluster
have marked this node UP.
- replace_token: start the node with the -Dcassandra.replace_token
option.
- replace_node_host_id: start the node with the
--replace-node-first-boot option to replace a given node
identified by its host_id.
- replace_address: start the node with the deprecated
--replace-address option.
Extra command line options may be passed using the
SCYLLA_EXT_OPTS environment variable.
Extra environment variables for running scylla can be passed using the
SCYLLA_EXT_ENV environment variable.
Those are represented in a single string comprised of one or more
pairs of "var=value" separated by either space or semicolon (';')
"""
if wait_for_binary_proto is None:
wait_for_binary_proto = self.cluster.force_wait_for_cluster_start and not no_wait
if wait_other_notice is None:
wait_other_notice = self.cluster.force_wait_for_cluster_start and not no_wait
if jvm_args is None:
jvm_args = []
scylla_cassandra_mapping = {'-Dcassandra.replace_address_first_boot':
'--replace-address-first-boot'}
# Replace args in the form
# ['-Dcassandra.foo=bar'] to ['-Dcassandra.foo', 'bar']
translated_args = []
new_jvm_args = []
for jvm_arg in jvm_args:
if '=' in jvm_arg:
split_option = jvm_arg.split("=")
e_msg = ("Option %s not in the form '-Dcassandra.foo=bar'. "
"Please check your test" % jvm_arg)
assert len(split_option) == 2, e_msg
option, value = split_option
# If we have information on how to translate the jvm option,
# translate it
if option in scylla_cassandra_mapping:
translated_args += [scylla_cassandra_mapping[option],
value]
# Otherwise, just pass it as is
else:
new_jvm_args.append(jvm_arg)
else:
new_jvm_args.append(jvm_arg)
jvm_args = new_jvm_args
if self.is_running():
raise NodeError(f"{self.name} is already running")
if not self.is_docker():
for itf in list(self.network_interfaces.values()):
if itf is not None and replace_address is None:
try:
common.check_socket_available(itf)
except Exception as msg:
print(f"{msg}. Looking for offending processes...")
for proc in psutil.process_iter():
if any(self.cluster.ipprefix in cmd for cmd in proc.cmdline()):
print(f"name={proc.name()} pid={proc.pid} cmdline={proc.cmdline()}")
raise msg
marks = []
if wait_other_notice:
marks = [(node, node.mark_log()) for node in
list(self.cluster.nodes.values()) if node.is_live()]
self.mark = self.mark_log()
launch_bin = common.join_bin(self.get_path(), BIN_DIR, 'scylla')
options_file = os.path.join(self.get_path(), 'conf', 'scylla.yaml')
# TODO: we do not support forcing specific settings
# TODO: workaround for api-address as we do not load it
# from config file scylla#59
conf_file = os.path.join(self.get_conf_dir(), common.SCYLLA_CONF)
with open(conf_file, 'r') as f:
data = yaml.safe_load(f)
jvm_args = jvm_args + ['--api-address', data['api_address']]
jvm_args = jvm_args + ['--collectd-hostname',
f'{socket.gethostname()}.{self.name}']
args = [launch_bin, '--options-file', options_file, '--log-to-stdout', '1']
MB = 1024 * 1024
def process_opts(opts):
ext_args = OrderedDict()
opts_i = 0
while opts_i < len(opts):
# the command line options show up either like "--foo value-of-foo"
# or as a single option like --yes-i-insist
assert opts[opts_i].startswith('-')
o = opts[opts_i]
opts_i += 1
if '=' in o:
opt = o.replace('=', ' ', 1).split()
key = opt[0]
val = opt[1]
else:
key = o
vals = []
while opts_i < len(opts) and not opts[opts_i].startswith('-'):
vals.append(opts[opts_i])
opts_i += 1
val = ' '.join(vals)
if key not in ext_args and not key.startswith("--scylla-manager"):
ext_args[key] = val
return ext_args
# Lets search for default overrides in SCYLLA_EXT_OPTS
env_args = process_opts(os.getenv('SCYLLA_EXT_OPTS', "").split())
# precalculate self._mem_mb_per_cpu if --memory is given in SCYLLA_EXT_OPTS
# and it wasn't set explicitly by the test
if not self._mem_mb_set_during_test and '--memory' in env_args:
memory = self.parse_size(env_args['--memory'])
smp = int(env_args['--smp']) if '--smp' in env_args else self._smp
self._mem_mb_per_cpu = int((memory / smp) // MB)
cmd_args = process_opts(jvm_args)
# use '--memory' in jmv_args if mem_mb_per_cpu was not set by the test
if not self._mem_mb_set_during_test and '--memory' in cmd_args:
self._memory = self.parse_size(cmd_args['--memory'])
ext_args = env_args
ext_args.update(cmd_args)
for k, v in ext_args.items():
if k == '--smp':
# get smp from args if not set by the test
if not self._smp_set_during_test:
self._smp = int(v)
elif k != '--memory':
args.append(k)
if v:
args.append(v)
args.extend(translated_args)
# calculate memory from smp * mem_mb_per_cpu
# if not given in jvm_args
if not self._memory:
self._memory = int(self._smp * self._mem_mb_per_cpu * MB)
assert '--smp' not in args and '--memory' not in args, args
args += ['--smp', str(self._smp)]
args += ['--memory', f"{int(self._memory // MB)}M"]
if '--developer-mode' not in args:
args += ['--developer-mode', 'true']
if '--default-log-level' not in args:
args += ['--default-log-level', self.__global_log_level]
if self.scylla_mode() == 'debug' and '--blocked-reactor-notify-ms' not in args:
args += ['--blocked-reactor-notify-ms', '5000']
# TODO add support for classes_log_level
if '--collectd' not in args:
args += ['--collectd', '0']
if '--cpuset' not in args:
args += ['--overprovisioned']
if '--prometheus-address' not in args:
args += ['--prometheus-address', data['api_address']]
if replace_node_host_id:
assert replace_address is None, "replace_node_host_id and replace_address cannot be specified together"
args += ['--replace-node-first-boot', replace_node_host_id]
elif replace_address:
args += ['--replace-address', replace_address]
args += ['--unsafe-bypass-fsync', '1']
current_node_version = self.node_install_dir_version() or self.cluster.version()
current_node_is_enterprise = parse_version(current_node_version) > parse_version("2018.1")
# The '--kernel-page-cache' was introduced by
# https://github.com/scylladb/scylla/commit/8785dd62cb740522d80eb12f8272081f85be9b7e from 4.5 version
# and 2022.1 Enterprise version
kernel_page_cache_supported = not current_node_is_enterprise and parse_version(current_node_version) >= parse_version('4.5.dev')
kernel_page_cache_supported |= current_node_is_enterprise and parse_version(current_node_version) >= parse_version('2022.1.dev')
if kernel_page_cache_supported and '--kernel-page-cache' not in args:
args += ['--kernel-page-cache', '1']
commitlog_o_dsync_supported = (
(not current_node_is_enterprise and parse_version(current_node_version) >= parse_version('3.2'))
or (current_node_is_enterprise and parse_version(current_node_version) >= parse_version('2020.1'))
)
if commitlog_o_dsync_supported:
args += ['--commitlog-use-o-dsync', '0']
# The '--max-networking-io-control-blocks' was introduced by
# https://github.com/scylladb/scylla/commit/2cfc517874e98c5780c1b1b4c38440a8123f86f6 from 4.6 version
# and 2022.1 Enterprise version
max_networking_io_control_blocks_supported = not current_node_is_enterprise and parse_version(current_node_version) >= parse_version('4.6')
max_networking_io_control_blocks_supported |= current_node_is_enterprise and parse_version(current_node_version) >= parse_version('2022.1.dev')
if max_networking_io_control_blocks_supported and '--max-networking-io-control-blocks' not in args:
args += ['--max-networking-io-control-blocks', '1000']
ext_env = {}
scylla_ext_env = os.getenv('SCYLLA_EXT_ENV', "").strip()
if scylla_ext_env:
scylla_ext_env = re.split(r'[; ]', scylla_ext_env)
for s in scylla_ext_env:
try:
[k, v] = s.split('=', 1)
except ValueError as e:
print(f"Bad SCYLLA_EXT_ENV variable: {s}: {e}")
else:
ext_env[k] = v
message = f"Starting scylla: args={args} wait_other_notice={wait_other_notice} wait_for_binary_proto={wait_for_binary_proto}"
self.debug(message)
scylla_process = self._start_scylla(args, marks, update_pid,
wait_other_notice,
wait_for_binary_proto,
ext_env)
self._start_jmx(data)
ip_addr, _ = self.network_interfaces['storage']
jmx_port = int(self.jmx_port)
if not self._wait_java_up(ip_addr, jmx_port):
e_msg = "Error starting node {}: unable to connect to scylla-jmx port {}:{}".format(
self.name, ip_addr, jmx_port)
raise NodeError(e_msg, scylla_process)
self._update_pid(scylla_process)
wait_for(func=lambda: self.is_running(), timeout=10, step=0.01)
if self.scylla_manager and self.scylla_manager.is_agent_available:
self.start_scylla_manager_agent()
return scylla_process
def start_dse(self,
join_ring=True,
no_wait=False,
verbose=False,
update_pid=True,
wait_other_notice=False,
replace_token=None,
replace_address=None,
jvm_args=None,
wait_for_binary_proto=False,
profile_options=None,
use_jna=False):
"""
Start the node. Options includes:
- join_ring: if false, start the node with -Dcassandra.join_ring=False
- no_wait: by default, this method returns when the node is started
and listening to clients.
If no_wait=True, the method returns sooner.
- wait_other_notice: if True, this method returns only when all other
live node of the cluster have marked this node UP.
- replace_token: start the node with the -Dcassandra.replace_token
option.
- replace_address: start the node with the
-Dcassandra.replace_address option.
"""
if jvm_args is None:
jvm_args = []
raise NotImplementedError('ScyllaNode.start_dse')
def _update_jmx_pid(self, wait=True):
pidfile = os.path.join(self.get_path(), 'scylla-jmx.pid')
start = time.time()
while not (os.path.isfile(pidfile) and os.stat(pidfile).st_size > 0):
elapsed = time.time() - start
if elapsed > 30.0 or not wait:
if wait:
print("Timed out waiting for pidfile {} to be filled (after {} seconds): File {} size={}".format(
pidfile,
elapsed,
'exists' if os.path.isfile(pidfile) else 'does not exist' if not os.path.exists(pidfile) else 'is not a file',
os.stat(pidfile).st_size if os.path.exists(pidfile) else -1))
break
else:
time.sleep(0.1)
if os.path.isfile(pidfile) and os.stat(pidfile).st_size > 0:
try:
with open(pidfile, 'r') as f:
self.jmx_pid = int(f.readline().strip())
except IOError as e:
raise NodeError('Problem starting node %s scylla-jmx due to %s' %
(self.name, e))
else:
self.jmx_pid = None
def nodetool(self, *args, **kwargs):
"""
Kill scylla-jmx in case of timeout, to supply enough debugging information
"""
try:
return super().nodetool(*args, **kwargs)
except subprocess.TimeoutExpired:
self.error("nodetool timeout, going to kill scylla-jmx with SIGQUIT")
self.kill_jmx(signal.SIGQUIT)
time.sleep(5) # give the java process time to print the threaddump into the log
raise
def kill_jmx(self, __signal):
if self.jmx_pid:
os.kill(self.jmx_pid, __signal)
def _update_scylla_agent_pid(self):
pidfile = os.path.join(self.get_path(), 'scylla-agent.pid')
start = time.time()
while not (os.path.isfile(pidfile) and os.stat(pidfile).st_size > 0):
if time.time() - start > 30.0:
print("Timed out waiting for pidfile {} to be filled (current time is %s): File {} size={}".format(
pidfile,
datetime.now(),
'exists' if os.path.isfile(pidfile) else 'does not exist' if not os.path.exists(pidfile) else 'is not a file',
os.stat(pidfile).st_size if os.path.exists(pidfile) else -1))
break
else:
time.sleep(0.1)
try:
with open(pidfile, 'r') as f:
self.agent_pid = int(f.readline().strip())
except IOError as e:
raise NodeError('Problem starting node %s scylla-agent due to %s' %
(self.name, e))
def do_stop(self, gently=True):
"""
Stop the node.
- gently: Let Scylla and Scylla JMX clean up and shut down properly.
Otherwise do a 'kill -9' which shuts down faster.
"""
did_stop = False
self._update_jmx_pid(wait=False)
if self.scylla_manager and self.scylla_manager.is_agent_available:
self._update_scylla_agent_pid()
for proc in [self._process_jmx, self._process_scylla, self._process_agent]:
if proc:
did_stop = True
if gently:
try:
proc.terminate()
except OSError:
pass
else:
try:
proc.kill()
except OSError:
pass
else:
signal_mapping = {True: signal.SIGTERM, False: signal.SIGKILL}
for pid in [self.jmx_pid, self.pid, self.agent_pid]:
if pid:
did_stop = True
try:
os.kill(pid, signal_mapping[gently])
except OSError:
pass
return did_stop
def _wait_until_stopped(self, wait_seconds):
return wait_for(func=lambda: not self.is_running(), timeout=wait_seconds)
def wait_until_stopped(self, wait_seconds=None, marks=None, dump_core=True):
"""
Wait until node is stopped after do_stop was called.
- wait_other_notice: return only when the other live nodes of the
cluster have marked this node has dead.
- marks: optional list of (node, mark) to call watch_log_for_death on.
"""
marks = marks or []
if wait_seconds is None:
wait_seconds = 127 if self.scylla_mode() != 'debug' else 600
start = time.time()
if self.is_running():
if not self._wait_until_stopped(wait_seconds):
if dump_core and self.pid:
# Aborting is intended to generate a core dump
# so the reason the node didn't stop normally can be studied.
self.warning("{} is still running after {} seconds. Trying to generate coredump using kill({}, SIGQUIT)...".format(
self.name, wait_seconds, self.pid))
try:
os.kill(self.pid, signal.SIGQUIT)
except OSError:
pass
self._wait_until_stopped(300)
if self.is_running() and self.pid:
self.warning("{} is still running after {} seconds. Killing process using kill({}, SIGKILL)...".format(
self.name, wait_seconds, self.pid))
os.kill(self.pid, signal.SIGKILL)
self._wait_until_stopped(10)
while self.jmx_pid and time.time() - start < wait_seconds:
try:
os.kill(self.jmx_pid, 0)
time.sleep(1)
except OSError:
self.jmx_pid = None
pass
if self.jmx_pid:
try:
self.warning("{} scylla-jmx is still running. Killing process using kill({}, SIGKILL)...".format(
self.name, wait_seconds, self.jmx_pid))
os.kill(self.jmx_pid, signal.SIGKILL)
except OSError:
pass
if self.is_running():
raise NodeError(f"Problem stopping node {self.name}")
for node, mark in marks:
if node != self:
node.watch_log_for_death(self, from_mark=mark)
def stop(self, wait=True, wait_other_notice=False, other_nodes=None, gently=True, wait_seconds=None, marks=None):
"""
Stop the node.
- wait: if True (the default), wait for the Scylla process to be
really dead. Otherwise return after having sent the kill signal.
stop() will wait up to wait_seconds, by default 127 seconds
(or 600 in debug mode), for the Scylla process to stop gracefully.
After this wait, it will try to kill the node using SIGQUIT,
and if that failed, it will throw an
exception stating it couldn't stop the node.
- wait_other_notice: return only when the other live nodes of the
cluster have marked this node has dead.
- other_nodes: optional list of nodes to apply wait_other_notice on.
- marks: optional list of (node, mark) to call watch_log_for_death on.
- gently: Let Scylla and Scylla JMX clean up and shut down properly.
Otherwise do a 'kill -9' which shuts down faster.
"""
marks = marks or []
was_running = self.is_running()
if was_running:
if wait_other_notice:
if not other_nodes:
other_nodes = list(self.cluster.nodes.values())
if not marks:
marks = [(node, node.mark_log()) for node in
other_nodes if
node.is_live() and node is not self]
self.do_stop(gently=gently)
if wait or wait_other_notice:
self.wait_until_stopped(wait_seconds, marks, dump_core=gently)
return was_running
def import_config_files(self):
# TODO: override node - enable logging
self._create_directory()
self._update_config()
self.copy_config_files()
self.update_yaml()
self.__copy_logback_files()
def copy_config_files(self):
Node.copy_config_files(self)
conf_pattern = os.path.join(self.get_tools_java_dir(), 'conf', "jvm*.options")
for filename in glob.glob(conf_pattern):
if os.path.isfile(filename):
shutil.copy(filename, self.get_conf_dir())
def get_tools_java_dir(self):
return common.get_tools_java_dir(self.node_install_dir, self._relative_repos_root or '..')
def get_jmx_dir(self):
return common.get_jmx_dir(self.node_install_dir, self._relative_repos_root or '..')
def get_cqlsh_dir(self):
return os.path.join(self.node_install_dir, 'tools', 'cqlsh')
def __copy_logback_files(self):
shutil.copy(os.path.join(self.get_tools_java_dir(), 'conf', 'logback-tools.xml'),
os.path.join(self.get_conf_dir(), 'logback-tools.xml'))
def import_dse_config_files(self):
raise NotImplementedError('ScyllaNode.import_dse_config_files')
def copy_config_files_dse(self):
raise NotImplementedError('ScyllaNode.copy_config_files_dse')
def clean_runtime_file(self):
"""Remove cassandra.in.sh file that created runtime during cluster build """
cassandra_in_sh = os.path.join(self.get_node_cassandra_root(), BIN_DIR, CASSANDRA_SH)
if os.path.exists(cassandra_in_sh):
os.remove(cassandra_in_sh)
def hard_link_or_copy(self, src, dst, extra_perms=0, always_copy=False, replace=False):
def do_copy(src, dst, extra_perms=0):
shutil.copy(src, dst)
os.chmod(dst, os.stat(src).st_mode | extra_perms)
if always_copy:
return do_copy(src, dst, extra_perms)
if os.path.exists(dst) and replace:
os.remove(dst)
try:
os.link(src, dst)
except OSError as oserror:
if oserror.errno == errno.EXDEV or oserror.errno == errno.EMLINK:
do_copy(src, dst, extra_perms)
else:
raise RuntimeError(f"Unable to create hard link from {src} to {dst}: {oserror}")
def _copy_binaries(self, files, src_path, dest_path, exist_ok=False, replace=False, extra_perms=0):
os.makedirs(dest_path, exist_ok=exist_ok)
for name in files:
self.hard_link_or_copy(src=os.path.join(src_path, name),
dst=os.path.join(dest_path, name),
extra_perms=extra_perms,
replace=replace)
def import_bin_files(self, exist_ok=False, replace=False):
# selectively copying files to reduce risk of using unintended items
self._copy_binaries(files=[CASSANDRA_SH, 'nodetool'],
src_path=os.path.join(self.get_tools_java_dir(), BIN_DIR),
dest_path=os.path.join(self.get_path(), 'resources', 'cassandra', BIN_DIR),
exist_ok=exist_ok,
replace=replace
)
# selectively copying files to reduce risk of using unintended items
# Copy sstable tools
self._copy_binaries(files=['sstabledump', 'sstablelevelreset', 'sstablemetadata',
'sstablerepairedset', 'sstablesplit'],
src_path=os.path.join(self.get_tools_java_dir(), 'tools', BIN_DIR),
dest_path=os.path.join(self.get_path(), 'resources', 'cassandra', 'tools', BIN_DIR),
exist_ok=exist_ok,
replace=replace
)
# TODO: - currently no scripts only executable - copying exec
if self.is_scylla_reloc():
self._relative_repos_root = '../..'
self.hard_link_or_copy(src=os.path.join(self.node_install_dir, BIN_DIR, 'scylla'),