-
Notifications
You must be signed in to change notification settings - Fork 1
/
ssh_controller.py
executable file
·1397 lines (1176 loc) · 45 KB
/
ssh_controller.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
#!/usr/bin/env python3
import multiprocessing as mp
import time
import os
import argparse
import datetime
import inspect
import sys
import json
import socket
import traceback
try:
import paramiko
except ImportError:
os.system("pip3 install paramiko")
import paramiko
try:
import netifaces as nf
except ImportError:
os.system("pip3 install netifaces")
import netifaces as nf
class IPAddrHelper(object):
@staticmethod
def ipv4_addresses():
ip_list = []
for interface in nf.interfaces():
for link in nf.ifaddresses(interface).get(nf.AF_INET, ()):
ip_list.append(link["addr"])
return ip_list
@staticmethod
def ipv6_addresses():
ip_list = []
for interface in nf.interfaces():
for link in nf.ifaddresses(interface).get(nf.AF_INET6, ()):
ip_list.append(link["addr"])
return ip_list
@staticmethod
def simple_ipv6_addresses():
ip_addrs = IPAddrHelper.ipv6_addresses()
ret_data = []
for ip_str in ip_addrs:
ret_data.append(ip_str.split("%")[0])
pass
return ret_data
pass
@staticmethod
def is_local(ip):
ip_from_dns = IPAddrHelper.query_ip_from_dns(ip)
local_ip_addr = IPAddrHelper.ipv4_addresses() + IPAddrHelper.ipv6_addresses()
for ip_addr in ip_from_dns:
if ip_addr in local_ip_addr:
return True
return False
return ip in IPAddrHelper.ipv4_addresses() + IPAddrHelper.ipv6_addresses()
@staticmethod
def query_ip_from_dns(hostname: str):
ip_list = [hostname]
def load_ipaddr_helper(net_proto):
tmp_list = []
try:
ipv_addr = socket.getaddrinfo(hostname, None, net_proto)
for each_elem in ipv_addr:
real_ip = each_elem[4][0]
tmp_list.append(real_ip)
except Exception as e:
print(
"failed get ip address, with err={}, stack={}".format(
e, traceback.print_exc()
),
file=sys.stderr,
flush=True,
)
return tmp_list
ip_list += load_ipaddr_helper(socket.AF_INET)
ip_list += load_ipaddr_helper(socket.AF_INET6)
ip_list = [x for x in set(ip_list) if x is not None and len(x) != 0]
return ip_list
pass
# ip_str = [
# "bps-node-14",
# "bps-node-15",
# "github.com",
# "",
# "localhost",
# "127.0.0.1",
# "::ffff:157.245.159.242",
# "fdbd:dc02:2a:716::17",
# "fdbd:dc02:2a:10e::28",
# ]
# for host_name in ip_str:
# print(
# "The target of {} is {}".format(
# host_name, IPAddrHelper.query_ip_from_dns(host_name)
# )
# )
# print(
# "The target of {} is local = {}".format(
# host_name, IPAddrHelper.is_local(host_name)
# )
# )
# exit(-1)
class ArgHelper(object):
@staticmethod
def load_arguments():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("--H", type=str, help="host ID [1,2,3,4,5]")
parser.add_argument(
"--cmd", type=str, default="", help="executing your command"
)
parser.add_argument(
"--sync", action="store_true", help="Sync data between local to remote"
)
parser.add_argument(
"--sync_path", type=str, default="", help="The source file path to sync"
)
parser.add_argument(
"--sudo", action="store_true", help="working under sudo mode"
)
parser.add_argument(
"--user", type=str, default="newplan", help="username for ssh"
)
parser.add_argument(
"--passwd", type=str, default=" ", help="password to login remote machine"
)
parser.add_argument(
"--port", type=int, default=22, help="the port of ssh service"
)
parser.add_argument(
"--host", type=str, default="", help="the host ip for this session"
)
parser.add_argument(
"--allow_print",
type=str,
default="",
help="the node to display the ret, split by ',' or all to show all the node ",
)
parser.add_argument(
"--stream_log",
action="store_true",
default=False,
help="get streamed logs from remote sessions",
)
parser.add_argument(
"--interactive",
action="store_true",
default=False,
help="working under interactive mode",
)
parser.add_argument(
"--use_glog",
action="store_true",
default=True,
help="enable glog as logger or not",
)
parser.add_argument(
"--env",
type=str,
default="",
help="speficy the environment for execution, multiple envs are split by ';'",
)
parser.add_argument(
"--set_env",
type=str,
default=None,
help="put local environment variables to remote, split by','."
' for example: --set_env="PATH,LIBRARY_PATH"',
)
parser.add_argument(
"--enable_full_log",
action="store_true",
help="enable full log for other module",
)
parser.add_argument(
"--log_level",
type=str,
default="info",
help="log level for print result,"
" the valid values are must in "
"[info, debug, warning, error],"
" and are case insensitive",
)
parser.add_argument(
"--key",
type=str,
default="",
help="Key to log remote session for ssh, instead of using passward",
)
parser.add_argument(
"--dump_args",
action="store_true",
default=True,
help="dump arguments for this session, only work for debug model",
)
parser.add_argument(
"--dump_log",
action="store_true",
default=False,
help="dump output logs for remote session, including stdout and stderr",
)
parser.add_argument(
"--log_path",
type=str,
default="",
help="dump output logs for remote session, including stdout and stderr",
)
parser.add_argument(
"--log_individual",
action="store_true",
default=False,
help="log individual for prefix",
)
parser.add_argument(
"--debug_shell",
action="store_true",
default=False,
help="show the execution of shell commands in remote session for debug",
)
return parser.parse_args()
args = ArgHelper.load_arguments()
class ResourceHelper(object):
@staticmethod
def is_valid(path: str, check_exist=True, check_file=False, check_directory=False):
pass_check = True
if pass_check and check_exist:
if not os.path.exists(path):
logger.warning(
"check is valid for {} failed, not existing".format(path)
)
pass_check = False
if pass_check and check_file:
if not os.path.isfile(path):
logger.warning("check is valid for {} failed, not a file".format(path))
pass_check = False
if pass_check and check_directory:
if not os.path.isdir(path):
logger.warning(
"check is valid for {} failed, not a directory".format(path)
)
pass_check = False
return pass_check
@staticmethod
def check_or_die(
path: str, check_exist=True, check_file=False, check_directory=False
):
if not ResourceHelper.is_valid(path, check_exist, check_file, check_directory):
logger.fatal(
"Failed to check for: path={}, check_exist={}, check_file={},check_directory={}".format(
path, check_exist, check_file, check_directory
)
)
pass
@staticmethod
def str_time_now():
now = int(round(time.time() * 1000))
now02 = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime(now / 1000))
return now02
def load_logger(args):
def get_buildin_loger():
import logging
log_level = None
log_level_str = args.log_level.upper()
if log_level_str == "INFO":
log_level = logging.INFO
elif log_level_str == "DEBUG":
log_level = logging.DEBUG
elif log_level_str == "WARNING":
log_level = logging.WARNING
elif log_level_str == "ERROR":
log_level = logging.ERROR
else:
assert log_level_str in (
"INFO",
"DEBUG",
"WARNING",
"ERROR",
), 'Invalid log level: {}, must be in ["INFO", "DEBUG", "WARNING", "ERROR"]'.format(
log_level
)
print(
"[INIT: {} {}:{}] \tSeting log level to: {}".format(
datetime.datetime.now(),
__file__,
inspect.currentframe().f_lineno,
log_level_str,
),
flush=True,
)
logging.basicConfig(
level=log_level,
format="[%(levelname)s: %(asctime)s %(filename)s:%(lineno)d] \t%(message)s",
)
# format='[%(levelname)s: %(asctime)s %(thread)d %(funcName)s %(filename)s:%(lineno)d] \t%(message)s'
logger = logging.getLogger(__name__)
return logger
def get_glog():
import glog as logger
return logger
if args.use_glog:
try:
logger = get_glog()
except ImportError as e:
args.use_glog = False
logger = get_buildin_loger()
pass
else:
logger = get_buildin_loger()
if not args.enable_full_log and not args.use_glog:
from importlib import reload
import logging
logging.shutdown()
reload(logging)
pass
return logger
logger = load_logger(args)
class SshClientImpl:
"A wrapper of paramiko.SSHClient"
TIMEOUT = 4 # by default, the maximum time to wait for an ssh connection is 4s
def __del__(
self,
):
if self._fp_handler_ is not None:
self._fp_handler_.close()
if self._pipelined_channel is not None:
self._pipelined_channel.close()
if self._ssh_interactive is not None:
self._ssh_interactive.close()
self.client.close()
def __init__(
self,
host,
port,
username,
password=None,
key=None,
passphrase=None,
rsa_pub=None,
log_file_name=None,
):
self.username = username
self.password = password
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.host = host
self.port = port
self._ssh_interactive = None
self._pipelined_channel = None
self._cached_bytes_ = b""
p_key = key
self.log_file_name = log_file_name
self._fp_handler_ = None
# ref: https://blog.csdn.net/DaMercy/article/details/127780178
if rsa_pub != None: # rsa_pub = "~/.ssh/id_rsa"
logger.debug("Using public RSA key to loggin remote")
ResourceHelper.check_or_die(path=rsa_pub)
p_key = paramiko.RSAKey.from_private_key_file(rsa_pub, password=None)
self.client.connect(
host,
port,
username=username,
password=password,
pkey=p_key,
timeout=self.TIMEOUT,
)
else:
self.client.connect(
host,
port,
username=username,
password=password,
pkey=key,
timeout=self.TIMEOUT,
)
def using_interactive_channel(self, cmd):
# ref: https://blog.csdn.net/weixin_39912556/article/details/80587180
# ref: https://blog.csdn.net/qq_31127143/article/details/124707117
if self._ssh_interactive is None:
self._ssh_interactive = self.client.invoke_shell()
# self._ssh_interactive.set_combine_stderr(True)
# self._ssh_interactive.settimeout(90)
self._ssh_interactive.settimeout(0.0)
try:
self._ssh_interactive.send(cmd + "\r")
# self._ssh_interactive.send('echo EXECUTION-STATUS:"$?"\r')
except Exception as e:
logger.error(
f"Error of executing {cmd}, error: {e}, stack: {traceback.print_exc()}"
)
def use_streamed_channel(self, cmd):
# non_blocking mode: https://gist.github.com/kdheepak/c18f030494fea16ffd92d95c93a6d40d
# https://stackoverflow.com/questions/760978/long-running-ssh-commands-in-python-paramiko-module-and-how-to-end-them
if self._pipelined_channel is None:
self._pipelined_channel = self.client.get_transport().open_session()
# self._pipelined_channel.settimeout(0.0)
self._pipelined_channel.set_combine_stderr(True)
# self._pipelined_channel.get_pty()
try:
self._pipelined_channel.exec_command(cmd)
pass
except Exception as e:
logger.error(
f"Error of executing {cmd}, error: {e}, stack: {traceback.print_exc()}"
)
pass
def dump_log(self, data_utf8):
if args.dump_log == False:
return
if data_utf8 is None or len(data_utf8) == 0:
return
if self._fp_handler_ is None:
if len(args.log_path) == 0:
logger.fatal("No log file specified")
raise ValueError("No log file specified in --log_path")
if (
args.log_individual is True
and len(args.log_prefix) != 0
and len(args.log_path) != 0
):
args.unqiue_log_path = os.path.join(args.log_path, args.log_prefix)
else:
args.unqiue_log_path = args.log_path
if not os.path.exists(args.unqiue_log_path):
os.makedirs(name=args.unqiue_log_path, mode=0o777, exist_ok=True)
real_log_path = os.path.join(args.unqiue_log_path, self.log_file_name)
self._fp_handler_ = open(real_log_path + ".txt", "bw")
pass
self._fp_handler_.write(data_utf8)
self._fp_handler_.flush()
def __read_helper__(self, channel, repeat=10, read_byte=4096):
cnt = 0
while not channel.recv_ready():
time.sleep(0.1)
cnt += 1
if cnt > repeat:
return None
pass
try:
read_data = channel.recv(read_byte)
self._cached_bytes_ += read_data
self.dump_log(read_data)
ret_str = self._cached_bytes_.decode("utf-8")
self._cached_bytes_ = b"" # only clean result when decode success
# ret_str = channel.recv(read_byte).decode("utf-8")
prefix_format = "<{}>: ".format(self.host)
joint_prefix = "\n" + " " * len(prefix_format)
split_tmp_result = ret_str.split("\n")
ret_str = (
prefix_format
+ joint_prefix.join(split_tmp_result[:-1])
+ "\n"
+ split_tmp_result[-1] # for last one, we should alway keep the \n
)
return ret_str
except UnicodeDecodeError as e:
logger.warning(
f"node({self.host}:{self.port}) decode error, will cache it and redecode it again"
f", for reason: {e}, the stack:{traceback.print_exc()}"
)
return None
pass
def query_streamed_channel(self): # not finished yet
assert self._pipelined_channel is not None, (
"Invalid ssh interactive channel, "
"please using 'using_streamed_channel' "
f"to submit the command to {self.host}:{self.port}"
)
execution_status = None
if self._pipelined_channel.exit_status_ready():
execution_status = self._pipelined_channel.recv_exit_status()
result = self.__read_helper__(self._pipelined_channel)
if result is not None:
return result, None
last_bytes = []
if self._pipelined_channel.exit_status_ready():
while True:
new_data = self.__read_helper__(self._pipelined_channel)
if new_data is not None:
last_bytes.append(new_data)
else:
break
ret = None if len(last_bytes) == 0 else "".join(last_bytes)
return ret, execution_status
pass
def querying_interactive_channel(self):
assert self._ssh_interactive is not None, (
"Invalid ssh interactive channel, "
"please using 'using_interactive_channel' "
f"to submit the command to {self.host}:{self.port}"
)
cnt = 0
while not self._ssh_interactive.recv_ready():
time.sleep(0.2)
cnt += 1
if cnt > 10:
return None
try:
ret_str = self._ssh_interactive.recv(16384).decode("utf-8")
prefix_format = "<{}>: ".format(self.host)
joint_prefix = "\n" + " " * len(prefix_format)
split_tmp_result = ret_str.split("\n")
ret_str = (
prefix_format
+ joint_prefix.join(split_tmp_result[:-1])
+ "\n"
+ split_tmp_result[-1] # for last one, we should alway keep the \n
)
except Exception as e:
logger.error(
f"node({self.host}:{self.port}) unknown error for execution"
f", for reason: {e}, stack: {traceback.print_exc()}"
)
return ret_str
def get_interactive_channel(self):
return self._ssh_interactive
def get_channel(self):
return self.client
def close(self):
if self.client is not None:
self.client.close()
self.client = None
def _load_env_helper_(self, env):
env_prefix = ""
if env is None:
return env_prefix
env = env.strip()
if len(env) == 0:
return [env_prefix for x in range(5)] # return immediately if error
while len(env) > 0 and env[-1] == ";":
env = env[:-2]
while len(env) > 0 and env[-1] == "/":
env = env[:-2]
BASE_PREFIX = env
cpp_include_path = f"{BASE_PREFIX}/include:"
c_include_path = f"{BASE_PREFIX}/include:"
path = f"{BASE_PREFIX}/bin:"
ld_library_path = f"{BASE_PREFIX}/lib:{BASE_PREFIX}/lib64:"
library_path = f"{BASE_PREFIX}/lib:{BASE_PREFIX}/lib64:"
return path, c_include_path, cpp_include_path, ld_library_path, library_path
def load_env(self, env=args.env):
env_prefix = " set -e; "
env_vect = env.split(";")
env_str: dict[list] = {
"path": [],
"c_include_path": [],
"cpp_include_path": [],
"ld_library_path": [],
"library_path": [],
}
for each_env in env_vect:
(
path,
c_include_path,
cpp_include_path,
ld_library_path,
library_path,
) = self._load_env_helper_(each_env)
env_str["path"].append(path)
env_str["c_include_path"].append(c_include_path)
env_str["cpp_include_path"].append(cpp_include_path)
env_str["ld_library_path"].append(ld_library_path)
env_str["library_path"].append(library_path)
ret_env_var = ""
ret_env_var += " export PATH={}:$PATH;".format("".join(env_str["path"]))
ret_env_var += " export C_INCLUDE_PATH={}:$C_INCLUDE_PATH;".format(
"".join(env_str["c_include_path"])
)
ret_env_var += " export CPLUS_INCLUDE_PATH={}:$CPLUS_INCLUDE_PATH;".format(
"".join(env_str["cpp_include_path"])
)
ret_env_var += " export LD_LIBRARY_PATH={}:$LD_LIBRARY_PATH;".format(
"".join(env_str["ld_library_path"])
)
ret_env_var += " export LIBRARY_PATH={}:$LIBRARY_PATH;".format(
"".join(env_str["library_path"])
)
return ret_env_var + env_prefix
def execute(self, command, sudo=False):
feed_password = False
if args.sudo:
logger.warning("WARNING: execute with sudo")
command = "sudo -S -p '' %s" % command
feed_password = True
real_execute_cmd = self.load_env() + command
logger.debug(
"[{}:{}] Real execution cmd: {}".format(
self.host, self.port, real_execute_cmd
)
)
stdin, stdout, stderr = self.client.exec_command(real_execute_cmd, get_pty=True)
if args.sudo and feed_password:
stdin.write(self.password + "\n")
stdin.flush()
return {
"out": stdout.readlines(),
"err": stderr.readlines(),
"retval": stdout.channel.recv_exit_status(),
}
# ref: https://www.cnblogs.com/chen/p/9493546.html
class SFTPService:
def __init__(self, ssh_ctx):
self.borrowed_ctx = ssh_ctx
self._sftp_channel = paramiko.SFTPClient.from_transport(
self.borrowed_ctx.get_channel().get_transport()
)
self.__is_local_node = IPAddrHelper.is_local(self.borrowed_ctx.host)
assert len(self.borrowed_ctx.host) != 0, "invalid remote host node"
pass
def __file_filter__(self, name) -> bool:
if name is None or name == "." or name == "..":
return True
return False
def copy_files(self, source, target):
"""Uploads the contents of the source directory to the target path. The
target directory needs to exists. All subdirectories in source are
created under target.
"""
if source == target and self.__is_local_node:
logger.warning("IGNORE self-node: {}".format(self.borrowed_ctx.host))
return
item_name = None
try:
if os.path.isdir(source): # create directory if it is
self.mkdir_remote(target, ignore_existing=True)
if os.path.isfile(source): #
assert (
None not in [target, source]
and target.startswith("/")
and source.startswith("/")
), "invalid path for src={}, and dest={}, please use the abs path, start with '/'".format(
source, target
)
# tmp create remote dir and delete them latter
# self.mkdir_remote(target, ignore_existing=True)
self._sftp_channel.put(source, target)
# self._sftp_channel.rmdir(target)
return
for item in os.listdir(source):
if self.__file_filter__(item): # donnot copy current path
continue
if os.path.isfile(os.path.join(source, item)):
logger.debug(
"processing {} --> {}".format(
os.path.join(source, item), self.borrowed_ctx.host
)
)
item_name = item
self._sftp_channel.put(
os.path.join(source, item), "%s/%s" % (target, item)
)
else:
self.mkdir_remote("%s/%s" % (target, item), ignore_existing=True)
self.copy_files(
os.path.join(source, item), "%s/%s" % (target, item)
)
except Exception as e:
logger.warning(
"Error of processing copy {}/{} to {}/{} in target = ({}:{}), for reason: {}, stack: {}".format(
source,
item_name,
target,
item_name,
self.borrowed_ctx.host,
self.borrowed_ctx.port,
e,
traceback.print_exc(),
)
)
exit(0)
def mkdir_remote(self, path, mode=1776, ignore_existing=False):
"""Augments mkdir by adding an option to not fail if the folder exists"""
try:
self._sftp_channel.mkdir(path) # , mode)
except IOError:
if ignore_existing:
pass
else:
print("failed to process: ")
raise
def close(self):
logger.warning("Closing the sftp server at {}".format(self.borrowed_ctx.host))
self._sftp_channel.close()
class SSHClientSession:
def __init__(self, host, port, username, password, id):
self.remote_host = host
self.remote_port = port
self.remote_username = username
self.remote_password = password
self.id = id
self.node_idx = -1
self.parent_channel, self.child_channel = mp.Pipe()
self.process_handler = None
self.is_connected = False
logger.info(f"Creating SSHClient for {host}:{port}")
def send_command(self, command, using_sudo, interactive, allow_print):
################################
allowed_cluster = [x.strip() for x in allow_print.split(",")]
packed_task = {
"cmd": command,
"using_sudo": using_sudo,
"interactive": interactive,
"allow_print": False,
}
if self.id in allowed_cluster or allow_print.strip() == "all":
packed_task["allow_print"] = True
if interactive:
packed_task["interactive"] = True
else:
packed_task["interactive"] = False
self.parent_channel.send(json.dumps(packed_task))
logger.debug(
f"Send cmd({command}) to the channel "
f"{self.remote_host}:{self.remote_port}"
)
def is_active(self):
return self.is_connected is True
def block_until_connected(self):
logger.debug(
"Querying the status of connection "
f"({self.remote_host}:{self.remote_port})"
)
if self.is_connected is False:
while True:
if self.parent_channel.poll():
data = self.parent_channel.recv()
if data == "CONNECTION_IS_READY":
self.is_connected = True
elif data == "CONNECTION_IS_FAILED":
self.is_connected = False
return
else:
logger.fatal("UNKNOWN connection status")
exit(-1)
break
else:
logger.info(
f"{self.id}({self.remote_host}:{self.remote_port})"
" is not ready to recv"
)
time.sleep(0.5)
logger.info(
f"The SSH connection ({self.remote_host}:{self.remote_port}) is ready"
)
def get_ret_from_channel(self):
ret = None
if self.parent_channel.poll():
ret = self.parent_channel.recv()
ret = json.loads(ret)
return ret
def query_command(self, command, allowed_print=True):
while True:
ret = self.get_ret_from_channel()
if ret is None:
if not args.interactive:
logger.warning(
f"{self.id}({self.remote_host}:{self.remote_port}) "
"has not returned the result...."
)
time.sleep(1)
else:
break
encounting_error = False
if args.interactive == True:
allowed_print = False
if ret["status"] is False: # encounting errors
logger.error("Encounter an error at {}".format(self.id))
allowed_print = True
encounting_error = True
if allowed_print or encounting_error:
logger.warning(
"The result of execution cmd ({}) from {}({}:{}) is:\n{}".format(
ret["cmd"],
self.id,
self.remote_host,
self.remote_port,
" ".join(ret["out"]).replace(
"EVERYTHING_IS_TERMINATED_CORRECTLY_WITH=200-DONE\r\n", ""
)
+ " ".join(ret["err"]).replace(
"EVERYTHING_IS_TERMINATED_CORRECTLY_WITH=200-DONE\r\n", ""
),
)
)
return ret["status"] is True
def sftp_file_mode(self, io_channel):
logger.info(
f"{self.id}({self.remote_host}:{self.remote_port}) is working in sftp mode"
)
self._sftp_service = SFTPService(self.ssh_client)
task = io_channel.recv()
try:
tmp_task = json.loads(task)
struct_task = json.loads(tmp_task["cmd"])
assert (
struct_task["type"] == "SYNC_FOLDER"
), "Error of unknown service type {}".format(struct_task["type"])
self._sftp_service.copy_files(
source=struct_task["src"], target=struct_task["target"]
)
ret_task = {
"type": struct_task["type"],
"status": True,
"src": struct_task["src"],
"target": struct_task["target"],
}
io_channel.send(json.dumps(ret_task))
except Exception as e:
logger.error(
f"Encounter error of processing on node {self.remote_host}, for reason: {e}, stack: {traceback.print_exc()}"
)
pass
def deamon_execution(self, io_channel):
logger.debug(
f"Creating deamon_execution for {self.remote_host}:{self.remote_port}"
)
is_connected = False
try:
self.ssh_client = SshClientImpl(
host=self.remote_host,
port=self.remote_port,
username=self.remote_username,
password=self.remote_password,
rsa_pub=args.key if len(args.key) != 0 else None,
log_file_name=self.id + "." + str(self.node_idx),
)
is_connected = True
except Exception as e:
logger.error(
f"Cannot connected to {self.remote_host}:{self.remote_port}, for error: {e}, stack: {traceback.print_exc()}"
)
finally:
pass
if is_connected:
io_channel.send("CONNECTION_IS_READY")
else:
io_channel.send("CONNECTION_IS_FAILED")
return
if args.sync:
self.sftp_file_mode(io_channel)
else:
self.task_routing(io_channel)
pass
def wait_task_from_master(self, io_channel):
logger.debug(
f"{self.remote_host}:{self.remote_port} is ready, wait for tasks from master..."
)
if io_channel.poll(): # the upper layer has submitted new task
recv_data = io_channel.recv() # accept new cmd
else: # otherwise, return None
time.sleep(0.5)