-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathnebula_service.py
738 lines (649 loc) · 26.4 KB
/
nebula_service.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
# --coding:utf-8--
#
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License.
import os
import subprocess
import time
import random
import shutil
import socket
import glob
import signal
import copy
import fcntl
import logging
from pathlib import Path
from contextlib import closing
from tests.common.constants import TMP_DIR
from tests.common.utils import get_ssl_config
from nebula3.gclient.net import ConnectionPool
from nebula3.Config import Config
NEBULA_START_COMMAND_FORMAT = "bin/nebula-{} --flagfile conf/nebula-{}.conf {}"
class NebulaProcess(object):
def __init__(self, name, ports, suffix_index=0, params=None, is_standalone=False):
self.is_sa = is_standalone
if params is None:
params = {}
if is_standalone == False:
assert len(ports) == 4, 'should have 4 ports but have {}'.format(len(ports))
self.name = name
self.tcp_port, self.tcp_internal_port, self.http_port, self.https_port = ports
else:
assert len(ports) == 12, 'should have 12 ports but have {}'.format(len(ports))
self.name = name
self.tcp_port, self.tcp_internal_port, self.http_port, self.https_port = ports[0:4]
self.meta_port, self.meta_tcp_internal_port, self.meta_http_port, self.meta_https_port = ports[4:8]
self.storage_port, self.storage_tcp_internal_port, self.storage_http_port, self.storage_https_port = ports[8:12]
if name == "listener":
self.binary_name = "storaged"
self.conf_name = "storaged-listener"
else:
self.binary_name = name
self.conf_name = name
self.suffix_index = suffix_index
self.params = params
self.host = '127.0.0.1'
self.pid = None
def update_param(self, params):
self.params.update(params)
def update_meta_server_addrs(self, address):
self.update_param({'meta_server_addrs': address})
def _format_nebula_command(self):
if self.is_sa == False:
process_params = {
'log_dir': 'logs{}'.format(self.suffix_index),
'pid_file': 'pids{}/nebula-{}.pid'.format(self.suffix_index, self.binary_name),
'port': self.tcp_port,
'ws_http_port': self.http_port,
}
else:
process_params = {
'log_dir': 'logs{}'.format(self.suffix_index),
'pid_file': 'pids{}/nebula-{}.pid'.format(self.suffix_index, self.binary_name),
'port': self.tcp_port,
'ws_http_port': self.http_port,
'meta_port': self.meta_port,
'ws_meta_http_port': self.meta_http_port,
'storage_port': self.storage_port,
'ws_storage_http_port': self.storage_http_port,
}
# data path
if self.binary_name.upper() != 'GRAPHD':
process_params['data_path'] = 'data{}/{}'.format(
self.suffix_index, self.binary_name
)
process_params.update(self.params)
cmd = [
'bin/nebula-{}'.format(self.binary_name),
'--flagfile',
'conf/nebula-{}.conf'.format(self.conf_name),
] + ['--{}={}'.format(key, value) for key, value in process_params.items()]
return " ".join(cmd)
def start(self):
cmd = self._format_nebula_command()
print("exec: " + cmd)
p = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE)
p.wait()
if p.returncode != 0:
print("error: " + bytes.decode(p.communicate()[0]))
self.pid = p.pid
def kill(self, sig):
if not self.is_alive():
return
try:
os.kill(self.pid, sig)
except OSError as err:
print("stop nebula-{} {} failed: {}".format(self.name, self.pid, str(err)))
def is_alive(self):
if self.pid is None:
return False
process = subprocess.Popen(
['ps', '-eo', 'pid,args'], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout = process.communicate()
for line in bytes.decode(stdout[0]).splitlines():
p = line.lstrip().split(' ', 1)[0]
if str(p) == str(self.pid):
return True
return False
class NebulaService(object):
def __init__(
self,
build_dir,
src_dir,
metad_num=1,
storaged_num=1,
graphd_num=1,
listener_num=1,
ca_signed=False,
debug_log=True,
use_standalone=False,
query_concurrently=False,
**kwargs,
):
assert graphd_num > 0 and metad_num > 0 and storaged_num > 0 and listener_num >= 0
self.build_dir = str(build_dir)
self.src_dir = str(src_dir)
self.work_dir = os.path.join(
self.build_dir,
'server_' + time.strftime('%Y-%m-%dT%H-%M-%S', time.localtime()),
)
self.pids = {}
self.metad_num, self.storaged_num, self.graphd_num, self.listener_num = (
metad_num,
storaged_num,
graphd_num,
listener_num,
)
self.metad_processes, self.storaged_processes, self.graphd_processes, self.listener_processes = (
[],
[],
[],
[],
)
self.all_processes = []
self.all_ports = []
self.metad_param, self.storaged_param, self.graphd_param, self.listener_param = {}, {}, {}, {}
self.storaged_port = 0
self.graphd_port = 0
self.listener_port = 0
self.ca_signed = ca_signed
self.is_graph_ssl = (
kwargs.get("enable_graph_ssl", "false").upper() == "TRUE"
or kwargs.get("enable_ssl", "false").upper() == "TRUE"
)
self.debug_log = debug_log
self.ports_per_process = 4
self.lock_file = os.path.join(TMP_DIR, "cluster_port.lock")
self.delimiter = "\n"
self.query_concurrently = query_concurrently
if use_standalone == False:
self._make_params(**kwargs)
self.init_process()
else:
self._make_sa_params(**kwargs)
self.init_standalone()
def init_standalone(self):
process_count = self.metad_num + self.storaged_num + self.graphd_num + self.listener_num
ports_count = process_count * self.ports_per_process
self.all_ports = self._find_free_port(ports_count)
print(self.all_ports)
sa_ports_count= self.metad_num + self.storaged_num + self.graphd_num
index = 0
standalone = NebulaProcess(
"standalone",
self.all_ports[index: index + sa_ports_count],
index,
self.graphd_param,
is_standalone=True
)
index = index + 1
listener = NebulaProcess(
"listener",
self.all_ports[index: index + self.ports_per_process],
0,
self.listener_param
)
self.graphd_processes.append(standalone)
self.listener_processes.append(listener)
self.all_processes = (
self.graphd_processes + self.listener_processes
)
# update meta address
meta_server_addrs = ','.join(
[
'{}:{}'.format(process.host, process.meta_port)
for process in self.graphd_processes
]
)
for p in self.all_processes:
p.update_meta_server_addrs(meta_server_addrs)
def init_process(self):
process_count = self.metad_num + self.storaged_num + self.graphd_num + self.listener_num
ports_count = process_count * self.ports_per_process
self.all_ports = self._find_free_port(ports_count)
index = 0
for suffix_index in range(self.metad_num):
metad = NebulaProcess(
"metad",
self.all_ports[index: index + self.ports_per_process],
suffix_index,
self.metad_param,
)
self.metad_processes.append(metad)
index += self.ports_per_process
for suffix_index in range(self.storaged_num):
storaged = NebulaProcess(
"storaged",
self.all_ports[index: index + self.ports_per_process],
suffix_index,
self.storaged_param,
)
self.storaged_processes.append(storaged)
index += self.ports_per_process
if suffix_index == 0:
self.storaged_port = self.all_ports[0]
for suffix_index in range(self.graphd_num):
graphd = NebulaProcess(
"graphd",
self.all_ports[index: index + self.ports_per_process],
suffix_index,
self.graphd_param,
)
self.graphd_processes.append(graphd)
index += self.ports_per_process
if suffix_index == 0:
self.graphd_port = self.all_ports[0]
for suffix_index in range(self.storaged_num, self.storaged_num+self.listener_num):
listener = NebulaProcess(
"listener",
self.all_ports[index: index + self.ports_per_process],
suffix_index,
self.listener_param
)
self.listener_processes.append(listener)
index += self.ports_per_process
if suffix_index == 0:
self.listener_port = self.all_ports[0]
self.all_processes = (
self.metad_processes + self.storaged_processes + self.graphd_processes + self.listener_processes
)
# update meta address
meta_server_addrs = ','.join(
[
'{}:{}'.format(process.host, process.tcp_port)
for process in self.metad_processes
]
)
for p in self.all_processes:
p.update_meta_server_addrs(meta_server_addrs)
def _make_params(self, **kwargs):
# common params for meta/storage/graph
_params = {
'heartbeat_interval_secs': 1,
'expired_time_factor': 60,
}
if self.ca_signed:
_params['cert_path'] = 'share/resources/test.derive.crt'
_params['key_path'] = 'share/resources/test.derive.key'
_params['ca_path'] = 'share/resources/test.ca.pem'
else:
_params['cert_path'] = 'share/resources/test.ca.pem'
_params['key_path'] = 'share/resources/test.ca.key'
_params['password_path'] = 'share/resources/test.ca.password'
if self.debug_log:
_params['v'] = '4'
# params for graph only
self.graphd_param = copy.copy(_params)
self.graphd_param['local_config'] = 'false'
self.graphd_param['enable_authorize'] = 'true'
self.graphd_param['system_memory_high_watermark_ratio'] = '0.95'
self.graphd_param['num_rows_to_check_memory'] = '4'
self.graphd_param['session_reclaim_interval_secs'] = '2'
# Login retry
self.graphd_param['failed_login_attempts'] = '5'
self.graphd_param['password_lock_time_in_secs'] = '10'
# expression depth limit
self.graphd_param['max_expression_depth'] = '128'
if self.query_concurrently:
self.graphd_param['max_job_size'] = '4'
# params for storage only
self.storaged_param = copy.copy(_params)
if self.query_concurrently:
self.storaged_param["query_concurrently"] = "true"
self.storaged_param['local_config'] = 'false'
self.storaged_param['raft_heartbeat_interval_secs'] = '30'
self.storaged_param['skip_wait_in_rate_limiter'] = 'true'
# params for listener only
self.listener_param = copy.copy(self.storaged_param)
# params for meta only
self.metad_param = copy.copy(_params)
self.metad_param["default_parts_num"] = 1
for p in [self.metad_param, self.storaged_param, self.graphd_param, self.listener_param]:
p.update(kwargs)
def _make_sa_params(self, **kwargs):
_params = {
'heartbeat_interval_secs': 1,
'expired_time_factor': 60,
}
if self.ca_signed:
_params['cert_path'] = 'share/resources/test.derive.crt'
_params['key_path'] = 'share/resources/test.derive.key'
_params['ca_path'] = 'share/resources/test.ca.pem'
else:
_params['cert_path'] = 'share/resources/test.ca.pem'
_params['key_path'] = 'share/resources/test.ca.key'
_params['password_path'] = 'share/resources/test.ca.password'
if self.debug_log:
_params['v'] = '4'
self.graphd_param = copy.copy(_params)
self.graphd_param['local_config'] = 'false'
self.graphd_param['enable_authorize'] = 'true'
self.graphd_param['system_memory_high_watermark_ratio'] = '0.95'
self.graphd_param['num_rows_to_check_memory'] = '4'
self.graphd_param['session_reclaim_interval_secs'] = '2'
# Login retry
self.graphd_param['failed_login_attempts'] = '5'
self.graphd_param['password_lock_time_in_secs'] = '10'
self.graphd_param['raft_heartbeat_interval_secs'] = '30'
self.graphd_param['skip_wait_in_rate_limiter'] = 'true'
self.graphd_param['add_local_host'] = 'false'
if self.query_concurrently:
self.graphd_param['max_job_size'] = '4'
self.graphd_param["default_parts_num"] = 1
for p in [self.metad_param, self.storaged_param, self.graphd_param]:
p.update(kwargs)
def set_work_dir(self, work_dir):
self.work_dir = work_dir
def _copy_nebula_conf(self):
bin_path = self.build_dir + '/bin/'
conf_path = self.src_dir + '/conf/'
for item in ['nebula-graphd', 'nebula-storaged', 'nebula-metad']:
shutil.copy(bin_path + item, self.work_dir + '/bin/')
shutil.copy(
conf_path + '{}.conf.default'.format(item),
self.work_dir + '/conf/{}.conf'.format(item),
)
shutil.copy(conf_path+'nebula-storaged-listener.conf.default', self.work_dir+'/conf/nebula-storaged-listener.conf')
resources_dir = self.work_dir + '/share/resources/'
os.makedirs(resources_dir)
# timezone file
shutil.copy(
self.build_dir + '/../resources/date_time_zonespec.csv', resources_dir
)
shutil.copy(self.build_dir + '/../resources/gflags.json', resources_dir)
# cert files
shutil.copy(self.src_dir + '/tests/cert/test.ca.key', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.ca.pem', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.ca.password', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.derive.key', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.derive.crt', resources_dir)
def _copy_standalone_conf(self):
bin_path = self.build_dir + '/bin/'
conf_path = self.src_dir + '/conf/'
for item in ['nebula-standalone']:
shutil.copy(bin_path + item, self.work_dir + '/bin/')
shutil.copy(
conf_path + '{}.conf.default'.format(item),
self.work_dir + '/conf/{}.conf'.format(item),
)
resources_dir = self.work_dir + '/share/resources/'
os.makedirs(resources_dir)
# timezone file
shutil.copy(
self.build_dir + '/../resources/date_time_zonespec.csv', resources_dir
)
shutil.copy(self.build_dir + '/../resources/gflags.json', resources_dir)
# cert files
shutil.copy(self.src_dir + '/tests/cert/test.ca.key', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.ca.pem', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.ca.password', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.derive.key', resources_dir)
shutil.copy(self.src_dir + '/tests/cert/test.derive.crt', resources_dir)
@staticmethod
def is_port_in_use(port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
return s.connect_ex(('localhost', port)) == 0
@staticmethod
def get_free_port():
for _ in range(30):
try:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(('', random.randint(10000, 20000)))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
except OSError as e:
pass
# TODO(yee): Find free port range
def _find_free_port(self, count):
assert count % self.ports_per_process == 0
Path(self.lock_file).touch(exist_ok=True)
# thread safe
with open(self.lock_file, 'r+') as fl:
fcntl.flock(fl.fileno(), fcntl.LOCK_EX)
context = fl.read().strip()
lock_ports = [int(p) for p in context.split(self.delimiter) if p != ""]
all_ports = []
for i in range(count):
if i % self.ports_per_process == 0:
for _ in range(100):
tcp_port = NebulaService.get_free_port()
# force internal tcp port with port+1
if all(
(tcp_port + i) not in all_ports + lock_ports
for i in range(0, 2)
):
all_ports.append(tcp_port)
all_ports.append(tcp_port + 1)
break
elif i % self.ports_per_process == 1:
continue
else:
for _ in range(100):
port = NebulaService.get_free_port()
if port not in all_ports + lock_ports:
all_ports.append(port)
break
fl.seek(0)
fl.truncate()
fl.write(self.delimiter.join([str(p) for p in all_ports + lock_ports]))
fl.write(self.delimiter)
return all_ports
def _telnet_port(self, port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sk:
sk.settimeout(1)
result = sk.connect_ex(('127.0.0.1', port))
return result == 0
def install_standalone(self, work_dir=None):
if work_dir is not None:
self.work_dir = work_dir
print("workdir not exist")
if os.path.exists(self.work_dir):
shutil.rmtree(self.work_dir)
os.mkdir(self.work_dir)
print("work directory: " + self.work_dir)
os.chdir(self.work_dir)
installed_files = ['bin', 'conf', 'scripts']
for f in installed_files:
os.mkdir(self.work_dir + '/' + f)
self._copy_standalone_conf()
max_suffix = max([self.graphd_num, self.storaged_num, self.metad_num])
for i in range(max_suffix):
os.mkdir(self.work_dir + '/logs{}'.format(i))
os.mkdir(self.work_dir + '/pids{}'.format(i))
def install(self, work_dir=None):
if work_dir is not None:
self.work_dir = work_dir
if os.path.exists(self.work_dir):
shutil.rmtree(self.work_dir)
os.mkdir(self.work_dir)
print("work directory: " + self.work_dir)
os.chdir(self.work_dir)
installed_files = ['bin', 'conf', 'scripts']
for f in installed_files:
os.mkdir(self.work_dir + '/' + f)
self._copy_nebula_conf()
max_suffix = max([self.graphd_num, self.storaged_num, self.metad_num])
for i in range(max_suffix):
os.mkdir(self.work_dir + '/logs{}'.format(i))
os.mkdir(self.work_dir + '/pids{}'.format(i))
def _check_servers_status(self, ports):
ports_status = {}
for port in ports:
ports_status[port] = False
for i in range(0, 20):
for port in ports_status:
if ports_status[port]:
continue
if self._telnet_port(port):
ports_status[port] = True
is_ok = True
for port in ports_status:
if not ports_status[port]:
is_ok = False
if is_ok:
return True
time.sleep(1)
return False
def start(self):
os.chdir(self.work_dir)
start_time = time.time()
for p in self.all_processes:
p.start()
config = Config()
config.max_connection_pool_size = 20
config.timeout = 60000
# init connection pool
client_pool = ConnectionPool()
# assert client_pool.init([("127.0.0.1", int(self.graphd_port))], config)
ssl_config = get_ssl_config(self.is_graph_ssl, self.ca_signed)
print("begin to add hosts")
ok = False
# wait graph is ready, and then add hosts
for _ in range(20):
try:
ok = client_pool.init(
[("127.0.0.1", self.graphd_processes[0].tcp_port)],
config,
ssl_config,
)
if ok:
break
except:
pass
time.sleep(1)
assert ok, "graph is not ready"
# get session from the pool
client = client_pool.get_session('root', 'nebula')
hosts = ",".join(
[
"127.0.0.1:{}".format(str(storaged.tcp_port))
for storaged in self.storaged_processes
]
)
cmd = "ADD HOSTS {}".format(hosts)
print("add hosts cmd is {}".format(cmd))
resp = client.execute(cmd)
assert resp.is_succeeded(), resp.error_msg()
# sign text search service
NEBULA_TEST_ES_ADDRESS = os.environ.get("NEBULA_TEST_ES_ADDRESS")
if NEBULA_TEST_ES_ADDRESS is not None:
cmd = f"SIGN IN TEXT SERVICE({NEBULA_TEST_ES_ADDRESS});"
print("sign text service cmd is {}".format(cmd))
resp = client.execute(cmd)
assert resp.is_succeeded(), resp.error_msg()
client.release()
# wait nebula start
server_ports = [p.tcp_port for p in self.all_processes]
if not self._check_servers_status(server_ports):
self._collect_pids()
self.kill_all(signal.SIGKILL)
elapse = time.time() - start_time
raise Exception(f'nebula servers not ready in {elapse}s')
self._collect_pids()
return [p.tcp_port for p in self.graphd_processes]
def start_standalone(self):
os.chdir(self.work_dir)
start_time = time.time()
for p in self.all_processes:
print('start stand alone process')
p.start()
config = Config()
config.max_connection_pool_size = 20
config.timeout = 60000
# init connection pool
client_pool = ConnectionPool()
# assert client_pool.init([("127.0.0.1", int(self.graphd_port))], config)
ssl_config = get_ssl_config(self.is_graph_ssl, self.ca_signed)
print("begin to add hosts")
ok = False
# wait graph is ready, and then add hosts
for _ in range(20):
try:
ok = client_pool.init(
[("127.0.0.1", self.graphd_processes[0].tcp_port)],
config,
ssl_config,
)
if ok:
break
except:
pass
time.sleep(1)
assert ok, "graph is not ready"
# get session from the pool
client = client_pool.get_session('root', 'nebula')
hosts = ",".join(
[
"127.0.0.1:{}".format(str(storaged.storage_port))
for storaged in self.graphd_processes
]
)
cmd = "ADD HOSTS {}".format(hosts)
print("add hosts cmd is {}".format(cmd))
resp = client.execute(cmd)
assert resp.is_succeeded(), resp.error_msg()
client.release()
# wait nebula start
server_ports = [p.tcp_port for p in self.all_processes]
if not self._check_servers_status(server_ports):
self._collect_pids()
self.kill_all(signal.SIGKILL)
elapse = time.time() - start_time
raise Exception(f'nebula servers not ready in {elapse}s')
self._collect_pids()
return [p.tcp_port for p in self.graphd_processes]
def _collect_pids(self):
for pf in glob.glob(self.work_dir + '/pid*/*.pid'):
with open(pf) as f:
self.pids[f.name] = int(f.readline())
def stop(self, cleanup=True):
print("try to stop nebula services...")
self._collect_pids()
if len(self.pids) == 0:
print("the cluster has been stopped and deleted.")
return
self.kill_all(signal.SIGTERM)
max_retries = 20
while self.is_procs_alive() and max_retries >= 0:
time.sleep(1)
max_retries = max_retries - 1
if self.is_procs_alive():
self.kill_all(signal.SIGKILL)
# thread safe
with open(self.lock_file, 'r+') as fl:
fcntl.flock(fl.fileno(), fcntl.LOCK_EX)
context = fl.read().strip()
lock_ports = {int(p) for p in context.split(self.delimiter) if p != ""}
for p in self.all_ports:
lock_ports.remove(p)
fl.seek(0)
fl.truncate()
fl.write(self.delimiter.join([str(p) for p in lock_ports]))
fl.write(self.delimiter)
if cleanup:
shutil.rmtree(self.work_dir, ignore_errors=True)
def kill_all(self, sig):
for p in self.pids:
self.kill(p, sig)
def kill(self, pid, sig):
if not self.is_proc_alive(pid):
return
try:
os.kill(self.pids[pid], sig)
except OSError as err:
print("stop nebula {} failed: {}".format(pid, str(err)))
def is_procs_alive(self):
return any(self.is_proc_alive(pid) for pid in self.pids)
def is_proc_alive(self, pid):
process = subprocess.Popen(
['ps', '-eo', 'pid,args'], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout = process.communicate()
for line in bytes.decode(stdout[0]).splitlines():
p = line.lstrip().split(' ', 1)[0]
if str(p) == str(self.pids[pid]):
return True
return False