forked from riptano/ccm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.py
2306 lines (1950 loc) · 99.3 KB
/
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 __future__ import absolute_import, with_statement
import errno
import glob
import locale
import logging
import os
import psutil
import re
import shlex
import shutil
import signal
import stat
import subprocess
import sys
import time
import warnings
from collections import namedtuple
from datetime import datetime
from distutils.version import LooseVersion #pylint: disable=import-error, no-name-in-module
import yaml
from six import print_, string_types
from ccmlib import common, extension
from ccmlib.repository import setup
from six.moves import xrange
logger = logging.getLogger(__name__)
NODE_WAIT_TIMEOUT_IN_SECS = 90
class Status():
UNINITIALIZED = "UNINITIALIZED"
UP = "UP"
DOWN = "DOWN"
DECOMMISSIONED = "DECOMMISSIONED"
class NodeError(Exception):
def __init__(self, msg, process=None):
Exception.__init__(self, msg)
self.process = process
class TimeoutError(Exception):
def __init__(self, data):
Exception.__init__(self, str(data))
@staticmethod
def raise_if_passed(start, timeout, msg, node=None):
if start + timeout < time.time():
raise TimeoutError.create(start, timeout, msg, node)
@staticmethod
def create(start, timeout, msg, node=None):
tstamp = time.strftime("%d %b %Y %H:%M:%S", time.gmtime())
duration = round(time.time() - start, 2)
node_s = " [{}]".format(node) if node else ""
msg = "{tstamp}{nodes} after {d}/{t} seconds {msg}".format(
tstamp=tstamp, nodes=node_s, msg=msg, d=duration, t=timeout)
return TimeoutError(msg)
class ToolError(Exception):
def __init__(self, command, exit_status, stdout=None, stderr=None):
self.command = command
self.exit_status = exit_status
self.stdout = stdout
self.stderr = stderr
message = "Subprocess {} exited with non-zero status; exit status: {}".format(command, exit_status)
if stdout:
message += "; \nstdout: "
message += self.__decode(stdout)
if stderr:
message += "; \nstderr: "
message += self.__decode(stderr)
Exception.__init__(self, message)
def __decode(self, value):
if isinstance(value, bytes):
return bytes.decode(value, locale.getpreferredencoding(False))
return value
# Groups: 1 = cf, 2 = tmp or none, 3 = suffix (Compacted or Data.db)
_sstable_regexp = re.compile('((?P<keyspace>[^\s-]+)-(?P<cf>[^\s-]+)-)?(?P<tmp>tmp(link)?-)?(?P<version>[^\s-]+)-(?P<number>\d+)-(?P<format>([a-z]+)-)?(?P<suffix>[a-zA-Z]+)\.[a-zA-Z0-9]+$')
class Node(object):
"""
Provides interactions to a Cassandra node.
"""
def __init__(self,
name,
cluster,
auto_bootstrap,
thrift_interface,
storage_interface,
jmx_port,
remote_debug_port,
initial_token,
save=True,
binary_interface=None,
byteman_port='0',
environment_variables=None,
byteman_startup_script=None,
derived_cassandra_version=None):
"""
Create a new Node.
- name: the name for that node
- cluster: the cluster this node is part of
- auto_bootstrap: whether or not this node should be set for auto-bootstrap
- thrift_interface: the (host, port) tuple for thrift
- storage_interface: the (host, port) tuple for internal cluster communication
- jmx_port: the port for JMX to bind to
- remote_debug_port: the port for remote debugging
- initial_token: the token for this node. If None, use Cassandra token auto-assignment
- save: copy all data useful for this node to the right position. Leaving this true
is almost always the right choice.
"""
self.name = name
self.cluster = cluster
self.status = Status.UNINITIALIZED
self.auto_bootstrap = auto_bootstrap
self.network_interfaces = {'thrift': common.normalize_interface(thrift_interface),
'storage': common.normalize_interface(storage_interface),
'binary': common.normalize_interface(binary_interface)}
(self.ip_addr, _) = self.network_interfaces['thrift'] if thrift_interface else self.network_interfaces['binary']
self.jmx_port = jmx_port
self.remote_debug_port = remote_debug_port
self.byteman_port = byteman_port
self.byteman_startup_script = byteman_startup_script
self.initial_token = initial_token
self.pid = None
self.data_center = None
self.workloads = []
self._dse_config_options = {}
self.__config_options = {}
self._topology = [('default', 'dc1')]
self.__install_dir = None
self.__global_log_level = None
self.__classes_log_level = {}
self.__environment_variables = environment_variables or {}
self.__original_java_home = None
self.__conf_updated = False
if derived_cassandra_version:
self._cassandra_version = derived_cassandra_version
else:
try:
self._cassandra_version = common.get_version_from_build(self.get_install_dir(), cassandra=True)
except common.CCMError:
self._cassandra_version = self.cluster.cassandra_version()
if save:
self.import_config_files()
self.import_bin_files()
if common.is_win():
self.__clean_bat()
@staticmethod
def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
"""
node_path = os.path.join(path, name)
filename = os.path.join(node_path, 'node.conf')
with open(filename, 'r') as f:
data = yaml.safe_load(f)
try:
itf = data['interfaces']
initial_token = None
if 'initial_token' in data:
initial_token = data['initial_token']
cassandra_version = None
if 'cassandra_version' in data:
cassandra_version = LooseVersion(data['cassandra_version'])
remote_debug_port = 2000
if 'remote_debug_port' in data:
remote_debug_port = data['remote_debug_port']
binary_interface = None
if 'binary' in itf and itf['binary'] is not None:
binary_interface = tuple(itf['binary'])
thrift_interface = None
if 'thrift' in itf and itf['thrift'] is not None:
thrift_interface = tuple(itf['thrift'])
node = cluster.create_node(data['name'], data['auto_bootstrap'], thrift_interface, tuple(itf['storage']), data['jmx_port'], remote_debug_port, initial_token, save=False, binary_interface=binary_interface, byteman_port=data['byteman_port'], derived_cassandra_version=cassandra_version)
node.status = data['status']
if 'pid' in data:
node.pid = int(data['pid'])
if 'install_dir' in data:
node.__install_dir = data['install_dir']
if 'config_options' in data:
node.__config_options = data['config_options']
if 'dse_config_options' in data:
node._dse_config_options = data['dse_config_options']
if 'environment_variables' in data:
node.__environment_variables = data['environment_variables']
if 'data_center' in data:
node.data_center = data['data_center']
if 'workloads' in data:
node.workloads = data['workloads']
return node
except KeyError as k:
raise common.LoadError("Error Loading " + filename + ", missing property: " + str(k))
def get_path(self):
"""
Returns the path to this node top level directory (where config/data is stored)
"""
return os.path.join(self.cluster.get_path(), self.name)
def get_bin_dir(self):
"""
Returns the path to the directory where Cassandra scripts are located
"""
return os.path.join(self.get_path(), 'bin')
def get_tool(self, toolname):
return common.join_bin(self.get_install_dir(), 'bin', toolname)
def get_tool_args(self, toolname):
return [common.join_bin(self.get_install_dir(), 'bin', toolname)]
def get_env(self):
update_conf = not self.__conf_updated
if update_conf:
self.__conf_updated = True
env = common.make_cassandra_env(self.get_install_dir(), self.get_path(), update_conf)
env = common.update_java_version(jvm_version=None,
install_dir=self.get_install_dir(),
cassandra_version=self.cluster.cassandra_version(),
env=env,
info_message=self.name)
for (key, value) in self.__environment_variables.items():
env[key] = value
return env
def get_install_cassandra_root(self):
return self.get_install_dir()
def get_node_cassandra_root(self):
return 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 address_for_current_version_slashy(self):
"""
Returns the address formatted for the current version (InetAddress/InetAddressAndPort.toString)
"""
if self.get_cassandra_version() >= '4.0':
return "/{}".format(str(self.address_and_port()))
else:
return "/{}".format(str(self.address()));
def address_for_version(self, version):
"""
Returns the address formatted for the specified (InetAddress.getHostAddress or
InetAddressAndPort.getHostAddressAndPort)
"""
if version >= '4.0':
return self.address_and_port()
else:
return "{}".format(str(self.address()));
def address_for_current_version(self):
"""
Returns the address formatted for the current version.
"""
return self.address_for_version(self.get_cassandra_version())
def address(self):
"""
Returns the IP use by this node for internal communication
"""
return self.network_interfaces['storage'][0]
def address_and_port(self):
"""
Returns the IP used for internal communication along with ports
"""
address = self.network_interfaces['storage'][0]
port = self.network_interfaces['storage'][1]
if address.find(":") != -1:
return "[{}]:{}".format(address, port)
else:
return str(address) + ':' + str(port)
def get_install_dir(self):
"""
Returns the path to the cassandra source directory used by this node.
"""
if self.__install_dir is None:
return self.cluster.get_install_dir()
else:
common.validate_install_dir(self.__install_dir)
return self.__install_dir
def node_setup(self, version, verbose):
dir, v = setup(version, verbose=verbose)
return dir
def set_install_dir(self, install_dir=None, version=None, verbose=False):
"""
Sets the path to the cassandra source directory for use by this node.
"""
if version is None:
self.__install_dir = install_dir
if install_dir is not None:
common.validate_install_dir(install_dir)
else:
self.__install_dir = self.node_setup(version, verbose=verbose)
self._cassandra_version = common.get_version_from_build(self.__install_dir, cassandra=True)
if self.get_base_cassandra_version() >= 4.0:
self.network_interfaces['thrift'] = None
self.import_config_files()
self.import_bin_files()
self.__conf_updated = False
if self.get_cassandra_version() >= '4':
self.set_configuration_options(values={'start_rpc': None}, delete_empty=True, delete_always=True)
self.set_configuration_options(values={'rpc_port': None}, delete_empty=True, delete_always=True)
else:
self.set_configuration_options(common.CCM_40_YAML_OPTIONS, delete_empty=True, delete_always=True)
return self
def set_workloads(self, workloads):
raise common.ArgumentError("Cannot set workloads on a cassandra node")
def get_cassandra_version(self):
return self._cassandra_version
def get_base_cassandra_version(self):
version = self.get_cassandra_version()
return float('.'.join(re.split('\.|-',version.vstring)[:2]))
def set_configuration_options(self, values=None, delete_empty=False, delete_always=False):
"""
Set Cassandra configuration options.
ex:
node.set_configuration_options(values={
'hinted_handoff_enabled' : True,
'concurrent_writes' : 64,
})
"""
if (not hasattr(self,'__config_options') and not hasattr(self,'_Node__config_options')) or self.__config_options is None:
self.__config_options = {}
if values is not None:
self.__config_options = common.merge_configuration(self.__config_options, values, delete_empty=delete_empty, delete_always=delete_always)
self.import_config_files()
def set_environment_variable(self, key, value):
self.__environment_variables[key] = value
self.import_config_files()
def set_batch_commitlog(self, enabled=False):
"""
The batch_commitlog option gives an easier way to switch to batch
commitlog (since it requires setting 2 options and unsetting one).
"""
if enabled:
values = {
"commitlog_sync": "batch",
"commitlog_sync_batch_window_in_ms": 5,
"commitlog_sync_period_in_ms": None
}
else:
values = {
"commitlog_sync": "periodic",
"commitlog_sync_batch_window_in_ms": None,
"commitlog_sync_period_in_ms": 10000
}
self.set_configuration_options(values)
def set_dse_configuration_options(self, values=None):
pass
def show(self, only_status=False, show_cluster=True):
"""
Print infos on this node configuration.
"""
self.__update_status()
indent = ''.join([" " for i in xrange(0, len(self.name) + 2)])
print_("{}: {}".format(self.name, self.__get_status_string()))
if not only_status:
if show_cluster:
print_("{}{}={}".format(indent, 'cluster', self.cluster.name))
print_("{}{}={}".format(indent, 'auto_bootstrap', self.auto_bootstrap))
if self.network_interfaces['thrift'] is not None:
print_("{}{}={}".format(indent, 'thrift', self.network_interfaces['thrift']))
if self.network_interfaces['binary'] is not None:
print_("{}{}={}".format(indent, 'binary', self.network_interfaces['binary']))
print_("{}{}={}".format(indent, 'storage', self.network_interfaces['storage']))
print_("{}{}={}".format(indent, 'jmx_port', self.jmx_port))
print_("{}{}={}".format(indent, 'remote_debug_port', self.remote_debug_port))
print_("{}{}={}".format(indent, 'byteman_port', self.byteman_port))
print_("{}{}={}".format(indent, 'initial_token', self.initial_token))
if self.pid:
print_("{}{}={}".format(indent, 'pid', self.pid))
def is_running(self):
"""
Return true if the node is running
"""
self.__update_status()
return self.status == Status.UP or self.status == Status.DECOMMISSIONED
def is_live(self):
"""
Return true if the node is live (it's run and is not decommissioned).
"""
self.__update_status()
return self.status == Status.UP
def log_directory(self):
return os.path.join(self.get_path(), 'logs')
def logfilename(self):
"""
Return the path to the current Cassandra log of this node.
"""
return os.path.join(self.log_directory(), 'system.log')
def debuglogfilename(self):
return os.path.join(self.log_directory(), 'debug.log')
def gclogfilename(self):
return os.path.join(self.log_directory(), 'gc.log.0.current')
def compactionlogfilename(self):
return os.path.join(self.log_directory(), 'compaction.log')
def envfilename(self):
return os.path.join(
self.get_conf_dir(),
common.CASSANDRA_WIN_ENV if common.is_win() else common.CASSANDRA_ENV
)
def grep_log(self, expr, filename='system.log', from_mark=None):
"""
Returns a list of lines matching the regular expression in parameter
in the Cassandra log of this node
"""
matchings = []
pattern = re.compile(expr)
with open(os.path.join(self.log_directory(), filename)) as f:
if from_mark:
f.seek(from_mark)
for line in f:
m = pattern.search(line)
if m:
matchings.append((line, m))
return matchings
def grep_log_for_errors(self, filename='system.log'):
"""
Returns a list of errors with stack traces
in the Cassandra log of this node
"""
return self.grep_log_for_errors_from(seek_start=getattr(self, 'error_mark', 0))
def grep_log_for_errors_from(self, filename='system.log', seek_start=0):
with open(os.path.join(self.log_directory(), filename)) as f:
f.seek(seek_start)
return _grep_log_for_errors(f.read())
def mark_log_for_errors(self, filename='system.log'):
"""
Ignore errors behind this point when calling
node.grep_log_for_errors()
"""
self.error_mark = self.mark_log(filename)
def mark_log(self, filename='system.log'):
"""
Returns "a mark" to the current position of this node Cassandra log.
This is for use with the from_mark parameter of watch_log_for_* methods,
allowing to watch the log from the position when this method was called.
"""
log_file = os.path.join(self.log_directory(), filename)
if not os.path.exists(log_file):
return 0
with open(log_file) as f:
f.seek(0, os.SEEK_END)
return f.tell()
def print_process_output(self, name, proc, verbose=False):
# If stderr_file exists on the process, we opted to
# store stderr in a separate temporary file, consume that.
if hasattr(proc, 'stderr_file') and proc.stderr_file is not None:
proc.stderr_file.seek(0)
stderr = proc.stderr_file.read()
else:
try:
stderr = proc.communicate()[1]
except ValueError:
stderr = ''
if len(stderr) > 1:
print_("[{} ERROR] {}".format(name, stderr.strip()))
# This will return when exprs are found or it timeouts
def watch_log_for(self, exprs, from_mark=None, timeout=600,
process=None, verbose=False, filename='system.log',
error_on_pid_terminated=False):
"""
Watch the log until one or more (regular) expressions are found or timeouts (a
TimeoutError is then raised). On successful completion, a list of pair (line matched,
match object) is returned.
Will raise NodeError if error_on_pit_terminated is True and C* pid is not running.
"""
start = time.time()
tofind = [exprs] if isinstance(exprs, string_types) else exprs
tofind = [re.compile(e) for e in tofind]
matchings = []
reads = ""
if len(tofind) == 0:
return None
log_file = os.path.join(self.log_directory(), filename)
output_read = False
while not os.path.exists(log_file):
time.sleep(.5)
TimeoutError.raise_if_passed(start=start, timeout=timeout, node=self.name,
msg="Timed out waiting for {} to be created.".format(log_file))
if process and not output_read:
process.poll()
if process.returncode is not None:
self.print_process_output(self.name, process, verbose)
output_read = True
if process.returncode != 0:
raise RuntimeError() # Shouldn't reuse RuntimeError but I'm lazy
with open(log_file) as f:
if from_mark:
f.seek(from_mark)
while True:
# First, if we have a process to check, then check it.
# Skip on Windows - stdout/stderr is cassandra.bat
if not common.is_win() and not output_read:
if process:
process.poll()
if process.returncode is not None:
self.print_process_output(self.name, process, verbose)
output_read = True
if process.returncode != 0:
raise RuntimeError() # Shouldn't reuse RuntimeError but I'm lazy
line = f.readline()
if line:
reads = reads + line
for e in tofind:
m = e.search(line)
if m:
matchings.append((line, m))
tofind.remove(e)
if len(tofind) == 0:
return matchings[0] if isinstance(exprs, string_types) else matchings
else:
# wait for the situation to clarify, either stop or just a pause in log production
time.sleep(1)
if error_on_pid_terminated:
self.raise_node_error_if_cassandra_process_is_terminated()
TimeoutError.raise_if_passed(start=start, timeout=timeout, node=self.name,
msg="Missing: {exprs} not found in {f}:\nTail: {tail}".format(
exprs=[e.pattern for e in tofind], f=filename, tail=reads[:50]))
# Checking "process" is tricky, as it may be itself terminated e.g. after "verbose"
# or if there is some race condition between log checking and start process finish
# so if the "error_on_pid_terminated" is requested we will give it a chance
# and will not check parent process termination
if process and not error_on_pid_terminated:
if common.is_win():
if not self.is_running():
return None
else:
process.poll()
if process.returncode == 0:
common.debug("{pid} or its child process terminated. watch_for_logs() for {l} will not continue.".format(
pid=process.pid, l=[e.pattern for e in tofind]))
return None
def watch_log_for_no_errors(self, exprs, from_mark=None, timeout=600, process=None, verbose=False, filename='system.log'):
"""
Watch the log until one or more (regular) expressions are found or timeouts (a
TimeoutError is then raised). On successful completion, a list of pair (line matched,
match object) is returned.
This method is different from watch_log_for as it will raise a AssertionError if the
log contain an error; this assertion will contain the errors found in the log.
"""
start = time.time()
tofind = [exprs] if isinstance(exprs, string_types) else exprs
tofind = [re.compile(e) for e in tofind]
seek_start=0
if from_mark:
seek_start = from_mark
while True:
TimeoutError.raise_if_passed(start=start, timeout=timeout, node=self.name,
msg="Missing: {exprs} not found in {f}".format(
exprs=[e.pattern for e in tofind], f=filename))
try:
# process is bin/cassandra so choosing to ignore this argument to avoid early termination
return self.watch_log_for(tofind, from_mark=from_mark, timeout=5, verbose=verbose, filename=filename)
except TimeoutError:
logger.debug("waited 5s watching for '{}' but was not found; checking for errors".format(tofind))
# since the api doesn't return the mark read it isn't thread safe to use mark
# as the length of the file can change between calls which may mean we skip over
# errors; to avoid this keep reading the whole file over and over again...
# unless a explicit mark is given to the method, will read from that offset
errors = self.grep_log_for_errors_from(filename=filename, seek_start=seek_start)
if errors:
msg = "Errors were found in the logs while watching for '{}'; attempting to fail the test".format(tofind)
logger.debug(msg)
raise AssertionError("{}:\n".format(msg) + '\n\n'.join(['\n'.join(msg) for msg in errors]))
def watch_log_for_death(self, nodes, from_mark=None, timeout=600, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked dead. This method returns nothing but throw a
TimeoutError if all the requested node have not been found to be
marked dead before timeout sec.
A mark as returned by mark_log() can be used as the from_mark
parameter to start watching the log from a given position. Otherwise
the log is watched from the beginning.
"""
tofind = nodes if isinstance(nodes, list) else [nodes]
tofind = ["%s is now [dead|DOWN]" % node.address_for_version(self.get_cassandra_version()) for node in tofind]
self.watch_log_for(tofind, from_mark=from_mark, timeout=timeout, filename=filename)
def watch_log_for_alive(self, nodes, from_mark=None, timeout=120, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
"""
tofind = nodes if isinstance(nodes, list) else [nodes]
tofind = ["%s.* now UP" % node.address_for_version(self.get_cassandra_version()) for node in tofind]
self.watch_log_for(tofind, from_mark=from_mark, timeout=timeout, filename=filename)
def raise_node_error_if_cassandra_process_is_terminated(self):
if not self._is_pid_running():
msg = "C* process with {pid} is terminated".format(pid=self.pid)
common.debug(msg)
raise NodeError(msg)
def wait_for_binary_interface(self, **kwargs):
"""
Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after given timeout (default NODE_WAIT_TIMEOUT_IN_SECS) in seconds.
Raises NodeError if C* process terminates during start.
Raises TimeoutError if log message for "starting listening" is not found in logs in given timeout.
"""
timeout = kwargs.get('timeout', NODE_WAIT_TIMEOUT_IN_SECS)
kwargs['timeout'] = timeout
if self.pid:
kwargs['error_on_pid_terminated'] = True
if self.cluster.version() >= '1.2':
self.watch_log_for("Starting listening for CQL clients", **kwargs)
binary_itf = self.network_interfaces['binary']
if not common.check_socket_listening(binary_itf, timeout=timeout):
warnings.warn("Binary interface %s:%s is not listening after %s seconds, node may have failed to start."
% (binary_itf[0], binary_itf[1], timeout))
def wait_for_thrift_interface(self, **kwargs):
"""
Waits for the Thrift interface to be listening.
Emits a warning if not listening after given timeout (default NODE_WAIT_TIMEOUT_IN_SECS) in seconds.
"""
if self.cluster.version() >= '4':
return
timeout = kwargs.get('timeout', NODE_WAIT_TIMEOUT_IN_SECS)
kwargs['timeout'] = timeout
self.watch_log_for("Listening for thrift clients...", **kwargs)
thrift_itf = self.network_interfaces['thrift']
if not common.check_socket_listening(thrift_itf, timeout=timeout):
warnings.warn(
"Thrift interface {}:{} is not listening after {} seconds, node may have failed to start.".format(
thrift_itf[0], thrift_itf[1], timeout))
def get_launch_bin(self):
cdir = self.get_install_dir()
launch_bin = common.join_bin(cdir, 'bin', 'cassandra')
# Copy back the cassandra scripts since profiling may have modified it the previous time
shutil.copy(launch_bin, self.get_bin_dir())
return common.join_bin(self.get_path(), 'bin', 'cassandra')
def add_custom_launch_arguments(self, args):
pass
def start(self,
join_ring=True,
no_wait=False,
verbose=False,
update_pid=True,
wait_other_notice=True,
replace_token=None,
replace_address=None,
jvm_args=None,
wait_for_binary_proto=False,
profile_options=None,
use_jna=False,
quiet_start=False,
allow_root=False,
set_migration_task=True,
jvm_version=None):
"""
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 truthy, this method returns only when all other live node of the cluster
have marked this node UP. if an integer, sets the timeout for how long to wait
- 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 = []
if set_migration_task and self.cluster.cassandra_version() >= '3.0.1':
jvm_args += ['-Dcassandra.migration_task_wait_in_seconds={}'.format(len(self.cluster.nodes) * 2)]
# Validate Windows env
if common.is_modern_windows_install(self.cluster.version()) and not common.is_ps_unrestricted():
raise NodeError("PS Execution Policy must be unrestricted when running C* 2.1+")
if not common.is_win() and quiet_start:
common.warning("Tried to set Windows quiet start behavior, but we're not running on Windows.")
if self.is_running():
raise NodeError("{} is already running".format(self.name))
for itf in list(self.network_interfaces.values()):
if itf is not None and replace_address is None:
common.assert_socket_available(itf)
if wait_other_notice:
marks = [(node, node.mark_log()) for node in list(self.cluster.nodes.values()) if node.is_live()]
else:
marks = []
self.mark = self.mark_log()
launch_bin = self.get_launch_bin()
# If Windows, change entries in .bat file to split conf from binaries
if common.is_win():
self.__clean_bat()
if profile_options is not None:
config = common.get_config()
if 'yourkit_agent' not in config:
raise NodeError("Cannot enable profile. You need to set 'yourkit_agent' to the path of your agent in a ~/.ccm/config")
cmd = '-agentpath:{}'.format(config['yourkit_agent'])
if 'options' in profile_options:
cmd = cmd + '=' + profile_options['options']
print_(cmd)
# Yes, it's fragile as shit
pattern = r'cassandra_parms="-Dlog4j.configuration=log4j-server.properties -Dlog4j.defaultInitOverride=true'
common.replace_in_file(launch_bin, pattern, ' ' + pattern + ' ' + cmd + '"')
os.chmod(launch_bin, os.stat(launch_bin).st_mode | stat.S_IEXEC)
env = self.get_env()
extension.append_to_server_env(self, env)
if common.is_win():
self._clean_win_jmx()
pidfile = os.path.join(self.get_path(), 'cassandra.pid')
args = [launch_bin]
self.add_custom_launch_arguments(args)
args = args + ['-p', pidfile, '-Dcassandra.join_ring=%s' % str(join_ring)]
args.append('-Dcassandra.logdir=%s' % os.path.join(self.get_path(), 'logs'))
if replace_token is not None:
args.append('-Dcassandra.replace_token=%s' % str(replace_token))
if replace_address is not None:
args.append('-Dcassandra.replace_address=%s' % str(replace_address))
if use_jna is False:
args.append('-Dcassandra.boot_without_jna=true')
if allow_root:
args.append('-R')
env['JVM_EXTRA_OPTS'] = env.get('JVM_EXTRA_OPTS', "") + " " + " ".join(jvm_args)
# Upgrade scenarios may want to test upgrades to a specific Java version. In case a prior C* version
# requires a lower Java version, we would keep its JAVA_HOME in self.__environment_variables and therefore
# prevent using the "intended" Java version for the C* version to upgrade to.
if not self.__original_java_home:
# Save the "original" JAVA_HOME + PATH to restore it.
self.__original_java_home = os.environ['JAVA_HOME']
else:
# Restore the "original" JAVA_HOME + PATH to restore it.
env['JAVA_HOME'] = self.__original_java_home
env = common.update_java_version(jvm_version=jvm_version,
install_dir=self.get_install_dir(),
cassandra_version=self.get_cassandra_version(),
env=env,
info_message=self.name)
# Need to update the node's environment for nodetool and other tools.
# (e.g. the host's JAVA_HOME points to Java 11, but the node's software is only for Java 8)
for k in 'JAVA_HOME', 'PATH':
self.__environment_variables[k] = env[k]
common.info("Starting {} with JAVA_HOME={} java_version={} cassandra_version={}, install_dir={}"
.format(self.name, env['JAVA_HOME'], common.get_jdk_version_int(),
self.get_cassandra_version(), self.get_install_dir()))
# In case we are restarting a node
# we risk reading the old cassandra.pid file
self._delete_old_pid()
# Always write the stdout+stderr of the launched process to log files to make finding startup issues easier.
start_time = time.time()
stdout_sink = open(os.path.join(self.log_directory(), 'startup-{}-stdout.log'.format(start_time)), "w+")
stderr_sink = open(os.path.join(self.log_directory(), 'startup-{}-stderr.log'.format(start_time)), "w+")
if common.is_win():
# clean up any old dirty_pid files from prior runs
dirty_pid_path = os.path.join(self.get_path() + "dirty_pid.tmp")
if (os.path.isfile(dirty_pid_path)):
os.remove(dirty_pid_path)
if quiet_start and self.cluster.version() >= '2.2.4':
args.append('-q')
process = subprocess.Popen(args, cwd=self.get_bin_dir(), env=env, stdout=stdout_sink, stderr=stderr_sink)
else:
process = subprocess.Popen(args, env=env, stdout=stdout_sink, stderr=stderr_sink)
process.stderr_file = stderr_sink
if verbose:
common.debug("verbose mode: waiting for the start process out/err (and termination)")
stdout, stderr = process.communicate()
print_(str(stdout))
print_(str(stderr))
# Our modified batch file writes a dirty output with more than just the pid - clean it to get in parity
# with *nix operation here.
if common.is_win():
self.__clean_win_pid()
self._update_pid(process)
print_("Started: {0} with pid: {1}".format(self.name, self.pid), file=sys.stderr, flush=True)
if update_pid or wait_for_binary_proto:
# at this moment we should have PID and it should be running...
if not self._wait_for_running(process, timeout_s=7):
raise NodeError("Node {n} is not running".format(n=self.name), process)
# if requested wait for other nodes to observe this one (via gossip)
if common.is_int_not_bool(wait_other_notice):
for node, mark in marks:
node.watch_log_for_alive(self, from_mark=mark, timeout=wait_other_notice)
elif wait_other_notice:
for node, mark in marks:
node.watch_log_for_alive(self, from_mark=mark)
# if requested wait for binary protocol to start
if common.is_int_not_bool(wait_for_binary_proto):
self.wait_for_binary_interface(from_mark=self.mark, timeout=wait_for_binary_proto)
elif wait_for_binary_proto:
self.wait_for_binary_interface(from_mark=self.mark)
return process
def _wait_for_running(self, process, timeout_s):
deadline = time.time() + timeout_s
while time.time() < deadline:
if self.is_running():
return True
time.sleep(0.5)
self._update_pid(process)
return self.is_running()
def stop(self, wait=True, wait_other_notice=False, signal_event=signal.SIGTERM, **kwargs):
"""
Stop the node.
- wait: if True (the default), wait for the Cassandra process to be
really dead. Otherwise return after having sent the kill signal.
- wait_other_notice: return only when the other live nodes of the
cluster have marked this node has dead.
- signal_event: Signal event to send to Cassandra; default is to
let Cassandra clean up and shut down properly (SIGTERM [15])
- Optional:
+ gently: Let Cassandra clean up and shut down properly; unless
false perform a 'kill -9' which shuts down faster.
"""
if self.is_running():
if wait_other_notice:
marks = [(node, node.mark_log()) for node in list(self.cluster.nodes.values()) if node.is_live() and node is not self]
if common.is_win():
# Just taskkill the instance, don't bother trying to shut it down gracefully.
# Node recovery should prevent data loss from hard shutdown.
# We have recurring issues with nodes not stopping / releasing files in the CI
# environment so it makes more sense just to murder it hard since there's
# really little downside.
# We want the node to flush its data before shutdown as some tests rely on small writes being present.
# The default Periodic sync at 10 ms may not have flushed data yet, causing tests to fail.
# This is not a hard requirement, however, so we swallow any exceptions this may throw and kill anyway.
if signal_event is signal.SIGTERM:
try:
self.flush()
except:
common.warning("Failed to flush node: {0} on shutdown.".format(self.name))
pass
os.system("taskkill /F /PID " + str(self.pid))
if self._find_pid_on_windows():
common.warning("Failed to terminate node: {0} with pid: {1}".format(self.name, self.pid))
else:
# Determine if the signal event should be updated to keep API compatibility
if 'gently' in kwargs and kwargs['gently'] is False:
signal_event = signal.SIGKILL
os.kill(self.pid, signal_event)
if wait_other_notice:
for node, mark in marks:
node.watch_log_for_death(self, from_mark=mark)
else:
time.sleep(.1)
still_running = self.is_running()
if still_running and wait:
wait_time_sec = 1
for i in xrange(0, 7):
# we'll double the wait time each try and cassandra should
# not take more than 1 minute to shutdown
time.sleep(wait_time_sec)
if not self.is_running():
return True
wait_time_sec = wait_time_sec * 2
raise NodeError("Problem stopping node %s" % self.name)
else:
return True
else:
return False
def wait_for_compactions(self, timeout=120):
"""
Wait for all compactions to finish on this node.
"""
pattern = re.compile("pending tasks: 0")
start = time.time()
while time.time() - start < timeout:
output, err, rc = self.nodetool("compactionstats")
if pattern.search(output):
return
time.sleep(1)
raise TimeoutError.create(start=start, timeout=timeout,
msg="Compactions did not finish in {} seconds".format(timeout),
node=self.name)
def nodetool_process(self, cmd):
env = self.get_env()
nodetool = self.get_tool('nodetool')
args = [nodetool, '-h', 'localhost', '-p', str(self.jmx_port)]
args += shlex.split(cmd)
return subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)