persist_data.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. """BitBake Persistent Data Store
  2. Used to store data in a central location such that other threads/tasks can
  3. access them at some future date. Acts as a convenience wrapper around sqlite,
  4. currently, providing a key/value store accessed by 'domain'.
  5. """
  6. # Copyright (C) 2007 Richard Purdie
  7. # Copyright (C) 2010 Chris Larson <chris_larson@mentor.com>
  8. #
  9. # SPDX-License-Identifier: GPL-2.0-only
  10. #
  11. import collections
  12. import logging
  13. import os.path
  14. import sys
  15. import warnings
  16. from bb.compat import total_ordering
  17. from collections import Mapping
  18. import sqlite3
  19. import contextlib
  20. sqlversion = sqlite3.sqlite_version_info
  21. if sqlversion[0] < 3 or (sqlversion[0] == 3 and sqlversion[1] < 3):
  22. raise Exception("sqlite3 version 3.3.0 or later is required.")
  23. logger = logging.getLogger("BitBake.PersistData")
  24. @total_ordering
  25. class SQLTable(collections.MutableMapping):
  26. class _Decorators(object):
  27. @staticmethod
  28. def retry(*, reconnect=True):
  29. """
  30. Decorator that restarts a function if a database locked sqlite
  31. exception occurs. If reconnect is True, the database connection
  32. will be closed and reopened each time a failure occurs
  33. """
  34. def retry_wrapper(f):
  35. def wrap_func(self, *args, **kwargs):
  36. # Reconnect if necessary
  37. if self.connection is None and reconnect:
  38. self.reconnect()
  39. count = 0
  40. while True:
  41. try:
  42. return f(self, *args, **kwargs)
  43. except sqlite3.OperationalError as exc:
  44. if count < 500 and ('is locked' in str(exc) or 'locking protocol' in str(exc)):
  45. count = count + 1
  46. if reconnect:
  47. self.reconnect()
  48. continue
  49. raise
  50. return wrap_func
  51. return retry_wrapper
  52. @staticmethod
  53. def transaction(f):
  54. """
  55. Decorator that starts a database transaction and creates a database
  56. cursor for performing queries. If no exception is thrown, the
  57. database results are commited. If an exception occurs, the database
  58. is rolled back. In all cases, the cursor is closed after the
  59. function ends.
  60. Note that the cursor is passed as an extra argument to the function
  61. after `self` and before any of the normal arguments
  62. """
  63. def wrap_func(self, *args, **kwargs):
  64. # Context manager will COMMIT the database on success,
  65. # or ROLLBACK on an exception
  66. with self.connection:
  67. # Automatically close the cursor when done
  68. with contextlib.closing(self.connection.cursor()) as cursor:
  69. return f(self, cursor, *args, **kwargs)
  70. return wrap_func
  71. """Object representing a table/domain in the database"""
  72. def __init__(self, cachefile, table):
  73. self.cachefile = cachefile
  74. self.table = table
  75. self.connection = None
  76. self._execute_single("CREATE TABLE IF NOT EXISTS %s(key TEXT PRIMARY KEY NOT NULL, value TEXT);" % table)
  77. @_Decorators.retry(reconnect=False)
  78. @_Decorators.transaction
  79. def _setup_database(self, cursor):
  80. cursor.execute("pragma synchronous = off;")
  81. # Enable WAL and keep the autocheckpoint length small (the default is
  82. # usually 1000). Persistent caches are usually read-mostly, so keeping
  83. # this short will keep readers running quickly
  84. cursor.execute("pragma journal_mode = WAL;")
  85. cursor.execute("pragma wal_autocheckpoint = 100;")
  86. def reconnect(self):
  87. if self.connection is not None:
  88. self.connection.close()
  89. self.connection = sqlite3.connect(self.cachefile, timeout=5)
  90. self.connection.text_factory = str
  91. self._setup_database()
  92. @_Decorators.retry()
  93. @_Decorators.transaction
  94. def _execute_single(self, cursor, *query):
  95. """
  96. Executes a single query and discards the results. This correctly closes
  97. the database cursor when finished
  98. """
  99. cursor.execute(*query)
  100. @_Decorators.retry()
  101. def _row_iter(self, f, *query):
  102. """
  103. Helper function that returns a row iterator. Each time __next__ is
  104. called on the iterator, the provided function is evaluated to determine
  105. the return value
  106. """
  107. class CursorIter(object):
  108. def __init__(self, cursor):
  109. self.cursor = cursor
  110. def __iter__(self):
  111. return self
  112. def __next__(self):
  113. row = self.cursor.fetchone()
  114. if row is None:
  115. self.cursor.close()
  116. raise StopIteration
  117. return f(row)
  118. def __enter__(self):
  119. return self
  120. def __exit__(self, typ, value, traceback):
  121. self.cursor.close()
  122. return False
  123. cursor = self.connection.cursor()
  124. try:
  125. cursor.execute(*query)
  126. return CursorIter(cursor)
  127. except:
  128. cursor.close()
  129. def __enter__(self):
  130. self.connection.__enter__()
  131. return self
  132. def __exit__(self, *excinfo):
  133. self.connection.__exit__(*excinfo)
  134. @_Decorators.retry()
  135. @_Decorators.transaction
  136. def __getitem__(self, cursor, key):
  137. cursor.execute("SELECT * from %s where key=?;" % self.table, [key])
  138. row = cursor.fetchone()
  139. if row is not None:
  140. return row[1]
  141. raise KeyError(key)
  142. @_Decorators.retry()
  143. @_Decorators.transaction
  144. def __delitem__(self, cursor, key):
  145. if key not in self:
  146. raise KeyError(key)
  147. cursor.execute("DELETE from %s where key=?;" % self.table, [key])
  148. @_Decorators.retry()
  149. @_Decorators.transaction
  150. def __setitem__(self, cursor, key, value):
  151. if not isinstance(key, str):
  152. raise TypeError('Only string keys are supported')
  153. elif not isinstance(value, str):
  154. raise TypeError('Only string values are supported')
  155. cursor.execute("SELECT * from %s where key=?;" % self.table, [key])
  156. row = cursor.fetchone()
  157. if row is not None:
  158. cursor.execute("UPDATE %s SET value=? WHERE key=?;" % self.table, [value, key])
  159. else:
  160. cursor.execute("INSERT into %s(key, value) values (?, ?);" % self.table, [key, value])
  161. @_Decorators.retry()
  162. @_Decorators.transaction
  163. def __contains__(self, cursor, key):
  164. cursor.execute('SELECT * from %s where key=?;' % self.table, [key])
  165. return cursor.fetchone() is not None
  166. @_Decorators.retry()
  167. @_Decorators.transaction
  168. def __len__(self, cursor):
  169. cursor.execute("SELECT COUNT(key) FROM %s;" % self.table)
  170. row = cursor.fetchone()
  171. if row is not None:
  172. return row[0]
  173. def __iter__(self):
  174. return self._row_iter(lambda row: row[0], "SELECT key from %s;" % self.table)
  175. def __lt__(self, other):
  176. if not isinstance(other, Mapping):
  177. raise NotImplemented
  178. return len(self) < len(other)
  179. def get_by_pattern(self, pattern):
  180. return self._row_iter(lambda row: row[1], "SELECT * FROM %s WHERE key LIKE ?;" %
  181. self.table, [pattern])
  182. def values(self):
  183. return list(self.itervalues())
  184. def itervalues(self):
  185. return self._row_iter(lambda row: row[0], "SELECT value FROM %s;" %
  186. self.table)
  187. def items(self):
  188. return list(self.iteritems())
  189. def iteritems(self):
  190. return self._row_iter(lambda row: (row[0], row[1]), "SELECT * FROM %s;" %
  191. self.table)
  192. @_Decorators.retry()
  193. @_Decorators.transaction
  194. def clear(self, cursor):
  195. cursor.execute("DELETE FROM %s;" % self.table)
  196. def has_key(self, key):
  197. return key in self
  198. class PersistData(object):
  199. """Deprecated representation of the bitbake persistent data store"""
  200. def __init__(self, d):
  201. warnings.warn("Use of PersistData is deprecated. Please use "
  202. "persist(domain, d) instead.",
  203. category=DeprecationWarning,
  204. stacklevel=2)
  205. self.data = persist(d)
  206. logger.debug(1, "Using '%s' as the persistent data cache",
  207. self.data.filename)
  208. def addDomain(self, domain):
  209. """
  210. Add a domain (pending deprecation)
  211. """
  212. return self.data[domain]
  213. def delDomain(self, domain):
  214. """
  215. Removes a domain and all the data it contains
  216. """
  217. del self.data[domain]
  218. def getKeyValues(self, domain):
  219. """
  220. Return a list of key + value pairs for a domain
  221. """
  222. return list(self.data[domain].items())
  223. def getValue(self, domain, key):
  224. """
  225. Return the value of a key for a domain
  226. """
  227. return self.data[domain][key]
  228. def setValue(self, domain, key, value):
  229. """
  230. Sets the value of a key for a domain
  231. """
  232. self.data[domain][key] = value
  233. def delValue(self, domain, key):
  234. """
  235. Deletes a key/value pair
  236. """
  237. del self.data[domain][key]
  238. def persist(domain, d):
  239. """Convenience factory for SQLTable objects based upon metadata"""
  240. import bb.utils
  241. cachedir = (d.getVar("PERSISTENT_DIR") or
  242. d.getVar("CACHE"))
  243. if not cachedir:
  244. logger.critical("Please set the 'PERSISTENT_DIR' or 'CACHE' variable")
  245. sys.exit(1)
  246. bb.utils.mkdirhier(cachedir)
  247. cachefile = os.path.join(cachedir, "bb_persist_data.sqlite3")
  248. return SQLTable(cachefile, domain)