Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use sftp to transfer files instead of dd #30

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions aws-throwaway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ anyhow = "1.0.42"
uuid = { version = "1.0.0", features = ["serde", "v4"] }
tracing = "0.1.15"
async-trait = "0.1.30"
russh-sftp = "^2.0.0-beta.3"

[dev-dependencies]
tracing-subscriber = { version = "0.3.1", features = ["env-filter", "json"] }
Expand Down
38 changes: 38 additions & 0 deletions aws-throwaway/examples/aws-throwaway-test-large-file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use aws_throwaway::{Aws, CleanupResources, Ec2InstanceDefinition, InstanceType};
use std::{path::Path, time::Instant};
use tracing_subscriber::EnvFilter;

#[tokio::main]
async fn main() {
let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout());
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.with_writer(non_blocking)
.init();

let aws = Aws::builder(CleanupResources::AllResources).build().await;
let instance = aws
.create_ec2_instance(Ec2InstanceDefinition::new(InstanceType::T2Micro))
.await;

let start = Instant::now();
std::fs::write("some_local_file", vec![0; 1024 * 1024 * 1]).unwrap(); // create 100MB file
println!("Time to create 100MB file locally {:?}", start.elapsed());

let start = Instant::now();
instance
.ssh()
.push_file(Path::new("some_local_file"), Path::new("some_remote_file"))
.await;
println!("Time to push 100MB file {:?}", start.elapsed());

let start = Instant::now();
instance
.ssh()
.pull_file(Path::new("some_remote_file"), Path::new("some_local_file"))
.await;
println!("Time to pull 100MB file {:?}", start.elapsed());

aws.cleanup_resources().await;
println!("\nAll AWS throwaway resources have been deleted")
}
150 changes: 59 additions & 91 deletions aws-throwaway/src/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,9 @@ use russh::{
ChannelMsg, Sig,
};
use russh_keys::{key::PublicKey, PublicKeyBase64};
use russh_sftp::{client::SftpSession, protocol::OpenFlags};
use std::{fmt::Display, io::Write, net::IpAddr, path::Path, sync::Arc};
use tokio::{
fs::File,
io::{AsyncReadExt, BufReader},
net::TcpStream,
};
use tokio::{fs::File, io::AsyncReadExt, net::TcpStream};

pub struct SshConnection {
address: IpAddr,
Expand Down Expand Up @@ -192,66 +189,55 @@ impl SshConnection {
let task = format!("pushing file from {source:?} to {}:{dest:?}", self.address);
tracing::info!("{task}");

let source = File::open(source)
let mut channel = self.session.channel_open_session().await.unwrap();
channel.request_subsystem(true, "sftp").await.unwrap();
let sftp = SftpSession::new(channel.into_stream()).await.unwrap();
let mut file = sftp
.open_with_flags(
dest.to_str().unwrap(),
OpenFlags::WRITE | OpenFlags::TRUNCATE | OpenFlags::CREATE,
)
.await
.unwrap();

let mut source = File::open(source)
.await
.map_err(|e| anyhow!(e).context(format!("Failed to read from {source:?}")))
.unwrap();
self.push_file_impl(&task, source, dest).await;

let mut bytes = vec![0u8; 1024 * 1024];
loop {
let read_count = source
.read(&mut bytes[..])
.await
.unwrap_or_else(|e| panic!("{task} failed to read from local disk with {e:?}"));
if read_count == 0 {
break;
}
tokio::io::AsyncWriteExt::write_all(&mut file, &bytes[0..read_count])
.await
.unwrap_or_else(|e| panic!("{task} failed to write to remote server with {e:?}"));
}
}

/// Create a file on the remote machine at `dest` with the provided bytes.
pub async fn push_file_from_bytes(&self, bytes: &[u8], dest: &Path) {
let task = format!("pushing raw bytes to {}:{dest:?}", self.address);
tracing::info!("{task}");

let source = BufReader::new(bytes);
self.push_file_impl(&task, source, dest).await;
}

async fn push_file_impl<R: AsyncReadExt + Unpin>(&self, task: &str, source: R, dest: &Path) {
let mut channel = self.session.channel_open_session().await.unwrap();
let command = format!("dd of='{0}'\nchmod 777 {0}", dest.to_str().unwrap());
channel.exec(true, command).await.unwrap();

let mut stdout = vec![];
let mut stderr = vec![];
let mut status = None;
let mut failed = None;
channel.data(source).await.unwrap();
channel.eof().await.unwrap();
while let Some(msg) = channel.wait().await {
match msg {
ChannelMsg::Data { data } => stdout.write_all(&data).unwrap(),
ChannelMsg::ExtendedData { data, ext } => {
if ext == 1 {
stderr.write_all(&data).unwrap()
} else {
tracing::warn!("received unknown extended data with extension type {ext} containing: {:?}", data.to_vec())
}
}
ChannelMsg::ExitStatus { exit_status } => {
status = Some(exit_status);
// cant exit immediately, there might be more data still
}
ChannelMsg::ExitSignal {
signal_name,
core_dumped,
error_message,
..
} => {
failed = Some(format!(
"killed via signal {signal_name:?} core_dumped={core_dumped} {error_message:?}"
))
}
_ => {}
}
}
let output = CommandOutput {
stdout: String::from_utf8(stdout).unwrap(),
stderr: String::from_utf8(stderr).unwrap(),
};

check_results(task, failed, status, &output);
channel.request_subsystem(true, "sftp").await.unwrap();
let sftp = SftpSession::new(channel.into_stream()).await.unwrap();
let mut file = sftp
.open_with_flags(
dest.to_str().unwrap(),
OpenFlags::WRITE | OpenFlags::TRUNCATE | OpenFlags::CREATE,
)
.await
.unwrap();
tokio::io::AsyncWriteExt::write_all(&mut file, bytes)
.await
.unwrap_or_else(|e| panic!("{task} failed to write to remote server with {e:?}"));
}

/// Pull a file from the remote machine to the local machine
Expand All @@ -260,46 +246,28 @@ impl SshConnection {
tracing::info!("{task}");

let mut channel = self.session.channel_open_session().await.unwrap();
let command = format!("dd if='{0}'\nchmod 777 {0}", source.to_str().unwrap());
channel.exec(true, command).await.unwrap();
channel.request_subsystem(true, "sftp").await.unwrap();
let sftp = SftpSession::new(channel.into_stream()).await.unwrap();
let mut file = sftp.open(source.to_str().unwrap()).await.unwrap();

let mut out = File::create(dest).await.unwrap();
let mut stderr = vec![];
let mut status = None;
let mut failed = None;
channel.eof().await.unwrap();
while let Some(msg) = channel.wait().await {
match msg {
ChannelMsg::Data { data } => tokio::io::AsyncWriteExt::write_all(&mut out, &data)
.await
.unwrap(),
ChannelMsg::ExtendedData { data, ext } => {
if ext == 1 {
stderr.write_all(&data).unwrap()
} else {
tracing::warn!("received unknown extended data with extension type {ext} containing: {:?}", data.to_vec())
}
}
ChannelMsg::ExitStatus { exit_status } => {
status = Some(exit_status);
// cant exit immediately, there might be more data still
}
ChannelMsg::ExitSignal {
signal_name,
core_dumped,
error_message,
..
} => {
failed = Some(format!(
"killed via signal {signal_name:?} core_dumped={core_dumped} {error_message:?}"
))
}
_ => {}
let mut dest = File::create(dest)
.await
.map_err(|e| anyhow!(e).context(format!("Failed to read from {source:?}")))
.unwrap();

let mut bytes = vec![0u8; 1024 * 1024];
loop {
let read_count = file
.read(&mut bytes[..])
.await
.unwrap_or_else(|e| panic!("{task} failed to read from local disk with {e:?}"));
if read_count == 0 {
break;
}
tokio::io::AsyncWriteExt::write_all(&mut dest, &bytes[0..read_count])
.await
.unwrap_or_else(|e| panic!("{task} failed to write to remote server with {e:?}"));
}

let output = String::from_utf8(stderr).unwrap();
check_results(&task, failed, status, &output);
}
}

Expand Down
Loading