Devuan fork of gpsd
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

838 lines
31 KiB

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