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.
 
 
 

596 lines
23 KiB

  1. # -*- coding: utf-8 -*-
  2. """NilmDB
  3. Object that represents a NILM database file.
  4. Manages both the SQL database and the table storage backend.
  5. """
  6. # Need absolute_import so that "import nilmdb" won't pull in
  7. # nilmdb.py, but will pull the parent nilmdb module instead.
  8. from __future__ import absolute_import
  9. import nilmdb.utils
  10. from nilmdb.utils.printf import *
  11. from nilmdb.server.interval import (Interval, DBInterval,
  12. IntervalSet, IntervalError)
  13. from nilmdb.server import bulkdata
  14. from nilmdb.server.errors import NilmDBError, StreamError, OverlapError
  15. import sqlite3
  16. import os
  17. import errno
  18. import bisect
  19. # Note about performance and transactions:
  20. #
  21. # Committing a transaction in the default sync mode (PRAGMA synchronous=FULL)
  22. # takes about 125msec. sqlite3 will commit transactions at 3 times:
  23. # 1: explicit con.commit()
  24. # 2: between a series of DML commands and non-DML commands, e.g.
  25. # after a series of INSERT, SELECT, but before a CREATE TABLE or PRAGMA.
  26. # 3: at the end of an explicit transaction, e.g. "with self.con as con:"
  27. #
  28. # To speed things up, we can set 'PRAGMA synchronous=OFF'. Or, it
  29. # seems that 'PRAGMA synchronous=NORMAL' and 'PRAGMA journal_mode=WAL'
  30. # give an equivalent speedup more safely. That is what is used here.
  31. _sql_schema_updates = {
  32. 0: """
  33. -- All streams
  34. CREATE TABLE streams(
  35. id INTEGER PRIMARY KEY, -- stream ID
  36. path TEXT UNIQUE NOT NULL, -- path, e.g. '/newton/prep'
  37. layout TEXT NOT NULL -- layout name, e.g. float32_8
  38. );
  39. -- Individual timestamped ranges in those streams.
  40. -- For a given start_time and end_time, this tells us that the
  41. -- data is stored between start_pos and end_pos.
  42. -- Times are stored as μs since Unix epoch
  43. -- Positions are opaque: PyTables rows, file offsets, etc.
  44. --
  45. -- Note: end_pos points to the row _after_ end_time, so end_pos-1
  46. -- is the last valid row.
  47. CREATE TABLE ranges(
  48. stream_id INTEGER NOT NULL,
  49. start_time INTEGER NOT NULL,
  50. end_time INTEGER NOT NULL,
  51. start_pos INTEGER NOT NULL,
  52. end_pos INTEGER NOT NULL
  53. );
  54. CREATE INDEX _ranges_index ON ranges (stream_id, start_time, end_time);
  55. """,
  56. 1: """
  57. -- Generic dictionary-type metadata that can be associated with a stream
  58. CREATE TABLE metadata(
  59. stream_id INTEGER NOT NULL,
  60. key TEXT NOT NULL,
  61. value TEXT
  62. );
  63. """,
  64. }
  65. @nilmdb.utils.must_close()
  66. class NilmDB(object):
  67. verbose = 0
  68. def __init__(self, basepath, max_results=None,
  69. bulkdata_args=None):
  70. if bulkdata_args is None:
  71. bulkdata_args = {}
  72. # set up path
  73. self.basepath = os.path.abspath(basepath)
  74. # Create the database path if it doesn't exist
  75. try:
  76. os.makedirs(self.basepath)
  77. except OSError as e:
  78. if e.errno != errno.EEXIST:
  79. raise IOError("can't create tree " + self.basepath)
  80. # Our data goes inside it
  81. self.data = bulkdata.BulkData(self.basepath, **bulkdata_args)
  82. # SQLite database too
  83. sqlfilename = os.path.join(self.basepath, "data.sql")
  84. self.con = sqlite3.connect(sqlfilename, check_same_thread = True)
  85. self._sql_schema_update()
  86. # See big comment at top about the performance implications of this
  87. self.con.execute("PRAGMA synchronous=NORMAL")
  88. self.con.execute("PRAGMA journal_mode=WAL")
  89. # Approximate largest number of elements that we want to send
  90. # in a single reply (for stream_intervals, stream_extract)
  91. if max_results:
  92. self.max_results = max_results
  93. else:
  94. self.max_results = 16384
  95. def get_basepath(self):
  96. return self.basepath
  97. def close(self):
  98. if self.con:
  99. self.con.commit()
  100. self.con.close()
  101. self.data.close()
  102. def _sql_schema_update(self):
  103. cur = self.con.cursor()
  104. version = cur.execute("PRAGMA user_version").fetchone()[0]
  105. oldversion = version
  106. while version in _sql_schema_updates:
  107. cur.executescript(_sql_schema_updates[version])
  108. version = version + 1
  109. if self.verbose: # pragma: no cover
  110. printf("Schema updated to %d\n", version)
  111. if version != oldversion:
  112. with self.con:
  113. cur.execute("PRAGMA user_version = {v:d}".format(v=version))
  114. def _check_user_times(self, start, end):
  115. if start is None:
  116. start = -1e12
  117. if end is None:
  118. end = 1e12
  119. if start >= end:
  120. raise NilmDBError("start must precede end")
  121. return (start, end)
  122. @nilmdb.utils.lru_cache(size = 16)
  123. def _get_intervals(self, stream_id):
  124. """
  125. Return a mutable IntervalSet corresponding to the given stream ID.
  126. """
  127. iset = IntervalSet()
  128. result = self.con.execute("SELECT start_time, end_time, "
  129. "start_pos, end_pos "
  130. "FROM ranges "
  131. "WHERE stream_id=?", (stream_id,))
  132. try:
  133. for (start_time, end_time, start_pos, end_pos) in result:
  134. iset += DBInterval(start_time, end_time,
  135. start_time, end_time,
  136. start_pos, end_pos)
  137. except IntervalError: # pragma: no cover
  138. raise NilmDBError("unexpected overlap in ranges table!")
  139. return iset
  140. def _sql_interval_insert(self, id, start, end, start_pos, end_pos):
  141. """Helper that adds interval to the SQL database only"""
  142. self.con.execute("INSERT INTO ranges "
  143. "(stream_id,start_time,end_time,start_pos,end_pos) "
  144. "VALUES (?,?,?,?,?)",
  145. (id, start, end, start_pos, end_pos))
  146. def _sql_interval_delete(self, id, start, end, start_pos, end_pos):
  147. """Helper that removes interval from the SQL database only"""
  148. self.con.execute("DELETE FROM ranges WHERE "
  149. "stream_id=? AND start_time=? AND "
  150. "end_time=? AND start_pos=? AND end_pos=?",
  151. (id, start, end, start_pos, end_pos))
  152. def _add_interval(self, stream_id, interval, start_pos, end_pos):
  153. """
  154. Add interval to the internal interval cache, and to the database.
  155. Note: arguments must be ints (not numpy.int64, etc)
  156. """
  157. # Load this stream's intervals
  158. iset = self._get_intervals(stream_id)
  159. # Check for overlap
  160. if iset.intersects(interval): # pragma: no cover (gets caught earlier)
  161. raise NilmDBError("new interval overlaps existing data")
  162. # Check for adjacency. If there's a stream in the database
  163. # that ends exactly when this one starts, and the database
  164. # rows match up, we can make one interval that covers the
  165. # time range [adjacent.start -> interval.end)
  166. # and database rows [ adjacent.start_pos -> end_pos ].
  167. # Only do this if the resulting interval isn't too large.
  168. max_merged_rows = 8000 * 60 * 60 * 1.05 # 1.05 hours at 8 KHz
  169. adjacent = iset.find_end(interval.start)
  170. if (adjacent is not None and
  171. start_pos == adjacent.db_endpos and
  172. (end_pos - adjacent.db_startpos) < max_merged_rows):
  173. # First delete the old one, both from our iset and the
  174. # database
  175. iset -= adjacent
  176. self._sql_interval_delete(stream_id,
  177. adjacent.db_start, adjacent.db_end,
  178. adjacent.db_startpos, adjacent.db_endpos)
  179. # Now update our interval so the fallthrough add is
  180. # correct.
  181. interval.start = adjacent.start
  182. start_pos = adjacent.db_startpos
  183. # Add the new interval to the iset
  184. iset.iadd_nocheck(DBInterval(interval.start, interval.end,
  185. interval.start, interval.end,
  186. start_pos, end_pos))
  187. # Insert into the database
  188. self._sql_interval_insert(stream_id, interval.start, interval.end,
  189. int(start_pos), int(end_pos))
  190. self.con.commit()
  191. def _remove_interval(self, stream_id, original, remove):
  192. """
  193. Remove an interval from the internal cache and the database.
  194. stream_id: id of stream
  195. original: original DBInterval; must be already present in DB
  196. to_remove: DBInterval to remove; must be subset of 'original'
  197. """
  198. # Just return if we have nothing to remove
  199. if remove.start == remove.end: # pragma: no cover
  200. return
  201. # Load this stream's intervals
  202. iset = self._get_intervals(stream_id)
  203. # Remove existing interval from the cached set and the database
  204. iset -= original
  205. self._sql_interval_delete(stream_id,
  206. original.db_start, original.db_end,
  207. original.db_startpos, original.db_endpos)
  208. # Add back the intervals that would be left over if the
  209. # requested interval is removed. There may be two of them, if
  210. # the removed piece was in the middle.
  211. def add(iset, start, end, start_pos, end_pos):
  212. iset += DBInterval(start, end, start, end, start_pos, end_pos)
  213. self._sql_interval_insert(stream_id, start, end, start_pos, end_pos)
  214. if original.start != remove.start:
  215. # Interval before the removed region
  216. add(iset, original.start, remove.start,
  217. original.db_startpos, remove.db_startpos)
  218. if original.end != remove.end:
  219. # Interval after the removed region
  220. add(iset, remove.end, original.end,
  221. remove.db_endpos, original.db_endpos)
  222. # Commit SQL changes
  223. self.con.commit()
  224. return
  225. def stream_list(self, path = None, layout = None, extended = False):
  226. """Return list of lists of all streams in the database.
  227. If path is specified, include only streams with a path that
  228. matches the given string.
  229. If layout is specified, include only streams with a layout
  230. that matches the given string.
  231. If extended = False, returns a list of lists containing
  232. the path and layout: [ path, layout ]
  233. If extended = True, returns a list of lists containing
  234. more information:
  235. path
  236. layout
  237. interval_min (earliest interval start)
  238. interval_max (latest interval end)
  239. rows (total number of rows of data)
  240. seconds (total time covered by this stream)
  241. """
  242. params = ()
  243. query = "SELECT streams.path, streams.layout"
  244. if extended:
  245. query += ", min(ranges.start_time), max(ranges.end_time) "
  246. query += ", coalesce(sum(ranges.end_pos - ranges.start_pos), 0) "
  247. query += ", coalesce(sum(ranges.end_time - ranges.start_time), 0) "
  248. query += " FROM streams"
  249. if extended:
  250. query += " LEFT JOIN ranges ON streams.id = ranges.stream_id"
  251. query += " WHERE 1=1"
  252. if layout is not None:
  253. query += " AND streams.layout=?"
  254. params += (layout,)
  255. if path is not None:
  256. query += " AND streams.path=?"
  257. params += (path,)
  258. query += " GROUP BY streams.id ORDER BY streams.path"
  259. result = self.con.execute(query, params).fetchall()
  260. return [ list(x) for x in result ]
  261. def stream_intervals(self, path, start = None, end = None, diffpath = None):
  262. """
  263. List all intervals in 'path' between 'start' and 'end'. If
  264. 'diffpath' is not none, list instead the set-difference
  265. between the intervals in the two streams; i.e. all interval
  266. ranges that are present in 'path' but not 'path2'.
  267. Returns (intervals, restart) tuple.
  268. intervals is a list of [start,end] timestamps of all intervals
  269. that exist for path, between start and end.
  270. restart, if nonzero, means that there were too many results to
  271. return in a single request. The data is complete from the
  272. starting timestamp to the point at which it was truncated,
  273. and a new request with a start time of 'restart' will fetch
  274. the next block of data.
  275. """
  276. stream_id = self._stream_id(path)
  277. intervals = self._get_intervals(stream_id)
  278. if diffpath:
  279. diffstream_id = self._stream_id(diffpath)
  280. diffintervals = self._get_intervals(diffstream_id)
  281. (start, end) = self._check_user_times(start, end)
  282. requested = Interval(start, end)
  283. result = []
  284. if diffpath:
  285. getter = intervals.set_difference(diffintervals, requested)
  286. else:
  287. getter = intervals.intersection(requested)
  288. for n, i in enumerate(getter):
  289. if n >= self.max_results:
  290. restart = i.start
  291. break
  292. result.append([i.start, i.end])
  293. else:
  294. restart = 0
  295. return (result, restart)
  296. def stream_create(self, path, layout_name):
  297. """Create a new table in the database.
  298. path: path to the data (e.g. '/newton/prep').
  299. Paths must contain at least two elements, e.g.:
  300. /newton/prep
  301. /newton/raw
  302. /newton/upstairs/prep
  303. /newton/upstairs/raw
  304. layout_name: string for nilmdb.layout.get_named(), e.g. 'float32_8'
  305. """
  306. # Create the bulk storage. Raises ValueError on error, which we
  307. # pass along.
  308. self.data.create(path, layout_name)
  309. # Insert into SQL database once the bulk storage is happy
  310. with self.con as con:
  311. con.execute("INSERT INTO streams (path, layout) VALUES (?,?)",
  312. (path, layout_name))
  313. def _stream_id(self, path):
  314. """Return unique stream ID"""
  315. result = self.con.execute("SELECT id FROM streams WHERE path=?",
  316. (path,)).fetchone()
  317. if result is None:
  318. raise StreamError("No stream at path " + path)
  319. return result[0]
  320. def stream_set_metadata(self, path, data):
  321. """Set stream metadata from a dictionary, e.g.
  322. { description = 'Downstairs lighting',
  323. v_scaling = 123.45 }
  324. This replaces all existing metadata.
  325. """
  326. stream_id = self._stream_id(path)
  327. with self.con as con:
  328. con.execute("DELETE FROM metadata WHERE stream_id=?", (stream_id,))
  329. for key in data:
  330. if data[key] != '':
  331. con.execute("INSERT INTO metadata VALUES (?, ?, ?)",
  332. (stream_id, key, data[key]))
  333. def stream_get_metadata(self, path):
  334. """Return stream metadata as a dictionary."""
  335. stream_id = self._stream_id(path)
  336. result = self.con.execute("SELECT metadata.key, metadata.value "
  337. "FROM metadata "
  338. "WHERE metadata.stream_id=?", (stream_id,))
  339. data = {}
  340. for (key, value) in result:
  341. data[key] = value
  342. return data
  343. def stream_update_metadata(self, path, newdata):
  344. """Update stream metadata from a dictionary"""
  345. data = self.stream_get_metadata(path)
  346. data.update(newdata)
  347. self.stream_set_metadata(path, data)
  348. def stream_rename(self, oldpath, newpath):
  349. """Rename a stream."""
  350. stream_id = self._stream_id(oldpath)
  351. # Rename the data
  352. self.data.rename(oldpath, newpath)
  353. # Rename the stream in the database
  354. with self.con as con:
  355. con.execute("UPDATE streams SET path=? WHERE id=?",
  356. (newpath, stream_id))
  357. def stream_destroy(self, path):
  358. """Fully remove a table and all of its data from the database.
  359. No way to undo it! Metadata is removed."""
  360. stream_id = self._stream_id(path)
  361. # Delete the cached interval data (if it was cached)
  362. self._get_intervals.cache_remove(self, stream_id)
  363. # Delete the data
  364. self.data.destroy(path)
  365. # Delete metadata, stream, intervals
  366. with self.con as con:
  367. con.execute("DELETE FROM metadata WHERE stream_id=?", (stream_id,))
  368. con.execute("DELETE FROM ranges WHERE stream_id=?", (stream_id,))
  369. con.execute("DELETE FROM streams WHERE id=?", (stream_id,))
  370. def stream_insert(self, path, start, end, data):
  371. """Insert new data into the database.
  372. path: Path at which to add the data
  373. start: Starting timestamp
  374. end: Ending timestamp
  375. data: Textual data, formatted according to the layout of path
  376. """
  377. # First check for basic overlap using timestamp info given.
  378. stream_id = self._stream_id(path)
  379. iset = self._get_intervals(stream_id)
  380. interval = Interval(start, end)
  381. if iset.intersects(interval):
  382. raise OverlapError("new data overlaps existing data at range: "
  383. + str(iset & interval))
  384. # Tenatively append the data. This will raise a ValueError if
  385. # there are any parse errors.
  386. table = self.data.getnode(path)
  387. row_start = table.nrows
  388. table.append_string(data, start, end)
  389. row_end = table.nrows
  390. # Insert the record into the sql database.
  391. self._add_interval(stream_id, interval, row_start, row_end)
  392. # And that's all
  393. return
  394. def _find_start(self, table, dbinterval):
  395. """
  396. Given a DBInterval, find the row in the database that
  397. corresponds to the start time. Return the first database
  398. position with a timestamp (first element) greater than or
  399. equal to 'start'.
  400. """
  401. # Optimization for the common case where an interval wasn't truncated
  402. if dbinterval.start == dbinterval.db_start:
  403. return dbinterval.db_startpos
  404. return bisect.bisect_left(bulkdata.TimestampOnlyTable(table),
  405. dbinterval.start,
  406. dbinterval.db_startpos,
  407. dbinterval.db_endpos)
  408. def _find_end(self, table, dbinterval):
  409. """
  410. Given a DBInterval, find the row in the database that follows
  411. the end time. Return the first database position after the
  412. row with timestamp (first element) greater than or equal
  413. to 'end'.
  414. """
  415. # Optimization for the common case where an interval wasn't truncated
  416. if dbinterval.end == dbinterval.db_end:
  417. return dbinterval.db_endpos
  418. # Note that we still use bisect_left here, because we don't
  419. # want to include the given timestamp in the results. This is
  420. # so a queries like 1:00 -> 2:00 and 2:00 -> 3:00 return
  421. # non-overlapping data.
  422. return bisect.bisect_left(bulkdata.TimestampOnlyTable(table),
  423. dbinterval.end,
  424. dbinterval.db_startpos,
  425. dbinterval.db_endpos)
  426. def stream_extract(self, path, start = None, end = None, count = False):
  427. """
  428. Returns (data, restart) tuple.
  429. data is ASCII-formatted data from the database, formatted
  430. according to the layout of the stream.
  431. restart, if nonzero, means that there were too many results to
  432. return in a single request. The data is complete from the
  433. starting timestamp to the point at which it was truncated,
  434. and a new request with a start time of 'restart' will fetch
  435. the next block of data.
  436. count, if true, means to not return raw data, but just the count
  437. of rows that would have been returned. This is much faster
  438. than actually fetching the data. It is not limited by
  439. max_results.
  440. """
  441. stream_id = self._stream_id(path)
  442. table = self.data.getnode(path)
  443. intervals = self._get_intervals(stream_id)
  444. (start, end) = self._check_user_times(start, end)
  445. requested = Interval(start, end)
  446. result = []
  447. matched = 0
  448. remaining = self.max_results
  449. restart = 0
  450. for interval in intervals.intersection(requested):
  451. # Reading single rows from the table is too slow, so
  452. # we use two bisections to find both the starting and
  453. # ending row for this particular interval, then
  454. # read the entire range as one slice.
  455. row_start = self._find_start(table, interval)
  456. row_end = self._find_end(table, interval)
  457. if count:
  458. matched += row_end - row_start
  459. continue
  460. # Shorten it if we'll hit the maximum number of results
  461. row_max = row_start + remaining
  462. if row_max < row_end:
  463. row_end = row_max
  464. restart = table[row_max][0]
  465. # Gather these results up
  466. result.append(table.get_as_text(row_start, row_end))
  467. # Count them
  468. remaining -= row_end - row_start
  469. if restart:
  470. break
  471. if count:
  472. return matched
  473. return ("".join(result), restart)
  474. def stream_remove(self, path, start = None, end = None):
  475. """
  476. Remove data from the specified time interval within a stream.
  477. Removes all data in the interval [start, end), and intervals
  478. are truncated or split appropriately. Returns the number of
  479. data points removed.
  480. """
  481. stream_id = self._stream_id(path)
  482. table = self.data.getnode(path)
  483. intervals = self._get_intervals(stream_id)
  484. (start, end) = self._check_user_times(start, end)
  485. to_remove = Interval(start, end)
  486. removed = 0
  487. # Can't remove intervals from within the iterator, so we need to
  488. # remember what's currently in the intersection now.
  489. all_candidates = list(intervals.intersection(to_remove, orig = True))
  490. for (dbint, orig) in all_candidates:
  491. # Find row start and end
  492. row_start = self._find_start(table, dbint)
  493. row_end = self._find_end(table, dbint)
  494. # Adjust the DBInterval to match the newly found ends
  495. dbint.db_start = dbint.start
  496. dbint.db_end = dbint.end
  497. dbint.db_startpos = row_start
  498. dbint.db_endpos = row_end
  499. # Remove interval from the database
  500. self._remove_interval(stream_id, orig, dbint)
  501. # Remove data from the underlying table storage
  502. table.remove(row_start, row_end)
  503. # Count how many were removed
  504. removed += row_end - row_start
  505. return removed