aiida.transports package#
Module for classes and utilities to define transports to other machines.
Subpackages#
- aiida.transports.plugins package
- Submodules
LocalTransport
LocalTransport.DEFAULT_MINIMUM_JOB_POLL_INTERVAL
LocalTransport._DEFAULT_SAFE_OPEN_INTERVAL
LocalTransport.__abstractmethods__
LocalTransport.__init__()
LocalTransport.__module__
LocalTransport.__str__()
LocalTransport._abc_impl
LocalTransport._exec_command_internal()
LocalTransport._local_listdir()
LocalTransport._os_path_split_asunder()
LocalTransport._valid_auth_options
LocalTransport.chdir()
LocalTransport.chmod()
LocalTransport.chown()
LocalTransport.close()
LocalTransport.copy()
LocalTransport.copyfile()
LocalTransport.copytree()
LocalTransport.curdir
LocalTransport.exec_command_wait_bytes()
LocalTransport.get()
LocalTransport.get_attribute()
LocalTransport.getcwd()
LocalTransport.getfile()
LocalTransport.gettree()
LocalTransport.gotocomputer_command()
LocalTransport.isdir()
LocalTransport.isfile()
LocalTransport.listdir()
LocalTransport.makedirs()
LocalTransport.mkdir()
LocalTransport.normalize()
LocalTransport.open()
LocalTransport.path_exists()
LocalTransport.put()
LocalTransport.putfile()
LocalTransport.puttree()
LocalTransport.remove()
LocalTransport.rename()
LocalTransport.rmdir()
LocalTransport.rmtree()
LocalTransport.symlink()
SshTransport
SshTransport._MAX_EXEC_COMMAND_LOG_SIZE
SshTransport.__abstractmethods__
SshTransport.__init__()
SshTransport.__module__
SshTransport.__str__()
SshTransport._abc_impl
SshTransport._close_proxies()
SshTransport._exec_command_internal()
SshTransport._exec_cp()
SshTransport._get_allow_agent_suggestion_string()
SshTransport._get_compress_suggestion_string()
SshTransport._get_gss_auth_suggestion_string()
SshTransport._get_gss_deleg_creds_suggestion_string()
SshTransport._get_gss_host_suggestion_string()
SshTransport._get_gss_kex_suggestion_string()
SshTransport._get_key_filename_suggestion_string()
SshTransport._get_key_policy_suggestion_string()
SshTransport._get_load_system_host_keys_suggestion_string()
SshTransport._get_look_for_keys_suggestion_string()
SshTransport._get_port_suggestion_string()
SshTransport._get_proxy_command_suggestion_string()
SshTransport._get_proxy_jump_suggestion_string()
SshTransport._get_timeout_suggestion_string()
SshTransport._get_username_suggestion_string()
SshTransport._local_listdir()
SshTransport._os_path_split_asunder()
SshTransport._symlink()
SshTransport._valid_auth_options
SshTransport._valid_connect_options
SshTransport._valid_connect_params
SshTransport.chdir()
SshTransport.chmod()
SshTransport.chown()
SshTransport.close()
SshTransport.copy()
SshTransport.copyfile()
SshTransport.copytree()
SshTransport.exec_command_wait_bytes()
SshTransport.get()
SshTransport.get_attribute()
SshTransport.getcwd()
SshTransport.getfile()
SshTransport.gettree()
SshTransport.gotocomputer_command()
SshTransport.isdir()
SshTransport.isfile()
SshTransport.listdir()
SshTransport.lstat()
SshTransport.makedirs()
SshTransport.mkdir()
SshTransport.normalize()
SshTransport.open()
SshTransport.path_exists()
SshTransport.put()
SshTransport.putfile()
SshTransport.puttree()
SshTransport.remove()
SshTransport.rename()
SshTransport.rmdir()
SshTransport.rmtree()
SshTransport.sftp
SshTransport.sshclient
SshTransport.stat()
SshTransport.symlink()
convert_to_bool()
parse_sshconfig()
- Submodules
Submodules#
Common cli utilities for transport plugins.
- aiida.transports.cli.common_params(command_func)[source]#
Decorate a command function with common click parameters for all transport plugins.
- aiida.transports.cli.configure_computer_main(computer, user, **kwargs)[source]#
Configure a computer via the CLI.
- aiida.transports.cli.create_configure_cmd(transport_type)[source]#
Create verdi computer configure subcommand for a transport type.
- aiida.transports.cli.create_option(name, spec)[source]#
Create a click option from a name and partial specs as used in transport auth_options.
- aiida.transports.cli.interactive_default(key, also_non_interactive=False)[source]#
Create a contextual_default value callback for an auth_param key.
- Parameters:
key – the name of the option.
also_non_interactive – indicates whether this option should provide a default also in non-interactive mode. If False, the option will raise MissingParameter if no explicit value is specified when the command is called in non-interactive mode.
- aiida.transports.cli.match_comp_transport(ctx, param, computer, transport_type)[source]#
Check the computer argument against the transport type.
- aiida.transports.cli.transport_option_default(name, computer)[source]#
Determine the default value for an auth_param key.
- aiida.transports.cli.transport_options(transport_type)[source]#
Decorate a command with all options for a computer configure subcommand for transport_type.
Transport interface.
- class aiida.transports.transport.Transport(*args, **kwargs)[source]#
Bases:
ABC
Abstract class for a generic transport (ssh, local, …) contains the set of minimal methods.
- DEFAULT_MINIMUM_JOB_POLL_INTERVAL = 10#
- _DEFAULT_SAFE_OPEN_INTERVAL = 30.0#
- _MAGIC_CHECK = re.compile('[*?[]')#
- __abstractmethods__ = frozenset({'_exec_command_internal', 'chdir', 'chmod', 'chown', 'close', 'copy', 'copyfile', 'copytree', 'exec_command_wait_bytes', 'get', 'get_attribute', 'getcwd', 'getfile', 'gettree', 'gotocomputer_command', 'isdir', 'isfile', 'listdir', 'makedirs', 'mkdir', 'normalize', 'open', 'path_exists', 'put', 'putfile', 'puttree', 'remove', 'rename', 'rmdir', 'rmtree', 'symlink'})#
- __annotations__ = {'_valid_auth_options': <class 'list'>}#
- __dict__ = mappingproxy({'__module__': 'aiida.transports.transport', '__annotations__': {'_valid_auth_options': <class 'list'>}, '__doc__': 'Abstract class for a generic transport (ssh, local, ...) contains the set of minimal methods.', 'DEFAULT_MINIMUM_JOB_POLL_INTERVAL': 10, '_DEFAULT_SAFE_OPEN_INTERVAL': 30.0, '_valid_auth_params': None, '_MAGIC_CHECK': re.compile('[*?[]'), '_valid_auth_options': [], '_common_auth_options': [('use_login_shell', {'default': True, 'switch': True, 'prompt': 'Use login shell when executing command', 'help': ' Not using a login shell can help suppress potential spurious text output that can prevent AiiDA from parsing the output of commands, but may result in some startup files (.profile) not being sourced.', 'non_interactive_default': True}), ('safe_interval', {'type': <class 'float'>, 'prompt': 'Connection cooldown time (s)', 'help': 'Minimum time interval in seconds between opening new connections.', 'callback': <function validate_positive_number>})], '__init__': <function Transport.__init__>, '__enter__': <function Transport.__enter__>, '__exit__': <function Transport.__exit__>, 'is_open': <property object>, 'open': <function Transport.open>, 'close': <function Transport.close>, '__repr__': <function Transport.__repr__>, '__str__': <function Transport.__str__>, 'set_logger_extra': <function Transport.set_logger_extra>, 'get_short_doc': <classmethod(<function Transport.get_short_doc>)>, 'get_valid_auth_params': <classmethod(<function Transport.get_valid_auth_params>)>, 'auth_options': <aiida.common.lang.classproperty object>, '_get_safe_interval_suggestion_string': <classmethod(<function Transport._get_safe_interval_suggestion_string>)>, '_get_use_login_shell_suggestion_string': <classmethod(<function Transport._get_use_login_shell_suggestion_string>)>, 'logger': <property object>, 'get_safe_open_interval': <function Transport.get_safe_open_interval>, 'chdir': <function Transport.chdir>, 'chmod': <function Transport.chmod>, 'chown': <function Transport.chown>, 'copy': <function Transport.copy>, 'copyfile': <function Transport.copyfile>, 'copytree': <function Transport.copytree>, 'copy_from_remote_to_remote': <function Transport.copy_from_remote_to_remote>, '_exec_command_internal': <function Transport._exec_command_internal>, 'exec_command_wait_bytes': <function Transport.exec_command_wait_bytes>, 'exec_command_wait': <function Transport.exec_command_wait>, 'get': <function Transport.get>, 'getfile': <function Transport.getfile>, 'gettree': <function Transport.gettree>, 'getcwd': <function Transport.getcwd>, 'get_attribute': <function Transport.get_attribute>, 'get_mode': <function Transport.get_mode>, 'isdir': <function Transport.isdir>, 'isfile': <function Transport.isfile>, 'listdir': <function Transport.listdir>, 'listdir_withattributes': <function Transport.listdir_withattributes>, 'makedirs': <function Transport.makedirs>, 'mkdir': <function Transport.mkdir>, 'normalize': <function Transport.normalize>, 'put': <function Transport.put>, 'putfile': <function Transport.putfile>, 'puttree': <function Transport.puttree>, 'remove': <function Transport.remove>, 'rename': <function Transport.rename>, 'rmdir': <function Transport.rmdir>, 'rmtree': <function Transport.rmtree>, 'gotocomputer_command': <function Transport.gotocomputer_command>, 'symlink': <function Transport.symlink>, 'whoami': <function Transport.whoami>, 'path_exists': <function Transport.path_exists>, 'glob': <function Transport.glob>, 'iglob': <function Transport.iglob>, 'glob1': <function Transport.glob1>, 'glob0': <function Transport.glob0>, 'has_magic': <function Transport.has_magic>, '_gotocomputer_string': <function Transport._gotocomputer_string>, '__dict__': <attribute '__dict__' of 'Transport' objects>, '__weakref__': <attribute '__weakref__' of 'Transport' objects>, '__abstractmethods__': frozenset({'_exec_command_internal', 'getcwd', 'remove', 'isfile', 'puttree', 'get', 'rename', 'makedirs', 'chmod', 'get_attribute', 'mkdir', 'putfile', 'chdir', 'open', 'gettree', 'normalize', 'path_exists', 'gotocomputer_command', 'getfile', 'copy', 'exec_command_wait_bytes', 'copyfile', 'rmtree', 'rmdir', 'chown', 'copytree', 'close', 'listdir', 'symlink', 'isdir', 'put'}), '_abc_impl': <_abc._abc_data object>})#
- __enter__()[source]#
For transports that require opening a connection, opens all required channels (used in ‘with’ statements).
This object can be used in nested with statements and the connection will only be opened once and closed when the final with scope finishes e.g.:
t = Transport() with t: # Connection is now open.. with t: # ..still open.. pass # ..still open.. # ...closed
- __exit__(type_, value, traceback)[source]#
Closes connections, if needed (used in ‘with’ statements).
- __init__(*args, **kwargs)[source]#
__init__ method of the Transport base class.
- Parameters:
safe_interval – (optional, default self._DEFAULT_SAFE_OPEN_INTERVAL) Minimum time interval in seconds between opening new connections.
use_login_shell – (optional, default True) if False, do not use a login shell when executing command
- __module__ = 'aiida.transports.transport'#
- __weakref__#
list of weak references to the object
- _abc_impl = <_abc._abc_data object>#
- _common_auth_options = [('use_login_shell', {'default': True, 'help': ' Not using a login shell can help suppress potential spurious text output that can prevent AiiDA from parsing the output of commands, but may result in some startup files (.profile) not being sourced.', 'non_interactive_default': True, 'prompt': 'Use login shell when executing command', 'switch': True}), ('safe_interval', {'callback': <function validate_positive_number>, 'help': 'Minimum time interval in seconds between opening new connections.', 'prompt': 'Connection cooldown time (s)', 'type': <class 'float'>})]#
- abstract _exec_command_internal(command, **kwargs)[source]#
Execute the command on the shell, similarly to os.system.
Enforce the execution to be run from the cwd (as given by self.getcwd), if this is not None.
If possible, use the higher-level exec_command_wait function.
- Parameters:
command (str) – execute the command given as a string
- Returns:
stdin, stdout, stderr and the session, when this exists (can be None).
- classmethod _get_safe_interval_suggestion_string(computer)[source]#
Return as a suggestion the default safe interval of this Transport class.
This is used to provide a default in
verdi computer configure
.
- classmethod _get_use_login_shell_suggestion_string(computer)[source]#
Return a suggestion for the specific field.
- _valid_auth_params = None#
- auth_options = {'safe_interval': {'callback': <function validate_positive_number>, 'help': 'Minimum time interval in seconds between opening new connections.', 'prompt': 'Connection cooldown time (s)', 'type': <class 'float'>}, 'use_login_shell': {'default': True, 'help': ' Not using a login shell can help suppress potential spurious text output that can prevent AiiDA from parsing the output of commands, but may result in some startup files (.profile) not being sourced.', 'non_interactive_default': True, 'prompt': 'Use login shell when executing command', 'switch': True}}#
- abstract chown(path, uid, gid)[source]#
Change the owner (uid) and group (gid) of a file. As with python’s os.chown function, you must pass both arguments, so if you only want to change one, use stat first to retrieve the current owner and group.
- abstract copy(remotesource, remotedestination, dereference=False, recursive=True)[source]#
Copy a file or a directory from remote source to remote destination (On the same remote machine)
- Parameters:
remotesource (str) – path of the remote source directory / file
remotedestination (str) – path of the remote destination directory / file
dereference (bool) – if True copy the contents of any symlinks found, otherwise copy the symlinks themselves
recursive (bool) – if True copy directories recursively, otherwise only copy the specified file(s)
- Raises:
OSError, if one of src or dst does not exist
- copy_from_remote_to_remote(transportdestination, remotesource, remotedestination, **kwargs)[source]#
Copy files or folders from a remote computer to another remote computer.
- Parameters:
transportdestination – transport to be used for the destination computer
remotesource (str) – path to the remote source directory / file
remotedestination (str) – path to the remote destination directory / file
kwargs – keyword parameters passed to the call to transportdestination.put, except for ‘dereference’ that is passed to self.get
Note
the keyword ‘dereference’ SHOULD be set to False for the final put (onto the destination), while it can be set to the value given in kwargs for the get from the source. In that way, a symbolic link would never be followed in the final copy to the remote destination. That way we could avoid getting unknown (potentially malicious) files into the destination computer. HOWEVER, since dereference=False is currently NOT supported by all plugins, we still force it to True for the final put.
Note
the supported keys in kwargs are callback, dereference, overwrite and ignore_nonexisting.
- abstract copyfile(remotesource, remotedestination, dereference=False)[source]#
Copy a file from remote source to remote destination (On the same remote machine)
- Parameters:
- Raises:
OSError – if one of src or dst does not exist
- abstract copytree(remotesource, remotedestination, dereference=False)[source]#
Copy a folder from remote source to remote destination (On the same remote machine)
- Parameters:
- Raises:
OSError – if one of src or dst does not exist
- exec_command_wait(command, stdin=None, encoding='utf-8', **kwargs)[source]#
Executes the specified command and waits for it to finish.
- Note:
this function also decodes the bytes received into a string with the specified encoding, which is set to be
utf-8
by default (for backward-compatibility with earlier versions) of AiiDA. Use this method only if you are sure that you are getting a properly encoded string; otherwise, use theexec_command_wait_bytes
method that returns the undecoded byte stream.- Note:
additional kwargs are passed to the
exec_command_wait_bytes
function, that might use them depending on the plugin.- Parameters:
command – the command to execute
stdin – (optional,default=None) can be a string or a file-like object.
encoding – the encoding to use to decode the byte stream received from the remote command execution.
- Returns:
a tuple with (return_value, stdout, stderr) where stdout and stderr are both strings, decoded with the specified encoding.
- abstract exec_command_wait_bytes(command, stdin=None, **kwargs)[source]#
Execute the command on the shell, waits for it to finish, and return the retcode, the stdout and the stderr as bytes.
Enforce the execution to be run from the pwd (as given by self.getcwd), if this is not None.
The command implementation can have some additional plugin-specific kwargs.
- Parameters:
command (str) – execute the command given as a string
stdin – (optional,default=None) can be a string or a file-like object.
- Returns:
a tuple: the retcode (int), stdout (bytes) and stderr (bytes).
- abstract get(remotepath, localpath, *args, **kwargs)[source]#
Retrieve a file or folder from remote source to local destination dst must be an absolute path (src not necessarily)
- Parameters:
remotepath – (str) remote_folder_path
localpath – (str) local_folder_path
- abstract get_attribute(path)[source]#
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
- Parameters:
path (str) – path to file
- Returns:
object FixedFieldsAttributeDict
- get_mode(path)[source]#
Return the portion of the file’s mode that can be set by chmod().
- Parameters:
path (str) – path to file
- Returns:
the portion of the file’s mode that can be set by chmod()
- get_safe_open_interval()[source]#
Get an interval (in seconds) that suggests how long the user should wait between consecutive calls to open the transport. This can be used as a way to get the user to not swamp a limited number of connections, etc. However it is just advisory.
If returns 0, it is taken that there are no reasons to limit the frequency of open calls.
In the main class, it returns a default value (>0 for safety), set in the _DEFAULT_SAFE_OPEN_INTERVAL attribute of the class. Plugins should override it.
- Returns:
The safe interval between calling open, in seconds
- Return type:
- classmethod get_short_doc()[source]#
Return the first non-empty line of the class docstring, if available
- abstract getcwd()[source]#
Get working directory
- Returns:
a string identifying the current working directory
- abstract getfile(remotepath, localpath, *args, **kwargs)[source]#
Retrieve a file from remote source to local destination dst must be an absolute path (src not necessarily)
- abstract gettree(remotepath, localpath, *args, **kwargs)[source]#
Retrieve a folder recursively from remote source to local destination dst must be an absolute path (src not necessarily)
- glob(pathname)[source]#
Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la fnmatch.
- glob0(dirname, basename)[source]#
Wrap basename i a list if it is empty or if dirname/basename is an existing path, else return empty list.
- abstract gotocomputer_command(remotedir)[source]#
Return a string to be run using os.system in order to connect via the transport to the remote directory.
Expected behaviors:
A new bash session is opened
A reasonable error message is produced if the folder does not exist
- Parameters:
remotedir (str) – the full path of the remote directory
- iglob(pathname)[source]#
Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la fnmatch.
- property is_open#
- abstract isdir(path)[source]#
True if path is an existing directory.
- Parameters:
path (str) – path to directory
- Returns:
boolean
- abstract isfile(path)[source]#
Return True if path is an existing file.
- Parameters:
path (str) – path to file
- Returns:
boolean
- abstract listdir(path='.', pattern=None)[source]#
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.
- listdir_withattributes(path='.', pattern=None)[source]#
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.
- Parameters:
- Returns:
a list of dictionaries, one per entry. The schema of the dictionary is the following:
{ 'name': String, 'attributes': FileAttributeObject, 'isdir': Bool }
where ‘name’ is the file or folder directory, and any other information is metadata (if the file is a folder, a directory, …). ‘attributes’ behaves as the output of transport.get_attribute(); isdir is a boolean indicating if the object is a directory or not.
- property logger#
Return the internal logger. If you have set extra parameters using set_logger_extra(), a suitable LoggerAdapter instance is created, bringing with itself also the extras.
- abstract makedirs(path, ignore_existing=False)[source]#
Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist.
- abstract normalize(path='.')[source]#
Return the normalized path (on the server) of a given path. This can be used to quickly resolve symbolic links or determine what the server is considering to be the “current folder”.
- abstract put(localpath, remotepath, *args, **kwargs)[source]#
Put a file or a directory from local src to remote dst. src must be an absolute path (dst not necessarily)) Redirects to putfile and puttree.
- abstract putfile(localpath, remotepath, *args, **kwargs)[source]#
Put a file from local src to remote dst. src must be an absolute path (dst not necessarily))
- abstract puttree(localpath, remotepath, *args, **kwargs)[source]#
Put a folder recursively from local src to remote dst. src must be an absolute path (dst not necessarily))
- abstract remove(path)[source]#
Remove the file at the given path. This only works on files; for removing folders (directories), use rmdir.
- abstract rename(oldpath, newpath)[source]#
Rename a file or folder from oldpath to newpath.
- Parameters:
- Raises:
OSError – if oldpath/newpath is not found
ValueError – if oldpath/newpath is not a valid string
- abstract rmdir(path)[source]#
Remove the folder named path. This works only for empty folders. For recursive remove, use rmtree.
- Parameters:
path (str) – absolute path to the folder to remove
- abstract rmtree(path)[source]#
Remove recursively the content at path
- Parameters:
path (str) – absolute path to remove
- set_logger_extra(logger_extra)[source]#
Pass the data that should be passed automatically to self.logger as ‘extra’ keyword. This is typically useful if you pass data obtained using get_dblogger_extra in aiida.orm.utils.log, to automatically log also to the DbLog table.
- Parameters:
logger_extra – data that you want to pass as extra to the self.logger. To write to DbLog, it should be created by the aiida.orm.utils.log.get_dblogger_extra function. Pass None if you do not want to have extras passed.
- exception aiida.transports.transport.TransportInternalError[source]#
Bases:
InternalError
Raised if there is a transport error that is raised to an internal error (e.g. a transport method called without opening the channel first).
- __annotations__ = {}#
- __module__ = 'aiida.transports.transport'#
- aiida.transports.transport.validate_positive_number(ctx, param, value)[source]#
Validate that the number passed to this parameter is a positive number.
- Parameters:
ctx – the click.Context
param – the parameter
value – the value passed for the parameter
- Raises:
click.BadParameter – if the value is not a positive number
General utilities for Transport classes.
- class aiida.transports.util.FileAttribute(init=None)[source]#
Bases:
FixedFieldsAttributeDict
A class, resembling a dictionary, to describe the attributes of a file, that is returned by get_attribute(). Possible keys: st_size, st_uid, st_gid, st_mode, st_atime, st_mtime
- __annotations__ = {}#
- __module__ = 'aiida.transports.util'#
- _valid_fields = ('st_size', 'st_uid', 'st_gid', 'st_mode', 'st_atime', 'st_mtime')#
- class aiida.transports.util._DetachedProxyCommand(command_line)[source]#
Bases:
ProxyCommand
Modifies paramiko’s ProxyCommand by launching the process in a separate process group.
- __init__(command_line)[source]#
Create a new CommandProxy instance. The instance created by this class can be passed as an argument to the .Transport class.
- Parameters:
command_line (str) – the command that should be executed and used as the proxy.
- __module__ = 'aiida.transports.util'#
- aiida.transports.util.copy_from_remote_to_remote(transportsource, transportdestination, remotesource, remotedestination, **kwargs)[source]#
Copy files or folders from a remote computer to another remote computer.
- Parameters:
transportsource – transport to be used for the source computer
transportdestination – transport to be used for the destination computer
remotesource (str) – path to the remote source directory / file
remotedestination (str) – path to the remote destination directory / file
kwargs – keyword parameters passed to the final put, except for ‘dereference’ that is passed to the initial get
Note
it uses the method transportsource.copy_from_remote_to_remote