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.
 
 
 

562 lines
21 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
  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 up testing, or if this transaction speed becomes an issue,
  29. # the sync=False option to NilmDB.__init__ will set PRAGMA synchronous=OFF.
  30. # Don't touch old entries -- just add new ones.
  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, sync=True, 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. # We use check_same_thread = False, assuming that the rest
  85. # of the code (e.g. Server) will be smart and not access this
  86. # database from multiple threads simultaneously. Otherwise
  87. # false positives will occur when the database is only opened
  88. # in one thread, and only accessed in another.
  89. self.con = sqlite3.connect(sqlfilename, check_same_thread = False)
  90. self._sql_schema_update()
  91. # See big comment at top about the performance implications of this
  92. if sync:
  93. self.con.execute("PRAGMA synchronous=FULL")
  94. else:
  95. self.con.execute("PRAGMA synchronous=OFF")
  96. # Approximate largest number of elements that we want to send
  97. # in a single reply (for stream_intervals, stream_extract)
  98. if max_results:
  99. self.max_results = max_results
  100. else:
  101. self.max_results = 16384
  102. def get_basepath(self):
  103. return self.basepath
  104. def close(self):
  105. if self.con:
  106. self.con.commit()
  107. self.con.close()
  108. self.data.close()
  109. def _sql_schema_update(self):
  110. cur = self.con.cursor()
  111. version = cur.execute("PRAGMA user_version").fetchone()[0]
  112. oldversion = version
  113. while version in _sql_schema_updates:
  114. cur.executescript(_sql_schema_updates[version])
  115. version = version + 1
  116. if self.verbose: # pragma: no cover
  117. printf("Schema updated to %d\n", version)
  118. if version != oldversion:
  119. with self.con:
  120. cur.execute("PRAGMA user_version = {v:d}".format(v=version))
  121. def _fill_in_limits(self, start, end):
  122. if start is None:
  123. start = -1e12
  124. if end is None:
  125. end = 1e12
  126. return (start, end)
  127. @nilmdb.utils.lru_cache(size = 16)
  128. def _get_intervals(self, stream_id):
  129. """
  130. Return a mutable IntervalSet corresponding to the given stream ID.
  131. """
  132. iset = IntervalSet()
  133. result = self.con.execute("SELECT start_time, end_time, "
  134. "start_pos, end_pos "
  135. "FROM ranges "
  136. "WHERE stream_id=?", (stream_id,))
  137. try:
  138. for (start_time, end_time, start_pos, end_pos) in result:
  139. iset += DBInterval(start_time, end_time,
  140. start_time, end_time,
  141. start_pos, end_pos)
  142. except IntervalError: # pragma: no cover
  143. raise NilmDBError("unexpected overlap in ranges table!")
  144. return iset
  145. def _sql_interval_insert(self, id, start, end, start_pos, end_pos):
  146. """Helper that adds interval to the SQL database only"""
  147. self.con.execute("INSERT INTO ranges "
  148. "(stream_id,start_time,end_time,start_pos,end_pos) "
  149. "VALUES (?,?,?,?,?)",
  150. (id, start, end, start_pos, end_pos))
  151. def _sql_interval_delete(self, id, start, end, start_pos, end_pos):
  152. """Helper that removes interval from the SQL database only"""
  153. self.con.execute("DELETE FROM ranges WHERE "
  154. "stream_id=? AND start_time=? AND "
  155. "end_time=? AND start_pos=? AND end_pos=?",
  156. (id, start, end, start_pos, end_pos))
  157. def _add_interval(self, stream_id, interval, start_pos, end_pos):
  158. """
  159. Add interval to the internal interval cache, and to the database.
  160. Note: arguments must be ints (not numpy.int64, etc)
  161. """
  162. # Load this stream's intervals
  163. iset = self._get_intervals(stream_id)
  164. # Check for overlap
  165. if iset.intersects(interval): # pragma: no cover (gets caught earlier)
  166. raise NilmDBError("new interval overlaps existing data")
  167. # Check for adjacency. If there's a stream in the database
  168. # that ends exactly when this one starts, and the database
  169. # rows match up, we can make one interval that covers the
  170. # time range [adjacent.start -> interval.end)
  171. # and database rows [ adjacent.start_pos -> end_pos ].
  172. # Only do this if the resulting interval isn't too large.
  173. max_merged_rows = 8000 * 60 * 60 * 1.05 # 1.05 hours at 8 KHz
  174. adjacent = iset.find_end(interval.start)
  175. if (adjacent is not None and
  176. start_pos == adjacent.db_endpos and
  177. (end_pos - adjacent.db_startpos) < max_merged_rows):
  178. # First delete the old one, both from our iset and the
  179. # database
  180. iset -= adjacent
  181. self._sql_interval_delete(stream_id,
  182. adjacent.db_start, adjacent.db_end,
  183. adjacent.db_startpos, adjacent.db_endpos)
  184. # Now update our interval so the fallthrough add is
  185. # correct.
  186. interval.start = adjacent.start
  187. start_pos = adjacent.db_startpos
  188. # Add the new interval to the iset
  189. iset.iadd_nocheck(DBInterval(interval.start, interval.end,
  190. interval.start, interval.end,
  191. start_pos, end_pos))
  192. # Insert into the database
  193. self._sql_interval_insert(stream_id, interval.start, interval.end,
  194. int(start_pos), int(end_pos))
  195. self.con.commit()
  196. def _remove_interval(self, stream_id, original, remove):
  197. """
  198. Remove an interval from the internal cache and the database.
  199. stream_id: id of stream
  200. original: original DBInterval; must be already present in DB
  201. to_remove: DBInterval to remove; must be subset of 'original'
  202. """
  203. # Just return if we have nothing to remove
  204. if remove.start == remove.end: # pragma: no cover
  205. return
  206. # Load this stream's intervals
  207. iset = self._get_intervals(stream_id)
  208. # Remove existing interval from the cached set and the database
  209. iset -= original
  210. self._sql_interval_delete(stream_id,
  211. original.db_start, original.db_end,
  212. original.db_startpos, original.db_endpos)
  213. # Add back the intervals that would be left over if the
  214. # requested interval is removed. There may be two of them, if
  215. # the removed piece was in the middle.
  216. def add(iset, start, end, start_pos, end_pos):
  217. iset += DBInterval(start, end, start, end, start_pos, end_pos)
  218. self._sql_interval_insert(stream_id, start, end, start_pos, end_pos)
  219. if original.start != remove.start:
  220. # Interval before the removed region
  221. add(iset, original.start, remove.start,
  222. original.db_startpos, remove.db_startpos)
  223. if original.end != remove.end:
  224. # Interval after the removed region
  225. add(iset, remove.end, original.end,
  226. remove.db_endpos, original.db_endpos)
  227. # Commit SQL changes
  228. self.con.commit()
  229. return
  230. def stream_list(self, path = None, layout = None):
  231. """Return list of [path, layout] lists of all streams
  232. in the database.
  233. If path is specified, include only streams with a path that
  234. matches the given string.
  235. If layout is specified, include only streams with a layout
  236. that matches the given string.
  237. """
  238. where = "WHERE 1=1"
  239. params = ()
  240. if layout:
  241. where += " AND layout=?"
  242. params += (layout,)
  243. if path:
  244. where += " AND path=?"
  245. params += (path,)
  246. result = self.con.execute("SELECT path, layout "
  247. "FROM streams " + where, params).fetchall()
  248. return sorted(list(x) for x in result)
  249. def stream_intervals(self, path, start = None, end = None):
  250. """
  251. Returns (intervals, restart) tuple.
  252. intervals is a list of [start,end] timestamps of all intervals
  253. that exist for path, between start and end.
  254. restart, if nonzero, means that there were too many results to
  255. return in a single request. The data is complete from the
  256. starting timestamp to the point at which it was truncated,
  257. and a new request with a start time of 'restart' will fetch
  258. the next block of data.
  259. """
  260. stream_id = self._stream_id(path)
  261. intervals = self._get_intervals(stream_id)
  262. (start, end) = self._fill_in_limits(start, end)
  263. requested = Interval(start, end)
  264. result = []
  265. for n, i in enumerate(intervals.intersection(requested)):
  266. if n >= self.max_results:
  267. restart = i.start
  268. break
  269. result.append([i.start, i.end])
  270. else:
  271. restart = 0
  272. return (result, restart)
  273. def stream_create(self, path, layout_name):
  274. """Create a new table in the database.
  275. path: path to the data (e.g. '/newton/prep').
  276. Paths must contain at least two elements, e.g.:
  277. /newton/prep
  278. /newton/raw
  279. /newton/upstairs/prep
  280. /newton/upstairs/raw
  281. layout_name: string for nilmdb.layout.get_named(), e.g. 'float32_8'
  282. """
  283. # Create the bulk storage. Raises ValueError on error, which we
  284. # pass along.
  285. self.data.create(path, layout_name)
  286. # Insert into SQL database once the bulk storage is happy
  287. with self.con as con:
  288. con.execute("INSERT INTO streams (path, layout) VALUES (?,?)",
  289. (path, layout_name))
  290. def _stream_id(self, path):
  291. """Return unique stream ID"""
  292. result = self.con.execute("SELECT id FROM streams WHERE path=?",
  293. (path,)).fetchone()
  294. if result is None:
  295. raise StreamError("No stream at path " + path)
  296. return result[0]
  297. def stream_set_metadata(self, path, data):
  298. """Set stream metadata from a dictionary, e.g.
  299. { description = 'Downstairs lighting',
  300. v_scaling = 123.45 }
  301. This replaces all existing metadata.
  302. """
  303. stream_id = self._stream_id(path)
  304. with self.con as con:
  305. con.execute("DELETE FROM metadata WHERE stream_id=?", (stream_id,))
  306. for key in data:
  307. if data[key] != '':
  308. con.execute("INSERT INTO metadata VALUES (?, ?, ?)",
  309. (stream_id, key, data[key]))
  310. def stream_get_metadata(self, path):
  311. """Return stream metadata as a dictionary."""
  312. stream_id = self._stream_id(path)
  313. result = self.con.execute("SELECT metadata.key, metadata.value "
  314. "FROM metadata "
  315. "WHERE metadata.stream_id=?", (stream_id,))
  316. data = {}
  317. for (key, value) in result:
  318. data[key] = value
  319. return data
  320. def stream_update_metadata(self, path, newdata):
  321. """Update stream metadata from a dictionary"""
  322. data = self.stream_get_metadata(path)
  323. data.update(newdata)
  324. self.stream_set_metadata(path, data)
  325. def stream_destroy(self, path):
  326. """Fully remove a table and all of its data from the database.
  327. No way to undo it! Metadata is removed."""
  328. stream_id = self._stream_id(path)
  329. # Delete the cached interval data (if it was cached)
  330. self._get_intervals.cache_remove(self, stream_id)
  331. # Delete the data
  332. self.data.destroy(path)
  333. # Delete metadata, stream, intervals
  334. with self.con as con:
  335. con.execute("DELETE FROM metadata WHERE stream_id=?", (stream_id,))
  336. con.execute("DELETE FROM ranges WHERE stream_id=?", (stream_id,))
  337. con.execute("DELETE FROM streams WHERE id=?", (stream_id,))
  338. def stream_insert(self, path, start, end, data):
  339. """Insert new data into the database.
  340. path: Path at which to add the data
  341. start: Starting timestamp
  342. end: Ending timestamp
  343. data: Rows of data, to be passed to bulkdata table.append
  344. method. E.g. nilmdb.layout.Parser.data
  345. """
  346. # First check for basic overlap using timestamp info given.
  347. stream_id = self._stream_id(path)
  348. iset = self._get_intervals(stream_id)
  349. interval = Interval(start, end)
  350. if iset.intersects(interval):
  351. raise OverlapError("new data overlaps existing data at range: "
  352. + str(iset & interval))
  353. # Insert the data
  354. table = self.data.getnode(path)
  355. row_start = table.nrows
  356. table.append(data)
  357. row_end = table.nrows
  358. # Insert the record into the sql database.
  359. self._add_interval(stream_id, interval, row_start, row_end)
  360. # And that's all
  361. return
  362. def _find_start(self, table, dbinterval):
  363. """
  364. Given a DBInterval, find the row in the database that
  365. corresponds to the start time. Return the first database
  366. position with a timestamp (first element) greater than or
  367. equal to 'start'.
  368. """
  369. # Optimization for the common case where an interval wasn't truncated
  370. if dbinterval.start == dbinterval.db_start:
  371. return dbinterval.db_startpos
  372. return bisect.bisect_left(bulkdata.TimestampOnlyTable(table),
  373. dbinterval.start,
  374. dbinterval.db_startpos,
  375. dbinterval.db_endpos)
  376. def _find_end(self, table, dbinterval):
  377. """
  378. Given a DBInterval, find the row in the database that follows
  379. the end time. Return the first database position after the
  380. row with timestamp (first element) greater than or equal
  381. to 'end'.
  382. """
  383. # Optimization for the common case where an interval wasn't truncated
  384. if dbinterval.end == dbinterval.db_end:
  385. return dbinterval.db_endpos
  386. # Note that we still use bisect_left here, because we don't
  387. # want to include the given timestamp in the results. This is
  388. # so a queries like 1:00 -> 2:00 and 2:00 -> 3:00 return
  389. # non-overlapping data.
  390. return bisect.bisect_left(bulkdata.TimestampOnlyTable(table),
  391. dbinterval.end,
  392. dbinterval.db_startpos,
  393. dbinterval.db_endpos)
  394. def stream_extract(self, path, start = None, end = None, count = False):
  395. """
  396. Returns (data, restart) tuple.
  397. data is a list of raw data from the database, suitable for
  398. passing to e.g. nilmdb.layout.Formatter to translate into
  399. textual form.
  400. restart, if nonzero, means that there were too many results to
  401. return in a single request. The data is complete from the
  402. starting timestamp to the point at which it was truncated,
  403. and a new request with a start time of 'restart' will fetch
  404. the next block of data.
  405. count, if true, means to not return raw data, but just the count
  406. of rows that would have been returned. This is much faster
  407. than actually fetching the data. It is not limited by
  408. max_results.
  409. """
  410. stream_id = self._stream_id(path)
  411. table = self.data.getnode(path)
  412. intervals = self._get_intervals(stream_id)
  413. (start, end) = self._fill_in_limits(start, end)
  414. requested = Interval(start, end)
  415. result = []
  416. matched = 0
  417. remaining = self.max_results
  418. restart = 0
  419. for interval in intervals.intersection(requested):
  420. # Reading single rows from the table is too slow, so
  421. # we use two bisections to find both the starting and
  422. # ending row for this particular interval, then
  423. # read the entire range as one slice.
  424. row_start = self._find_start(table, interval)
  425. row_end = self._find_end(table, interval)
  426. if count:
  427. matched += row_end - row_start
  428. continue
  429. # Shorten it if we'll hit the maximum number of results
  430. row_max = row_start + remaining
  431. if row_max < row_end:
  432. row_end = row_max
  433. restart = table[row_max][0]
  434. # Gather these results up
  435. result.extend(table[row_start:row_end])
  436. # Count them
  437. remaining -= row_end - row_start
  438. if restart:
  439. break
  440. if count:
  441. return matched
  442. return (result, restart)
  443. def stream_remove(self, path, start = None, end = None):
  444. """
  445. Remove data from the specified time interval within a stream.
  446. Removes all data in the interval [start, end), and intervals
  447. are truncated or split appropriately. Returns the number of
  448. data points removed.
  449. """
  450. stream_id = self._stream_id(path)
  451. table = self.data.getnode(path)
  452. intervals = self._get_intervals(stream_id)
  453. (start, end) = self._fill_in_limits(start, end)
  454. to_remove = Interval(start, end)
  455. removed = 0
  456. # Can't remove intervals from within the iterator, so we need to
  457. # remember what's currently in the intersection now.
  458. all_candidates = list(intervals.intersection(to_remove, orig = True))
  459. for (dbint, orig) in all_candidates:
  460. # Find row start and end
  461. row_start = self._find_start(table, dbint)
  462. row_end = self._find_end(table, dbint)
  463. # Adjust the DBInterval to match the newly found ends
  464. dbint.db_start = dbint.start
  465. dbint.db_end = dbint.end
  466. dbint.db_startpos = row_start
  467. dbint.db_endpos = row_end
  468. # Remove interval from the database
  469. self._remove_interval(stream_id, orig, dbint)
  470. # Remove data from the underlying table storage
  471. table.remove(row_start, row_end)
  472. # Count how many were removed
  473. removed += row_end - row_start
  474. return removed