scorecard.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #***************************************************************************
  4. # _ _ ____ _
  5. # Project ___| | | | _ \| |
  6. # / __| | | | |_) | |
  7. # | (__| |_| | _ <| |___
  8. # \___|\___/|_| \_\_____|
  9. #
  10. # Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  11. #
  12. # This software is licensed as described in the file COPYING, which
  13. # you should have received as part of this distribution. The terms
  14. # are also available at https://curl.se/docs/copyright.html.
  15. #
  16. # You may opt to use, copy, modify, merge, publish, distribute and/or sell
  17. # copies of the Software, and permit persons to whom the Software is
  18. # furnished to do so, under the terms of the COPYING file.
  19. #
  20. # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  21. # KIND, either express or implied.
  22. #
  23. # SPDX-License-Identifier: curl
  24. #
  25. ###########################################################################
  26. #
  27. import argparse
  28. import json
  29. import logging
  30. import os
  31. import re
  32. import sys
  33. from statistics import mean
  34. from typing import Dict, Any, Optional, List
  35. from testenv import Env, Httpd, Nghttpx, CurlClient, Caddy, ExecResult, NghttpxFwd
  36. log = logging.getLogger(__name__)
  37. class ScoreCardException(Exception):
  38. pass
  39. class ScoreCard:
  40. def __init__(self, env: Env,
  41. httpd: Optional[Httpd],
  42. nghttpx: Optional[Nghttpx],
  43. caddy: Optional[Caddy],
  44. verbose: int,
  45. curl_verbose: int):
  46. self.verbose = verbose
  47. self.env = env
  48. self.httpd = httpd
  49. self.nghttpx = nghttpx
  50. self.caddy = caddy
  51. self._silent_curl = not curl_verbose
  52. def info(self, msg):
  53. if self.verbose > 0:
  54. sys.stderr.write(msg)
  55. sys.stderr.flush()
  56. def handshakes(self, proto: str) -> Dict[str, Any]:
  57. props = {}
  58. sample_size = 5
  59. self.info(f'TLS Handshake\n')
  60. for authority in [
  61. 'curl.se', 'google.com', 'cloudflare.com', 'nghttp2.org'
  62. ]:
  63. self.info(f' {authority}...')
  64. props[authority] = {}
  65. for ipv in ['ipv4', 'ipv6']:
  66. self.info(f'{ipv}...')
  67. c_samples = []
  68. hs_samples = []
  69. errors = []
  70. for i in range(sample_size):
  71. curl = CurlClient(env=self.env, silent=self._silent_curl)
  72. args = [
  73. '--http3-only' if proto == 'h3' else '--http2',
  74. f'--{ipv}', f'https://{authority}/'
  75. ]
  76. r = curl.run_direct(args=args, with_stats=True)
  77. if r.exit_code == 0 and len(r.stats) == 1:
  78. c_samples.append(r.stats[0]['time_connect'])
  79. hs_samples.append(r.stats[0]['time_appconnect'])
  80. else:
  81. errors.append(f'exit={r.exit_code}')
  82. props[authority][f'{ipv}-connect'] = mean(c_samples) \
  83. if len(c_samples) else -1
  84. props[authority][f'{ipv}-handshake'] = mean(hs_samples) \
  85. if len(hs_samples) else -1
  86. props[authority][f'{ipv}-errors'] = errors
  87. self.info('ok.\n')
  88. return props
  89. def _make_docs_file(self, docs_dir: str, fname: str, fsize: int):
  90. fpath = os.path.join(docs_dir, fname)
  91. data1k = 1024*'x'
  92. flen = 0
  93. with open(fpath, 'w') as fd:
  94. while flen < fsize:
  95. fd.write(data1k)
  96. flen += len(data1k)
  97. return flen
  98. def _check_downloads(self, r: ExecResult, count: int):
  99. error = ''
  100. if r.exit_code != 0:
  101. error += f'exit={r.exit_code} '
  102. if r.exit_code != 0 or len(r.stats) != count:
  103. error += f'stats={len(r.stats)}/{count} '
  104. fails = [s for s in r.stats if s['response_code'] != 200]
  105. if len(fails) > 0:
  106. error += f'{len(fails)} failed'
  107. return error if len(error) > 0 else None
  108. def transfer_single(self, url: str, proto: str, count: int):
  109. sample_size = count
  110. count = 1
  111. samples = []
  112. errors = []
  113. self.info(f'single...')
  114. for i in range(sample_size):
  115. curl = CurlClient(env=self.env, silent=self._silent_curl)
  116. r = curl.http_download(urls=[url], alpn_proto=proto, no_save=True,
  117. with_headers=False)
  118. err = self._check_downloads(r, count)
  119. if err:
  120. errors.append(err)
  121. else:
  122. total_size = sum([s['size_download'] for s in r.stats])
  123. samples.append(total_size / r.duration.total_seconds())
  124. return {
  125. 'count': count,
  126. 'samples': sample_size,
  127. 'speed': mean(samples) if len(samples) else -1,
  128. 'errors': errors
  129. }
  130. def transfer_serial(self, url: str, proto: str, count: int):
  131. sample_size = 1
  132. samples = []
  133. errors = []
  134. url = f'{url}?[0-{count - 1}]'
  135. self.info(f'serial...')
  136. for i in range(sample_size):
  137. curl = CurlClient(env=self.env, silent=self._silent_curl)
  138. r = curl.http_download(urls=[url], alpn_proto=proto, no_save=True,
  139. with_headers=False)
  140. err = self._check_downloads(r, count)
  141. if err:
  142. errors.append(err)
  143. else:
  144. total_size = sum([s['size_download'] for s in r.stats])
  145. samples.append(total_size / r.duration.total_seconds())
  146. return {
  147. 'count': count,
  148. 'samples': sample_size,
  149. 'speed': mean(samples) if len(samples) else -1,
  150. 'errors': errors
  151. }
  152. def transfer_parallel(self, url: str, proto: str, count: int):
  153. sample_size = 1
  154. samples = []
  155. errors = []
  156. url = f'{url}?[0-{count - 1}]'
  157. self.info(f'parallel...')
  158. for i in range(sample_size):
  159. curl = CurlClient(env=self.env, silent=self._silent_curl)
  160. r = curl.http_download(urls=[url], alpn_proto=proto, no_save=True,
  161. with_headers=False,
  162. extra_args=['--parallel',
  163. '--parallel-max', str(count)])
  164. err = self._check_downloads(r, count)
  165. if err:
  166. errors.append(err)
  167. else:
  168. total_size = sum([s['size_download'] for s in r.stats])
  169. samples.append(total_size / r.duration.total_seconds())
  170. return {
  171. 'count': count,
  172. 'samples': sample_size,
  173. 'speed': mean(samples) if len(samples) else -1,
  174. 'errors': errors
  175. }
  176. def download_url(self, label: str, url: str, proto: str, count: int):
  177. self.info(f' {count}x{label}: ')
  178. props = {
  179. 'single': self.transfer_single(url=url, proto=proto, count=10),
  180. 'serial': self.transfer_serial(url=url, proto=proto, count=count),
  181. 'parallel': self.transfer_parallel(url=url, proto=proto,
  182. count=count),
  183. }
  184. self.info(f'ok.\n')
  185. return props
  186. def downloads(self, proto: str, count: int,
  187. fsizes: List[int]) -> Dict[str, Any]:
  188. scores = {}
  189. if self.httpd:
  190. if proto == 'h3':
  191. port = self.env.h3_port
  192. via = 'nghttpx'
  193. descr = f'port {port}, proxying httpd'
  194. else:
  195. port = self.env.https_port
  196. via = 'httpd'
  197. descr = f'port {port}'
  198. self.info(f'{via} downloads\n')
  199. scores[via] = {
  200. 'description': descr,
  201. }
  202. for fsize in fsizes:
  203. label = f'{int(fsize / 1024)}KB' if fsize < 1024*1024 else \
  204. f'{int(fsize / (1024 * 1024))}MB'
  205. fname = f'score{label}.data'
  206. self._make_docs_file(docs_dir=self.httpd.docs_dir,
  207. fname=fname, fsize=fsize)
  208. url = f'https://{self.env.domain1}:{port}/{fname}'
  209. results = self.download_url(label=label, url=url,
  210. proto=proto, count=count)
  211. scores[via][label] = results
  212. if self.caddy:
  213. port = self.caddy.port
  214. via = 'caddy'
  215. descr = f'port {port}'
  216. self.info('caddy downloads\n')
  217. scores[via] = {
  218. 'description': descr,
  219. }
  220. for fsize in fsizes:
  221. label = f'{int(fsize / 1024)}KB' if fsize < 1024*1024 else \
  222. f'{int(fsize / (1024 * 1024))}MB'
  223. fname = f'score{label}.data'
  224. self._make_docs_file(docs_dir=self.caddy.docs_dir,
  225. fname=fname, fsize=fsize)
  226. url = f'https://{self.env.domain1}:{port}/{fname}'
  227. results = self.download_url(label=label, url=url,
  228. proto=proto, count=count)
  229. scores[via][label] = results
  230. return scores
  231. def do_requests(self, url: str, proto: str, count: int,
  232. max_parallel: int = 1):
  233. sample_size = 1
  234. samples = []
  235. errors = []
  236. url = f'{url}?[0-{count - 1}]'
  237. extra_args = ['--parallel', '--parallel-max', str(max_parallel)] \
  238. if max_parallel > 1 else []
  239. self.info(f'{max_parallel}...')
  240. for i in range(sample_size):
  241. curl = CurlClient(env=self.env, silent=self._silent_curl)
  242. r = curl.http_download(urls=[url], alpn_proto=proto, no_save=True,
  243. with_headers=False,
  244. extra_args=extra_args)
  245. err = self._check_downloads(r, count)
  246. if err:
  247. errors.append(err)
  248. else:
  249. for _ in r.stats:
  250. samples.append(count / r.duration.total_seconds())
  251. return {
  252. 'count': count,
  253. 'samples': sample_size,
  254. 'speed': mean(samples) if len(samples) else -1,
  255. 'errors': errors
  256. }
  257. def requests_url(self, url: str, proto: str, count: int):
  258. self.info(f' {url}: ')
  259. props = {
  260. 'serial': self.do_requests(url=url, proto=proto, count=count),
  261. 'par-6': self.do_requests(url=url, proto=proto, count=count,
  262. max_parallel=6),
  263. 'par-25': self.do_requests(url=url, proto=proto, count=count,
  264. max_parallel=25),
  265. 'par-50': self.do_requests(url=url, proto=proto, count=count,
  266. max_parallel=50),
  267. 'par-100': self.do_requests(url=url, proto=proto, count=count,
  268. max_parallel=100),
  269. }
  270. self.info(f'ok.\n')
  271. return props
  272. def requests(self, proto: str) -> Dict[str, Any]:
  273. scores = {}
  274. if self.httpd:
  275. if proto == 'h3':
  276. port = self.env.h3_port
  277. via = 'nghttpx'
  278. descr = f'port {port}, proxying httpd'
  279. else:
  280. port = self.env.https_port
  281. via = 'httpd'
  282. descr = f'port {port}'
  283. self.info(f'{via} requests\n')
  284. self._make_docs_file(docs_dir=self.httpd.docs_dir,
  285. fname='reqs10.data', fsize=10*1024)
  286. url1 = f'https://{self.env.domain1}:{port}/reqs10.data'
  287. scores[via] = {
  288. 'description': descr,
  289. '10KB': self.requests_url(url=url1, proto=proto, count=10000),
  290. }
  291. if self.caddy:
  292. port = self.caddy.port
  293. via = 'caddy'
  294. descr = f'port {port}'
  295. self.info('caddy requests\n')
  296. self._make_docs_file(docs_dir=self.caddy.docs_dir,
  297. fname='req10.data', fsize=10 * 1024)
  298. url1 = f'https://{self.env.domain1}:{port}/req10.data'
  299. scores[via] = {
  300. 'description': descr,
  301. '10KB': self.requests_url(url=url1, proto=proto, count=5000),
  302. }
  303. return scores
  304. def score_proto(self, proto: str,
  305. handshakes: bool = True,
  306. downloads: Optional[List[int]] = None,
  307. download_count: int = 50,
  308. requests: bool = True):
  309. self.info(f"scoring {proto}\n")
  310. p = {}
  311. if proto == 'h3':
  312. p['name'] = 'h3'
  313. if not self.env.have_h3_curl():
  314. raise ScoreCardException('curl does not support HTTP/3')
  315. for lib in ['ngtcp2', 'quiche', 'msh3']:
  316. if self.env.curl_uses_lib(lib):
  317. p['implementation'] = lib
  318. break
  319. elif proto == 'h2':
  320. p['name'] = 'h2'
  321. if not self.env.have_h2_curl():
  322. raise ScoreCardException('curl does not support HTTP/2')
  323. for lib in ['nghttp2', 'hyper']:
  324. if self.env.curl_uses_lib(lib):
  325. p['implementation'] = lib
  326. break
  327. elif proto == 'h1' or proto == 'http/1.1':
  328. proto = 'http/1.1'
  329. p['name'] = proto
  330. p['implementation'] = 'hyper' if self.env.curl_uses_lib('hyper')\
  331. else 'native'
  332. else:
  333. raise ScoreCardException(f"unknown protocol: {proto}")
  334. if 'implementation' not in p:
  335. raise ScoreCardException(f'did not recognized {p} lib')
  336. p['version'] = Env.curl_lib_version(p['implementation'])
  337. score = {
  338. 'curl': self.env.curl_fullname(),
  339. 'os': self.env.curl_os(),
  340. 'protocol': p,
  341. }
  342. if handshakes:
  343. score['handshakes'] = self.handshakes(proto=proto)
  344. if downloads and len(downloads) > 0:
  345. score['downloads'] = self.downloads(proto=proto,
  346. count=download_count,
  347. fsizes=downloads)
  348. if requests:
  349. score['requests'] = self.requests(proto=proto)
  350. self.info("\n")
  351. return score
  352. def fmt_ms(self, tval):
  353. return f'{int(tval*1000)} ms' if tval >= 0 else '--'
  354. def fmt_mb(self, val):
  355. return f'{val/(1024*1024):0.000f} MB' if val >= 0 else '--'
  356. def fmt_mbs(self, val):
  357. return f'{val/(1024*1024):0.000f} MB/s' if val >= 0 else '--'
  358. def fmt_reqs(self, val):
  359. return f'{val:0.000f} r/s' if val >= 0 else '--'
  360. def print_score(self, score):
  361. print(f'{score["protocol"]["name"].upper()} in {score["curl"]}')
  362. if 'handshakes' in score:
  363. print(f'{"Handshakes":<24} {"ipv4":25} {"ipv6":28}')
  364. print(f' {"Host":<17} {"Connect":>12} {"Handshake":>12} '
  365. f'{"Connect":>12} {"Handshake":>12} {"Errors":<20}')
  366. for key, val in score["handshakes"].items():
  367. print(f' {key:<17} {self.fmt_ms(val["ipv4-connect"]):>12} '
  368. f'{self.fmt_ms(val["ipv4-handshake"]):>12} '
  369. f'{self.fmt_ms(val["ipv6-connect"]):>12} '
  370. f'{self.fmt_ms(val["ipv6-handshake"]):>12} '
  371. f'{"/".join(val["ipv4-errors"] + val["ipv6-errors"]):<20}'
  372. )
  373. if 'downloads' in score:
  374. print('Downloads')
  375. print(f' {"Server":<8} {"Size":>8} {"Single":>12} {"Serial":>12}'
  376. f' {"Parallel":>12} {"Errors":<20}')
  377. skeys = {}
  378. for dkey, dval in score["downloads"].items():
  379. for k in dval.keys():
  380. skeys[k] = True
  381. for skey in skeys:
  382. for dkey, dval in score["downloads"].items():
  383. if skey in dval:
  384. sval = dval[skey]
  385. if isinstance(sval, str):
  386. continue
  387. errors = []
  388. for key, val in sval.items():
  389. if 'errors' in val:
  390. errors.extend(val['errors'])
  391. print(f' {dkey:<8} {skey:>8} '
  392. f'{self.fmt_mbs(sval["single"]["speed"]):>12} '
  393. f'{self.fmt_mbs(sval["serial"]["speed"]):>12} '
  394. f'{self.fmt_mbs(sval["parallel"]["speed"]):>12} '
  395. f' {"/".join(errors):<20}')
  396. if 'requests' in score:
  397. print('Requests, max in parallel')
  398. print(f' {"Server":<8} {"Size":>8} '
  399. f'{"1 ":>12} {"6 ":>12} {"25 ":>12} '
  400. f'{"50 ":>12} {"100 ":>12} {"Errors":<20}')
  401. for dkey, dval in score["requests"].items():
  402. for skey, sval in dval.items():
  403. if isinstance(sval, str):
  404. continue
  405. errors = []
  406. for key, val in sval.items():
  407. if 'errors' in val:
  408. errors.extend(val['errors'])
  409. line = f' {dkey:<8} {skey:>8} '
  410. for k in sval.keys():
  411. line += f'{self.fmt_reqs(sval[k]["speed"]):>12} '
  412. line += f' {"/".join(errors):<20}'
  413. print(line)
  414. def parse_size(s):
  415. m = re.match(r'(\d+)(mb|kb|gb)?', s, re.IGNORECASE)
  416. if m is None:
  417. raise Exception(f'unrecognized size: {s}')
  418. size = int(m.group(1))
  419. if m.group(2).lower() == 'kb':
  420. size *= 1024
  421. elif m.group(2).lower() == 'mb':
  422. size *= 1024 * 1024
  423. elif m.group(2).lower() == 'gb':
  424. size *= 1024 * 1024 * 1024
  425. return size
  426. def main():
  427. parser = argparse.ArgumentParser(prog='scorecard', description="""
  428. Run a range of tests to give a scorecard for a HTTP protocol
  429. 'h3' or 'h2' implementation in curl.
  430. """)
  431. parser.add_argument("-v", "--verbose", action='count', default=1,
  432. help="log more output on stderr")
  433. parser.add_argument("-j", "--json", action='store_true',
  434. default=False, help="print json instead of text")
  435. parser.add_argument("-H", "--handshakes", action='store_true',
  436. default=False, help="evaluate handshakes only")
  437. parser.add_argument("-d", "--downloads", action='store_true',
  438. default=False, help="evaluate downloads only")
  439. parser.add_argument("--download", action='append', type=str,
  440. default=None, help="evaluate download size")
  441. parser.add_argument("--download-count", action='store', type=int,
  442. default=50, help="perform that many downloads")
  443. parser.add_argument("-r", "--requests", action='store_true',
  444. default=False, help="evaluate requests only")
  445. parser.add_argument("--httpd", action='store_true', default=False,
  446. help="evaluate httpd server only")
  447. parser.add_argument("--caddy", action='store_true', default=False,
  448. help="evaluate caddy server only")
  449. parser.add_argument("--curl-verbose", action='store_true',
  450. default=False, help="run curl with `-v`")
  451. parser.add_argument("protocol", default='h2', nargs='?',
  452. help="Name of protocol to score")
  453. args = parser.parse_args()
  454. if args.verbose > 0:
  455. console = logging.StreamHandler()
  456. console.setLevel(logging.INFO)
  457. console.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
  458. logging.getLogger('').addHandler(console)
  459. protocol = args.protocol
  460. handshakes = True
  461. downloads = [1024*1024, 10*1024*1024, 100*1024*1024]
  462. requests = True
  463. test_httpd = protocol != 'h3'
  464. test_caddy = True
  465. if args.handshakes:
  466. downloads = None
  467. requests = False
  468. if args.downloads:
  469. handshakes = False
  470. requests = False
  471. if args.download:
  472. downloads = sorted([parse_size(x) for x in args.download])
  473. handshakes = False
  474. requests = False
  475. if args.requests:
  476. handshakes = False
  477. downloads = None
  478. if args.caddy:
  479. test_caddy = True
  480. test_httpd = False
  481. if args.httpd:
  482. test_caddy = False
  483. test_httpd = True
  484. rv = 0
  485. env = Env()
  486. env.setup()
  487. env.test_timeout = None
  488. httpd = None
  489. nghttpx = None
  490. caddy = None
  491. try:
  492. if test_httpd:
  493. httpd = Httpd(env=env)
  494. assert httpd.exists(), \
  495. f'httpd not found: {env.httpd}'
  496. httpd.clear_logs()
  497. assert httpd.start()
  498. if 'h3' == protocol:
  499. nghttpx = NghttpxFwd(env=env)
  500. nghttpx.clear_logs()
  501. assert nghttpx.start()
  502. if test_caddy and env.caddy:
  503. caddy = Caddy(env=env)
  504. caddy.clear_logs()
  505. assert caddy.start()
  506. card = ScoreCard(env=env, httpd=httpd, nghttpx=nghttpx, caddy=caddy,
  507. verbose=args.verbose, curl_verbose=args.curl_verbose)
  508. score = card.score_proto(proto=protocol,
  509. handshakes=handshakes,
  510. downloads=downloads,
  511. download_count=args.download_count,
  512. requests=requests)
  513. if args.json:
  514. print(json.JSONEncoder(indent=2).encode(score))
  515. else:
  516. card.print_score(score)
  517. except ScoreCardException as ex:
  518. sys.stderr.write(f"ERROR: {str(ex)}\n")
  519. rv = 1
  520. except KeyboardInterrupt:
  521. log.warning("aborted")
  522. rv = 1
  523. finally:
  524. if caddy:
  525. caddy.stop()
  526. if nghttpx:
  527. nghttpx.stop(wait_dead=False)
  528. if httpd:
  529. httpd.stop()
  530. sys.exit(rv)
  531. if __name__ == "__main__":
  532. main()