chitralverma commented on code in PR #7977:
URL: https://github.com/apache/opendal/pull/7977#discussion_r4756955087
##########
core/services/sftp/src/reader.rs:
##########
@@ -15,71 +15,132 @@
// specific language governing permissions and limitations
// under the License.
+use bytes::Bytes;
+use russh_sftp::protocol::{FileAttributes, OpenFlags};
+
use super::backend::*;
-use super::core::Manager;
+use super::core::PIPELINE_DEPTH;
+use super::core::SftpSessionRef;
+use super::core::close_handle_detached;
+use super::core::is_eof;
use super::core::is_not_found;
use super::core::is_sftp_failure;
use super::core::parse_sftp_error;
use super::lister::SftpLister;
use super::writer::SftpWriter;
-use bytes::BytesMut;
-use fastpool::bounded;
use opendal_core::raw::*;
use opendal_core::*;
-use openssh_sftp_client::file::File;
-use std::io::SeekFrom;
-use tokio::io::AsyncSeekExt;
+/// Streams a remote file by issuing several SFTP reads concurrently.
+///
+/// SFTP is a request/response protocol, so a single outstanding read caps
+/// throughput at one packet per round trip. Each call therefore fans out up to
+/// [`PIPELINE_DEPTH`] reads and returns them as one multi-chunk [`Buffer`].
pub struct SftpReadStream {
- /// Keep the connection alive while data stream is alive.
- _conn: bounded::Object<Manager>,
-
- file: File,
- chunk: usize,
- size: Option<usize>,
- read: usize,
- buf: BytesMut,
+ /// Keeps the session alive while data stream is alive.
+ conn: SftpSessionRef,
+
+ handle: String,
+ offset: u64,
+ /// Remaining bytes to read when the caller asked for a bounded range.
+ remaining: Option<u64>,
+ finished: bool,
+}
+
+impl Drop for SftpReadStream {
+ fn drop(&mut self) {
+ // A ranged or abandoned read never reaches EOF, so the remote handle
+ // has to be released here rather than at the end of the stream.
+ close_handle_detached(self.conn.session.clone(), std::mem::take(&mut
self.handle));
+ }
}
impl SftpReadStream {
- pub fn new(conn: bounded::Object<Manager>, file: File, size: Option<u64>)
-> Self {
+ pub fn new(conn: SftpSessionRef, handle: String, offset: u64, size:
Option<u64>) -> Self {
Self {
- _conn: conn,
- file,
- size: size.map(|v| v as usize),
- chunk: 2 * 1024 * 1024,
- read: 0,
- buf: BytesMut::new(),
+ conn,
+ handle,
+ offset,
+ remaining: size,
+ finished: false,
}
}
}
impl oio::ReadStream for SftpReadStream {
async fn read(&mut self) -> Result<Buffer> {
- if self.read >= self.size.unwrap_or(usize::MAX) {
+ if self.finished || self.remaining == Some(0) {
return Ok(Buffer::new());
}
- let size = if let Some(size) = self.size {
- (size - self.read).min(self.chunk)
- } else {
- self.chunk
- };
- self.buf.reserve(size);
+ let chunk = self.conn.read_len as u64;
- let Some(bytes) = self
- .file
- .read(size as u32, self.buf.split_off(0))
- .await
- .map_err(parse_sftp_error)?
- else {
+ // Plan a batch of reads covering contiguous offsets.
+ let mut planned = 0u64;
+ let mut wants = Vec::with_capacity(PIPELINE_DEPTH);
+ let mut inflight = Vec::with_capacity(PIPELINE_DEPTH);
+ for _ in 0..PIPELINE_DEPTH {
+ let want = match self.remaining {
+ Some(remaining) =>
remaining.saturating_sub(planned).min(chunk),
+ None => chunk,
+ };
+ if want == 0 {
+ break;
+ }
+
+ let offset = self.offset + planned;
+ planned += want;
+ wants.push(want);
+
+ let session = self.conn.session.clone();
+ let handle = self.handle.clone();
+ inflight.push(async move { session.read(handle, offset, want as
u32).await });
+ }
+
+ if inflight.is_empty() {
+ return Ok(Buffer::new());
+ }
+
+ let results = futures::future::join_all(inflight).await;
Review Comment:
04c34d691 removes it. Each `read()` sends one request of up to the server's
read limit, and `concurrent` reads open more streams.
*This comment is AI assisted.*
##########
core/services/sftp/src/core.rs:
##########
@@ -15,18 +15,164 @@
// specific language governing permissions and limitations
// under the License.
+use std::fmt::Debug;
+use std::sync::Arc;
+
use fastpool::{ManageObject, ObjectStatus, bounded};
use log::debug;
use opendal_core::raw::*;
use opendal_core::*;
-use openssh::KnownHosts;
-use openssh::SessionBuilder;
-use openssh_sftp_client::Sftp;
-use openssh_sftp_client::SftpOptions;
-use std::fmt::Debug;
-use std::path::Path;
-use std::path::PathBuf;
-use std::sync::Arc;
+use russh::client;
+use russh::keys::PrivateKeyWithHashAlg;
+use russh_sftp::client::RawSftpSession;
+use russh_sftp::client::rawsession::Limits;
+use russh_sftp::protocol::FileAttributes;
+
+/// Largest payload we ever ask the remote server for in a single SFTP packet.
+///
+/// The effective value is additionally clamped by the limits advertised
through
+/// the `[email protected]` extension.
+const MAX_CHUNK_SIZE: u32 = 256 * 1024;
+
+/// Conservative payload size used when the server does not advertise limits.
+///
+/// SFTP v3 has no negotiation for this, and 32 KiB is the value the OpenSSH
+/// client itself falls back to.
+const DEFAULT_CHUNK_SIZE: u32 = 32 * 1024;
+
+/// Number of SFTP read/write packets kept in flight at once.
+///
+/// SFTP is a request/response protocol, so throughput on links with
non-trivial
+/// latency is bound by the number of outstanding requests rather than
bandwidth.
+pub const PIPELINE_DEPTH: usize = 8;
+
+/// OpenSSH extension providing `rename` with POSIX overwrite semantics.
+pub const POSIX_RENAME: &str = "[email protected]";
+
+/// Number of SSH handshakes allowed to run at the same time.
+///
+/// Servers cap how many connections may be mid-authentication at once
+/// (`MaxStartups` defaults to `10:30:100` in OpenSSH, which starts dropping
+/// connections past ten), so growing the pool in a burst must be throttled.
+const MAX_CONCURRENT_HANDSHAKES: usize = 4;
+
+/// Number of agent identities tried before giving up.
+///
+/// Each attempt counts against the server's `MaxAuthTries`, which defaults to
+/// six in OpenSSH and drops the connection once exceeded.
+#[cfg(unix)]
+const MAX_AGENT_IDENTITIES: usize = 4;
+
+/// Specifies how `SftpBackend` validates the remote host key.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KnownHostsStrategy {
+ /// The host key must be present in `known_hosts` and match.
+ ///
+ /// This mirrors `ssh -o StrictHostKeyChecking=yes`.
+ Strict,
+ /// Accept a previously unseen host key and record it in `known_hosts`.
+ ///
+ /// A changed key is still rejected. This mirrors
+ /// `ssh -o StrictHostKeyChecking=accept-new`.
+ Add,
+ /// Accept whatever key the server presents.
+ ///
+ /// This mirrors `ssh -o StrictHostKeyChecking=no`.
+ Accept,
+}
+
+/// Validates the remote host key according to [`KnownHostsStrategy`].
+struct SshHandler {
Review Comment:
04c34d691 adds `SshEndpoint { user, host, port }`, parsed once in `build()`.
The handler now holds only the `known_hosts` name and the verifier.
*This comment is AI assisted.*
##########
core/services/sftp/src/core.rs:
##########
@@ -95,56 +272,247 @@ pub struct Manager {
root: String,
user: Option<String>,
key: Option<String>,
- known_hosts_strategy: KnownHosts,
+ known_hosts_strategy: KnownHostsStrategy,
+ /// Throttles concurrent SSH handshakes, see [`MAX_CONCURRENT_HANDSHAKES`].
+ handshakes: tokio::sync::Semaphore,
}
-impl ManageObject for Manager {
- type Object = Sftp;
- type Error = Error;
+impl Manager {
+ /// Authenticates the session, preferring the configured key and otherwise
+ /// falling back to an SSH agent and the usual default key locations.
+ async fn authenticate(
+ &self,
+ handle: &mut client::Handle<SshHandler>,
+ user: &str,
+ ) -> Result<()> {
+ if let Some(key) = &self.key {
+ let private_key = russh::keys::load_secret_key(key,
None).map_err(|err| {
+ Error::new(ErrorKind::ConfigInvalid, "sftp failed to load
private key")
+ .set_source(err)
+ })?;
+
+ if self
+ .try_publickey(handle, user, private_key)
+ .await?
+ .is_some()
+ {
+ return Ok(());
+ }
- async fn create(&self) -> Result<Self::Object, Self::Error> {
- let mut session = SessionBuilder::default();
+ return Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "sftp public key authentication failed",
+ ));
+ }
- if let Some(user) = &self.user {
- session.user(user.clone());
+ if self.try_agent(handle, user).await? {
+ return Ok(());
}
- if let Some(key) = &self.key {
- session.keyfile(key);
+ for candidate in default_key_paths() {
+ let Ok(private_key) = russh::keys::load_secret_key(&candidate,
None) else {
+ continue;
+ };
+ if self
+ .try_publickey(handle, user, private_key)
+ .await?
+ .is_some()
+ {
+ return Ok(());
+ }
}
- session.known_hosts_check(self.known_hosts_strategy.clone());
+ Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "sftp authentication failed: no usable credentials, set `key` to a
private key path",
+ ))
+ }
+
+ async fn try_publickey(
+ &self,
+ handle: &mut client::Handle<SshHandler>,
+ user: &str,
+ private_key: russh::keys::PrivateKey,
+ ) -> Result<Option<()>> {
+ // RSA keys must be signed with the strongest hash the server accepts;
+ // servers commonly reject the legacy SHA-1 `ssh-rsa` signatures.
+ let hash_alg = handle
+ .best_supported_rsa_hash()
+ .await
+ .map_err(parse_ssh_error)?
+ .flatten();
- let session = session
- .connect(&self.endpoint)
+ let result = handle
+ .authenticate_publickey(
+ user,
+ PrivateKeyWithHashAlg::new(Arc::new(private_key), hash_alg),
+ )
.await
.map_err(parse_ssh_error)?;
- let sftp = Sftp::from_session(session, SftpOptions::default())
+ Ok(result.success().then_some(()))
+ }
+
+ async fn try_agent(&self, handle: &mut client::Handle<SshHandler>, user:
&str) -> Result<bool> {
+ #[cfg(unix)]
+ {
+ use russh::keys::agent::AgentIdentity;
+
+ let Ok(mut agent) =
russh::keys::agent::client::AgentClient::connect_env().await else {
+ return Ok(false);
+ };
+ let Ok(identities) = agent.request_identities().await else {
+ return Ok(false);
+ };
+
+ let hash_alg = handle
+ .best_supported_rsa_hash()
+ .await
+ .map_err(parse_ssh_error)?
+ .flatten();
+
+ // Every attempt counts against the server's `MaxAuthTries` (6 by
+ // default), and exhausting it disconnects instead of reporting a
+ // clean authentication failure.
+ for identity in identities.into_iter().take(MAX_AGENT_IDENTITIES) {
+ let AgentIdentity::PublicKey { key, .. } = identity else {
+ continue;
+ };
+
+ let Ok(result) = handle
+ .authenticate_publickey_with(user, key, hash_alg, &mut
agent)
+ .await
+ else {
+ continue;
+ };
+ if result.success() {
+ return Ok(true);
+ }
+ }
+ }
+
+ let _ = (handle, user);
+ Ok(false)
+ }
+}
+
+impl ManageObject for Manager {
+ type Object = SftpConnection;
+ type Error = Error;
+
+ async fn create(&self) -> Result<Self::Object, Self::Error> {
+ let _permit = self.handshakes.acquire().await.map_err(|err| {
+ Error::new(ErrorKind::Unexpected, "sftp connection limiter
closed").set_source(err)
+ })?;
+
+ let (endpoint_user, host, port) = parse_endpoint(&self.endpoint)?;
+
+ // A user encoded in the endpoint takes precedence over the builder
value.
+ let user = endpoint_user
+ .or_else(|| self.user.clone())
+ .or_else(default_user)
+ .ok_or_else(|| {
+ Error::new(
+ ErrorKind::ConfigInvalid,
+ "sftp user is not set and cannot be inferred from the
environment",
+ )
+ })?;
+
+ let handler = SshHandler {
+ host: host.clone(),
+ port,
+ strategy: self.known_hosts_strategy,
+ };
+
+ let mut handle = client::connect(
+ Arc::new(client::Config::default()),
+ (host.as_str(), port),
+ handler,
+ )
+ .await
+ .map_err(parse_ssh_error)?;
+
+ self.authenticate(&mut handle, &user).await?;
+
+ let channel = handle
+ .channel_open_session()
+ .await
+ .map_err(parse_ssh_error)?;
+ channel
+ .request_subsystem(true, "sftp")
.await
- .map_err(parse_sftp_error)?;
+ .map_err(parse_ssh_error)?;
+
+ let config = russh_sftp::client::Config {
+ // Every request is a single round trip, so allow slow servers more
+ // room than the crate default of 10 seconds.
+ request_timeout_secs: 60,
Review Comment:
04c34d691 removes the 60 s request timeout. A per-request limit would abort
a server-side `copy-data` of a large file, and `TimeoutLayer` already bounds
operations; a comment says so. The other limits are named constants.
*This comment is AI assisted.*
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]