Skip to content

Performance difference between SFTPClient put and open methods #2235

Open

Description

@rgibbard

I am noticing a big difference in transfer performance between using the SFTPClient.put() method vs using SFTPClient.open() even when mimicking the way SFTPClient.put() operates.

dd if=/dev/zero of=/tmp/100m.img bs=1024 count=0 seek=$[1024*100]
import logging
from time import perf_counter

logger = logging.getLogger("ssh_test")
logging.basicConfig(level="INFO")


def test_paramiko_put():
    import paramiko

    start = perf_counter()

    source = "/tmp/100m.img"
    target = "/tmp/100m-paraminko-put-copy.img"

    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    bytes_copied = 0
    throughput = []
    def progress_callback(size, file_size):
        nonlocal bytes_copied, throughput, start
        bytes_copied = size

        if bytes_copied % (1024 * 1024 * 10) == 0:
            sample = bytes_copied / (perf_counter() - start) / 1024 / 1024
            logger.info("paramiko_put: %.6f MB/s", sample)
            throughput.append(sample)

    ssh.connect("localhost", port=2222, username="vscode", password="vscode")
    transport = ssh.get_transport()
    sftp = transport.open_sftp_client()
    sftp.put(source, target, callback=progress_callback)

    return (perf_counter() - start, sum(throughput)/len(throughput))

   
def test_paramiko_mimick_put():
    import paramiko
    import os

    start = perf_counter()

    source = "/tmp/100m.img"
    target = "/tmp/100m-paraminko-copy.img"

    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect("localhost", port=2222, username="vscode", password="vscode")
    transport = ssh.get_transport()
    sftp = transport.open_sftp_client()

    bytes_copied = 0
    throughput = []
    def progress_callback(size, file_size):
        nonlocal bytes_copied, throughput, start
        bytes_copied = size

        if bytes_copied % (1024 * 1024 * 10) == 0:
            sample = bytes_copied / (perf_counter() - start) / 1024 / 1024
            logger.info("paramiko_put: %.6f MB/s", sample)
            throughput.append(sample)

    file_size = os.stat(source).st_size
    reader = sftp.file(source, mode="rb")
    writer = sftp.file(target, mode="wb")
    writer.set_pipelined(True)

    size = 0
    while True:
        data = reader.read(32768)
        writer.write(data)
        size += len(data)
        if len(data) == 0:
            break

        progress_callback(size, file_size)

    reader.close()
    writer.close()

    return (perf_counter() - start, sum(throughput)/len(throughput))



tests = {
    'paramiko_put': test_paramiko_put(),
    'paramiko_mimick_put': test_paramiko_mimick_put(),
}

for k, v in tests.items():
    print(k, v)
INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.4p1)
INFO:paramiko.transport:Authentication (publickey) failed.
INFO:paramiko.transport:Authentication (password) successful!
INFO:paramiko.transport.sftp:[chan 0] Opened sftp connection (server version 3)
INFO:ssh_test:paramiko_put: 27.600279 MB/s
INFO:ssh_test:paramiko_put: 37.961904 MB/s
INFO:ssh_test:paramiko_put: 45.995843 MB/s
INFO:ssh_test:paramiko_put: 49.008660 MB/s
INFO:ssh_test:paramiko_put: 48.492214 MB/s
INFO:ssh_test:paramiko_put: 49.089114 MB/s
INFO:ssh_test:paramiko_put: 48.663036 MB/s
INFO:ssh_test:paramiko_put: 50.963728 MB/s
INFO:ssh_test:paramiko_put: 50.162616 MB/s
INFO:ssh_test:paramiko_put: 50.997146 MB/s
INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.4p1)
INFO:paramiko.transport:Authentication (publickey) failed.
INFO:paramiko.transport:Authentication (password) successful!
INFO:paramiko.transport.sftp:[chan 0] Opened sftp connection (server version 3)
INFO:ssh_test:paramiko_mimick_put: 1.958528 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.972298 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.979350 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.975763 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.980049 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.979022 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.976248 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.978444 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.976587 MB/s
INFO:ssh_test:paramiko_mimick_put: 1.975596 MB/s
paramiko_put (1.9805563550035004, 45.89345396184179)
paramiko_mimick_put (50.62033093300124, 1.975188623889063)

Any idea why I am seeing such a drastic difference in performance?

Activity

  1. jun66j5 commented on Apr 28, 2023

    @jun66j5
    Contributor

    Your code is wrong. It is caused by non-prefetch reader. See prefetch in SFTPClient.get().

  2. rgibbard commented on Apr 28, 2023

    @rgibbard
    Author

    @jun66j5 At the risk of missing something obvious here, I dont see prefetch being called in the code path for SFTPClient.put(). If I add a prefetch call like this:

        file_size = os.stat(source).st_size
        reader = sftp.file(source, mode="rb")
        reader.prefetch(file_size)
        writer = sftp.file(target, mode="wb")
        writer.set_pipelined(True)
    

    An exception is thrown:

    paramiko.ssh_exception.SSHException: Server connection dropped: 
    Exception ignored in: <function SFTPFile.__del__ at 0x7f0bdf80d580>
    

    I believe this is caused by also calling writer.set_pipelined(True). Removing that line eliminates the exception, but I still only achieve 1-2Mb/s throughput.

    My goal here is to achieve similar throughput to paramiko get/put functions with the SFTPClient.open function as implemented in the smart_open package

  3. jun66j5 commented on Apr 28, 2023

    @jun66j5
    Contributor
    paramiko.ssh_exception.SSHException: Server connection dropped: 
    Exception ignored in: <function SFTPFile.__del__ at 0x7f0bdf80d580>
    

    I believe this is caused by also calling writer.set_pipelined(True).

    I'd suggest checking log of the remote ssh server, rather than believing something.

  4. rgibbard commented on Apr 28, 2023

    @rgibbard
    Author

    @jun66j5 My test environment is completely local inside a VSCode devcontainer. Im reading a file via ssh on the localhost and writing to a different file via ssh on the same host. Commenting out either writer.set_pipelined(True) or reader.prefetch(file_size) results in a successful (but slow) test every time, while having both in place results in an exception:

    INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.4p1)
    INFO:paramiko.transport:Authentication (publickey) failed.
    INFO:paramiko.transport:Authentication (password) successful!
    INFO:paramiko.transport.sftp:[chan 0] Opened sftp connection (server version 3)
    Traceback (most recent call last):
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_client.py", line 852, in _read_response
        t, data = self._read_packet()
                  ^^^^^^^^^^^^^^^^^^^
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp.py", line 212, in _read_packet
        x = self._read_all(4)
            ^^^^^^^^^^^^^^^^^
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp.py", line 199, in _read_all
        raise EOFError()
    EOFError
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/workspaces/test/scratch.py", line 206, in <module>
        test_paramiko_mimick_put()
      File "/workspaces/test/scratch.py", line 167, in test_paramiko_mimick_put
        writer.write(data)
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/file.py", line 389, in write
        self._write_all(data)
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/file.py", line 507, in _write_all
        count = self._write(data)
                ^^^^^^^^^^^^^^^^^
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_file.py", line 208, in _write
        t, msg = self.sftp._read_response(req)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_client.py", line 854, in _read_response
        raise SSHException("Server connection dropped: {}".format(e))
    paramiko.ssh_exception.SSHException: Server connection dropped: 
    Exception ignored in: <function SFTPFile.__del__ at 0x7f54273c1440>
    Traceback (most recent call last):
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_file.py", line 76, in __del__
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_file.py", line 102, in _close
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_client.py", line 840, in _async_request
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/message.py", line 279, in add_string
    TypeError: 'NoneType' object is not callable
    Exception ignored in: <function SFTPFile.__del__ at 0x7f54273c1440>
    Traceback (most recent call last):
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_file.py", line 76, in __del__
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_file.py", line 102, in _close
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/sftp_client.py", line 840, in _async_request
      File "/home/vscode/.local/lib/python3.11/site-packages/paramiko/message.py", line 279, in add_string
    TypeError: 'NoneType' object is not callable
    

    All of this is besides the point. My true goal here is to understand how to achieve the same throughput of get/put using only the SFTPClient.open function. Do you have any sample code you can share that achieves this?

  5. VideoFX commented on Dec 23, 2023

    @VideoFX

    I am also looking for a throughput solution to slow sftp SFTPClient put.
    What is everyone else doing as an alternative to slow SFTPClient performance?

  6. mxmlnkn commented on Sep 22, 2024

    @mxmlnkn

    What is everyone else doing as an alternative to slow SFTPClient performance?

    Maybe they are looking at alternatives such as asyncssh. At least that's what I am considering after the time I sunk into debugging my performance problems without much to show for it. Alternatively, I am considering reimplementing SFTPFile myself in order to implement better prefetching, but I'll have to check whether the existing implementation uses any important private methods or whether there is a sufficiently lower-level API to do this without having to do a full pull-request-merge cycle.

    I can reproduce the issue with the initial code. On my system, the performance difference is even worse, yielding a faster bandwidth with put and half the bandwidth with mimick_put compared to the initial post, yielding a 60x performance difference between the compared methods:

    INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.9p1)
    INFO:paramiko.transport:Authentication (publickey) failed.
    INFO:paramiko.transport:Authentication (publickey) successful!
    INFO:paramiko.transport.sftp:[chan 0] Opened sftp connection (server version 3)
    INFO:ssh_test:paramiko_put: 41.737382 MB/s
    INFO:ssh_test:paramiko_put: 58.197692 MB/s
    INFO:ssh_test:paramiko_put: 58.869641 MB/s
    INFO:ssh_test:paramiko_put: 57.517450 MB/s
    INFO:ssh_test:paramiko_put: 61.627766 MB/s
    INFO:ssh_test:paramiko_put: 60.718390 MB/s
    INFO:ssh_test:paramiko_put: 60.124658 MB/s
    INFO:ssh_test:paramiko_put: 65.259553 MB/s
    INFO:ssh_test:paramiko_put: 67.687190 MB/s
    INFO:ssh_test:paramiko_put: 71.059979 MB/s
    INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.9p1)
    INFO:paramiko.transport:Authentication (publickey) failed.
    INFO:paramiko.transport:Authentication (publickey) successful!
    INFO:paramiko.transport.sftp:[chan 0] Opened sftp connection (server version 3)
    INFO:ssh_test:paramiko_put: 0.967411 MB/s
    INFO:ssh_test:paramiko_put: 0.973420 MB/s
    INFO:ssh_test:paramiko_put: 0.974629 MB/s
    INFO:ssh_test:paramiko_put: 0.973878 MB/s
    INFO:ssh_test:paramiko_put: 0.972270 MB/s
    INFO:ssh_test:paramiko_put: 0.973372 MB/s
    INFO:ssh_test:paramiko_put: 0.974858 MB/s
    INFO:ssh_test:paramiko_put: 0.975022 MB/s
    INFO:ssh_test:paramiko_put: 0.974901 MB/s
    INFO:ssh_test:paramiko_put: 0.975217 MB/s
    paramiko_put (1.487747226958163, 60.27997015620451)
    paramiko_mimick_put (102.58539228199515, 0.9734976085463816)
    

    One thing to notice is that your comparison is unfair because test_paramiko_put reads from a local file and uploads it via put while test_paramiko_mimick_put reads a remote file while also writing it into another remote file! I.e., you are not benchmarking a pure put but a get+put combination and therefore running into the same issue I have with pure read performance.

    When I add the prefetch call as proposed, then I also get:

    Traceback (most recent call last):
      File "/home/user/.local/lib/python3.10/site-packages/paramiko/sftp_client.py", line 887, in _read_response
        t, data = self._read_packet()
      File "/home/user/.local/lib/python3.10/site-packages/paramiko/sftp.py", line 212, in _read_packet
        x = self._read_all(4)
      File "/home/user/.local/lib/python3.10/site-packages/paramiko/sftp.py", line 199, in _read_all
        raise EOFError()
    EOFError
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "benchmark-paramiko-put.py", line 92, in <module>
        'paramiko_mimick_put': test_paramiko_mimick_put(),
      File "benchmark-paramiko-put.py", line 76, in test_paramiko_mimick_put
        writer.write(data)
      File "/home/user/.local/lib/python3.10/site-packages/paramiko/file.py", line 389, in write
        self._write_all(data)
      File "/home/user/.local/lib/python3.10/site-packages/paramiko/file.py", line 507, in _write_all
        count = self._write(data)
      File "/home/user/.local/lib/python3.10/site-packages/paramiko/sftp_file.py", line 208, in _write
        t, msg = self.sftp._read_response(req)
      File "/home/user/.local/lib/python3.10/site-packages/paramiko/sftp_client.py", line 889, in _read_response
        raise SSHException("Server connection dropped: {}".format(e))
    paramiko.ssh_exception.SSHException: Server connection dropped: 

    I get this error with and without the writer.set_pipelined(True) line. And with writer.set_pipelined(False), I get another error: OSError: Socket is closed.

    But to make the comparison fair, let's read the file locally and upload that:

    --- benchmark-paramiko-put.original.py	2024-09-22 12:42:47.856641700 +0200
    +++ benchmark-paramiko-put.py	2024-09-22 12:43:12.769949500 +0200
    @@ -65,7 +65,7 @@
                 throughput.append(sample)
     
         file_size = os.stat(source).st_size
    -    reader = sftp.file(source, mode="rb")
    +    reader = open(source, mode="rb")
         writer = sftp.file(target, mode="wb")
         writer.set_pipelined(True)

    Now, I get much better performance, meaning the read is the actual problem, not the put:

    INFO:ssh_test:paramiko_put: 22.959431 MB/s
    INFO:ssh_test:paramiko_put: 40.256995 MB/s
    INFO:ssh_test:paramiko_put: 53.800512 MB/s
    INFO:ssh_test:paramiko_put: 64.744807 MB/s
    INFO:ssh_test:paramiko_put: 73.926219 MB/s
    INFO:ssh_test:paramiko_put: 81.606683 MB/s
    INFO:ssh_test:paramiko_put: 83.374353 MB/s
    INFO:ssh_test:paramiko_put: 89.197684 MB/s
    INFO:ssh_test:paramiko_put: 93.552245 MB/s
    INFO:ssh_test:paramiko_put: 94.262769 MB/s
    INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.9p1)
    INFO:paramiko.transport:Authentication (publickey) failed.
    INFO:paramiko.transport:Authentication (publickey) successful!
    INFO:paramiko.transport.sftp:[chan 0] Opened sftp connection (server version 3)
    INFO:ssh_test:paramiko_put: 28.322850 MB/s
    INFO:ssh_test:paramiko_put: 38.271709 MB/s
    INFO:ssh_test:paramiko_put: 46.921938 MB/s
    INFO:ssh_test:paramiko_put: 52.997129 MB/s
    INFO:ssh_test:paramiko_put: 60.502546 MB/s
    INFO:ssh_test:paramiko_put: 67.844080 MB/s
    INFO:ssh_test:paramiko_put: 67.306279 MB/s
    INFO:ssh_test:paramiko_put: 65.590013 MB/s
    INFO:ssh_test:paramiko_put: 70.150480 MB/s
    INFO:ssh_test:paramiko_put: 71.680126 MB/s
    paramiko_put (1.1391590000130236, 69.76816981185198)
    paramiko_mimick_put (1.5107419199775904, 56.95871478726112)
    

    If one really wants to read from remote and put to remote, then one could buffer it:

    --- benchmark-paramiko-put.original.py	2024-09-22 12:42:47.856641700 +0200
    +++ benchmark-paramiko-put.py	2024-09-22 12:45:37.232097900 +0200
    @@ -1,3 +1,4 @@
    +import io
     import logging
     from time import perf_counter
     
    @@ -66,6 +67,9 @@
     
         file_size = os.stat(source).st_size
         reader = sftp.file(source, mode="rb")
    +    reader.prefetch(file_size)
    +    reader = io.BytesIO(reader.read())
    +
         writer = sftp.file(target, mode="wb")
         writer.set_pipelined(True)
     

    Output:

    INFO:ssh_test:paramiko_put: 36.517458 MB/s
    INFO:ssh_test:paramiko_put: 41.868149 MB/s
    INFO:ssh_test:paramiko_put: 49.471601 MB/s
    INFO:ssh_test:paramiko_put: 54.517335 MB/s
    INFO:ssh_test:paramiko_put: 56.867437 MB/s
    INFO:ssh_test:paramiko_put: 59.290616 MB/s
    INFO:ssh_test:paramiko_put: 63.060975 MB/s
    INFO:ssh_test:paramiko_put: 68.375185 MB/s
    INFO:ssh_test:paramiko_put: 73.223815 MB/s
    INFO:ssh_test:paramiko_put: 72.035791 MB/s
    INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.9p1)
    INFO:paramiko.transport:Authentication (publickey) failed.
    INFO:paramiko.transport:Authentication (publickey) successful!
    INFO:paramiko.transport.sftp:[chan 0] Opened sftp connection (server version 3)
    INFO:ssh_test:paramiko_put: 8.295763 MB/s
    INFO:ssh_test:paramiko_put: 15.505361 MB/s
    INFO:ssh_test:paramiko_put: 22.330503 MB/s
    INFO:ssh_test:paramiko_put: 28.563787 MB/s
    INFO:ssh_test:paramiko_put: 32.251855 MB/s
    INFO:ssh_test:paramiko_put: 37.162545 MB/s
    INFO:ssh_test:paramiko_put: 40.403155 MB/s
    INFO:ssh_test:paramiko_put: 43.594052 MB/s
    INFO:ssh_test:paramiko_put: 47.661369 MB/s
    INFO:ssh_test:paramiko_put: 51.513503 MB/s
    paramiko_put (1.4590060940245166, 57.52283619494394)
    paramiko_mimick_put (2.0042129849316552, 32.72818944137601)
    

    Of course, this adds a possibly huge memory overhead for very large files. But, because of the aforementioned paramiko.ssh_exception.SSHException: Server connection dropped: error, I don't know how one would stream a file with prefetching without fully buffering it locally. It seems like a bug to me that this does not work. Almost as if the read and writes over the connection interfere with each other, but then why does it only happen with prefetching? As the prefetching runs in another thread, maybe the locking mechanism to avoid concurrent read/writes to the connection contains errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions