2021-11-25 09:40:25 +00:00
|
|
|
import paramiko as pikuniku # :P
|
2021-11-20 14:40:07 +00:00
|
|
|
|
2021-11-26 06:03:13 +00:00
|
|
|
from paramiko.client import SSHClient, WarningPolicy
|
2021-11-20 14:40:07 +00:00
|
|
|
|
|
|
|
from io import BytesIO
|
2021-11-25 09:40:25 +00:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import Union, Optional
|
2021-11-20 14:40:07 +00:00
|
|
|
|
|
|
|
import errno
|
|
|
|
import stat
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
|
2021-11-20 14:40:07 +00:00
|
|
|
class Connection:
|
2021-11-25 09:40:25 +00:00
|
|
|
"""Class representing an SSH/SFTP connection to a Vessel
|
|
|
|
"""
|
|
|
|
|
2021-11-20 14:40:07 +00:00
|
|
|
def __init__(self, vessel):
|
2021-11-25 09:40:25 +00:00
|
|
|
"""Initialize a new Connection to a Vessel
|
|
|
|
|
|
|
|
Args:
|
|
|
|
vessel (classes.vessel.Vessel): Vessel object to open connection to
|
|
|
|
"""
|
2021-11-20 14:40:07 +00:00
|
|
|
self._vessel = vessel
|
|
|
|
self._client = SSHClient()
|
|
|
|
self._client.load_system_host_keys()
|
2021-11-26 06:03:13 +00:00
|
|
|
self._client.set_missing_host_key_policy(WarningPolicy)
|
2021-11-26 06:39:21 +00:00
|
|
|
self._client.connect(vessel.address, vessel.port, vessel.username,
|
2021-11-26 10:23:39 +00:00
|
|
|
vessel.password, timeout=vessel.timeout,
|
|
|
|
passphrase=vessel.passphrase)
|
2021-11-20 14:40:07 +00:00
|
|
|
self._transport = self._client.get_transport()
|
|
|
|
self._transport.set_keepalive(10)
|
|
|
|
self._sftp = self._client.open_sftp()
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def _exists(self, path: Union[str, Path]) -> bool:
|
|
|
|
"""Check if a path exists on the Vessel. Symlinks are not followed.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
path (str, pathlib.Path): Path to check on the vessel
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: True if the path exists on the Vessel, else False
|
|
|
|
"""
|
2021-11-20 14:40:07 +00:00
|
|
|
try:
|
|
|
|
self._sftp.stat(str(path))
|
|
|
|
return True
|
|
|
|
except FileNotFoundError:
|
|
|
|
return False
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def _isdir(self, path: Union[str, Path]) -> bool:
|
|
|
|
"""Check if a path is a directory on the Vessel. Symlinks are followed.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
path (str, pathlib.Path): Path to check on the vessel
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: True if the path provided is a directory on the Vessel, False
|
|
|
|
if it is a different kind of file.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
FileNotFoundError: Raised if the path does not exist on the Vessel
|
|
|
|
"""
|
2021-11-20 14:40:07 +00:00
|
|
|
return stat.S_ISDIR(self._sftp.lstat(str(path)).st_mode)
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def _mkdir(self, path: Union[str, Path]) -> None:
|
|
|
|
"""Create new directory on the Vessel
|
|
|
|
|
|
|
|
Args:
|
|
|
|
path (str, pathlib.Path): Path at which to create a new directory
|
|
|
|
on the Vessel
|
2021-11-20 14:40:07 +00:00
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
Raises:
|
|
|
|
IOError: Raised if the directory cannot be created
|
|
|
|
"""
|
|
|
|
self._sftp.mkdir(str(path))
|
|
|
|
|
|
|
|
def _listdir(self, path: Optional[Union[str, Path]] = None) -> list[Optional[str]]:
|
|
|
|
"""List files in a directory on the Vessel
|
|
|
|
|
|
|
|
Args:
|
|
|
|
path (str, pathlib.Path, optional): Path at which to list contents.
|
|
|
|
Will use current working directory if None. Defaults to None.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
list: List of the names of files (str) located at the provided path
|
|
|
|
"""
|
2021-11-26 06:49:27 +00:00
|
|
|
return self._sftp.listdir(str(path) if path else ".")
|
2021-11-20 14:40:07 +00:00
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def _remove(self, path: Union[str, Path]) -> None:
|
|
|
|
"""Remove a file from the Vessel
|
|
|
|
|
|
|
|
Args:
|
|
|
|
path (str, pathlib.Path): Path of the file to delete
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
FileNotFoundError: Raised if no file is found at the given path
|
|
|
|
IOError: Raised if the file cannot be deleted
|
|
|
|
"""
|
2021-11-20 14:40:07 +00:00
|
|
|
return self._sftp.remove(str(path))
|
|
|
|
|
2021-11-26 10:23:39 +00:00
|
|
|
def assertTempDirectory(self) -> None:
|
|
|
|
"""Make sure that the temp directory exists on the Vessel
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
ValueError: Raised if the path is already in use on the vessel but
|
|
|
|
is not a directory.
|
|
|
|
IOError: Raised if the directory does not exist but cannot be
|
|
|
|
created.
|
|
|
|
"""
|
|
|
|
if not self._exists(self._vessel.tempdir):
|
|
|
|
self._mkdir(self._vessel.tempdir)
|
|
|
|
elif not self._isdir(self._vessel.tempdir):
|
|
|
|
raise ValueError(
|
|
|
|
f"{self._vessel.tempdir} exists but is not a directory on Vessel {self._vessel.name}!")
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def assertDirectories(self, directory) -> None:
|
|
|
|
"""Make sure that destination and temp directories exist on the Vessel
|
|
|
|
|
|
|
|
Args:
|
|
|
|
directory (classes.directory.Directory): Directory object
|
|
|
|
representing the directory to check
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
ValueError: Raised if a path is already in use on the vessel but
|
|
|
|
not a directory.
|
|
|
|
IOError: Raised if a directory that does not exist cannot be
|
|
|
|
created.
|
|
|
|
"""
|
2021-11-22 10:14:38 +00:00
|
|
|
for d in [directory, self._vessel.tempdir]:
|
2021-11-20 14:40:07 +00:00
|
|
|
if not self._exists(d):
|
|
|
|
self._mkdir(d)
|
|
|
|
elif not self._isdir(d):
|
2021-11-25 09:40:25 +00:00
|
|
|
raise ValueError(
|
|
|
|
f"{d} exists but is not a directory on Vessel {self._vessel.name}!")
|
|
|
|
|
|
|
|
def assertChunkComplete(self, chunk, path: Optional[Union[str, Path]] = None) -> bool:
|
|
|
|
"""Check if a Chunk has been uploaded correctly
|
2021-11-20 14:40:07 +00:00
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
Args:
|
|
|
|
chunk (classes.chunk.Chunk): Chunk object to verify upload for
|
|
|
|
path (str, pathlib.Path, optional): Optional path at which to
|
|
|
|
check. If None, will get default path from Chunk object.
|
|
|
|
Defaults to None.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: True if file has been uploaded correctly, else False
|
|
|
|
"""
|
2021-11-22 10:14:38 +00:00
|
|
|
path = path or self._vessel.tempdir / chunk.getTempName()
|
2021-11-20 14:40:07 +00:00
|
|
|
|
|
|
|
if self._exists(path):
|
2021-11-25 09:40:25 +00:00
|
|
|
# "-b" should not be required, but makes sure to use binary mode
|
|
|
|
_, o, _ = self._client.exec_command("sha256sum -b " + str(path))
|
|
|
|
|
|
|
|
# Blocking for the command to complete
|
2021-11-20 14:40:07 +00:00
|
|
|
o.channel.recv_exit_status()
|
2021-11-25 09:40:25 +00:00
|
|
|
|
|
|
|
# Remove the file if it is broken
|
2021-11-20 14:40:07 +00:00
|
|
|
if not o.readline().split()[0] == chunk.getHash():
|
|
|
|
self._remove(path)
|
2021-11-25 09:40:25 +00:00
|
|
|
|
2021-11-20 14:40:07 +00:00
|
|
|
else:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2021-11-25 15:31:49 +00:00
|
|
|
def pushChunk(self, chunk, path: Optional[Union[str, Path]] = None) -> None:
|
2021-11-25 09:40:25 +00:00
|
|
|
"""Push the content of a Chunk object to the Vessel
|
|
|
|
|
|
|
|
Args:
|
|
|
|
chunk (classes.chunk.Chunk): Chunk object containing the data to
|
|
|
|
push to the Vessel
|
|
|
|
path (str, pathlib.Path, optional): Path at which to store the
|
|
|
|
Chunk on the Vessel. If None, use default location provided by
|
|
|
|
Chunk object. Defaults to None.
|
|
|
|
"""
|
|
|
|
path = path or (self._vessel.tempdir / chunk.getTempName())
|
2021-11-20 14:40:07 +00:00
|
|
|
flo = BytesIO(chunk.data)
|
2021-11-26 10:23:39 +00:00
|
|
|
self._sftp.putfo(flo, str(path), len(chunk.data))
|
2021-11-20 14:40:07 +00:00
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def compileComplete(self, remotefile) -> None:
|
|
|
|
"""Build a complete File from uploaded Chunks.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
remotefile (classes.remotefile.RemoteFile): RemoteFile object
|
|
|
|
describing the uploaded File
|
|
|
|
"""
|
2021-11-20 14:40:07 +00:00
|
|
|
numchunks = remotefile.getStatus() + 1
|
2021-11-25 09:40:25 +00:00
|
|
|
|
|
|
|
# Get files in correct order to concatenate
|
|
|
|
files = " ".join(
|
|
|
|
[str(self._vessel.tempdir / f"{remotefile.file.uuid}_{i}.part") for i in range(numchunks)])
|
|
|
|
|
2021-11-20 14:40:07 +00:00
|
|
|
completefile = remotefile.file.getChunk(-1)
|
|
|
|
outname = completefile.getTempName()
|
2021-11-22 10:14:38 +00:00
|
|
|
outpath = self._vessel.tempdir / outname
|
2021-11-25 09:40:25 +00:00
|
|
|
_, o, _ = self._client.exec_command(f"cat {files} > {outpath}")
|
|
|
|
|
|
|
|
# Block for command to complete
|
2021-11-20 14:40:07 +00:00
|
|
|
o.channel.recv_exit_status()
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def assertComplete(self, remotefile, allow_retry: bool = False) -> bool:
|
|
|
|
"""Check if File has been reassembled from Chunks correctly
|
|
|
|
|
|
|
|
Args:
|
|
|
|
remotefile (classes.remotefile.RemoteFile): RemoteFile object
|
|
|
|
describing the uploaded File
|
|
|
|
allow_retry (bool, optional): If True, assume that compileComplete
|
|
|
|
failed for some other reason than corrupt Chunks, and only delete
|
|
|
|
compiled file, else clear entire temporary directory. Defaults to
|
|
|
|
False.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: True if file was reassembled correctly, else False
|
|
|
|
"""
|
2021-11-22 10:14:38 +00:00
|
|
|
completefile = remotefile.file.getChunk(-1)
|
|
|
|
outname = completefile.getTempName()
|
|
|
|
outpath = self._vessel.tempdir / outname
|
|
|
|
|
|
|
|
if not self._exists(outpath):
|
|
|
|
return False
|
|
|
|
|
|
|
|
if not self.assertChunkComplete(completefile):
|
|
|
|
if allow_retry:
|
|
|
|
self._remove(outpath)
|
|
|
|
else:
|
|
|
|
self.clearTempDir()
|
|
|
|
return False
|
2021-11-25 09:40:25 +00:00
|
|
|
|
2021-11-22 10:14:38 +00:00
|
|
|
return True
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def moveComplete(self, remotefile) -> None:
|
|
|
|
"""Moves reassembled file to output destination
|
|
|
|
|
|
|
|
Args:
|
|
|
|
remotefile (classes.remotefile.RemoteFile): RemoteFile object
|
|
|
|
describing the uploaded File.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
[type]: [description]
|
|
|
|
"""
|
2021-11-22 10:14:38 +00:00
|
|
|
completefile = remotefile.file.getChunk(-1)
|
2021-11-26 10:23:39 +00:00
|
|
|
destination = remotefile.file.getFullPath()
|
|
|
|
self._sftp.posix_rename(
|
2021-11-25 09:40:25 +00:00
|
|
|
str(self._vessel.tempdir / completefile.getTempName()), str(destination))
|
|
|
|
|
|
|
|
# Make sure that file has actually been created at destination
|
2021-11-22 10:14:38 +00:00
|
|
|
self._sftp.stat(str(destination))
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def getCurrentUploadUUID(self) -> Optional[str]:
|
|
|
|
"""Get UUID of file currently being uploaded
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str, optional: UUID of the File being uploaded, if any, else None
|
|
|
|
"""
|
2021-11-22 10:14:38 +00:00
|
|
|
for f in self._listdir(self._vessel.tempdir):
|
|
|
|
if f.endswith(".part"):
|
|
|
|
return f.split("_")[0]
|
|
|
|
|
2021-11-25 09:40:25 +00:00
|
|
|
def clearTempDir(self) -> None:
|
|
|
|
"""Clean up the temporary directory on the Vessel
|
|
|
|
"""
|
2021-11-22 10:14:38 +00:00
|
|
|
for f in self._listdir(self._vessel.tempdir):
|
|
|
|
self._remove(self._vessel.tempdir / f)
|
2021-11-20 14:40:07 +00:00
|
|
|
|
|
|
|
def __del__(self):
|
2021-11-25 09:40:25 +00:00
|
|
|
"""Close SSH connection when ending Connection
|
|
|
|
"""
|
|
|
|
self._client.close()
|