forked from aiidateam/aiida-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh_async.py
More file actions
1316 lines (1084 loc) · 53.8 KB
/
ssh_async.py
File metadata and controls
1316 lines (1084 loc) · 53.8 KB
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
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""Plugin for transport over SSH asynchronously."""
## TODO: put & get methods could be simplified with the asyncssh.sftp.mget() & put() method or sftp.glob()
## https://github.com/aiidateam/aiida-core/issues/6719
import asyncio
import glob
import os
from pathlib import Path, PurePath
from typing import Optional, Union
import click
from aiida.common.escaping import escape_for_bash
from aiida.common.exceptions import InvalidOperation
from aiida.transports.transport import (
AsyncTransport,
Transport,
TransportPath,
has_magic,
validate_positive_number,
)
__all__ = ('AsyncSshTransport',)
def validate_script(ctx, param, value: str):
if value == 'None':
return value
if not os.path.isabs(value):
raise click.BadParameter(f'{value} is not an absolute path')
if not os.path.isfile(value):
raise click.BadParameter(f'The script file: {value} does not exist')
if not os.access(value, os.X_OK):
raise click.BadParameter(f'The script {value} is not executable')
return value
def validate_backend(ctx, param, value: str):
if value not in ['asyncssh', 'openssh']:
raise click.BadParameter(f'{value} is not a valid backend, choose either `asyncssh` or `openssh`')
return value
class AsyncSshTransport(AsyncTransport):
"""Transport plugin via SSH, asynchronously."""
_DEFAULT_max_io_allowed = 8
# note, I intentionally wanted to keep connection parameters as simple as possible.
_valid_auth_options = [
(
# the underscore is added to avoid conflict with the machine property
# which is passed to __init__ as parameter `machine=computer.hostname`
'host',
{
'type': str,
'prompt': "Host as in 'ssh <HOST>' (needs to be a password-less setup in your ssh config)",
'help': (
'Password-less host-setup to connect, as in command `ssh <HOST>`.'
' You need to have a `Host <HOST>` entry defined in your `~/.ssh/config` file.'
" Note, if not provided, we will use the 'hostname' that was set by you during setup."
),
'non_interactive_default': True,
},
),
(
'max_io_allowed',
{
'type': int,
'default': _DEFAULT_max_io_allowed,
'prompt': 'Maximum number of concurrent I/O operations',
'help': 'Depends on various factors, such as your network bandwidth, the server load, etc.'
' (An experimental number)',
'non_interactive_default': True,
'callback': validate_positive_number,
},
),
(
'script_before',
{
'type': str,
'default': 'None',
'prompt': 'Local script to run *before* opening connection (path)',
'help': ' (optional) Specify a script to run *before* opening SSH connection. '
'The script should be executable',
'non_interactive_default': True,
'callback': validate_script,
},
),
(
'backend',
{
'type': str,
'default': 'asyncssh',
'prompt': 'Type of async backend to use, `asyncssh` or `openssh`',
'help': '`openssh` uses the `ssh` command line tool to connect to the remote machine,'
'e.g. it is useful in case of multiplexing. '
'The `asyncssh` backend is the default and is recommended for most use cases.',
'non_interactive_default': True,
'callback': validate_backend,
},
),
]
@classmethod
def _get_host_suggestion_string(cls, computer):
"""Return a suggestion for the parameter 'host'.
Note: the name of this methood is not arbitrary! In order to be picked up during
`verdi computer configure` command, it has to be in the following format:
`_get_<PARAMETER_NAME>_suggestion_string`
"""
# Originally set as 'Hostname' during `verdi computer setup`
# and is passed as `machine=computer.hostname` in the codebase
# unfortunately, name of hostname and machine are used interchangeably in the aiida-core codebase
# TODO: an issue is open: https://github.com/aiidateam/aiida-core/issues/6726
return computer.hostname
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# the machine is passed as `machine=computer.hostname` in the codebase
# 'machine' is immutable.
# 'host' is mutable, so it can be changed via command:
# 'verdi computer configure core.ssh_async <LABEL>'.
# by default, 'host' is set to 'machine' in the __init__ method, if not provided.
# NOTE: to guarantee a connection,
# a computer with core.ssh_async transport plugin should be configured before any instantiation.
self.machine = kwargs.pop('host', kwargs.pop('machine'))
self._max_io_allowed = kwargs.pop('max_io_allowed', self._DEFAULT_max_io_allowed)
self._semaphore = asyncio.Semaphore(self._max_io_allowed)
self.script_before = kwargs.pop('script_before', 'None')
if kwargs.get('backend') == 'openssh':
from .async_backend import _OpenSSH
self.async_backend = _OpenSSH(self.machine, self.logger, self._bash_command_str)
else:
# default backend is asyncssh
from .async_backend import _AsyncSSH
self.async_backend = _AsyncSSH(self.machine, self.logger, self._bash_command_str) # type: ignore[assignment]
@property
def max_io_allowed(self):
return self._max_io_allowed
async def open_async(self):
"""Open the transport.
This plugin supports running scripts before and during the connection.
The scripts are run locally, not on the remote machine.
:raises InvalidOperation: if the transport is already open
"""
if self._is_open:
# That means the transport is already open, while it should not
raise InvalidOperation('Cannot open the transport twice')
if self.script_before != 'None':
os.system(f'{self.script_before}')
try:
await self.async_backend.open()
except OSError as exc:
raise OSError(f'Error while opening the transport: {exc}')
self._is_open = True
return self
async def close_async(self):
"""Close the transport.
:raises InvalidOperation: if the transport is already closed
"""
if not self._is_open:
raise InvalidOperation('Cannot close the transport: it is already closed')
try:
await self.async_backend.close()
except Exception as exc:
raise OSError(f'Error while closing the transport: {exc}')
self._is_open = False
def __str__(self):
return f"{'OPEN' if self._is_open else 'CLOSED'} [AsyncSshTransport]"
async def get_async(
self,
remotepath: TransportPath,
localpath: TransportPath,
dereference=True,
overwrite=True,
ignore_nonexisting=False,
preserve=False,
*args,
**kwargs,
):
"""Get a file or folder from remote to local.
Redirects to getfile or gettree.
:param remotepath: an absolute remote path
:param localpath: an absolute local path
:param dereference: follow symbolic links.
Default = True
:param overwrite: if True overwrites files and folders.
Default = False
:param ignore_nonexisting: if True, does not raise an error if the remotepath does not exist
Default = False
:param preserve: preserve file attributes
Default = False
:type remotepath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type localpath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type overwrite: bool
:type ignore_nonexisting: bool
:type preserve: bool
:raise ValueError: if local path is invalid
:raise OSError: if the remotepath is not found
"""
remotepath = str(remotepath)
localpath = str(localpath)
if not os.path.isabs(localpath):
raise ValueError('The localpath must be an absolute path')
if has_magic(remotepath):
if has_magic(localpath):
raise ValueError('Pathname patterns are not allowed in the destination')
# use the self glob to analyze the path remotely
to_copy_list = await self.glob_async(remotepath)
rename_local = False
if len(to_copy_list) > 1:
# I can't scp more than one file on a single file
if os.path.isfile(localpath):
raise OSError('Remote destination is not a directory')
# I can't scp more than one file in a non existing directory
elif not os.path.exists(localpath): # this should hold only for files
raise OSError('Remote directory does not exist')
else: # the remote path is a directory
rename_local = True
for file in to_copy_list:
if await self.isfile_async(file):
if rename_local: # copying more than one file in one directory
# here is the case isfile and more than one file
remote = os.path.join(localpath, os.path.split(file)[1])
await self.getfile_async(file, remote, dereference, overwrite, preserve)
else: # one file to copy on one file
await self.getfile_async(file, localpath, dereference, overwrite, preserve)
else:
await self.gettree_async(file, localpath, dereference, overwrite, preserve)
elif await self.isdir_async(remotepath):
await self.gettree_async(remotepath, localpath, dereference, overwrite, preserve)
elif await self.isfile_async(remotepath):
if os.path.isdir(localpath):
remote = os.path.join(localpath, os.path.split(remotepath)[1])
await self.getfile_async(remotepath, remote, dereference, overwrite, preserve)
else:
await self.getfile_async(remotepath, localpath, dereference, overwrite, preserve)
elif ignore_nonexisting:
pass
else:
raise OSError(f'The remote path {remotepath} does not exist')
async def getfile_async(
self,
remotepath: TransportPath,
localpath: TransportPath,
dereference=True,
overwrite=True,
preserve=False,
*args,
**kwargs,
):
"""Get a file from remote to local.
:param remotepath: an absolute remote path
:param localpath: an absolute local path
:param overwrite: if True overwrites files and folders.
Default = False
:param dereference: follow symbolic links.
Default = True
:param preserve: preserve file attributes
Default = False
:type remotepath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type localpath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type overwrite: bool
:type preserve: bool
:raise ValueError: if local path is invalid
:raise OSError: if unintentionally overwriting
"""
remotepath = str(remotepath)
localpath = str(localpath)
if not os.path.isabs(localpath):
raise ValueError('localpath must be an absolute path')
if os.path.isfile(localpath) and not overwrite:
raise OSError('Destination already exists: not overwriting it')
async with self._semaphore:
try:
await self.async_backend.get(
remotepath=remotepath,
localpath=localpath,
dereference=dereference,
preserve=preserve,
recursive=False,
)
except OSError as exc:
raise OSError(f'Error while downloading file {remotepath}: {exc}')
async def gettree_async(
self,
remotepath: TransportPath,
localpath: TransportPath,
dereference=True,
overwrite=True,
preserve=False,
*args,
**kwargs,
):
"""Get a folder recursively from remote to local.
:param remotepath: an absolute remote path
:param localpath: an absolute local path
:param dereference: follow symbolic links.
Default = True
:param overwrite: if True overwrites files and folders.
Default = True
:param preserve: preserve file attributes
Default = False
:type remotepath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type localpath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type overwrite: bool
:type preserve: bool
:raise ValueError: if local path is invalid
:raise OSError: if the remotepath is not found
:raise OSError: if unintentionally overwriting
"""
remotepath = str(remotepath)
localpath = str(localpath)
if not remotepath:
raise OSError('Remotepath must be a non empty string')
if not localpath:
raise ValueError('Localpaths must be a non empty string')
if not os.path.isabs(localpath):
raise ValueError('Localpaths must be an absolute path')
if not await self.isdir_async(remotepath):
raise OSError(f'Input remotepath is not a folder: {localpath}')
if os.path.exists(localpath) and not overwrite:
raise OSError("Can't overwrite existing files")
if os.path.isfile(localpath):
raise OSError('Cannot copy a directory into a file')
if not os.path.isdir(localpath): # in this case copy things in the remotepath directly
os.makedirs(localpath, exist_ok=True) # and make a directory at its place
else: # localpath exists already: copy the folder inside of it!
localpath = os.path.join(localpath, os.path.split(remotepath)[1])
os.makedirs(localpath, exist_ok=overwrite) # create a nested folder
content_list = await self.listdir_async(remotepath)
for content_ in content_list:
parentpath = str(PurePath(remotepath) / content_)
async with self._semaphore:
try:
await self.async_backend.get(
remotepath=parentpath,
localpath=localpath,
dereference=dereference,
preserve=preserve,
recursive=True,
)
except OSError as exc:
raise OSError(f'Error while downloading file {parentpath}: {exc}')
async def put_async(
self,
localpath: TransportPath,
remotepath: TransportPath,
dereference=True,
overwrite=True,
ignore_nonexisting=False,
preserve=False,
*args,
**kwargs,
):
"""Put a file or a folder from local to remote.
Redirects to putfile or puttree.
:param remotepath: an absolute remote path
:param localpath: an absolute local path
:param dereference: follow symbolic links
Default = True
:param overwrite: if True overwrites files and folders
Default = False
:param ignore_nonexisting: if True, does not raise an error if the localpath does not exist
Default = False
:param preserve: preserve file attributes
Default = False
:type remotepath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type localpath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type overwrite: bool
:type ignore_nonexisting: bool
:type preserve: bool
:raise ValueError: if local path is invalid
:raise OSError: if the localpath does not exist
"""
localpath = str(localpath)
remotepath = str(remotepath)
if not os.path.isabs(localpath):
raise ValueError('The localpath must be an absolute path')
if not os.path.isabs(remotepath):
# Historically remotepath could be a relative path, but it is not supported anymore.
raise OSError('The remotepath must be an absolute path')
if has_magic(localpath):
if has_magic(remotepath):
raise ValueError('Pathname patterns are not allowed in the destination')
# use the imported glob to analyze the path locally
to_copy_list = glob.glob(localpath)
rename_remote = False
if len(to_copy_list) > 1:
# I can't scp more than one file on a single file
if await self.isfile_async(remotepath):
raise OSError('Remote destination is not a directory')
# I can't scp more than one file in a non existing directory
elif not await self.path_exists_async(remotepath):
raise OSError('Remote directory does not exist')
else: # the remote path is a directory
rename_remote = True
for file in to_copy_list:
if os.path.isfile(file):
if rename_remote: # copying more than one file in one directory
# here is the case isfile and more than one file
remotefile = os.path.join(remotepath, os.path.split(file)[1])
await self.putfile_async(file, remotefile, dereference, overwrite, preserve)
elif await self.isdir_async(remotepath): # one file to copy in '.'
remotefile = os.path.join(remotepath, os.path.split(file)[1])
await self.putfile_async(file, remotefile, dereference, overwrite, preserve)
else: # one file to copy on one file
await self.putfile_async(file, remotepath, dereference, overwrite, preserve)
else:
await self.puttree_async(file, remotepath, dereference, overwrite, preserve)
elif os.path.isdir(localpath):
await self.puttree_async(localpath, remotepath, dereference, overwrite, preserve)
elif os.path.isfile(localpath):
if await self.isdir_async(remotepath):
remote = os.path.join(remotepath, os.path.split(localpath)[1])
await self.putfile_async(localpath, remote, dereference, overwrite, preserve)
else:
await self.putfile_async(localpath, remotepath, dereference, overwrite, preserve)
elif not ignore_nonexisting:
raise OSError(f'The local path {localpath} does not exist')
async def putfile_async(
self,
localpath: TransportPath,
remotepath: TransportPath,
dereference=True,
overwrite=True,
preserve=False,
*args,
**kwargs,
):
"""Put a file from local to remote.
:param remotepath: an absolute remote path
:param localpath: an absolute local path
:param overwrite: if True overwrites files and folders
Default = True
:param preserve: preserve file attributes
Default = False
:type remotepath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type localpath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type overwrite: bool
:type preserve: bool
:raise ValueError: if local path is invalid
:raise OSError: if the localpath does not exist,
or unintentionally overwriting
"""
localpath = str(localpath)
remotepath = str(remotepath)
if not os.path.isabs(localpath):
raise ValueError('The localpath must be an absolute path')
if not os.path.isabs(remotepath):
# Historically remotepath could be a relative path, but it is not supported anymore.
raise OSError('The remotepath must be an absolute path')
if await self.isfile_async(remotepath) and not overwrite:
raise OSError('Destination already exists: not overwriting it')
async with self._semaphore:
try:
await self.async_backend.put(
localpath=localpath,
remotepath=remotepath,
dereference=dereference,
preserve=preserve,
recursive=False,
)
except OSError as exc:
raise OSError(f'Error while uploading file {localpath}: {exc}')
async def puttree_async(
self,
localpath: TransportPath,
remotepath: TransportPath,
dereference=True,
overwrite=True,
preserve=False,
*args,
**kwargs,
):
"""Put a folder recursively from local to remote.
:param localpath: an absolute local path
:param remotepath: an absolute remote path
:param dereference: follow symbolic links
Default = True
:param overwrite: if True overwrites files and folders (boolean).
Default = True
:param preserve: preserve file attributes
Default = False
:type localpath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type remotepath: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type overwrite: bool
:type preserve: bool
:raise ValueError: if local path is invalid
:raise OSError: if the localpath does not exist, or trying to overwrite
:raise OSError: if remotepath is invalid
"""
localpath = str(localpath)
remotepath = str(remotepath)
if not os.path.isabs(localpath):
raise ValueError('The localpath must be an absolute path')
if not os.path.exists(localpath):
raise OSError('The localpath does not exists')
if not os.path.isdir(localpath):
raise ValueError(f'Input localpath is not a folder: {localpath}')
if not remotepath:
raise OSError('remotepath must be a non empty string')
if await self.path_exists_async(remotepath) and not overwrite:
raise OSError("Can't overwrite existing files")
if await self.isfile_async(remotepath):
raise OSError('Cannot copy a directory into a file')
if not await self.isdir_async(remotepath): # in this case copy things in the remotepath directly
await self.makedirs_async(remotepath) # and make a directory at its place
else: # remotepath exists already: copy the folder inside of it!
remotepath = os.path.join(remotepath, os.path.split(localpath)[1])
await self.makedirs_async(remotepath, ignore_existing=overwrite) # create a nested folder
# This is written in this way, only because AiiDA expects to put file inside an existing folder
# Or to put and rename the parent folder at the same time
content_list = os.listdir(localpath)
for content_ in content_list:
parentpath = str(PurePath(localpath) / content_)
async with self._semaphore:
try:
await self.async_backend.put(
localpath=parentpath,
remotepath=remotepath,
dereference=dereference,
preserve=preserve,
recursive=True,
)
except OSError as exc:
raise OSError(f'Error while uploading file {parentpath}: {exc}')
async def copy_async(
self,
remotesource: TransportPath,
remotedestination: TransportPath,
dereference: bool = False,
recursive: bool = True,
preserve: bool = False,
):
"""Copy a file or a folder from remote to remote.
:param remotesource: abs path to the remote source directory / file
:param remotedestination: abs path to the remote destination directory / file
:param dereference: follow symbolic links
:param recursive: copy recursively
:param preserve: preserve file attributes
Default = False
:type remotesource: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type remotedestination: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type recursive: bool
:type preserve: bool
:raises: OSError, src does not exist or if the copy execution failed.
:raises: FileNotFoundError, if either remotesource does not exists
or remotedestination's parent path does not exists
"""
remotesource = str(remotesource)
remotedestination = str(remotedestination)
if has_magic(remotedestination):
raise ValueError('Pathname patterns are not allowed in the destination')
if not remotedestination:
raise ValueError('remotedestination must be a non empty string')
if not remotesource:
raise ValueError('remotesource must be a non empty string')
await self.async_backend.copy(
remotesource=remotesource,
remotedestination=remotedestination,
dereference=dereference,
recursive=recursive,
preserve=preserve,
)
async def copyfile_async(
self,
remotesource: TransportPath,
remotedestination: TransportPath,
dereference: bool = False,
preserve: bool = False,
):
"""Copy a file from remote to remote.
:param remotesource: path to the remote source file
:param remotedestination: path to the remote destination file
:param dereference: follow symbolic links
:param preserve: preserve file attributes
Default = False
:type remotesource: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type remotedestination: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type preserve: bool
:raises: OSError, src does not exist or if the copy execution failed.
"""
return await self.copy_async(remotesource, remotedestination, dereference, recursive=False, preserve=preserve)
async def copytree_async(
self,
remotesource: TransportPath,
remotedestination: TransportPath,
dereference: bool = False,
preserve: bool = False,
):
"""Copy a folder from remote to remote.
:param remotesource: path to the remote source directory
:param remotedestination: path to the remote destination directory
:param dereference: follow symbolic links
:param preserve: preserve file attributes
Default = False
:type remotesource: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type remotedestination: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type dereference: bool
:type preserve: bool
:raises: OSError, src does not exist or if the copy execution failed.
"""
return await self.copy_async(remotesource, remotedestination, dereference, recursive=True, preserve=preserve)
async def compress_async(
self,
format: str,
remotesources: Union[TransportPath, list[TransportPath]],
remotedestination: TransportPath,
root_dir: TransportPath,
overwrite: bool = True,
dereference: bool = False,
):
"""Compress a remote directory.
This method supports `remotesources` with glob patterns.
:param format: format of compression, should support: 'tar', 'tar.gz', 'tar.bz', 'tar.xz'
:param remotesources: path (list of paths) to the remote directory(ies) (and/)or file(s) to compress
:param remotedestination: path to the remote destination file (including file name).
:param root_dir: the path that compressed files will be relative to.
:param overwrite: if True, overwrite the file at remotedestination if it already exists.
:param dereference: if True, follow symbolic links.
Compress where they point to, instead of the links themselves.
:raises ValueError: if format is not supported
:raises OSError: if remotesource does not exist, or a matching file/folder cannot be found
:raises OSError: if remotedestination already exists and overwrite is False. Or if it is a directory.
:raises OSError: if cannot create remotedestination
:raises OSError: if root_dir is not a directory
"""
if not await self.isdir_async(root_dir):
raise OSError(f'The relative root {root_dir} does not exist, or is not a directory.')
if await self.isdir_async(remotedestination):
raise OSError(f'The remote destination {remotedestination} is a directory, should include a filename.')
if not overwrite and await self.path_exists_async(remotedestination):
raise OSError(f'The remote destination {remotedestination} already exists.')
if format not in ['tar', 'tar.gz', 'tar.bz2', 'tar.xz']:
raise ValueError(f'Unsupported compression format: {format}')
await self.makedirs_async(Path(remotedestination).parent, ignore_existing=True)
compression_flag = {
'tar': '',
'tar.gz': 'z',
'tar.bz2': 'j',
'tar.xz': 'J',
}[format]
if not isinstance(remotesources, list):
remotesources = [remotesources]
copy_list = []
for source in remotesources:
if has_magic(source):
copy_list += await self.glob_async(source, ignore_nonexisting=False)
else:
if not await self.path_exists_async(source):
raise OSError(f'The remote path {source} does not exist')
copy_list.append(source)
copy_items = ' '.join([escape_for_bash(str(Path(item).relative_to(root_dir))) for item in copy_list])
# note: order of the flags is important
tar_command = (
f'tar -c{compression_flag!s}{"h" if dereference else ""}f '
f'{escape_for_bash(str(remotedestination))} -C {escape_for_bash(str(root_dir))} ' + copy_items
)
retval, stdout, stderr = await self.exec_command_wait_async(tar_command)
if retval == 0:
if stderr.strip():
self.logger.warning(f'There was nonempty stderr in the tar command: {stderr}')
else:
self.logger.error(
"Problem executing tar. Exit code: {}, stdout: '{}', stderr: '{}', command: '{}'".format(
retval, stdout, stderr, tar_command
)
)
raise OSError(f'Error while creating the tar archive. Exit code: {retval}')
async def extract_async(
self,
remotesource: TransportPath,
remotedestination: TransportPath,
overwrite: bool = True,
strip_components: int = 0,
):
"""Extract a remote archive.
Does not accept glob patterns, as it doesn't make much sense and we don't have a usecase for it.
:param remotesource: path to the remote archive to extract
:param remotedestination: path to the remote destination directory
:param overwrite: if True, overwrite the file at remotedestination if it already exists
(we don't have a usecase for False, sofar. The parameter is kept for clarity.)
:param strip_components: strip NUMBER leading components from file names on extraction
:raises OSError: if the remotesource does not exist.
:raises OSError: if the extraction fails.
"""
if not overwrite:
raise NotImplementedError('The overwrite=False is not implemented yet')
if not await self.path_exists_async(remotesource):
raise OSError(f'The remote path {remotesource} does not exist')
await self.makedirs_async(remotedestination, ignore_existing=True)
tar_command = (
f'tar --strip-components {strip_components} -xf '
f'{escape_for_bash(str(remotesource))} -C {escape_for_bash(str(remotedestination))} '
)
retval, stdout, stderr = await self.exec_command_wait_async(tar_command)
if retval == 0:
if stderr.strip():
self.logger.warning(f'There was nonempty stderr in the tar command: {stderr}')
else:
self.logger.error(
"Problem executing tar. Exit code: {}, stdout: '{}', " "stderr: '{}', command: '{}'".format(
retval, stdout, stderr, tar_command
)
)
raise OSError(f'Error while extracting the tar archive. Exit code: {retval}')
async def exec_command_wait_async(
self,
command: str,
stdin: Optional[str] = None,
encoding: str = 'utf-8',
workdir: Optional[TransportPath] = None,
timeout: Optional[float] = None,
**kwargs,
):
"""Execute a command on the remote machine and wait for it to finish.
:param command: the command to execute
:param stdin: the input to pass to the command
Default = None
:param encoding: (IGNORED) this is here just to keep the same signature as the one in `Transport` class
Default = 'utf-8'
:param workdir: the working directory where to execute the command
Default = None
:param timeout: the timeout in seconds
Default = None
:type command: str
:type stdin: str
:type encoding: str
:type workdir: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:type timeout: float
:return: a tuple with the return code, the stdout and the stderr of the command
:rtype: tuple(int, str, str)
"""
if workdir:
workdir = str(workdir)
command = f'cd {escape_for_bash(workdir)} && ( {command} )'
async with self._semaphore:
try:
result = await self.async_backend.run(
command=command,
stdin=stdin,
timeout=timeout,
)
except Exception as exc:
self.logger.warning(f'Failed to execute command on remote connection: {exc}')
raise
return result
async def get_attribute_async(self, path: TransportPath):
"""Return an object FixedFieldsAttributeDict for file in a given path,
as defined in aiida.common.extendeddicts
Each attribute object consists in a dictionary with the following keys:
* st_size: size of files, in bytes
* st_uid: user id of owner
* st_gid: group id of owner
* st_mode: protection bits
* st_atime: time of most recent access
* st_mtime: time of most recent modification
:param path: path to file
:type path: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:return: object FixedFieldsAttributeDict
"""
path = str(path)
from aiida.transports.util import FileAttribute
obj_stat = await self.async_backend.lstat(path)
aiida_attr = FileAttribute()
for key in aiida_attr._valid_fields:
if key == 'st_size':
aiida_attr[key] = obj_stat.size
elif key == 'st_uid':
aiida_attr[key] = obj_stat.uid
elif key == 'st_gid':
aiida_attr[key] = obj_stat.gid
elif key == 'st_mode':
aiida_attr[key] = obj_stat.permissions
elif key == 'st_atime':
aiida_attr[key] = obj_stat.atime
elif key == 'st_mtime':
aiida_attr[key] = obj_stat.mtime
else:
raise NotImplementedError(f'Mapping the {key} attribute is not implemented')
return aiida_attr
async def isdir_async(self, path: TransportPath):
"""Return True if the given path is a directory, False otherwise.
Return False also if the path does not exist.
:param path: the absolute path to check
:type path: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:return: True if the path is a directory, False otherwise
"""
# Return False on empty string
if not path:
return False
path = str(path)
return await self.async_backend.isdir(path)
async def isfile_async(self, path: TransportPath):
"""Return True if the given path is a file, False otherwise.
Return False also if the path does not exist.
:param path: the absolute path to check
:type path: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:return: True if the path is a file, False otherwise
"""
# Return False on empty string
if not path:
return False
path = str(path)
return await self.async_backend.isfile(path)
async def listdir_async(self, path: TransportPath, pattern=None):
"""Return a list of the names of the entries in the given path.
The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.
:param path: an absolute path
:param pattern: if used, listdir returns a list of files matching
filters in Unix style. Unix only.
:type path: :class:`Path <pathlib.Path>`, :class:`PurePosixPath <pathlib.PurePosixPath>`, or `str`
:return: a list of strings
"""
path = str(path)
if not pattern:
list_ = await self.async_backend.listdir(path)
else:
patterned_path = pattern if pattern.startswith('/') else Path(path).joinpath(pattern)
# I put the type ignore here because the asyncssh.sftp.glob()
# method always returns a sequence of str, if input is str
list_ = list(await self.glob_async(patterned_path))
for item in ['..', '.']:
if item in list_:
list_.remove(item)
return list_
async def listdir_withattributes_async(self, path: TransportPath, pattern: Optional[str] = None):
"""Return a list of the names of the entries in the given path.
The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.
:param path: absolute path to list