Debian Codegraph @

ftpbench.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 # Copyright (C) 2007-2016 Giampaolo Rodola' <[email protected]>.
4 # Use of this source code is governed by MIT license that can be
5 # found in the LICENSE file.
6
7 """
8 FTP server benchmark script.
9
10 In order to run this you must have a listening FTP server with a user
11 with writing permissions configured.
12 This is a stand-alone script which does not depend from pyftpdlib.
13 It just requires python >= 2.6 (and optionally psutil to keep track
14 of FTP server memory usage).
15
16 Example usages:
17 ftpbench -u USER -p PASSWORD
18 ftpbench -u USER -p PASSWORD -H ftp.domain.com -P 21 # host / port
19 ftpbench -u USER -p PASSWORD -b transfer
20 ftpbench -u USER -p PASSWORD -b concurrence
21 ftpbench -u USER -p PASSWORD -b all
22 ftpbench -u USER -p PASSWORD -b concurrence -n 500 # 500 clients
23 ftpbench -u USER -p PASSWORD -b concurrence -s 20M # file size
24 ftpbench -u USER -p PASSWORD -b concurrence -p 3521 # memory usage
25 """
26
27 # Some benchmarks (Linux 3.0.0, Intel core duo - 3.1 Ghz).
28
29 # pyftpdlib 1.0.0:
30 #
31 # (starting with 6.7M of memory being used)
32 # STOR (client -> server) 557.97 MB/sec 6.7M
33 # RETR (server -> client) 1613.82 MB/sec 6.8M
34 # 300 concurrent clients (connect, login) 1.20 secs 8.8M
35 # STOR (1 file with 300 idle clients) 567.52 MB/sec 8.8M
36 # RETR (1 file with 300 idle clients) 1561.41 MB/sec 8.8M
37 # 300 concurrent clients (RETR 10.0M file) 3.26 secs 10.8M
38 # 300 concurrent clients (STOR 10.0M file) 8.46 secs 12.6M
39 # 300 concurrent clients (QUIT) 0.07 secs
40 #
41 #
42 # proftpd 1.3.4a:
43 #
44 # (starting with 1.4M of memory being used)
45 # STOR (client -> server) 554.67 MB/sec 3.2M
46 # RETR (server -> client) 1517.12 MB/sec 3.2M
47 # 300 concurrent clients (connect, login) 9.30 secs 568.6M
48 # STOR (1 file with 300 idle clients) 484.11 MB/sec 570.6M
49 # RETR (1 file with 300 idle clients) 1534.61 MB/sec 570.6M
50 # 300 concurrent clients (RETR 10.0M file) 3.67 secs 568.6M
51 # 300 concurrent clients (STOR 10.0M file) 11.21 secs 568.7M
52 # 300 concurrent clients (QUIT) 0.43 secs
53 #
54 #
55 # vsftpd 2.3.2
56 #
57 # (starting with 352.0K of memory being used)
58 # STOR (client -> server) 607.23 MB/sec 816.0K
59 # RETR (server -> client) 1506.59 MB/sec 816.0K
60 # 300 concurrent clients (connect, login) 18.91 secs 140.9M
61 # STOR (1 file with 300 idle clients) 618.99 MB/sec 141.4M
62 # RETR (1 file with 300 idle clients) 1402.48 MB/sec 141.4M
63 # 300 concurrent clients (RETR 10.0M file) 3.64 secs 140.9M
64 # 300 concurrent clients (STOR 10.0M file) 9.74 secs 140.9M
65 # 300 concurrent clients (QUIT) 0.00 secs
66
67
68 from __future__ import division, print_function
69 import asynchat
70 import asyncore
71 import atexit
72 import contextlib
73 import ftplib
74 import optparse
75 import os
76 import ssl
77 import sys
78 import time
79 try:
80 import resource
81 except ImportError:
82 resource = None
83
84 try:
85 import psutil
86 except ImportError:
87 psutil = None
88
89
90 HOST = 'localhost'
91 PORT = 21
92 USER = None
93 PASSWORD = None
94 TESTFN = "$testfile"
95 BUFFER_LEN = 8192
96 SERVER_PROC = None
97 TIMEOUT = None
98 FILE_SIZE = "10M"
99 SSL = False
100 PY3 = sys.version_info >= (3, 0)
101
102 server_memory = []
103 # python >= 2.7.9
104 SSLWantReadError = getattr(ssl, "SSLWantReadError", object())
105 SSLWantWriteError = getattr(ssl, "SSLWantWriteError", object())
106 # python <= 2.7.8
107 SSL_ERROR_WANT_READ = getattr(ssl, "SSL_ERROR_WANT_READ", object())
108 SSL_ERROR_WANT_WRITE = getattr(ssl, "SSL_ERROR_WANT_WRITE", object())
109
110
111 if not sys.stdout.isatty() or os.name != 'posix':
112 def hilite(s, *args, **kwargs):
113 return s
114 else:
115 # http://goo.gl/6V8Rm
116 def hilite(string, ok=True, bold=False):
117 """Return an highlighted version of 'string'."""
118 attr = []
119 if ok is None: # no color
120 pass
121 elif ok: # green
122 attr.append('32')
123 else: # red
124 attr.append('31')
125 if bold:
126 attr.append('1')
127 return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
128
129
130 def print_bench(what, value, unit=""):
131 s = "%s %s %-8s" % (
132 hilite("%-50s" % what, ok=None, bold=0),
133 hilite("%8.2f" % value),
134 unit,
135 )
136 if server_memory:
137 s += "%s" % hilite(server_memory.pop())
138 print(s.strip())
139
140
141 # http://goo.gl/zeJZl
142 def bytes2human(n, format="%(value).1f%(symbol)s"):
143 """
144 >>> bytes2human(10000)
145 '9K'
146 >>> bytes2human(100001221)
147 '95M'
148 """
149 symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
150 prefix = {}
151 for i, s in enumerate(symbols[1:]):
152 prefix[s] = 1 << (i + 1) * 10
153 for symbol in reversed(symbols[1:]):
154 if n >= prefix[symbol]:
155 value = float(n) / prefix[symbol]
156 return format % locals()
157 return format % dict(symbol=symbols[0], value=n)
158
159
160 # http://goo.gl/zeJZl
161 def human2bytes(s):
162 """
163 >>> human2bytes('1M')
164 1048576
165 >>> human2bytes('1G')
166 1073741824
167 """
168 symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
169 letter = s[-1:].strip().upper()
170 num = s[:-1]
171 assert num.isdigit() and letter in symbols, s
172 num = float(num)
173 prefix = {symbols[0]: 1}
174 for i, s in enumerate(symbols[1:]):
175 prefix[s] = 1 << (i + 1) * 10
176 return int(num * prefix[letter])
177
178
179 def register_memory():
180 """Register an approximation of memory used by FTP server process
181 and all of its children.
182 """
183 # XXX How to get a reliable representation of memory being used is
184 # not clear. (rss - shared) seems kind of ok but we might also use
185 # the private working set via get_memory_maps().private*.
186 def get_mem(proc):
187 if os.name == 'posix':
188 mem = proc.memory_info_ex()
189 counter = mem.rss
190 if 'shared' in mem._fields:
191 counter -= mem.shared
192 return counter
193 else:
194 # TODO figure out what to do on Windows
195 return proc.get_memory_info().rss
196
197 if SERVER_PROC is not None:
198 mem = get_mem(SERVER_PROC)
199 for child in SERVER_PROC.children():
200 mem += get_mem(child)
201 server_memory.append(bytes2human(mem))
202
203
204 def timethis(what):
205 """"Utility function for making simple benchmarks (calculates time calls).
206 It can be used either as a context manager or as a decorator.
207 """
208 @contextlib.contextmanager
209 def benchmark():
210 timer = time.clock if sys.platform == "win32" else time.time
211 start = timer()
212 yield
213 stop = timer()
214 res = (stop - start)
215 print_bench(what, res, "secs")
216
217 if hasattr(what, "__call__"):
218 def timed(*args, **kwargs):
219 with benchmark():
220 return what(*args, **kwargs)
221 return timed
222 else:
223 return benchmark()
224
225
226 def connect():
227 """Connect to FTP server, login and return an ftplib.FTP instance."""
228 ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS
229 ftp = ftp_class(timeout=TIMEOUT)
230 ftp.connect(HOST, PORT)
231 ftp.login(USER, PASSWORD)
232 if SSL:
233 ftp.prot_p() # secure data connection
234 return ftp
235
236
237 def retr(ftp):
238 """Same as ftplib's retrbinary() but discard the received data."""
239 ftp.voidcmd('TYPE I')
240 with contextlib.closing(ftp.transfercmd("RETR " + TESTFN)) as conn:
241 recv_bytes = 0
242 while True:
243 data = conn.recv(BUFFER_LEN)
244 if not data:
245 break
246 recv_bytes += len(data)
247 ftp.voidresp()
248
249
250 def stor(ftp=None):
251 """Same as ftplib's storbinary() but just sends dummy data
252 instead of reading it from a real file.
253 """
254 if ftp is None:
255 ftp = connect()
256 quit = True
257 else:
258 quit = False
259 ftp.voidcmd('TYPE I')
260 with contextlib.closing(ftp.transfercmd("STOR " + TESTFN)) as conn:
261 chunk = b'x' * BUFFER_LEN
262 total_sent = 0
263 while True:
264 sent = conn.send(chunk)
265 total_sent += sent
266 if total_sent >= FILE_SIZE:
267 break
268 ftp.voidresp()
269 if quit:
270 ftp.quit()
271 return ftp
272
273
274 def bytes_per_second(ftp, retr=True):
275 """Return the number of bytes transmitted in 1 second."""
276 tot_bytes = 0
277 if retr:
278 def request_file():
279 ftp.voidcmd('TYPE I')
280 conn = ftp.transfercmd("retr " + TESTFN)
281 return conn
282
283 with contextlib.closing(request_file()) as conn:
284 register_memory()
285 stop_at = time.time() + 1.0
286 while stop_at > time.time():
287 chunk = conn.recv(BUFFER_LEN)
288 if not chunk:
289 a = time.time()
290 ftp.voidresp()
291 conn.close()
292 conn = request_file()
293 stop_at += time.time() - a
294 tot_bytes += len(chunk)
295
296 try:
297 while chunk:
298 chunk = conn.recv(BUFFER_LEN)
299 ftp.voidresp()
300 conn.close()
301 except (ftplib.error_temp, ftplib.error_perm):
302 pass
303 else:
304 ftp.voidcmd('TYPE I')
305 with contextlib.closing(ftp.transfercmd("STOR " + TESTFN)) as conn:
306 register_memory()
307 chunk = b'x' * BUFFER_LEN
308 stop_at = time.time() + 1
309 while stop_at > time.time():
310 tot_bytes += conn.send(chunk)
311 ftp.voidresp()
312
313 return tot_bytes
314
315
316 def cleanup():
317 ftp = connect()
318 try:
319 if TESTFN in ftp.mlsd():
320 ftp.delete(TESTFN)
321 except (ftplib.error_perm, ftplib.error_temp) as err:
322 msg = "could not delete %r test file on cleanup: %r" % (TESTFN, err)
323 print(hilite(msg, ok=False), file=sys.stderr)
324 ftp.quit()
325
326
327 def bench_stor(ftp=None, title="STOR (client -> server)"):
328 if ftp is None:
329 ftp = connect()
330 tot_bytes = bytes_per_second(ftp, retr=False)
331 print_bench(title, round(tot_bytes / 1024.0 / 1024.0, 2), "MB/sec")
332 ftp.quit()
333
334
335 def bench_retr(ftp=None, title="RETR (server -> client)"):
336 if ftp is None:
337 ftp = connect()
338 tot_bytes = bytes_per_second(ftp, retr=True)
339 print_bench(title, round(tot_bytes / 1024.0 / 1024.0, 2), "MB/sec")
340 ftp.quit()
341
342
343 def bench_multi(howmany):
344 # The OS usually sets a limit of 1024 as the maximum number of
345 # open file descriptors for the current process.
346 # Let's set the highest number possible, just to be sure.
347 if howmany > 500 and resource is not None:
348 soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
349 resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard))
350
351 def bench_multi_connect():
352 with timethis("%i concurrent clients (connect, login)" % howmany):
353 clients = []
354 for x in range(howmany):
355 clients.append(connect())
356 register_memory()
357 return clients
358
359 def bench_multi_retr(clients):
360 stor(clients[0])
361 with timethis(
362 "%s concurrent clients (RETR %s file)" % (
363 howmany, bytes2human(FILE_SIZE),
364 ),
365 ):
366 for ftp in clients:
367 ftp.voidcmd('TYPE I')
368 conn = ftp.transfercmd("RETR " + TESTFN)
369 AsyncReader(conn)
370 register_memory()
371 asyncore.loop(use_poll=True)
372 for ftp in clients:
373 ftp.voidresp()
374
375 def bench_multi_stor(clients):
376 with timethis(
377 "%s concurrent clients (STOR %s file)" % (
378 howmany, bytes2human(FILE_SIZE),
379 ),
380 ):
381 for ftp in clients:
382 ftp.voidcmd('TYPE I')
383 conn = ftp.transfercmd("STOR " + TESTFN)
384 AsyncWriter(conn, FILE_SIZE)
385 register_memory()
386 asyncore.loop(use_poll=True)
387 for ftp in clients:
388 ftp.voidresp()
389
390 def bench_multi_quit(clients):
391 for ftp in clients:
392 AsyncQuit(ftp.sock)
393 with timethis("%i concurrent clients (QUIT)" % howmany):
394 asyncore.loop(use_poll=True)
395
396 clients = bench_multi_connect()
397 bench_stor(title="STOR (1 file with %s idle clients)" % len(clients))
398 bench_retr(title="RETR (1 file with %s idle clients)" % len(clients))
399 bench_multi_retr(clients)
400 bench_multi_stor(clients)
401 bench_multi_quit(clients)
402
403
404 @contextlib.contextmanager
405 def handle_ssl_want_rw_errs():
406 try:
407 yield
408 except (SSLWantReadError, SSLWantWriteError) as err:
409 if DEBUG:
410 print(err)
411 except ssl.SSLError as err:
412 if err.args[0] in (SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE):
413 if DEBUG:
414 print(err)
415 else:
416 raise
417
418
419 class AsyncReader(asyncore.dispatcher):
420 """Just read data from a connected socket, asynchronously."""
421
422 def __init__(self, sock):
423 asyncore.dispatcher.__init__(self, sock)
424
425 def handle_read(self):
426 if SSL:
427 with handle_ssl_want_rw_errs():
428 chunk = self.socket.recv(65536)
429 else:
430 chunk = self.socket.recv(65536)
431 if not chunk:
432 self.close()
433
434 def handle_close(self):
435 self.close()
436
437 def handle_error(self):
438 raise
439
440
441 class AsyncWriter(asyncore.dispatcher):
442 """Just write dummy data to a connected socket, asynchronously."""
443
444 def __init__(self, sock, size):
445 asyncore.dispatcher.__init__(self, sock)
446 self.size = size
447 self.sent = 0
448 self.chunk = b'x' * BUFFER_LEN
449
450 def handle_write(self):
451 if SSL:
452 with handle_ssl_want_rw_errs():
453 self.sent += asyncore.dispatcher.send(self, self.chunk)
454 else:
455 self.sent += asyncore.dispatcher.send(self, self.chunk)
456 if self.sent >= self.size:
457 self.handle_close()
458
459 def handle_error(self):
460 raise
461
462
463 class AsyncQuit(asynchat.async_chat):
464
465 def __init__(self, sock):
466 asynchat.async_chat.__init__(self, sock)
467 self.in_buffer = []
468 self.set_terminator(b'\r\n')
469 self.push(b'QUIT\r\n')
470
471 def collect_incoming_data(self, data):
472 self.in_buffer.append(data)
473
474 def found_terminator(self):
475 self.handle_close()
476
477 def handle_error(self):
478 raise
479
480
481 class OptFormatter(optparse.IndentedHelpFormatter):
482
483 def format_epilog(self, s):
484 return s.lstrip()
485
486 def format_option(self, option):
487 result = []
488 opts = self.option_strings[option]
489 result.append(' %s\n' % opts)
490 if option.help:
491 help_text = ' %s\n\n' % self.expand_default(option)
492 result.append(help_text)
493 return ''.join(result)
494
495
496 def main():
497 global HOST, PORT, USER, PASSWORD, SERVER_PROC, TIMEOUT, SSL, FILE_SIZE, \
498 DEBUG
499 USAGE = "%s -u USERNAME -p PASSWORD [-H] [-P] [-b] [-n] [-s] [-k] " \
500 "[-t] [-d] [-S]" % (os.path.basename(__file__))
501 parser = optparse.OptionParser(
502 usage=USAGE,
503 epilog=__doc__[__doc__.find('Example'):],
504 formatter=OptFormatter(),
505 )
506 parser.add_option('-u', '--user', dest='user', help='username')
507 parser.add_option('-p', '--pass', dest='password', help='password')
508 parser.add_option(
509 '-H', '--host', dest='host', default=HOST,
510 help='hostname',
511 )
512 parser.add_option(
513 '-P', '--port', dest='port', default=PORT, help='port',
514 type=int,
515 )
516 parser.add_option(
517 '-b', '--benchmark', dest='benchmark',
518 default='transfer',
519 help="benchmark type ('transfer', 'download', 'upload', "
520 "'concurrence', 'all')",
521 )
522 parser.add_option(
523 '-n', '--clients', dest='clients', default=200,
524 type="int",
525 help="number of concurrent clients used by "
526 "'concurrence' benchmark",
527 )
528 parser.add_option(
529 '-s', '--filesize', dest='filesize', default="10M",
530 help="file size used by 'concurrence' benchmark "
531 "(e.g. '10M')",
532 )
533 parser.add_option(
534 '-k', '--pid', dest='pid', default=None, type="int",
535 help="the PID of the FTP server process, to track its "
536 "memory usage",
537 )
538 parser.add_option(
539 '-t', '--timeout', dest='timeout',
540 default=TIMEOUT, type="int", help="the socket timeout",
541 )
542 parser.add_option(
543 '-d', '--debug', action='store_true', dest='debug',
544 help="whether to print debugging info",
545 )
546 parser.add_option(
547 '-S', '--ssl', action='store_true', dest='ssl',
548 help="whether to use FTPS",
549 )
550
551 options, args = parser.parse_args()
552 if not options.user or not options.password:
553 sys.exit(USAGE)
554 else:
555 USER = options.user
556 PASSWORD = options.password
557 HOST = options.host
558 PORT = options.port
559 TIMEOUT = options.timeout
560 SSL = bool(options.ssl)
561 DEBUG = options.debug
562 if SSL and sys.version_info < (2, 7):
563 sys.exit("--ssl option requires python >= 2.7")
564 try:
565 FILE_SIZE = human2bytes(options.filesize)
566 except (ValueError, AssertionError):
567 parser.error("invalid file size %r" % options.filesize)
568 if options.pid is not None:
569 if psutil is None:
570 raise ImportError("-p option requires psutil module")
571 SERVER_PROC = psutil.Process(options.pid)
572
573 # before starting make sure we have write permissions
574 ftp = connect()
575 conn = ftp.transfercmd("STOR " + TESTFN)
576 conn.close()
577 ftp.voidresp()
578 ftp.delete(TESTFN)
579 ftp.quit()
580 atexit.register(cleanup)
581
582 # start benchmark
583 if SERVER_PROC is not None:
584 register_memory()
585 print(
586 "(starting with %s of memory being used)" % (
587 hilite(server_memory.pop())
588 ),
589 )
590 if options.benchmark == 'download':
591 stor()
592 bench_retr()
593 elif options.benchmark == 'upload':
594 bench_stor()
595 elif options.benchmark == 'transfer':
596 bench_stor()
597 bench_retr()
598 elif options.benchmark == 'concurrence':
599 bench_multi(options.clients)
600 elif options.benchmark == 'all':
601 bench_stor()
602 bench_retr()
603 bench_multi(options.clients)
604 else:
605 sys.exit("invalid 'benchmark' parameter %r" % options.benchmark)
606
607
608 if __name__ == '__main__':
609 main()