persist_data.py 10 KB

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