1
0

speedtest.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2012-2016 Matt Martz
  4. # All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  7. # not use this file except in compliance with the License. You may obtain
  8. # a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. # License for the specific language governing permissions and limitations
  16. # under the License.
  17. import os
  18. import re
  19. import csv
  20. import sys
  21. import math
  22. import errno
  23. import signal
  24. import socket
  25. import timeit
  26. import datetime
  27. import platform
  28. import threading
  29. import xml.parsers.expat
  30. try:
  31. import gzip
  32. GZIP_BASE = gzip.GzipFile
  33. except ImportError:
  34. gzip = None
  35. GZIP_BASE = object
  36. __version__ = '1.0.0'
  37. class FakeShutdownEvent(object):
  38. """Class to fake a threading.Event.isSet so that users of this module
  39. are not required to register their own threading.Event()
  40. """
  41. @staticmethod
  42. def isSet():
  43. "Dummy method to always return false"""
  44. return False
  45. # Some global variables we use
  46. USER_AGENT = None
  47. SOURCE = None
  48. SHUTDOWN_EVENT = FakeShutdownEvent()
  49. SCHEME = 'http'
  50. DEBUG = False
  51. # Used for bound_interface
  52. SOCKET_SOCKET = socket.socket
  53. # Begin import game to handle Python 2 and Python 3
  54. try:
  55. import json
  56. except ImportError:
  57. try:
  58. import simplejson as json
  59. except ImportError:
  60. json = None
  61. try:
  62. import xml.etree.cElementTree as ET
  63. except ImportError:
  64. try:
  65. import xml.etree.ElementTree as ET
  66. except ImportError:
  67. from xml.dom import minidom as DOM
  68. ET = None
  69. try:
  70. from urllib2 import urlopen, Request, HTTPError, URLError
  71. except ImportError:
  72. from urllib.request import urlopen, Request, HTTPError, URLError
  73. try:
  74. from httplib import HTTPConnection
  75. except ImportError:
  76. from http.client import HTTPConnection
  77. try:
  78. from httplib import HTTPSConnection
  79. except ImportError:
  80. try:
  81. from http.client import HTTPSConnection
  82. except ImportError:
  83. HTTPSConnection = None
  84. try:
  85. from Queue import Queue
  86. except ImportError:
  87. from queue import Queue
  88. try:
  89. from urlparse import urlparse
  90. except ImportError:
  91. from urllib.parse import urlparse
  92. try:
  93. from urlparse import parse_qs
  94. except ImportError:
  95. try:
  96. from urllib.parse import parse_qs
  97. except ImportError:
  98. from cgi import parse_qs
  99. try:
  100. from hashlib import md5
  101. except ImportError:
  102. from md5 import md5
  103. try:
  104. from argparse import ArgumentParser as ArgParser
  105. from argparse import SUPPRESS as ARG_SUPPRESS
  106. PARSER_TYPE_INT = int
  107. PARSER_TYPE_STR = str
  108. except ImportError:
  109. from optparse import OptionParser as ArgParser
  110. from optparse import SUPPRESS_HELP as ARG_SUPPRESS
  111. PARSER_TYPE_INT = 'int'
  112. PARSER_TYPE_STR = 'string'
  113. try:
  114. from cStringIO import StringIO
  115. BytesIO = None
  116. except ImportError:
  117. try:
  118. from io import StringIO, BytesIO
  119. except ImportError:
  120. from StringIO import StringIO
  121. BytesIO = None
  122. try:
  123. import builtins
  124. except ImportError:
  125. def print_(*args, **kwargs):
  126. """The new-style print function for Python 2.4 and 2.5.
  127. Taken from https://pypi.python.org/pypi/six/
  128. Modified to set encoding to UTF-8 if not set when stdout may not be
  129. a tty such as when piping to head
  130. """
  131. fp = kwargs.pop("file", sys.stdout)
  132. if fp is None:
  133. return
  134. def write(data):
  135. if not isinstance(data, basestring):
  136. data = str(data)
  137. # If the file has an encoding, encode unicode with it.
  138. encoding = fp.encoding or 'UTF-8' # Diverges for notty
  139. if (isinstance(fp, file) and
  140. isinstance(data, unicode) and
  141. encoding is not None):
  142. errors = getattr(fp, "errors", None)
  143. if errors is None:
  144. errors = "strict"
  145. data = data.encode(encoding, errors)
  146. fp.write(data)
  147. want_unicode = False
  148. sep = kwargs.pop("sep", None)
  149. if sep is not None:
  150. if isinstance(sep, unicode):
  151. want_unicode = True
  152. elif not isinstance(sep, str):
  153. raise TypeError("sep must be None or a string")
  154. end = kwargs.pop("end", None)
  155. if end is not None:
  156. if isinstance(end, unicode):
  157. want_unicode = True
  158. elif not isinstance(end, str):
  159. raise TypeError("end must be None or a string")
  160. if kwargs:
  161. raise TypeError("invalid keyword arguments to print()")
  162. if not want_unicode:
  163. for arg in args:
  164. if isinstance(arg, unicode):
  165. want_unicode = True
  166. break
  167. if want_unicode:
  168. newline = unicode("\n")
  169. space = unicode(" ")
  170. else:
  171. newline = "\n"
  172. space = " "
  173. if sep is None:
  174. sep = space
  175. if end is None:
  176. end = newline
  177. for i, arg in enumerate(args):
  178. if i:
  179. write(sep)
  180. write(arg)
  181. write(end)
  182. else:
  183. print_ = getattr(builtins, 'print')
  184. del builtins
  185. # Exception "constants" to support Python 2 through Python 3
  186. try:
  187. import ssl
  188. try:
  189. CERT_ERROR = (ssl.CertificateError,)
  190. except AttributeError:
  191. CERT_ERROR = tuple()
  192. HTTP_ERRORS = ((HTTPError, URLError, socket.error, ssl.SSLError) +
  193. CERT_ERROR)
  194. except ImportError:
  195. HTTP_ERRORS = (HTTPError, URLError, socket.error)
  196. class SpeedtestException(Exception):
  197. """Base exception for this module"""
  198. class SpeedtestHTTPError(SpeedtestException):
  199. """Base HTTP exception for this module"""
  200. class SpeedtestConfigError(SpeedtestException):
  201. """Configuration provided is invalid"""
  202. class ConfigRetrievalError(SpeedtestHTTPError):
  203. """Could not retrieve config.php"""
  204. class ServersRetrievalError(SpeedtestHTTPError):
  205. """Could not retrieve speedtest-servers.php"""
  206. class InvalidServerIDType(SpeedtestException):
  207. """Server ID used for filtering was not an integer"""
  208. class NoMatchedServers(SpeedtestException):
  209. """No servers matched when filtering"""
  210. class SpeedtestMiniConnectFailure(SpeedtestException):
  211. """Could not connect to the provided speedtest mini server"""
  212. class InvalidSpeedtestMiniServer(SpeedtestException):
  213. """Server provided as a speedtest mini server does not actually appear
  214. to be a speedtest mini server
  215. """
  216. class ShareResultsConnectFailure(SpeedtestException):
  217. """Could not connect to speedtest.net API to POST results"""
  218. class ShareResultsSubmitFailure(SpeedtestException):
  219. """Unable to successfully POST results to speedtest.net API after
  220. connection
  221. """
  222. class SpeedtestUploadTimeout(SpeedtestException):
  223. """testlength configuration reached during upload
  224. Used to ensure the upload halts when no additional data should be sent
  225. """
  226. class SpeedtestBestServerFailure(SpeedtestException):
  227. """Unable to determine best server"""
  228. class GzipDecodedResponse(GZIP_BASE):
  229. """A file-like object to decode a response encoded with the gzip
  230. method, as described in RFC 1952.
  231. Largely copied from ``xmlrpclib``/``xmlrpc.client`` and modified
  232. to work for py2.4-py3
  233. """
  234. def __init__(self, response):
  235. # response doesn't support tell() and read(), required by
  236. # GzipFile
  237. if not gzip:
  238. raise SpeedtestHTTPError('HTTP response body is gzip encoded, '
  239. 'but gzip support is not available')
  240. IO = BytesIO or StringIO
  241. self.io = IO(response.read())
  242. gzip.GzipFile.__init__(self, mode='rb', fileobj=self.io)
  243. def close(self):
  244. try:
  245. gzip.GzipFile.close(self)
  246. finally:
  247. self.io.close()
  248. def bound_socket(*args, **kwargs):
  249. """Bind socket to a specified source IP address"""
  250. sock = SOCKET_SOCKET(*args, **kwargs)
  251. sock.bind((SOURCE, 0))
  252. return sock
  253. def distance(origin, destination):
  254. """Determine distance between 2 sets of [lat,lon] in km"""
  255. lat1, lon1 = origin
  256. lat2, lon2 = destination
  257. radius = 6371 # km
  258. dlat = math.radians(lat2 - lat1)
  259. dlon = math.radians(lon2 - lon1)
  260. a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
  261. math.cos(math.radians(lat1)) *
  262. math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
  263. math.sin(dlon / 2))
  264. c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  265. d = radius * c
  266. return d
  267. def build_user_agent():
  268. """Build a Mozilla/5.0 compatible User-Agent string"""
  269. global USER_AGENT
  270. if USER_AGENT:
  271. return USER_AGENT
  272. ua_tuple = (
  273. 'Mozilla/5.0',
  274. '(%s; U; %s; en-us)' % (platform.system(), platform.architecture()[0]),
  275. 'Python/%s' % platform.python_version(),
  276. '(KHTML, like Gecko)',
  277. 'speedtest-cli/%s' % __version__
  278. )
  279. USER_AGENT = ' '.join(ua_tuple)
  280. printer(USER_AGENT, debug=True)
  281. return USER_AGENT
  282. def build_request(url, data=None, headers=None, bump=''):
  283. """Build a urllib2 request object
  284. This function automatically adds a User-Agent header to all requests
  285. """
  286. if not USER_AGENT:
  287. build_user_agent()
  288. if not headers:
  289. headers = {}
  290. if url[0] == ':':
  291. schemed_url = '%s%s' % (SCHEME, url)
  292. else:
  293. schemed_url = url
  294. if '?' in url:
  295. delim = '&'
  296. else:
  297. delim = '?'
  298. # WHO YOU GONNA CALL? CACHE BUSTERS!
  299. final_url = '%s%sx=%s.%s' % (schemed_url, delim,
  300. int(timeit.time.time() * 1000),
  301. bump)
  302. headers.update({
  303. 'User-Agent': USER_AGENT,
  304. 'Cache-Control': 'no-cache',
  305. })
  306. printer('%s %s' % (('GET', 'POST')[bool(data)], final_url),
  307. debug=True)
  308. return Request(final_url, data=data, headers=headers)
  309. def catch_request(request):
  310. """Helper function to catch common exceptions encountered when
  311. establishing a connection with a HTTP/HTTPS request
  312. """
  313. try:
  314. uh = urlopen(request)
  315. return uh, False
  316. except HTTP_ERRORS:
  317. e = sys.exc_info()[1]
  318. return None, e
  319. def get_response_stream(response):
  320. """Helper function to return either a Gzip reader if
  321. ``Content-Encoding`` is ``gzip`` otherwise the response itself
  322. """
  323. try:
  324. getheader = response.headers.getheader
  325. except AttributeError:
  326. getheader = response.getheader
  327. if getheader('content-encoding') == 'gzip':
  328. return GzipDecodedResponse(response)
  329. return response
  330. def get_attributes_by_tag_name(dom, tag_name):
  331. """Retrieve an attribute from an XML document and return it in a
  332. consistent format
  333. Only used with xml.dom.minidom, which is likely only to be used
  334. with python versions older than 2.5
  335. """
  336. elem = dom.getElementsByTagName(tag_name)[0]
  337. return dict(list(elem.attributes.items()))
  338. def print_dots(current, total, start=False, end=False):
  339. """Built in callback function used by Thread classes for printing
  340. status
  341. """
  342. if SHUTDOWN_EVENT.isSet():
  343. return
  344. sys.stdout.write('.')
  345. if current + 1 == total and end is True:
  346. sys.stdout.write('\n')
  347. sys.stdout.flush()
  348. def do_nothing(*args, **kwargs):
  349. pass
  350. class HTTPDownloader(threading.Thread):
  351. """Thread class for retrieving a URL"""
  352. def __init__(self, i, request, start, timeout):
  353. threading.Thread.__init__(self)
  354. self.request = request
  355. self.result = [0]
  356. self.starttime = start
  357. self.timeout = timeout
  358. self.i = i
  359. def run(self):
  360. try:
  361. if (timeit.default_timer() - self.starttime) <= self.timeout:
  362. f = urlopen(self.request)
  363. while (not SHUTDOWN_EVENT.isSet() and
  364. (timeit.default_timer() - self.starttime) <=
  365. self.timeout):
  366. self.result.append(len(f.read(10240)))
  367. if self.result[-1] == 0:
  368. break
  369. f.close()
  370. except IOError:
  371. pass
  372. class HTTPUploaderData(object):
  373. """File like object to improve cutting off the upload once the timeout
  374. has been reached
  375. """
  376. def __init__(self, length, start, timeout):
  377. self.length = length
  378. self.start = start
  379. self.timeout = timeout
  380. self._data = None
  381. self.total = [0]
  382. def _create_data(self):
  383. chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  384. multiplier = int(round(int(self.length) / 36.0))
  385. IO = BytesIO or StringIO
  386. self._data = IO(
  387. ('content1=%s' %
  388. (chars * multiplier)[0:int(self.length) - 9]
  389. ).encode()
  390. )
  391. @property
  392. def data(self):
  393. if not self._data:
  394. self._create_data()
  395. return self._data
  396. def read(self, n=10240):
  397. if ((timeit.default_timer() - self.start) <= self.timeout and
  398. not SHUTDOWN_EVENT.isSet()):
  399. chunk = self.data.read(n)
  400. self.total.append(len(chunk))
  401. return chunk
  402. else:
  403. raise SpeedtestUploadTimeout
  404. def __len__(self):
  405. return self.length
  406. class HTTPUploader(threading.Thread):
  407. """Thread class for putting a URL"""
  408. def __init__(self, i, request, start, size, timeout):
  409. threading.Thread.__init__(self)
  410. self.request = request
  411. self.request.data.start = self.starttime = start
  412. self.size = size
  413. self.result = None
  414. self.timeout = timeout
  415. self.i = i
  416. def run(self):
  417. request = self.request
  418. try:
  419. if ((timeit.default_timer() - self.starttime) <= self.timeout and
  420. not SHUTDOWN_EVENT.isSet()):
  421. try:
  422. f = urlopen(request)
  423. except TypeError:
  424. # PY24 expects a string or buffer
  425. # This also causes issues with Ctrl-C, but we will concede
  426. # for the moment that Ctrl-C on PY24 isn't immediate
  427. request = build_request(self.request.get_full_url(),
  428. data=request.data.read(self.size))
  429. f = urlopen(request)
  430. f.read(11)
  431. f.close()
  432. self.result = sum(self.request.data.total)
  433. else:
  434. self.result = 0
  435. except (IOError, SpeedtestUploadTimeout):
  436. self.result = sum(self.request.data.total)
  437. class SpeedtestResults(object):
  438. """Class for holding the results of a speedtest, including:
  439. Download speed
  440. Upload speed
  441. Ping/Latency to test server
  442. Data about server that the test was run against
  443. Additionally this class can return a result data as a dictionary or CSV,
  444. as well as submit a POST of the result data to the speedtest.net API
  445. to get a share results image link.
  446. """
  447. def __init__(self, download=0, upload=0, ping=0, server=None):
  448. self.download = download
  449. self.upload = upload
  450. self.ping = ping
  451. if server is None:
  452. self.server = {}
  453. else:
  454. self.server = server
  455. self._share = None
  456. self.timestamp = datetime.datetime.utcnow().isoformat()
  457. self.bytes_received = 0
  458. self.bytes_sent = 0
  459. def __repr__(self):
  460. return repr(self.dict())
  461. def share(self):
  462. """POST data to the speedtest.net API to obtain a share results
  463. link
  464. """
  465. if self._share:
  466. return self._share
  467. download = int(round(self.download / 1000.0, 0))
  468. ping = int(round(self.ping, 0))
  469. upload = int(round(self.upload / 1000.0, 0))
  470. # Build the request to send results back to speedtest.net
  471. # We use a list instead of a dict because the API expects parameters
  472. # in a certain order
  473. api_data = [
  474. 'recommendedserverid=%s' % self.server['id'],
  475. 'ping=%s' % ping,
  476. 'screenresolution=',
  477. 'promo=',
  478. 'download=%s' % download,
  479. 'screendpi=',
  480. 'upload=%s' % upload,
  481. 'testmethod=http',
  482. 'hash=%s' % md5(('%s-%s-%s-%s' %
  483. (ping, upload, download, '297aae72'))
  484. .encode()).hexdigest(),
  485. 'touchscreen=none',
  486. 'startmode=pingselect',
  487. 'accuracy=1',
  488. 'bytesreceived=%s' % self.bytes_received,
  489. 'bytessent=%s' % self.bytes_sent,
  490. 'serverid=%s' % self.server['id'],
  491. ]
  492. headers = {'Referer': 'http://c.speedtest.net/flash/speedtest.swf'}
  493. request = build_request('://www.speedtest.net/api/api.php',
  494. data='&'.join(api_data).encode(),
  495. headers=headers)
  496. f, e = catch_request(request)
  497. if e:
  498. raise ShareResultsConnectFailure(e)
  499. response = f.read()
  500. code = f.code
  501. f.close()
  502. if int(code) != 200:
  503. raise ShareResultsSubmitFailure('Could not submit results to '
  504. 'speedtest.net')
  505. qsargs = parse_qs(response.decode())
  506. resultid = qsargs.get('resultid')
  507. if not resultid or len(resultid) != 1:
  508. raise ShareResultsSubmitFailure('Could not submit results to '
  509. 'speedtest.net')
  510. self._share = 'http://www.speedtest.net/result/%s.png' % resultid[0]
  511. return self._share
  512. def dict(self):
  513. """Return dictionary of result data"""
  514. return {
  515. 'download': self.download,
  516. 'upload': self.upload,
  517. 'ping': self.ping,
  518. 'server': self.server,
  519. 'timestamp': self.timestamp
  520. }
  521. def csv(self, delimiter=','):
  522. """Return data in CSV format"""
  523. data = self.dict()
  524. out = StringIO()
  525. writer = csv.writer(out, delimiter=delimiter, lineterminator='')
  526. writer.writerow([data['server']['id'], data['server']['sponsor'],
  527. data['server']['name'], data['timestamp'],
  528. data['server']['d'], data['ping'], data['download'],
  529. data['upload']])
  530. return out.getvalue()
  531. def json(self, pretty=False):
  532. """Return data in JSON format"""
  533. kwargs = {}
  534. if pretty:
  535. kwargs.update({
  536. 'indent': 4,
  537. 'sort_keys': True
  538. })
  539. return json.dumps(self.dict(), **kwargs)
  540. class Speedtest(object):
  541. """Class for performing standard speedtest.net testing operations"""
  542. def __init__(self, config=None):
  543. self.config = {}
  544. self.get_config()
  545. if config is not None:
  546. self.config.update(config)
  547. self.servers = {}
  548. self.closest = []
  549. self.best = {}
  550. self.results = SpeedtestResults()
  551. def get_config(self):
  552. """Download the speedtest.net configuration and return only the data
  553. we are interested in
  554. """
  555. headers = {}
  556. if gzip:
  557. headers['Accept-Encoding'] = 'gzip'
  558. request = build_request('://www.speedtest.net/speedtest-config.php',
  559. headers=headers)
  560. uh, e = catch_request(request)
  561. if e:
  562. raise ConfigRetrievalError(e)
  563. configxml = []
  564. stream = get_response_stream(uh)
  565. while 1:
  566. configxml.append(stream.read(10240))
  567. if len(configxml[-1]) == 0:
  568. break
  569. stream.close()
  570. uh.close()
  571. if int(uh.code) != 200:
  572. return None
  573. printer(''.encode().join(configxml), debug=True)
  574. try:
  575. root = ET.fromstring(''.encode().join(configxml))
  576. server_config = root.find('server-config').attrib
  577. download = root.find('download').attrib
  578. upload = root.find('upload').attrib
  579. # times = root.find('times').attrib
  580. client = root.find('client').attrib
  581. except AttributeError:
  582. root = DOM.parseString(''.join(configxml))
  583. server_config = get_attributes_by_tag_name(root, 'server-config')
  584. download = get_attributes_by_tag_name(root, 'download')
  585. upload = get_attributes_by_tag_name(root, 'upload')
  586. # times = get_attributes_by_tag_name(root, 'times')
  587. client = get_attributes_by_tag_name(root, 'client')
  588. ignore_servers = list(
  589. map(int, server_config['ignoreids'].split(','))
  590. )
  591. ratio = int(upload['ratio'])
  592. upload_max = int(upload['maxchunkcount'])
  593. up_sizes = [32768, 65536, 131072, 262144, 524288, 1048576, 7340032]
  594. sizes = {
  595. 'upload': up_sizes[ratio - 1:],
  596. 'download': [350, 500, 750, 1000, 1500, 2000, 2500,
  597. 3000, 3500, 4000]
  598. }
  599. counts = {
  600. 'upload': int(upload_max * 2 / len(sizes['upload'])),
  601. 'download': int(download['threadsperurl'])
  602. }
  603. threads = {
  604. 'upload': int(upload['threads']),
  605. 'download': int(server_config['threadcount']) * 2
  606. }
  607. length = {
  608. 'upload': int(upload['testlength']),
  609. 'download': int(download['testlength'])
  610. }
  611. self.config.update({
  612. 'client': client,
  613. 'ignore_servers': ignore_servers,
  614. 'sizes': sizes,
  615. 'counts': counts,
  616. 'threads': threads,
  617. 'length': length,
  618. 'upload_max': upload_max
  619. })
  620. self.lat_lon = (float(client['lat']), float(client['lon']))
  621. return self.config
  622. def get_servers(self, servers=None):
  623. """Retrieve a the list of speedtest.net servers, optionally filtered
  624. to servers matching those specified in the ``servers`` argument
  625. """
  626. if servers is None:
  627. servers = []
  628. self.servers.clear()
  629. for i, s in enumerate(servers):
  630. try:
  631. servers[i] = int(s)
  632. except ValueError:
  633. raise InvalidServerIDType('%s is an invalid server type, must '
  634. 'be int' % s)
  635. urls = [
  636. '://www.speedtest.net/speedtest-servers-static.php',
  637. 'http://c.speedtest.net/speedtest-servers-static.php',
  638. '://www.speedtest.net/speedtest-servers.php',
  639. 'http://c.speedtest.net/speedtest-servers.php',
  640. ]
  641. headers = {}
  642. if gzip:
  643. headers['Accept-Encoding'] = 'gzip'
  644. errors = []
  645. for url in urls:
  646. try:
  647. request = build_request('%s?threads=%s' %
  648. (url,
  649. self.config['threads']['download']),
  650. headers=headers)
  651. uh, e = catch_request(request)
  652. if e:
  653. errors.append('%s' % e)
  654. raise ServersRetrievalError
  655. stream = get_response_stream(uh)
  656. serversxml = []
  657. while 1:
  658. serversxml.append(stream.read(10240))
  659. if len(serversxml[-1]) == 0:
  660. break
  661. stream.close()
  662. uh.close()
  663. if int(uh.code) != 200:
  664. raise ServersRetrievalError
  665. printer(''.encode().join(serversxml), debug=True)
  666. try:
  667. try:
  668. root = ET.fromstring(''.encode().join(serversxml))
  669. elements = root.getiterator('server')
  670. except AttributeError:
  671. root = DOM.parseString(''.join(serversxml))
  672. elements = root.getElementsByTagName('server')
  673. except (SyntaxError, xml.parsers.expat.ExpatError):
  674. raise ServersRetrievalError
  675. for server in elements:
  676. try:
  677. attrib = server.attrib
  678. except AttributeError:
  679. attrib = dict(list(server.attributes.items()))
  680. if servers and int(attrib.get('id')) not in servers:
  681. continue
  682. if int(attrib.get('id')) in self.config['ignore_servers']:
  683. continue
  684. try:
  685. d = distance(self.lat_lon,
  686. (float(attrib.get('lat')),
  687. float(attrib.get('lon'))))
  688. except:
  689. continue
  690. attrib['d'] = d
  691. try:
  692. self.servers[d].append(attrib)
  693. except KeyError:
  694. self.servers[d] = [attrib]
  695. printer(''.encode().join(serversxml), debug=True)
  696. break
  697. except ServersRetrievalError:
  698. continue
  699. if servers and not self.servers:
  700. raise NoMatchedServers
  701. return self.servers
  702. def set_mini_server(self, server):
  703. """Instead of querying for a list of servers, set a link to a
  704. speedtest mini server
  705. """
  706. urlparts = urlparse(server)
  707. name, ext = os.path.splitext(urlparts[2])
  708. if ext:
  709. url = os.path.dirname(server)
  710. else:
  711. url = server
  712. request = build_request(url)
  713. uh, e = catch_request(request)
  714. if e:
  715. raise SpeedtestMiniConnectFailure('Failed to connect to %s' %
  716. server)
  717. else:
  718. text = uh.read()
  719. uh.close()
  720. extension = re.findall('upload_?[Ee]xtension: "([^"]+)"',
  721. text.decode())
  722. if not extension:
  723. for ext in ['php', 'asp', 'aspx', 'jsp']:
  724. try:
  725. f = urlopen('%s/speedtest/upload.%s' % (url, ext))
  726. except:
  727. pass
  728. else:
  729. data = f.read().strip().decode()
  730. if (f.code == 200 and
  731. len(data.splitlines()) == 1 and
  732. re.match('size=[0-9]', data)):
  733. extension = [ext]
  734. break
  735. if not urlparts or not extension:
  736. raise InvalidSpeedtestMiniServer('Invalid Speedtest Mini Server: '
  737. '%s' % server)
  738. self.servers = [{
  739. 'sponsor': 'Speedtest Mini',
  740. 'name': urlparts[1],
  741. 'd': 0,
  742. 'url': '%s/speedtest/upload.%s' % (url.rstrip('/'), extension[0]),
  743. 'latency': 0,
  744. 'id': 0
  745. }]
  746. return self.servers
  747. def get_closest_servers(self, limit=5):
  748. """Limit servers to the closest speedtest.net servers based on
  749. geographic distance
  750. """
  751. if not self.servers:
  752. self.get_servers()
  753. for d in sorted(self.servers.keys()):
  754. for s in self.servers[d]:
  755. self.closest.append(s)
  756. if len(self.closest) == limit:
  757. break
  758. else:
  759. continue
  760. break
  761. printer(self.closest, debug=True)
  762. return self.closest
  763. def get_best_server(self, servers=None):
  764. """Perform a speedtest.net "ping" to determine which speedtest.net
  765. server has the lowest latency
  766. """
  767. if not servers:
  768. if not self.closest:
  769. servers = self.get_closest_servers()
  770. servers = self.closest
  771. results = {}
  772. for server in servers:
  773. cum = []
  774. url = os.path.dirname(server['url'])
  775. urlparts = urlparse('%s/latency.txt' % url)
  776. printer('%s %s/latency.txt' % ('GET', url), debug=True)
  777. for _ in range(0, 3):
  778. try:
  779. if urlparts[0] == 'https':
  780. h = HTTPSConnection(urlparts[1])
  781. else:
  782. h = HTTPConnection(urlparts[1])
  783. headers = {'User-Agent': USER_AGENT}
  784. start = timeit.default_timer()
  785. h.request("GET", urlparts[2], headers=headers)
  786. r = h.getresponse()
  787. total = (timeit.default_timer() - start)
  788. except HTTP_ERRORS:
  789. e = sys.exc_info()[1]
  790. printer('%r' % e, debug=True)
  791. cum.append(3600)
  792. continue
  793. text = r.read(9)
  794. if int(r.status) == 200 and text == 'test=test'.encode():
  795. cum.append(total)
  796. else:
  797. cum.append(3600)
  798. h.close()
  799. avg = round((sum(cum) / 6) * 1000.0, 3)
  800. results[avg] = server
  801. try:
  802. fastest = sorted(results.keys())[0]
  803. except IndexError:
  804. raise SpeedtestBestServerFailure('Unable to connect to servers to '
  805. 'test latency.')
  806. best = results[fastest]
  807. best['latency'] = fastest
  808. self.results.ping = fastest
  809. self.results.server = best
  810. self.best.update(best)
  811. printer(best, debug=True)
  812. return best
  813. def download(self, callback=do_nothing):
  814. """Test download speed against speedtest.net"""
  815. urls = []
  816. for size in self.config['sizes']['download']:
  817. for _ in range(0, self.config['counts']['download']):
  818. urls.append('%s/random%sx%s.jpg' %
  819. (os.path.dirname(self.best['url']), size, size))
  820. request_count = len(urls)
  821. requests = []
  822. for i, url in enumerate(urls):
  823. requests.append(build_request(url, bump=i))
  824. def producer(q, requests, request_count):
  825. for i, request in enumerate(requests):
  826. thread = HTTPDownloader(i, request, start,
  827. self.config['length']['download'])
  828. thread.start()
  829. q.put(thread, True)
  830. callback(i, request_count, start=True)
  831. finished = []
  832. def consumer(q, request_count):
  833. while len(finished) < request_count:
  834. thread = q.get(True)
  835. while thread.isAlive():
  836. thread.join(timeout=0.1)
  837. finished.append(sum(thread.result))
  838. callback(thread.i, request_count, end=True)
  839. q = Queue(self.config['threads']['download'])
  840. prod_thread = threading.Thread(target=producer,
  841. args=(q, requests, request_count))
  842. cons_thread = threading.Thread(target=consumer,
  843. args=(q, request_count))
  844. start = timeit.default_timer()
  845. prod_thread.start()
  846. cons_thread.start()
  847. while prod_thread.isAlive():
  848. prod_thread.join(timeout=0.1)
  849. while cons_thread.isAlive():
  850. cons_thread.join(timeout=0.1)
  851. stop = timeit.default_timer()
  852. self.results.bytes_received = sum(finished)
  853. self.results.download = (
  854. (self.results.bytes_received / (stop - start)) * 8.0
  855. )
  856. if self.results.download > 100000:
  857. self.config['threads']['upload'] = 8
  858. return self.results.download
  859. def upload(self, callback=do_nothing):
  860. """Test upload speed against speedtest.net"""
  861. sizes = []
  862. for size in self.config['sizes']['upload']:
  863. for _ in range(0, self.config['counts']['upload']):
  864. sizes.append(size)
  865. # request_count = len(sizes)
  866. request_count = self.config['upload_max']
  867. requests = []
  868. for i, size in enumerate(sizes):
  869. # We set ``0`` for ``start`` and handle setting the actual
  870. # ``start`` in ``HTTPUploader`` to get better measurements
  871. data = HTTPUploaderData(size, 0, self.config['length']['upload'])
  872. data._create_data()
  873. requests.append(
  874. (
  875. build_request(self.best['url'], data),
  876. size
  877. )
  878. )
  879. def producer(q, requests, request_count):
  880. for i, request in enumerate(requests[:request_count]):
  881. thread = HTTPUploader(i, request[0], start, request[1],
  882. self.config['length']['upload'])
  883. thread.start()
  884. q.put(thread, True)
  885. callback(i, request_count, start=True)
  886. finished = []
  887. def consumer(q, request_count):
  888. while len(finished) < request_count:
  889. thread = q.get(True)
  890. while thread.isAlive():
  891. thread.join(timeout=0.1)
  892. finished.append(thread.result)
  893. callback(thread.i, request_count, end=True)
  894. q = Queue(self.config['threads']['upload'])
  895. prod_thread = threading.Thread(target=producer,
  896. args=(q, requests, request_count))
  897. cons_thread = threading.Thread(target=consumer,
  898. args=(q, request_count))
  899. start = timeit.default_timer()
  900. prod_thread.start()
  901. cons_thread.start()
  902. while prod_thread.isAlive():
  903. prod_thread.join(timeout=0.1)
  904. while cons_thread.isAlive():
  905. cons_thread.join(timeout=0.1)
  906. stop = timeit.default_timer()
  907. self.results.bytes_sent = sum(finished)
  908. self.results.upload = (
  909. (self.results.bytes_sent / (stop - start)) * 8.0
  910. )
  911. return self.results.upload
  912. def ctrl_c(signum, frame):
  913. """Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded
  914. operations
  915. """
  916. SHUTDOWN_EVENT.set()
  917. print_('\nCancelling...')
  918. sys.exit(0)
  919. def version():
  920. """Print the version"""
  921. print_(__version__)
  922. sys.exit(0)
  923. def csv_header():
  924. """Print the CSV Headers"""
  925. print_('Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,'
  926. 'Upload')
  927. sys.exit(0)
  928. def parse_args():
  929. """Function to handle building and parsing of command line arguments"""
  930. description = (
  931. 'Command line interface for testing internet bandwidth using '
  932. 'speedtest.net.\n'
  933. '------------------------------------------------------------'
  934. '--------------\n'
  935. 'https://github.com/sivel/speedtest-cli')
  936. parser = ArgParser(description=description)
  937. # Give optparse.OptionParser an `add_argument` method for
  938. # compatibility with argparse.ArgumentParser
  939. try:
  940. parser.add_argument = parser.add_option
  941. except AttributeError:
  942. pass
  943. parser.add_argument('--bytes', dest='units', action='store_const',
  944. const=('byte', 8), default=('bit', 1),
  945. help='Display values in bytes instead of bits. Does '
  946. 'not affect the image generated by --share, nor '
  947. 'output from --json or --csv')
  948. parser.add_argument('--share', action='store_true',
  949. help='Generate and provide a URL to the speedtest.net '
  950. 'share results image')
  951. parser.add_argument('--simple', action='store_true', default=False,
  952. help='Suppress verbose output, only show basic '
  953. 'information')
  954. parser.add_argument('--csv', action='store_true', default=False,
  955. help='Suppress verbose output, only show basic '
  956. 'information in CSV format. Speeds listed in '
  957. 'bit/s and not affected by --bytes')
  958. parser.add_argument('--csv-delimiter', default=',', type=PARSER_TYPE_STR,
  959. help='Single character delimiter to use in CSV '
  960. 'output. Default ","')
  961. parser.add_argument('--csv-header', action='store_true', default=False,
  962. help='Print CSV headers')
  963. parser.add_argument('--json', action='store_true', default=False,
  964. help='Suppress verbose output, only show basic '
  965. 'information in JSON format. Speeds listed in '
  966. 'bit/s and not affected by --bytes')
  967. parser.add_argument('--list', action='store_true',
  968. help='Display a list of speedtest.net servers '
  969. 'sorted by distance')
  970. parser.add_argument('--server', help='Specify a server ID to test against',
  971. type=PARSER_TYPE_INT)
  972. parser.add_argument('--mini', help='URL of the Speedtest Mini server')
  973. parser.add_argument('--source', help='Source IP address to bind to')
  974. parser.add_argument('--timeout', default=10, type=PARSER_TYPE_INT,
  975. help='HTTP timeout in seconds. Default 10')
  976. parser.add_argument('--secure', action='store_true',
  977. help='Use HTTPS instead of HTTP when communicating '
  978. 'with speedtest.net operated servers')
  979. parser.add_argument('--version', action='store_true',
  980. help='Show the version number and exit')
  981. parser.add_argument('--debug', action='store_true',
  982. help=ARG_SUPPRESS, default=ARG_SUPPRESS)
  983. options = parser.parse_args()
  984. if isinstance(options, tuple):
  985. args = options[0]
  986. else:
  987. args = options
  988. return args
  989. def validate_optional_args(args):
  990. """Check if an argument was provided that depends on a module that may
  991. not be part of the Python standard library.
  992. If such an argument is supplied, and the module does not exist, exit
  993. with an error stating which module is missing.
  994. """
  995. optional_args = {
  996. 'json': ('json/simplejson python module', json),
  997. 'secure': ('SSL support', HTTPSConnection),
  998. }
  999. for arg, info in optional_args.items():
  1000. if getattr(args, arg, False) and info[1] is None:
  1001. raise SystemExit('%s is not installed. --%s is '
  1002. 'unavailable' % (info[0], arg))
  1003. def printer(string, quiet=False, debug=False, **kwargs):
  1004. """Helper function to print a string only when not quiet"""
  1005. if debug and not DEBUG:
  1006. return
  1007. if debug:
  1008. out = '\033[1;30mDEBUG: %s\033[0m' % string
  1009. else:
  1010. out = string
  1011. if not quiet:
  1012. print_(out, **kwargs)
  1013. def shell():
  1014. """Run the full speedtest.net test"""
  1015. global SHUTDOWN_EVENT, SOURCE, SCHEME, DEBUG
  1016. SHUTDOWN_EVENT = threading.Event()
  1017. signal.signal(signal.SIGINT, ctrl_c)
  1018. args = parse_args()
  1019. # Print the version and exit
  1020. if args.version:
  1021. version()
  1022. if args.csv_header:
  1023. csv_header()
  1024. if len(args.csv_delimiter) != 1:
  1025. raise SystemExit('--csv-delimiter must be a single character')
  1026. validate_optional_args(args)
  1027. socket.setdefaulttimeout(args.timeout)
  1028. # If specified bind to a specific IP address
  1029. if args.source:
  1030. SOURCE = args.source
  1031. socket.socket = bound_socket
  1032. if args.secure:
  1033. SCHEME = 'https'
  1034. debug = getattr(args, 'debug', False)
  1035. if debug == 'SUPPRESSHELP':
  1036. debug = False
  1037. if debug:
  1038. DEBUG = True
  1039. # Pre-cache the user agent string
  1040. build_user_agent()
  1041. if args.simple or args.csv or args.json:
  1042. quiet = True
  1043. else:
  1044. quiet = False
  1045. # Don't set a callback if we are running quietly
  1046. if quiet or debug:
  1047. callback = do_nothing
  1048. else:
  1049. callback = print_dots
  1050. printer('Retrieving speedtest.net configuration...', quiet)
  1051. try:
  1052. speedtest = Speedtest()
  1053. except ConfigRetrievalError:
  1054. printer('Cannot retrieve speedtest configuration')
  1055. sys.exit(1)
  1056. if args.list:
  1057. try:
  1058. speedtest.get_servers()
  1059. except ServersRetrievalError:
  1060. print_('Cannot retrieve speedtest server list')
  1061. sys.exit(1)
  1062. for _, servers in sorted(speedtest.servers.items()):
  1063. for server in servers:
  1064. line = ('%(id)5s) %(sponsor)s (%(name)s, %(country)s) '
  1065. '[%(d)0.2f km]' % server)
  1066. try:
  1067. print_(line)
  1068. except IOError:
  1069. e = sys.exc_info()[1]
  1070. if e.errno != errno.EPIPE:
  1071. raise
  1072. sys.exit(0)
  1073. # Set a filter of servers to retrieve
  1074. servers = []
  1075. if args.server:
  1076. servers.append(args.server)
  1077. printer('Testing from %(isp)s (%(ip)s)...' % speedtest.config['client'],
  1078. quiet)
  1079. if not args.mini:
  1080. printer('Retrieving speedtest.net server list...', quiet)
  1081. try:
  1082. speedtest.get_servers(servers)
  1083. except NoMatchedServers:
  1084. print_('No matched servers: %s' % args.server)
  1085. sys.exit(1)
  1086. except ServersRetrievalError:
  1087. print_('Cannot retrieve speedtest server list')
  1088. sys.exit(1)
  1089. except InvalidServerIDType:
  1090. print_('%s is an invalid server type, must be int' % args.server)
  1091. sys.exit(1)
  1092. printer('Selecting best server based on ping...', quiet)
  1093. speedtest.get_best_server()
  1094. elif args.mini:
  1095. speedtest.get_best_server(speedtest.set_mini_server(args.mini))
  1096. results = speedtest.results
  1097. printer('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: '
  1098. '%(latency)s ms' % results.server, quiet)
  1099. printer('Testing download speed', quiet,
  1100. end=('', '\n')[bool(debug)])
  1101. speedtest.download(callback=callback)
  1102. printer('Download: %0.2f M%s/s' %
  1103. ((results.download / 1000.0 / 1000.0) / args.units[1],
  1104. args.units[0]),
  1105. quiet)
  1106. printer('Testing upload speed', quiet,
  1107. end=('', '\n')[bool(debug)])
  1108. speedtest.upload(callback=callback)
  1109. printer('Upload: %0.2f M%s/s' %
  1110. ((results.upload / 1000.0 / 1000.0) / args.units[1],
  1111. args.units[0]),
  1112. quiet)
  1113. if args.simple:
  1114. print_('Ping: %s ms\nDownload: %0.2f M%s/s\nUpload: %0.2f M%s/s' %
  1115. (results.ping,
  1116. (results.download / 1000.0 / 1000.0) / args.units[1],
  1117. args.units[0],
  1118. (results.upload / 1000.0 / 1000.0) / args.units[1],
  1119. args.units[0]))
  1120. elif args.csv:
  1121. print_(results.csv(delimiter=args.csv_delimiter))
  1122. elif args.json:
  1123. print_(results.json())
  1124. if args.share:
  1125. printer('Share results: %s' % results.share(), quiet)
  1126. def main():
  1127. try:
  1128. shell()
  1129. except KeyboardInterrupt:
  1130. print_('\nCancelling...')
  1131. except (SpeedtestException, SystemExit):
  1132. e = sys.exc_info()[1]
  1133. if getattr(e, 'code', 1) != 0:
  1134. raise SystemExit('ERROR: %s' % e)
  1135. if __name__ == '__main__':
  1136. main()
  1137. # vim:ts=4:sw=4:expandtab