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. # Then a fake URL on a real host
  49. client = nilmdb.Client(url = "http://localhost:32180/fake/")
  50. with assert_raises(nilmdb.client.ClientError):
  51. client.version()
  52. client.close()
  53. # Now a real URL with no http:// prefix
  54. client = nilmdb.Client(url = "localhost:32180")
  55. version = client.version()
  56. client.close()
  57. # Now use the real URL
  58. client = nilmdb.Client(url = testurl)
  59. version = client.version()
  60. eq_(distutils.version.LooseVersion(version),
  61. distutils.version.LooseVersion(test_server.version))
  62. # Bad URLs should give 404, not 500
  63. with assert_raises(ClientError):
  64. client.http.get("/stream/create")
  65. client.close()
  66. def test_client_02_createlist(self):
  67. # Basic stream tests, like those in test_nilmdb:test_stream
  68. client = nilmdb.Client(url = testurl)
  69. # Database starts empty
  70. eq_(client.stream_list(), [])
  71. # Bad path
  72. with assert_raises(ClientError):
  73. client.stream_create("foo/bar/baz", "PrepData")
  74. with assert_raises(ClientError):
  75. client.stream_create("/foo", "PrepData")
  76. # Bad layout type
  77. with assert_raises(ClientError):
  78. client.stream_create("/newton/prep", "NoSuchLayout")
  79. # Bad method types
  80. with assert_raises(ClientError):
  81. client.http.put("/stream/list","")
  82. # Try a bunch of times to make sure the request body is getting consumed
  83. for x in range(10):
  84. with assert_raises(ClientError):
  85. client.http.post("/stream/list")
  86. client = nilmdb.Client(url = testurl)
  87. # Create three streams
  88. client.stream_create("/newton/prep", "PrepData")
  89. client.stream_create("/newton/raw", "RawData")
  90. client.stream_create("/newton/zzz/rawnotch", "RawNotchedData")
  91. # Verify we got 3 streams
  92. eq_(client.stream_list(), [ ["/newton/prep", "PrepData"],
  93. ["/newton/raw", "RawData"],
  94. ["/newton/zzz/rawnotch", "RawNotchedData"]
  95. ])
  96. # Match just one type or one path
  97. eq_(client.stream_list(layout="RawData"),
  98. [ ["/newton/raw", "RawData"] ])
  99. eq_(client.stream_list(path="/newton/raw"),
  100. [ ["/newton/raw", "RawData"] ])
  101. # Try messing with resource limits to trigger errors and get
  102. # more coverage. Here, make it so we can only create files 1
  103. # byte in size, which will trigger an IOError in the server when
  104. # we create a table.
  105. limit = resource.getrlimit(resource.RLIMIT_FSIZE)
  106. resource.setrlimit(resource.RLIMIT_FSIZE, (1, limit[1]))
  107. with assert_raises(ServerError) as e:
  108. client.stream_create("/newton/hello", "RawData")
  109. resource.setrlimit(resource.RLIMIT_FSIZE, limit)
  110. client.close()
  111. def test_client_03_metadata(self):
  112. client = nilmdb.Client(url = testurl)
  113. # Set / get metadata
  114. eq_(client.stream_get_metadata("/newton/prep"), {})
  115. eq_(client.stream_get_metadata("/newton/raw"), {})
  116. meta1 = { "description": "The Data",
  117. "v_scale": "1.234" }
  118. meta2 = { "description": "The Data" }
  119. meta3 = { "v_scale": "1.234" }
  120. client.stream_set_metadata("/newton/prep", meta1)
  121. client.stream_update_metadata("/newton/prep", {})
  122. client.stream_update_metadata("/newton/raw", meta2)
  123. client.stream_update_metadata("/newton/raw", meta3)
  124. eq_(client.stream_get_metadata("/newton/prep"), meta1)
  125. eq_(client.stream_get_metadata("/newton/raw"), meta1)
  126. eq_(client.stream_get_metadata("/newton/raw",
  127. [ "description" ] ), meta2)
  128. eq_(client.stream_get_metadata("/newton/raw",
  129. [ "description", "v_scale" ] ), meta1)
  130. # missing key
  131. eq_(client.stream_get_metadata("/newton/raw", "descr"),
  132. { "descr": None })
  133. eq_(client.stream_get_metadata("/newton/raw", [ "descr" ]),
  134. { "descr": None })
  135. # test wrong types (list instead of dict)
  136. with assert_raises(ClientError):
  137. client.stream_set_metadata("/newton/prep", [1,2,3])
  138. with assert_raises(ClientError):
  139. client.stream_update_metadata("/newton/prep", [1,2,3])
  140. # test wrong types (dict of non-strings)
  141. # numbers are OK; they'll get converted to strings
  142. client.stream_set_metadata("/newton/prep", { "hello": 1234 })
  143. # anything else is not
  144. with assert_raises(ClientError):
  145. client.stream_set_metadata("/newton/prep", { "world": { 1: 2 } })
  146. with assert_raises(ClientError):
  147. client.stream_set_metadata("/newton/prep", { "world": [ 1, 2 ] })
  148. client.close()
  149. def test_client_04_insert(self):
  150. client = nilmdb.Client(url = testurl)
  151. # Limit _max_data to 1 MB, since our test file is 1.5 MB
  152. old_max_data = nilmdb.client.client.StreamInserter._max_data
  153. nilmdb.client.client.StreamInserter._max_data = 1 * 1024 * 1024
  154. datetime_tz.localtz_set("America/New_York")
  155. testfile = "tests/data/prep-20120323T1000"
  156. start = datetime_tz.datetime_tz.smartparse("20120323T1000")
  157. start = start.totimestamp()
  158. rate = 120
  159. # First try a nonexistent path
  160. data = timestamper.TimestamperRate(testfile, start, 120)
  161. with assert_raises(ClientError) as e:
  162. result = client.stream_insert("/newton/no-such-path", data)
  163. in_("404 Not Found", str(e.exception))
  164. # Now try reversed timestamps
  165. data = timestamper.TimestamperRate(testfile, start, 120)
  166. data = reversed(list(data))
  167. with assert_raises(ClientError) as e:
  168. result = client.stream_insert("/newton/prep", data)
  169. in_("400 Bad Request", str(e.exception))
  170. in_("timestamp is not monotonically increasing", str(e.exception))
  171. # Now try empty data (no server request made)
  172. empty = cStringIO.StringIO("")
  173. data = timestamper.TimestamperRate(empty, start, 120)
  174. result = client.stream_insert("/newton/prep", data)
  175. eq_(result, None)
  176. # It's OK to insert an empty interval
  177. client.http.put("stream/insert", "", { "path": "/newton/prep",
  178. "start": 1, "end": 2 })
  179. eq_(list(client.stream_intervals("/newton/prep")), [[1, 2]])
  180. client.stream_remove("/newton/prep")
  181. eq_(list(client.stream_intervals("/newton/prep")), [])
  182. # Timestamps can be negative too
  183. client.http.put("stream/insert", "", { "path": "/newton/prep",
  184. "start": -2, "end": -1 })
  185. eq_(list(client.stream_intervals("/newton/prep")), [[-2, -1]])
  186. client.stream_remove("/newton/prep")
  187. eq_(list(client.stream_intervals("/newton/prep")), [])
  188. # Intervals that end at zero shouldn't be any different
  189. client.http.put("stream/insert", "", { "path": "/newton/prep",
  190. "start": -1, "end": 0 })
  191. eq_(list(client.stream_intervals("/newton/prep")), [[-1, 0]])
  192. client.stream_remove("/newton/prep")
  193. eq_(list(client.stream_intervals("/newton/prep")), [])
  194. # Try forcing a server request with equal start and end
  195. with assert_raises(ClientError) as e:
  196. client.http.put("stream/insert", "", { "path": "/newton/prep",
  197. "start": 0, "end": 0 })
  198. in_("400 Bad Request", str(e.exception))
  199. in_("start must precede end", str(e.exception))
  200. # Specify start/end (starts too late)
  201. data = timestamper.TimestamperRate(testfile, start, 120)
  202. with assert_raises(ClientError) as e:
  203. result = client.stream_insert("/newton/prep", data,
  204. start + 5, start + 120)
  205. in_("400 Bad Request", str(e.exception))
  206. in_("Data timestamp 1332511200.0 < start time 1332511205.0",
  207. str(e.exception))
  208. # Specify start/end (ends too early)
  209. data = timestamper.TimestamperRate(testfile, start, 120)
  210. with assert_raises(ClientError) as e:
  211. result = client.stream_insert("/newton/prep", data,
  212. start, start + 1)
  213. in_("400 Bad Request", str(e.exception))
  214. # Client chunks the input, so the exact timestamp here might change
  215. # if the chunk positions change.
  216. assert(re.search("Data timestamp 13325[0-9]+\.[0-9]+ "
  217. ">= end time 1332511201.0", str(e.exception))
  218. is not None)
  219. # Now do the real load
  220. data = timestamper.TimestamperRate(testfile, start, 120)
  221. result = client.stream_insert("/newton/prep", data,
  222. start, start + 119.999777)
  223. # Verify the intervals. Should be just one, even if the data
  224. # was inserted in chunks, due to nilmdb interval concatenation.
  225. intervals = list(client.stream_intervals("/newton/prep"))
  226. eq_(intervals, [[start, start + 119.999777]])
  227. # Try some overlapping data -- just insert it again
  228. data = timestamper.TimestamperRate(testfile, start, 120)
  229. with assert_raises(ClientError) as e:
  230. result = client.stream_insert("/newton/prep", data)
  231. in_("400 Bad Request", str(e.exception))
  232. in_("verlap", str(e.exception))
  233. nilmdb.client.client.StreamInserter._max_data = old_max_data
  234. client.close()
  235. def test_client_05_extractremove(self):
  236. # Misc tests for extract and remove. Most of them are in test_cmdline.
  237. client = nilmdb.Client(url = testurl)
  238. for x in client.stream_extract("/newton/prep", 999123, 999124):
  239. raise AssertionError("shouldn't be any data for this request")
  240. with assert_raises(ClientError) as e:
  241. client.stream_remove("/newton/prep", 123, 120)
  242. # Test count
  243. eq_(client.stream_count("/newton/prep"), 14400)
  244. client.close()
  245. def test_client_06_generators(self):
  246. # A lot of the client functionality is already tested by test_cmdline,
  247. # but this gets a bit more coverage that cmdline misses.
  248. client = nilmdb.Client(url = testurl)
  249. # Trigger a client error in generator
  250. start = datetime_tz.datetime_tz.smartparse("20120323T2000")
  251. end = datetime_tz.datetime_tz.smartparse("20120323T1000")
  252. for function in [ client.stream_intervals, client.stream_extract ]:
  253. with assert_raises(ClientError) as e:
  254. function("/newton/prep",
  255. start.totimestamp(),
  256. end.totimestamp()).next()
  257. in_("400 Bad Request", str(e.exception))
  258. in_("start must precede end", str(e.exception))
  259. # Trigger a curl error in generator
  260. with assert_raises(ServerError) as e:
  261. client.http.get_gen("http://nosuchurl/").next()
  262. # Trigger a curl error in generator
  263. with assert_raises(ServerError) as e:
  264. client.http.get_gen("http://nosuchurl/").next()
  265. # Check 404 for missing streams
  266. for function in [ client.stream_intervals, client.stream_extract ]:
  267. with assert_raises(ClientError) as e:
  268. function("/no/such/stream").next()
  269. in_("404 Not Found", str(e.exception))
  270. in_("No such stream", str(e.exception))
  271. client.close()
  272. def test_client_07_headers(self):
  273. # Make sure that /stream/intervals and /stream/extract
  274. # properly return streaming, chunked, text/plain response.
  275. # Pokes around in client.http internals a bit to look at the
  276. # response headers.
  277. client = nilmdb.Client(url = testurl)
  278. http = client.http
  279. # Use a warning rather than returning a test failure for the
  280. # transfer-encoding, so that we can still disable chunked
  281. # responses for debugging.
  282. def headers():
  283. h = ""
  284. for (k, v) in http._last_response.headers.items():
  285. h += k + ": " + v + "\n"
  286. return h.lower()
  287. # Intervals
  288. x = http.get("stream/intervals", { "path": "/newton/prep" })
  289. if "transfer-encoding: chunked" not in headers():
  290. warnings.warn("Non-chunked HTTP response for /stream/intervals")
  291. if "content-type: application/x-json-stream" not in headers():
  292. raise AssertionError("/stream/intervals content type "
  293. "is not application/x-json-stream:\n" +
  294. headers())
  295. # Extract
  296. x = http.get("stream/extract",
  297. { "path": "/newton/prep",
  298. "start": "123",
  299. "end": "124" })
  300. if "transfer-encoding: chunked" not in headers():
  301. warnings.warn("Non-chunked HTTP response for /stream/extract")
  302. if "content-type: text/plain;charset=utf-8" not in headers():
  303. raise AssertionError("/stream/extract is not text/plain:\n" +
  304. headers())
  305. client.close()
  306. def test_client_08_unicode(self):
  307. # Try both with and without posting JSON
  308. for post_json in (False, True):
  309. # Basic Unicode tests
  310. client = nilmdb.Client(url = testurl, post_json = post_json)
  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))