fake.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. # This code run compatibly under Python 2 and 3.x for x >= 2.
  2. # Preserve this property!
  3. #
  4. # This file is Copyright 2010 by the GPSD project
  5. # SPDX-License-Identifier: BSD-2-Clause
  6. """
  7. gpsfake.py -- classes for creating a controlled test environment around gpsd.
  8. The gpsfake(1) regression tester shipped with GPSD is a trivial wrapper
  9. around this code. For a more interesting usage example, see the
  10. valgrind-audit script shipped with the GPSD code.
  11. To use this code, start by instantiating a TestSession class. Use the
  12. prefix argument if you want to run the daemon under some kind of run-time
  13. monitor like valgrind or gdb. Here are some particularly useful possibilities:
  14. valgrind --tool=memcheck --gen-suppressions=yes --leak-check=yes
  15. Run under Valgrind, checking for malloc errors and memory leaks.
  16. xterm -e gdb -tui --args
  17. Run under gdb, controlled from a new xterm.
  18. You can use the options argument to pass in daemon options; normally you will
  19. use this to set the debug-logging level.
  20. On initialization, the test object spawns an instance of gpsd with no
  21. devices or clients attached, connected to a control socket.
  22. TestSession has methods to attach and detch fake GPSes. The
  23. TestSession class simulates GPS devices for you with objects composed
  24. from a pty and a class instance that cycles sentences into the master side
  25. from some specified logfile; gpsd reads the slave side. A fake GPS is
  26. identified by the string naming its slave device.
  27. TestSession also has methods to start and end client sessions. Daemon
  28. responses to a client are fed to a hook function which, by default,
  29. discards them. Note that this data is 'bytes' to accommodate possible
  30. binary data in Python 3; use polystr() if you need a str. You can
  31. change the hook to misc.get_bytes_stream(sys.stdout).write to dump
  32. responses to standard output (this is what the gpsfake executable does)
  33. or do something more exotic. A client session is identified by a small
  34. integer that counts the number of client session starts.
  35. There are a couple of convenience methods. TestSession.wait() does nothing,
  36. allowing a specified number of seconds to elapse. TestSession.send()
  37. ships commands to an open client session.
  38. TestSession does not currently capture the daemon's log output. It is
  39. run with -N, so the output will go to stderr (along with, for example,
  40. Valgrind notifications).
  41. Each FakeGPS instance tries to packetize the data from the logfile it
  42. is initialized with. It uses the same packet-getter as the daemon.
  43. Exception: if there is a Delay-Cookie line in a header comment, that
  44. delimiter is used to split up the test load.
  45. The TestSession code maintains a run queue of FakeGPS and gps.gs
  46. (client- session) objects. It repeatedly cycles through the run queue.
  47. For each client session object in the queue, it tries to read data
  48. from gpsd. For each fake GPS, it sends one line or packet of stored
  49. data. When a fake-GPS's go predicate becomes false, the fake GPS is
  50. removed from the run queue.
  51. There are two ways to use this code. The more deterministic is
  52. non-threaded mode: set up your client sessions and fake GPS devices,
  53. then call the run() method. The run() method will terminate when
  54. there are no more objects in the run queue. Note, you must have
  55. created at least one fake client or fake GPS before calling run(),
  56. otherwise it will terminate immediately.
  57. To allow for adding and removing clients while the test is running,
  58. run in threaded mode by calling the start() method. This simply calls
  59. the run method in a subthread, with locking of critical regions.
  60. """
  61. # This code runs compatibly under Python 2 and 3.x for x >= 2.
  62. # Preserve this property!
  63. from __future__ import absolute_import, print_function, division
  64. import os
  65. import pty
  66. import select
  67. import signal
  68. import socket
  69. import stat
  70. import subprocess
  71. import sys
  72. import termios # fcntl, array, struct
  73. import threading
  74. import time
  75. import gps
  76. from . import packet as sniffer
  77. # The magic number below has to be derived from observation. If
  78. # it's too high you'll slow the tests down a lot. If it's too low
  79. # you'll get regression tests timing out.
  80. # WRITE_PAD: Define a per-line delay on writes so we won't spam the
  81. # buffers in the pty layer or gpsd itself. Values smaller than the
  82. # system timer tick don't make any difference here. Can be set from
  83. # WRITE_PAD in the environment.
  84. if sys.platform.startswith("linux"):
  85. WRITE_PAD = 0.0
  86. elif sys.platform.startswith("freebsd"):
  87. # Hal Murray needs 0..005 for FreeBSD 12.1 on RasPi 3B.
  88. WRITE_PAD = 0.005
  89. elif sys.platform.startswith("openbsd"):
  90. WRITE_PAD = 0.001
  91. elif sys.platform.startswith("netbsd5"):
  92. WRITE_PAD = 0.200
  93. elif sys.platform.startswith("netbsd"):
  94. WRITE_PAD = 0.001
  95. elif sys.platform.startswith("darwin"):
  96. WRITE_PAD = 0.001
  97. else:
  98. WRITE_PAD = 0.004
  99. # Additional delays in slow mode
  100. WRITE_PAD_SLOWDOWN = 0.01
  101. # If a test takes longer than this, we deem it to have timed out
  102. TEST_TIMEOUT = 60
  103. def GetDelay(slow=False):
  104. "Get appropriate per-line delay."
  105. delay = float(os.getenv("WRITE_PAD", WRITE_PAD))
  106. if slow:
  107. delay += WRITE_PAD_SLOWDOWN
  108. return delay
  109. class TestError(BaseException):
  110. "Class TestError"
  111. def __init__(self, msg):
  112. super(TestError, self).__init__()
  113. self.msg = msg
  114. class TestLoadError(TestError):
  115. "Class TestLoadError, empty"
  116. class TestLoad(object):
  117. "Digest a logfile into a list of sentences we can cycle through."
  118. def __init__(self, logfp, predump=False, slow=False, oneshot=False):
  119. self.sentences = [] # This is the interesting part
  120. if isinstance(logfp, str):
  121. logfp = open(logfp, "rb")
  122. self.name = logfp.name
  123. self.logfp = logfp
  124. self.predump = predump
  125. self.type = None
  126. self.sourcetype = "pty"
  127. self.serial = None
  128. self.delay = GetDelay(slow)
  129. self.delimiter = None
  130. # Stash away a copy in case we need to resplit
  131. text = logfp.read()
  132. logfp = open(logfp.name, 'rb')
  133. # Grab the packets in the normal way
  134. getter = sniffer.new()
  135. # gps.packet.register_report(reporter)
  136. type_latch = None
  137. commentlen = 0
  138. while True:
  139. # Note that packet data is bytes rather than str
  140. (plen, ptype, packet, _counter) = getter.get(logfp.fileno())
  141. if plen <= 0:
  142. break
  143. if ptype == sniffer.COMMENT_PACKET:
  144. commentlen += len(packet)
  145. # Some comments are magic
  146. if b"Serial:" in packet:
  147. # Change serial parameters
  148. packet = packet[1:].strip()
  149. try:
  150. (_xx, baud, params) = packet.split()
  151. baud = int(baud)
  152. if params[0] in (b'7', b'8'):
  153. databits = int(params[0])
  154. else:
  155. raise ValueError
  156. if params[1] in (b'N', b'O', b'E'):
  157. parity = params[1]
  158. else:
  159. raise ValueError
  160. if params[2] in (b'1', b'2'):
  161. stopbits = int(params[2])
  162. else:
  163. raise ValueError
  164. except (ValueError, IndexError):
  165. raise TestLoadError("bad serial-parameter spec in %s" %
  166. self.name)
  167. self.serial = (baud, databits, parity, stopbits)
  168. elif b"Transport: UDP" in packet:
  169. self.sourcetype = "UDP"
  170. elif b"Transport: TCP" in packet:
  171. self.sourcetype = "TCP"
  172. elif b"Delay-Cookie:" in packet:
  173. if packet.startswith(b"#"):
  174. packet = packet[1:]
  175. try:
  176. (_dummy, self.delimiter, delay) = \
  177. packet.strip().split()
  178. self.delay = float(delay)
  179. except ValueError:
  180. raise TestLoadError("bad Delay-Cookie line in %s" %
  181. self.name)
  182. self.resplit = True
  183. else:
  184. if type_latch is None:
  185. type_latch = ptype
  186. if self.predump:
  187. print(repr(packet))
  188. if not packet:
  189. raise TestLoadError("zero-length packet from %s" %
  190. self.name)
  191. self.sentences.append(packet)
  192. # Look at the first packet to grok the GPS type
  193. self.textual = (type_latch == sniffer.NMEA_PACKET)
  194. if self.textual:
  195. self.legend = "gpsfake: line %d: "
  196. else:
  197. self.legend = "gpsfake: packet %d"
  198. # Maybe this needs to be split on different delimiters?
  199. if self.delimiter is not None:
  200. self.sentences = text[commentlen:].split(self.delimiter)
  201. # Do we want single-shot operation?
  202. if oneshot:
  203. self.sentences.append(b"# EOF\n")
  204. class PacketError(TestError):
  205. "Class PacketError, empty"
  206. class FakeGPS(object):
  207. "Class FakeGPS"
  208. def __init__(self, testload, progress=lambda x: None):
  209. self.exhausted = 0
  210. self.go_predicate = lambda: True
  211. self.index = 0
  212. self.progress = progress
  213. self.readers = 0
  214. self.testload = testload
  215. self.progress("gpsfake: %s provides %d sentences\n"
  216. % (self.testload.name, len(self.testload.sentences)))
  217. def write(self, line):
  218. "Throw an error if this superclass is ever instantiated."
  219. raise ValueError(line)
  220. def feed(self):
  221. "Feed a line from the contents of the GPS log to the daemon."
  222. line = self.testload.sentences[self.index
  223. % len(self.testload.sentences)]
  224. if b"%Delay:" in line:
  225. # Delay specified number of seconds
  226. delay = line.split()[1]
  227. time.sleep(int(delay))
  228. # self.write has to be set by the derived class
  229. self.write(line)
  230. time.sleep(self.testload.delay)
  231. self.index += 1
  232. class FakePTY(FakeGPS):
  233. "A FakePTY is a pty with a test log ready to be cycled to it."
  234. def __init__(self, testload,
  235. speed=4800, databits=8, parity='N', stopbits=1,
  236. progress=lambda x: None):
  237. super(FakePTY, self).__init__(testload, progress)
  238. # Allow Serial: header to be overridden by explicit speed.
  239. if self.testload.serial:
  240. (speed, databits, parity, stopbits) = self.testload.serial
  241. self.speed = speed
  242. baudrates = {
  243. 0: termios.B0,
  244. 50: termios.B50,
  245. 75: termios.B75,
  246. 110: termios.B110,
  247. 134: termios.B134,
  248. 150: termios.B150,
  249. 200: termios.B200,
  250. 300: termios.B300,
  251. 600: termios.B600,
  252. 1200: termios.B1200,
  253. 1800: termios.B1800,
  254. 2400: termios.B2400,
  255. 4800: termios.B4800,
  256. 9600: termios.B9600,
  257. 19200: termios.B19200,
  258. 38400: termios.B38400,
  259. 57600: termios.B57600,
  260. 115200: termios.B115200,
  261. 230400: termios.B230400,
  262. }
  263. (self.fd, self.slave_fd) = pty.openpty()
  264. self.byname = os.ttyname(self.slave_fd)
  265. os.chmod(self.byname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP |
  266. stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH)
  267. (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(
  268. self.slave_fd)
  269. cc[termios.VMIN] = 1
  270. cflag &= ~(termios.PARENB | termios.PARODD | termios.CRTSCTS)
  271. cflag |= termios.CREAD | termios.CLOCAL
  272. iflag = oflag = lflag = 0
  273. iflag &= ~ (termios.PARMRK | termios.INPCK)
  274. cflag &= ~ (termios.CSIZE | termios.CSTOPB | termios.PARENB |
  275. termios.PARODD)
  276. if databits == 7:
  277. cflag |= termios.CS7
  278. else:
  279. cflag |= termios.CS8
  280. if stopbits == 2:
  281. cflag |= termios.CSTOPB
  282. # Warning: attempting to set parity makes Fedora lose its cookies
  283. if parity == 'E':
  284. iflag |= termios.INPCK
  285. cflag |= termios.PARENB
  286. elif parity == 'O':
  287. iflag |= termios.INPCK
  288. cflag |= termios.PARENB | termios.PARODD
  289. ispeed = ospeed = baudrates[speed]
  290. try:
  291. termios.tcsetattr(self.slave_fd, termios.TCSANOW,
  292. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
  293. except termios.error:
  294. raise TestLoadError("error attempting to set serial mode to %s "
  295. " %s%s%s"
  296. % (speed, databits, parity, stopbits))
  297. def read(self):
  298. "Discard control strings written by gpsd."
  299. # A tcflush implementation works on Linux but fails on OpenBSD 4.
  300. termios.tcflush(self.fd, termios.TCIFLUSH)
  301. # Alas, the FIONREAD version also works on Linux and fails on OpenBSD.
  302. # try:
  303. # buf = array.array('i', [0])
  304. # fcntl.ioctl(self.master_fd, termios.FIONREAD, buf, True)
  305. # n = struct.unpack('i', buf)[0]
  306. # os.read(self.master_fd, n)
  307. # except IOError:
  308. # pass
  309. def write(self, line):
  310. self.progress("gpsfake: %s writes %d=%s\n"
  311. % (self.testload.name, len(line), repr(line)))
  312. os.write(self.fd, line)
  313. def drain(self):
  314. "Wait for the associated device to drain (e.g. before closing)."
  315. termios.tcdrain(self.fd)
  316. def cleansocket(host, port, socktype=socket.SOCK_STREAM):
  317. "Get a socket that we can re-use cleanly after it's closed."
  318. cs = socket.socket(socket.AF_INET, socktype)
  319. # This magic prevents "Address already in use" errors after
  320. # we release the socket.
  321. cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  322. cs.bind((host, port))
  323. return cs
  324. def freeport(socktype=socket.SOCK_STREAM):
  325. """Get a free port number for the given connection type.
  326. This lets the OS assign a unique port, and then assumes
  327. that it will become available for reuse once the socket
  328. is closed, and remain so long enough for the real use.
  329. """
  330. s = cleansocket("127.0.0.1", 0, socktype)
  331. port = s.getsockname()[1]
  332. s.close()
  333. return port
  334. class FakeTCP(FakeGPS):
  335. "A TCP serverlet with a test log ready to be cycled to it."
  336. def __init__(self, testload,
  337. host, port,
  338. progress=lambda x: None):
  339. super(FakeTCP, self).__init__(testload, progress)
  340. self.host = host
  341. self.dispatcher = cleansocket(self.host, int(port))
  342. # Get actual assigned port
  343. self.port = self.dispatcher.getsockname()[1]
  344. self.byname = "tcp://" + host + ":" + str(self.port)
  345. self.dispatcher.listen(5)
  346. self.readables = [self.dispatcher]
  347. def read(self):
  348. "Handle connection requests and data."
  349. readable, _writable, _errored = select.select(self.readables, [], [],
  350. 0)
  351. for s in readable:
  352. if s == self.dispatcher: # Connection request
  353. client_socket, _address = s.accept()
  354. self.readables = [client_socket]
  355. # Depending on timing, gpsd may try to reconnect between the
  356. # end of the log data and the remove_device. With no listener,
  357. # this results in spurious error messages. Keeping the
  358. # listener around avoids this. It will eventually be closed
  359. # by the Python object cleanup. self.dispatcher.close()
  360. else: # Incoming data
  361. data = s.recv(1024)
  362. if not data:
  363. s.close()
  364. self.readables.remove(s)
  365. def write(self, line):
  366. "Send the next log packet to everybody connected."
  367. self.progress("gpsfake: %s writes %d=%s\n"
  368. % (self.testload.name, len(line), repr(line)))
  369. for s in self.readables:
  370. if s != self.dispatcher:
  371. s.send(line)
  372. def drain(self):
  373. "Wait for the associated device(s) to drain (e.g. before closing)."
  374. for s in self.readables:
  375. if s != self.dispatcher:
  376. s.shutdown(socket.SHUT_RDWR)
  377. class FakeUDP(FakeGPS):
  378. "A UDP broadcaster with a test log ready to be cycled to it."
  379. def __init__(self, testload,
  380. ipaddr, port,
  381. progress=lambda x: None):
  382. super(FakeUDP, self).__init__(testload, progress)
  383. self.byname = "udp://" + ipaddr + ":" + str(port)
  384. self.ipaddr = ipaddr
  385. self.port = port
  386. self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  387. def read(self):
  388. "Discard control strings written by gpsd."
  389. return
  390. def write(self, line):
  391. self.progress("gpsfake: %s writes %d=%s\n"
  392. % (self.testload.name, len(line), repr(line)))
  393. self.sock.sendto(line, (self.ipaddr, int(self.port)))
  394. def drain(self):
  395. "Wait for the associated device to drain (e.g. before closing)."
  396. # shutdown() fails on UDP
  397. return # shutdown() fails on UDP
  398. class SubprogramError(TestError):
  399. "Class SubprogramError"
  400. def __str__(self):
  401. return repr(self.msg)
  402. class SubprogramInstance(object):
  403. "Class for generic subprogram."
  404. ERROR = SubprogramError
  405. def __init__(self):
  406. self.spawncmd = None
  407. self.process = None
  408. self.returncode = None
  409. self.env = None
  410. def spawn_sub(self, program, options, background=False, prefix="",
  411. env=None):
  412. "Spawn a subprogram instance."
  413. spawncmd = None
  414. # Look for program in GPSD_HOME env variable
  415. if os.environ.get('GPSD_HOME'):
  416. for path in os.environ['GPSD_HOME'].split(':'):
  417. _spawncmd = "%s/%s" % (path, program)
  418. if os.path.isfile(_spawncmd) and os.access(_spawncmd, os.X_OK):
  419. spawncmd = _spawncmd
  420. break
  421. # if we could not find it yet try PATH env variable for it
  422. if not spawncmd:
  423. if '/usr/sbin' not in os.environ['PATH']:
  424. os.environ['PATH'] = os.environ['PATH'] + ":/usr/sbin"
  425. for path in os.environ['PATH'].split(':'):
  426. _spawncmd = "%s/%s" % (path, program)
  427. if os.path.isfile(_spawncmd) and os.access(_spawncmd, os.X_OK):
  428. spawncmd = _spawncmd
  429. break
  430. if not spawncmd:
  431. raise self.ERROR("Cannot execute %s: executable not found. "
  432. "Set GPSD_HOME env variable" % program)
  433. self.spawncmd = [spawncmd] + options.split()
  434. if prefix:
  435. self.spawncmd = prefix.split() + self.spawncmd
  436. if env:
  437. self.env = os.environ.copy()
  438. self.env.update(env)
  439. self.process = subprocess.Popen(self.spawncmd, env=self.env)
  440. if not background:
  441. self.returncode = status = self.process.wait()
  442. if os.WIFSIGNALED(status) or os.WEXITSTATUS(status):
  443. raise self.ERROR("%s exited with status %d"
  444. % (program, status))
  445. def is_alive(self):
  446. "Is the program still alive?"
  447. if not self.process:
  448. return False
  449. self.returncode = self.process.poll()
  450. if self.returncode is None:
  451. return True
  452. self.process = None
  453. return False
  454. def kill(self):
  455. "Kill the program instance."
  456. while self.is_alive():
  457. try: # terminate() may fail if already killed
  458. self.process.terminate()
  459. except OSError:
  460. continue
  461. time.sleep(0.01)
  462. class DaemonError(SubprogramError):
  463. "Class DaemonError"
  464. class DaemonInstance(SubprogramInstance):
  465. "Control a gpsd instance."
  466. ERROR = DaemonError
  467. def __init__(self, control_socket=None):
  468. self.sock = None
  469. super(DaemonInstance, self).__init__()
  470. if control_socket:
  471. self.control_socket = control_socket
  472. else:
  473. tmpdir = os.environ.get('TMPDIR', '/tmp')
  474. self.control_socket = "%s/gpsfake-%d.sock" % (tmpdir, os.getpid())
  475. def spawn(self, options, port, background=False, prefix=""):
  476. "Spawn a daemon instance."
  477. # The -b option to suppress hanging on probe returns is needed to cope
  478. # with OpenBSD (and possibly other non-Linux systems) that don't
  479. # support anything we can use to implement the FakeGPS.read() method
  480. opts = (" -b -N -S %s -F %s %s"
  481. % (port, self.control_socket, options))
  482. # Derive a unique SHM key from the port # to avoid collisions.
  483. # Use 'Gp' as the prefix to avoid colliding with 'GPSD'.
  484. shmkey = '0x4770%.04X' % int(port)
  485. env = {'GPSD_SHM_KEY': shmkey}
  486. self.spawn_sub('gpsd', opts, background, prefix, env)
  487. def wait_ready(self):
  488. "Wait for the daemon to create the control socket."
  489. while self.is_alive():
  490. if os.path.exists(self.control_socket):
  491. return
  492. time.sleep(0.1)
  493. def __get_control_socket(self):
  494. # Now we know it's running, get a connection to the control socket.
  495. if not os.path.exists(self.control_socket):
  496. return None
  497. try:
  498. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
  499. self.sock.connect(self.control_socket)
  500. except socket.error:
  501. if self.sock:
  502. self.sock.close()
  503. self.sock = None
  504. return self.sock
  505. def add_device(self, path):
  506. "Add a device to the daemon's internal search list."
  507. if self.__get_control_socket():
  508. self.sock.sendall(gps.polybytes("+%s\r\n\x00" % path))
  509. self.sock.recv(12)
  510. self.sock.close()
  511. def remove_device(self, path):
  512. "Remove a device from the daemon's internal search list."
  513. if self.__get_control_socket():
  514. self.sock.sendall(gps.polybytes("-%s\r\n\x00" % path))
  515. self.sock.recv(12)
  516. self.sock.close()
  517. class TestSessionError(TestError):
  518. "class TestSessionError"
  519. # why does testSessionError() do nothing? "
  520. class TestSession(object):
  521. "Manage a session including a daemon with fake GPSes and clients."
  522. def __init__(self, prefix=None, port=None, options=None, verbose=0,
  523. predump=False, udp=False, tcp=False, slow=False,
  524. timeout=None):
  525. "Initialize the test session by launching the daemon."
  526. self.prefix = prefix
  527. self.options = options
  528. self.verbose = verbose
  529. self.predump = predump
  530. self.udp = udp
  531. self.tcp = tcp
  532. self.slow = slow
  533. self.daemon = DaemonInstance()
  534. self.fakegpslist = {}
  535. self.client_id = 0
  536. self.readers = 0
  537. self.writers = 0
  538. self.runqueue = []
  539. self.index = 0
  540. if port:
  541. self.port = port
  542. else:
  543. self.port = freeport()
  544. self.progress = lambda x: None
  545. # for debugging
  546. # self.progress = lambda x: sys.stderr.write("# Hi " + x)
  547. self.reporter = lambda x: None
  548. self.default_predicate = None
  549. self.fd_set = []
  550. self.threadlock = None
  551. self.timeout = TEST_TIMEOUT if timeout is None else timeout
  552. def spawn(self):
  553. "Spawn daemon"
  554. for sig in (signal.SIGQUIT, signal.SIGINT, signal.SIGTERM):
  555. signal.signal(sig, lambda unused, dummy: self.cleanup())
  556. self.daemon.spawn(background=True, prefix=self.prefix, port=self.port,
  557. options=self.options)
  558. self.daemon.wait_ready()
  559. def set_predicate(self, pred):
  560. "Set a default go predicate for the session."
  561. self.default_predicate = pred
  562. def gps_add(self, logfile, speed=19200, pred=None, oneshot=False):
  563. "Add a simulated GPS being fed by the specified logfile."
  564. self.progress("gpsfake: gps_add(%s, %d)\n" % (logfile, speed))
  565. if logfile not in self.fakegpslist:
  566. testload = TestLoad(logfile, predump=self.predump, slow=self.slow,
  567. oneshot=oneshot)
  568. if testload.sourcetype == "UDP" or self.udp:
  569. newgps = FakeUDP(testload, ipaddr="127.0.0.1",
  570. port=freeport(socket.SOCK_DGRAM),
  571. progress=self.progress)
  572. elif testload.sourcetype == "TCP" or self.tcp:
  573. # Let OS assign the port
  574. newgps = FakeTCP(testload, host="127.0.0.1", port=0,
  575. progress=self.progress)
  576. else:
  577. newgps = FakePTY(testload, speed=speed,
  578. progress=self.progress)
  579. if pred:
  580. newgps.go_predicate = pred
  581. elif self.default_predicate:
  582. newgps.go_predicate = self.default_predicate
  583. self.fakegpslist[newgps.byname] = newgps
  584. self.append(newgps)
  585. newgps.exhausted = 0
  586. self.daemon.add_device(newgps.byname)
  587. return newgps.byname
  588. def gps_remove(self, name):
  589. "Remove a simulated GPS from the daemon's search list."
  590. self.progress("gpsfake: gps_remove(%s)\n" % name)
  591. self.fakegpslist[name].drain()
  592. self.remove(self.fakegpslist[name])
  593. self.daemon.remove_device(name)
  594. del self.fakegpslist[name]
  595. def client_add(self, commands):
  596. "Initiate a client session and force connection to a fake GPS."
  597. self.progress("gpsfake: client_add()\n")
  598. try:
  599. newclient = gps.gps(port=self.port, verbose=self.verbose)
  600. except socket.error:
  601. if not self.daemon.is_alive():
  602. raise TestSessionError("daemon died")
  603. raise
  604. self.append(newclient)
  605. newclient.id = self.client_id + 1
  606. self.client_id += 1
  607. self.progress("gpsfake: client %d has %s\n"
  608. % (self.client_id, newclient.device))
  609. if commands:
  610. self.initialize(newclient, commands)
  611. return self.client_id
  612. def client_remove(self, cid):
  613. "Terminate a client session."
  614. self.progress("gpsfake: client_remove(%d)\n" % cid)
  615. for obj in self.runqueue:
  616. if isinstance(obj, gps.gps) and obj.id == cid:
  617. self.remove(obj)
  618. return True
  619. return False
  620. def wait(self, seconds):
  621. "Wait, doing nothing."
  622. self.progress("gpsfake: wait(%d)\n" % seconds)
  623. time.sleep(seconds)
  624. def gather(self, seconds):
  625. "Wait, doing nothing but watching for sentences."
  626. self.progress("gpsfake: gather(%d)\n" % seconds)
  627. time.sleep(seconds)
  628. def cleanup(self):
  629. "We're done, kill the daemon."
  630. self.progress("gpsfake: cleanup()\n")
  631. if self.daemon:
  632. self.daemon.kill()
  633. self.daemon = None
  634. def run(self):
  635. "Run the tests."
  636. try:
  637. self.progress("gpsfake: test loop begins\n")
  638. while self.daemon:
  639. if not self.daemon.is_alive():
  640. raise TestSessionError("daemon died")
  641. # We have to read anything that gpsd might have tried
  642. # to send to the GPS here -- under OpenBSD the
  643. # TIOCDRAIN will hang, otherwise.
  644. for device in self.runqueue:
  645. if isinstance(device, FakeGPS):
  646. device.read()
  647. had_output = False
  648. chosen = self.choose()
  649. if isinstance(chosen, FakeGPS):
  650. if (((chosen.exhausted and self.timeout and
  651. (time.time() - chosen.exhausted > self.timeout) and
  652. chosen.byname in self.fakegpslist))):
  653. sys.stderr.write(
  654. "Test timed out: maybe increase WRITE_PAD (= %s)\n"
  655. % GetDelay(self.slow))
  656. raise SystemExit(1)
  657. if not chosen.go_predicate(chosen.index, chosen):
  658. if chosen.exhausted == 0:
  659. chosen.exhausted = time.time()
  660. self.progress("gpsfake: GPS %s ran out of input\n"
  661. % chosen.byname)
  662. else:
  663. chosen.feed()
  664. elif isinstance(chosen, gps.gps):
  665. if chosen.enqueued:
  666. chosen.send(chosen.enqueued)
  667. chosen.enqueued = ""
  668. while chosen.waiting():
  669. if not self.daemon or not self.daemon.is_alive():
  670. raise TestSessionError("daemon died")
  671. ret = chosen.read()
  672. if 0 > ret:
  673. raise TestSessionError("daemon output stopped")
  674. # FIXME: test for 0 == ret.
  675. had_output = True
  676. if not chosen.valid & gps.PACKET_SET:
  677. continue
  678. self.reporter(chosen.bresponse)
  679. if ((chosen.data["class"] == "DEVICE" and
  680. chosen.data["activated"] == 0 and
  681. chosen.data["path"] in self.fakegpslist)):
  682. self.gps_remove(chosen.data["path"])
  683. self.progress(
  684. "gpsfake: GPS %s removed (notification)\n"
  685. % chosen.data["path"])
  686. else:
  687. raise TestSessionError("test object of unknown type")
  688. if not self.writers and not had_output:
  689. self.progress("gpsfake: no writers and no output\n")
  690. break
  691. self.progress("gpsfake: test loop ends\n")
  692. finally:
  693. self.cleanup()
  694. # All knowledge about locks and threading is below this line,
  695. # except for the bare fact that self.threadlock is set to None
  696. # in the class init method.
  697. def append(self, obj):
  698. "Add a producer or consumer to the object list."
  699. if self.threadlock:
  700. self.threadlock.acquire()
  701. self.runqueue.append(obj)
  702. if isinstance(obj, FakeGPS):
  703. self.writers += 1
  704. elif isinstance(obj, gps.gps):
  705. self.readers += 1
  706. if self.threadlock:
  707. self.threadlock.release()
  708. def remove(self, obj):
  709. "Remove a producer or consumer from the object list."
  710. if self.threadlock:
  711. self.threadlock.acquire()
  712. self.runqueue.remove(obj)
  713. if isinstance(obj, FakeGPS):
  714. self.writers -= 1
  715. elif isinstance(obj, gps.gps):
  716. self.readers -= 1
  717. self.index = min(len(self.runqueue) - 1, self.index)
  718. if self.threadlock:
  719. self.threadlock.release()
  720. def choose(self):
  721. "Atomically get the next object scheduled to do something."
  722. if self.threadlock:
  723. self.threadlock.acquire()
  724. chosen = self.index
  725. self.index += 1
  726. self.index %= len(self.runqueue)
  727. if self.threadlock:
  728. self.threadlock.release()
  729. return self.runqueue[chosen]
  730. def initialize(self, client, commands):
  731. "Arrange for client to ship specified commands when it goes active."
  732. client.enqueued = ""
  733. if not self.threadlock:
  734. client.send(commands)
  735. else:
  736. client.enqueued = commands
  737. def start(self):
  738. "Start thread"
  739. self.threadlock = threading.Lock()
  740. threading.Thread(target=self.run)
  741. # End
  742. # vim: set expandtab shiftwidth=4