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.
 
 
 

613 lines
24 KiB

  1. # -*- coding: utf-8 -*-
  2. import nilmdb
  3. from nilmdb.utils.printf import *
  4. from nilmdb.utils import timestamper
  5. from nilmdb.client import ClientError, ServerError
  6. from nilmdb.utils import datetime_tz
  7. from nose.plugins.skip import SkipTest
  8. from nose.tools import *
  9. from nose.tools import assert_raises
  10. import itertools
  11. import distutils.version
  12. import os
  13. import sys
  14. import threading
  15. import cStringIO
  16. import simplejson as json
  17. import unittest
  18. import warnings
  19. import resource
  20. import time
  21. import re
  22. from testutil.helpers import *
  23. testdb = "tests/client-testdb"
  24. testurl = "http://localhost:32180/"
  25. def setup_module():
  26. global test_server, test_db
  27. # Clear out DB
  28. recursive_unlink(testdb)
  29. # Start web app on a custom port
  30. test_db = nilmdb.utils.serializer_proxy(nilmdb.NilmDB)(testdb, sync = False)
  31. test_server = nilmdb.Server(test_db, host = "127.0.0.1",
  32. port = 32180, stoppable = False,
  33. fast_shutdown = True,
  34. force_traceback = False)
  35. test_server.start(blocking = False)
  36. def teardown_module():
  37. global test_server, test_db
  38. # Close web app
  39. test_server.stop()
  40. test_db.close()
  41. class TestClient(object):
  42. def test_client_01_basic(self):
  43. # Test a fake host
  44. client = nilmdb.Client(url = "http://localhost:1/")
  45. with assert_raises(nilmdb.client.ServerError):
  46. client.version()
  47. client.close()
  48. # Trigger same error with a PUT request
  49. client = nilmdb.Client(url = "http://localhost:1/")
  50. with assert_raises(nilmdb.client.ServerError):
  51. client.version()
  52. client.close()
  53. # Then a fake URL on a real host
  54. client = nilmdb.Client(url = "http://localhost:32180/fake/")
  55. with assert_raises(nilmdb.client.ClientError):
  56. client.version()
  57. client.close()
  58. # Now a real URL with no http:// prefix
  59. client = nilmdb.Client(url = "localhost:32180")
  60. version = client.version()
  61. client.close()
  62. # Now use the real URL
  63. client = nilmdb.Client(url = testurl)
  64. version = client.version()
  65. eq_(distutils.version.LooseVersion(version),
  66. distutils.version.LooseVersion(test_server.version))
  67. # Bad URLs should give 404, not 500
  68. with assert_raises(ClientError):
  69. client.http.get("/stream/create")
  70. client.close()
  71. def test_client_02_createlist(self):
  72. # Basic stream tests, like those in test_nilmdb:test_stream
  73. client = nilmdb.Client(url = testurl)
  74. # Database starts empty
  75. eq_(client.stream_list(), [])
  76. # Bad path
  77. with assert_raises(ClientError):
  78. client.stream_create("foo/bar/baz", "PrepData")
  79. with assert_raises(ClientError):
  80. client.stream_create("/foo", "PrepData")
  81. # Bad layout type
  82. with assert_raises(ClientError):
  83. client.stream_create("/newton/prep", "NoSuchLayout")
  84. # Bad method types
  85. with assert_raises(ClientError):
  86. client.http.put("/stream/list","")
  87. # Try a bunch of times to make sure the request body is getting consumed
  88. for x in range(10):
  89. with assert_raises(ClientError):
  90. client.http.post("/stream/list")
  91. client = nilmdb.Client(url = testurl)
  92. # Create three streams
  93. client.stream_create("/newton/prep", "PrepData")
  94. client.stream_create("/newton/raw", "RawData")
  95. client.stream_create("/newton/zzz/rawnotch", "RawNotchedData")
  96. # Verify we got 3 streams
  97. eq_(client.stream_list(), [ ["/newton/prep", "PrepData"],
  98. ["/newton/raw", "RawData"],
  99. ["/newton/zzz/rawnotch", "RawNotchedData"]
  100. ])
  101. # Match just one type or one path
  102. eq_(client.stream_list(layout="RawData"),
  103. [ ["/newton/raw", "RawData"] ])
  104. eq_(client.stream_list(path="/newton/raw"),
  105. [ ["/newton/raw", "RawData"] ])
  106. # Try messing with resource limits to trigger errors and get
  107. # more coverage. Here, make it so we can only create files 1
  108. # byte in size, which will trigger an IOError in the server when
  109. # we create a table.
  110. limit = resource.getrlimit(resource.RLIMIT_FSIZE)
  111. resource.setrlimit(resource.RLIMIT_FSIZE, (1, limit[1]))
  112. with assert_raises(ServerError) as e:
  113. client.stream_create("/newton/hello", "RawData")
  114. resource.setrlimit(resource.RLIMIT_FSIZE, limit)
  115. client.close()
  116. def test_client_03_metadata(self):
  117. client = nilmdb.Client(url = testurl)
  118. # Set / get metadata
  119. eq_(client.stream_get_metadata("/newton/prep"), {})
  120. eq_(client.stream_get_metadata("/newton/raw"), {})
  121. meta1 = { "description": "The Data",
  122. "v_scale": "1.234" }
  123. meta2 = { "description": "The Data" }
  124. meta3 = { "v_scale": "1.234" }
  125. client.stream_set_metadata("/newton/prep", meta1)
  126. client.stream_update_metadata("/newton/prep", {})
  127. client.stream_update_metadata("/newton/raw", meta2)
  128. client.stream_update_metadata("/newton/raw", meta3)
  129. eq_(client.stream_get_metadata("/newton/prep"), meta1)
  130. eq_(client.stream_get_metadata("/newton/raw"), meta1)
  131. eq_(client.stream_get_metadata("/newton/raw",
  132. [ "description" ] ), meta2)
  133. eq_(client.stream_get_metadata("/newton/raw",
  134. [ "description", "v_scale" ] ), meta1)
  135. # missing key
  136. eq_(client.stream_get_metadata("/newton/raw", "descr"),
  137. { "descr": None })
  138. eq_(client.stream_get_metadata("/newton/raw", [ "descr" ]),
  139. { "descr": None })
  140. # test wrong types (list instead of dict)
  141. with assert_raises(ClientError):
  142. client.stream_set_metadata("/newton/prep", [1,2,3])
  143. with assert_raises(ClientError):
  144. client.stream_update_metadata("/newton/prep", [1,2,3])
  145. client.close()
  146. def test_client_04_insert(self):
  147. client = nilmdb.Client(url = testurl)
  148. # Limit _max_data to 1 MB, since our test file is 1.5 MB
  149. old_max_data = nilmdb.client.client.StreamInserter._max_data
  150. nilmdb.client.client.StreamInserter._max_data = 1 * 1024 * 1024
  151. datetime_tz.localtz_set("America/New_York")
  152. testfile = "tests/data/prep-20120323T1000"
  153. start = datetime_tz.datetime_tz.smartparse("20120323T1000")
  154. start = start.totimestamp()
  155. rate = 120
  156. # First try a nonexistent path
  157. data = timestamper.TimestamperRate(testfile, start, 120)
  158. with assert_raises(ClientError) as e:
  159. result = client.stream_insert("/newton/no-such-path", data)
  160. in_("404 Not Found", str(e.exception))
  161. # Now try reversed timestamps
  162. data = timestamper.TimestamperRate(testfile, start, 120)
  163. data = reversed(list(data))
  164. with assert_raises(ClientError) as e:
  165. result = client.stream_insert("/newton/prep", data)
  166. in_("400 Bad Request", str(e.exception))
  167. in_("timestamp is not monotonically increasing", str(e.exception))
  168. # Now try empty data (no server request made)
  169. empty = cStringIO.StringIO("")
  170. data = timestamper.TimestamperRate(empty, start, 120)
  171. result = client.stream_insert("/newton/prep", data)
  172. eq_(result, None)
  173. # It's OK to insert an empty interval
  174. client.http.put("stream/insert", "", { "path": "/newton/prep",
  175. "start": 1, "end": 2 })
  176. eq_(list(client.stream_intervals("/newton/prep")), [[1, 2]])
  177. client.stream_remove("/newton/prep")
  178. eq_(list(client.stream_intervals("/newton/prep")), [])
  179. # Timestamps can be negative too
  180. client.http.put("stream/insert", "", { "path": "/newton/prep",
  181. "start": -2, "end": -1 })
  182. eq_(list(client.stream_intervals("/newton/prep")), [[-2, -1]])
  183. client.stream_remove("/newton/prep")
  184. eq_(list(client.stream_intervals("/newton/prep")), [])
  185. # Intervals that end at zero shouldn't be any different
  186. client.http.put("stream/insert", "", { "path": "/newton/prep",
  187. "start": -1, "end": 0 })
  188. eq_(list(client.stream_intervals("/newton/prep")), [[-1, 0]])
  189. client.stream_remove("/newton/prep")
  190. eq_(list(client.stream_intervals("/newton/prep")), [])
  191. # Try forcing a server request with equal start and end
  192. with assert_raises(ClientError) as e:
  193. client.http.put("stream/insert", "", { "path": "/newton/prep",
  194. "start": 0, "end": 0 })
  195. in_("400 Bad Request", str(e.exception))
  196. in_("start must precede end", str(e.exception))
  197. # Specify start/end (starts too late)
  198. data = timestamper.TimestamperRate(testfile, start, 120)
  199. with assert_raises(ClientError) as e:
  200. result = client.stream_insert("/newton/prep", data,
  201. start + 5, start + 120)
  202. in_("400 Bad Request", str(e.exception))
  203. in_("Data timestamp 1332511200.0 < start time 1332511205.0",
  204. str(e.exception))
  205. # Specify start/end (ends too early)
  206. data = timestamper.TimestamperRate(testfile, start, 120)
  207. with assert_raises(ClientError) as e:
  208. result = client.stream_insert("/newton/prep", data,
  209. start, start + 1)
  210. in_("400 Bad Request", str(e.exception))
  211. # Client chunks the input, so the exact timestamp here might change
  212. # if the chunk positions change.
  213. assert(re.search("Data timestamp 13325[0-9]+\.[0-9]+ "
  214. ">= end time 1332511201.0", str(e.exception))
  215. is not None)
  216. # Now do the real load
  217. data = timestamper.TimestamperRate(testfile, start, 120)
  218. result = client.stream_insert("/newton/prep", data,
  219. start, start + 119.999777)
  220. # Verify the intervals. Should be just one, even if the data
  221. # was inserted in chunks, due to nilmdb interval concatenation.
  222. intervals = list(client.stream_intervals("/newton/prep"))
  223. eq_(intervals, [[start, start + 119.999777]])
  224. # Try some overlapping data -- just insert it again
  225. data = timestamper.TimestamperRate(testfile, start, 120)
  226. with assert_raises(ClientError) as e:
  227. result = client.stream_insert("/newton/prep", data)
  228. in_("400 Bad Request", str(e.exception))
  229. in_("verlap", str(e.exception))
  230. nilmdb.client.client.StreamInserter._max_data = old_max_data
  231. client.close()
  232. def test_client_05_extractremove(self):
  233. # Misc tests for extract and remove. Most of them are in test_cmdline.
  234. client = nilmdb.Client(url = testurl)
  235. for x in client.stream_extract("/newton/prep", 999123, 999124):
  236. raise AssertionError("shouldn't be any data for this request")
  237. with assert_raises(ClientError) as e:
  238. client.stream_remove("/newton/prep", 123, 120)
  239. # Test count
  240. eq_(client.stream_count("/newton/prep"), 14400)
  241. client.close()
  242. def test_client_06_generators(self):
  243. # A lot of the client functionality is already tested by test_cmdline,
  244. # but this gets a bit more coverage that cmdline misses.
  245. client = nilmdb.Client(url = testurl)
  246. # Trigger a client error in generator
  247. start = datetime_tz.datetime_tz.smartparse("20120323T2000")
  248. end = datetime_tz.datetime_tz.smartparse("20120323T1000")
  249. for function in [ client.stream_intervals, client.stream_extract ]:
  250. with assert_raises(ClientError) as e:
  251. function("/newton/prep",
  252. start.totimestamp(),
  253. end.totimestamp()).next()
  254. in_("400 Bad Request", str(e.exception))
  255. in_("start must precede end", str(e.exception))
  256. # Trigger a curl error in generator
  257. with assert_raises(ServerError) as e:
  258. client.http.get_gen("http://nosuchurl/").next()
  259. # Trigger a curl error in generator
  260. with assert_raises(ServerError) as e:
  261. client.http.get_gen("http://nosuchurl/").next()
  262. # Check 404 for missing streams
  263. for function in [ client.stream_intervals, client.stream_extract ]:
  264. with assert_raises(ClientError) as e:
  265. function("/no/such/stream").next()
  266. in_("404 Not Found", str(e.exception))
  267. in_("No such stream", str(e.exception))
  268. client.close()
  269. def test_client_07_headers(self):
  270. # Make sure that /stream/intervals and /stream/extract
  271. # properly return streaming, chunked, text/plain response.
  272. # Pokes around in client.http internals a bit to look at the
  273. # response headers.
  274. client = nilmdb.Client(url = testurl)
  275. http = client.http
  276. # Use a warning rather than returning a test failure for the
  277. # transfer-encoding, so that we can still disable chunked
  278. # responses for debugging.
  279. def headers():
  280. h = ""
  281. for (k, v) in http._last_response.headers.items():
  282. h += k + ": " + v + "\n"
  283. return h.lower()
  284. # Intervals
  285. x = http.get("stream/intervals", { "path": "/newton/prep" })
  286. if "transfer-encoding: chunked" not in headers():
  287. warnings.warn("Non-chunked HTTP response for /stream/intervals")
  288. if "content-type: application/x-json-stream" not in headers():
  289. raise AssertionError("/stream/intervals content type "
  290. "is not application/x-json-stream:\n" +
  291. headers())
  292. # Extract
  293. x = http.get("stream/extract",
  294. { "path": "/newton/prep",
  295. "start": "123",
  296. "end": "124" })
  297. if "transfer-encoding: chunked" not in headers():
  298. warnings.warn("Non-chunked HTTP response for /stream/extract")
  299. if "content-type: text/plain;charset=utf-8" not in headers():
  300. raise AssertionError("/stream/extract is not text/plain:\n" +
  301. headers())
  302. # Make sure Access-Control-Allow-Origin gets set
  303. if "access-control-allow-origin: " not in headers():
  304. raise AssertionError("No Access-Control-Allow-Origin (CORS) "
  305. "header in /stream/extract response:\n" +
  306. headers())
  307. client.close()
  308. def test_client_08_unicode(self):
  309. # Basic Unicode tests
  310. client = nilmdb.Client(url = testurl)
  311. # Delete streams that exist
  312. for stream in client.stream_list():
  313. client.stream_destroy(stream[0])
  314. # Database is empty
  315. eq_(client.stream_list(), [])
  316. # Create Unicode stream, match it
  317. raw = [ u"/düsseldorf/raw", u"uint16_6" ]
  318. prep = [ u"/düsseldorf/prep", u"uint16_6" ]
  319. client.stream_create(*raw)
  320. eq_(client.stream_list(), [raw])
  321. eq_(client.stream_list(layout=raw[1]), [raw])
  322. eq_(client.stream_list(path=raw[0]), [raw])
  323. client.stream_create(*prep)
  324. eq_(client.stream_list(), [prep, raw])
  325. # Set / get metadata with Unicode keys and values
  326. eq_(client.stream_get_metadata(raw[0]), {})
  327. eq_(client.stream_get_metadata(prep[0]), {})
  328. meta1 = { u"alpha": u"α",
  329. u"β": u"beta" }
  330. meta2 = { u"alpha": u"α" }
  331. meta3 = { u"β": u"beta" }
  332. client.stream_set_metadata(prep[0], meta1)
  333. client.stream_update_metadata(prep[0], {})
  334. client.stream_update_metadata(raw[0], meta2)
  335. client.stream_update_metadata(raw[0], meta3)
  336. eq_(client.stream_get_metadata(prep[0]), meta1)
  337. eq_(client.stream_get_metadata(raw[0]), meta1)
  338. eq_(client.stream_get_metadata(raw[0], [ "alpha" ]), meta2)
  339. eq_(client.stream_get_metadata(raw[0], [ "alpha", "β" ]), meta1)
  340. client.close()
  341. def test_client_09_closing(self):
  342. # Make sure we actually close sockets correctly. New
  343. # connections will block for a while if they're not, since the
  344. # server will stop accepting new connections.
  345. for test in [1, 2]:
  346. start = time.time()
  347. for i in range(50):
  348. if time.time() - start > 15:
  349. raise AssertionError("Connections seem to be blocking... "
  350. "probably not closing properly.")
  351. if test == 1:
  352. # explicit close
  353. client = nilmdb.Client(url = testurl)
  354. with assert_raises(ClientError) as e:
  355. client.stream_remove("/newton/prep", 123, 120)
  356. client.close() # remove this to see the failure
  357. elif test == 2:
  358. # use the context manager
  359. with nilmdb.Client(url = testurl) as c:
  360. with assert_raises(ClientError) as e:
  361. c.stream_remove("/newton/prep", 123, 120)
  362. def test_client_10_context(self):
  363. # Test using the client's stream insertion context manager to
  364. # insert data.
  365. client = nilmdb.Client(testurl)
  366. client.stream_create("/context/test", "uint16_1")
  367. with client.stream_insert_context("/context/test") as ctx:
  368. # override _max_data to trigger frequent server updates
  369. ctx._max_data = 15
  370. with assert_raises(ValueError):
  371. ctx.insert_line("100 1")
  372. ctx.insert_line("100 1\n")
  373. ctx.insert_iter([ "101 1\n",
  374. "102 1\n",
  375. "103 1\n" ])
  376. ctx.insert_line("104 1\n")
  377. ctx.insert_line("105 1\n")
  378. ctx.finalize()
  379. ctx.insert_line("106 1\n")
  380. ctx.update_end(106.5)
  381. ctx.finalize()
  382. ctx.update_start(106.8)
  383. ctx.insert_line("107 1\n")
  384. ctx.insert_line("108 1\n")
  385. ctx.insert_line("109 1\n")
  386. ctx.insert_line("110 1\n")
  387. ctx.insert_line("111 1\n")
  388. ctx.update_end(113)
  389. ctx.insert_line("112 1\n")
  390. ctx.update_end(114)
  391. ctx.insert_line("113 1\n")
  392. ctx.update_end(115)
  393. ctx.insert_line("114 1\n")
  394. ctx.finalize()
  395. with assert_raises(ClientError):
  396. with client.stream_insert_context("/context/test", 100, 200) as ctx:
  397. ctx.insert_line("115 1\n")
  398. with assert_raises(ClientError):
  399. with client.stream_insert_context("/context/test", 200, 300) as ctx:
  400. ctx.insert_line("115 1\n")
  401. with client.stream_insert_context("/context/test", 200, 300) as ctx:
  402. # make sure our override wasn't permanent
  403. ne_(ctx._max_data, 15)
  404. ctx.insert_line("225 1\n")
  405. ctx.finalize()
  406. eq_(list(client.stream_intervals("/context/test")),
  407. [ [ 100, 105.000001 ],
  408. [ 106, 106.5 ],
  409. [ 106.8, 115 ],
  410. [ 200, 300 ] ])
  411. client.stream_destroy("/context/test")
  412. client.close()
  413. def test_client_11_emptyintervals(self):
  414. # Empty intervals are ok! If recording detection events
  415. # by inserting rows into the database, we want to be able to
  416. # have an interval where no events occurred. Test them here.
  417. client = nilmdb.Client(testurl)
  418. client.stream_create("/empty/test", "uint16_1")
  419. def info():
  420. result = []
  421. for interval in list(client.stream_intervals("/empty/test")):
  422. result.append((client.stream_count("/empty/test", *interval),
  423. interval))
  424. return result
  425. eq_(info(), [])
  426. # Insert a region with just a few points
  427. with client.stream_insert_context("/empty/test") as ctx:
  428. ctx.update_start(100)
  429. ctx.insert_line("140 1\n")
  430. ctx.insert_line("150 1\n")
  431. ctx.insert_line("160 1\n")
  432. ctx.update_end(200)
  433. ctx.finalize()
  434. eq_(info(), [(3, [100, 200])])
  435. # Delete chunk, which will leave one data point and two intervals
  436. client.stream_remove("/empty/test", 145, 175)
  437. eq_(info(), [(1, [100, 145]),
  438. (0, [175, 200])])
  439. # Try also creating a completely empty interval from scratch,
  440. # in a few different ways.
  441. client.stream_insert_block("/empty/test", "", 300, 350)
  442. client.stream_insert("/empty/test", [], 400, 450)
  443. with client.stream_insert_context("/empty/test", 500, 550):
  444. pass
  445. # If enough timestamps aren't provided, empty streams won't be created.
  446. client.stream_insert("/empty/test", [])
  447. with client.stream_insert_context("/empty/test"):
  448. pass
  449. client.stream_insert("/empty/test", [], start = 600)
  450. with client.stream_insert_context("/empty/test", start = 700):
  451. pass
  452. client.stream_insert("/empty/test", [], end = 850)
  453. with client.stream_insert_context("/empty/test", end = 950):
  454. pass
  455. # Try various things that might cause problems
  456. with client.stream_insert_context("/empty/test", 1000, 1050):
  457. ctx.finalize() # inserts [1000, 1050]
  458. ctx.finalize() # nothing
  459. ctx.finalize() # nothing
  460. ctx.insert_line("1100 1\n")
  461. ctx.finalize() # inserts [1100, 1100.000001]
  462. ctx.update_start(1199)
  463. ctx.insert_line("1200 1\n")
  464. ctx.update_end(1250)
  465. ctx.finalize() # inserts [1199, 1250]
  466. ctx.update_start(1299)
  467. ctx.finalize() # nothing
  468. ctx.update_end(1350)
  469. ctx.finalize() # nothing
  470. ctx.update_start(1400)
  471. ctx.update_end(1450)
  472. ctx.finalize()
  473. # implicit last finalize inserts [1400, 1450]
  474. # Check everything
  475. eq_(info(), [(1, [100, 145]),
  476. (0, [175, 200]),
  477. (0, [300, 350]),
  478. (0, [400, 450]),
  479. (0, [500, 550]),
  480. (0, [1000, 1050]),
  481. (1, [1100, 1100.000001]),
  482. (1, [1199, 1250]),
  483. (0, [1400, 1450]),
  484. ])
  485. # Clean up
  486. client.stream_destroy("/empty/test")
  487. client.close()
  488. def test_client_12_persistent(self):
  489. # Check that connections are persistent when they should be.
  490. # This is pretty hard to test; we have to poke deep into
  491. # the Requests library.
  492. with nilmdb.Client(url = testurl) as c:
  493. def connections():
  494. try:
  495. poolmanager = c.http._last_response.connection.poolmanager
  496. pool = poolmanager.pools[('http','localhost',32180)]
  497. return (pool.num_connections, pool.num_requests)
  498. except:
  499. raise SkipTest("can't get connection info")
  500. # First request makes a connection
  501. c.stream_create("/persist/test", "uint16_1")
  502. eq_(connections(), (1, 1))
  503. # Non-generator
  504. c.stream_list("/persist/test")
  505. eq_(connections(), (1, 2))
  506. c.stream_list("/persist/test")
  507. eq_(connections(), (1, 3))
  508. # Generators
  509. for x in c.stream_intervals("/persist/test"):
  510. pass
  511. eq_(connections(), (1, 4))
  512. for x in c.stream_intervals("/persist/test"):
  513. pass
  514. eq_(connections(), (1, 5))
  515. # Clean up
  516. c.stream_destroy("/persist/test")
  517. eq_(connections(), (1, 6))