dbutil.py.in 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. #!@PYTHON@
  2. # Copyright (C) 2012 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. @file Database Utilities
  18. This file holds the "dbutil" program, a general utility program for doing
  19. management of the BIND 10 database. There are two modes of operation:
  20. b10-dbutil --check [--verbose] database
  21. b10-dbutil --upgrade [--noconfirm] [--verbose] database
  22. The first form checks the version of the given database. The second form
  23. upgrades the database to the latest version of the schema, omitting the
  24. warning prompt if --noconfirm is given.
  25. For maximum safety, prior to the upgrade a backup database is created.
  26. The is the database name with ".backup" appended to it (or ".backup-n" if
  27. ".backup" already exists). This is used to restore the database if the
  28. upgrade fails.
  29. """
  30. # Exit codes
  31. # These are defined here because one of them is already used before most
  32. # of the import statements.
  33. EXIT_SUCCESS = 0
  34. EXIT_NEED_UPDATE = 1
  35. EXIT_VERSION_TOO_HIGH = 2
  36. EXIT_COMMAND_ERROR = 3
  37. EXIT_READ_ERROR = 4
  38. EXIT_UPGRADE_ERROR = 5
  39. EXIT_UNCAUGHT_EXCEPTION = 6
  40. import sys; sys.path.append("@@PYTHONPATH@@")
  41. # Normally, python exits with a status code of 1 on uncaught exceptions
  42. # Since we reserve exit status 1 for 'database needs upgrade', we
  43. # override the excepthook to exit with a different status
  44. def my_except_hook(a, b, c):
  45. sys.__excepthook__(a,b,c)
  46. sys.exit(EXIT_UNCAUGHT_EXCEPTION)
  47. sys.excepthook = my_except_hook
  48. import os, sqlite3, shutil
  49. from optparse import OptionParser
  50. import isc.util.process
  51. import isc.util.traceback_handler
  52. import isc.log
  53. from isc.log_messages.dbutil_messages import *
  54. isc.log.init("b10-dbutil")
  55. logger = isc.log.Logger("dbutil")
  56. isc.util.process.rename()
  57. TRACE_BASIC = logger.DBGLVL_TRACE_BASIC
  58. # @brief Version String
  59. # This is the version displayed to the user. It comprises the module name,
  60. # the module version number, and the overall BIND 10 version number (set in
  61. # configure.ac)
  62. VERSION = "b10-dbutil 20120319 (BIND 10 @PACKAGE_VERSION@)"
  63. # @brief Statements to Update the Database
  64. # These are in the form of a list of dictionaries, each of which contains the
  65. # information to perform an incremental upgrade from one version of the
  66. # database to the next. The information is:
  67. #
  68. # a) from: (major, minor) version that the database is expected to be at
  69. # to perform this upgrade.
  70. # b) to: (major, minor) version of the database to which this set of statements
  71. # upgrades the database to. (This is used for documentation purposes,
  72. # and to update the schema_version table when the upgrade is complete.)
  73. # c) statements: List of SQL statments to perform the upgrade.
  74. #
  75. # The incremental upgrades are performed one after the other. If the version
  76. # of the database does not exactly match that required for the incremental
  77. # upgrade, the upgrade is skipped. For this reason, the list must be in
  78. # ascending order (e.g. upgrade 1.0 to 2.0, 2.0 to 2.1, 2.1 to 2.2 etc.).
  79. #
  80. # Note that apart from the 1.0 to 2.0 upgrade, no upgrade need alter the
  81. # schema_version table: that is done by the upgrade process using the
  82. # information in the "to" field.
  83. UPGRADES = [
  84. {'from': (1, 0), 'to': (2, 0),
  85. 'statements': [
  86. # Move to the latest "V1" state of the database if not there
  87. # already.
  88. "CREATE TABLE IF NOT EXISTS diffs (" +
  89. "id INTEGER PRIMARY KEY, " +
  90. "zone_id INTEGER NOT NULL," +
  91. "version INTEGER NOT NULL, " +
  92. "operation INTEGER NOT NULL, " +
  93. "name STRING NOT NULL COLLATE NOCASE, " +
  94. "rrtype STRING NOT NULL COLLATE NOCASE, " +
  95. "ttl INTEGER NOT NULL, " +
  96. "rdata STRING NOT NULL)",
  97. # Within SQLite with can only rename tables and add columns; we
  98. # can't drop columns nor can we alter column characteristics.
  99. # So the strategy is to rename the table, create the new table,
  100. # then copy all data across. This means creating new indexes
  101. # as well; these are created after the data has been copied.
  102. # zones table
  103. "DROP INDEX zones_byname",
  104. "ALTER TABLE zones RENAME TO old_zones",
  105. "CREATE TABLE zones (" +
  106. "id INTEGER PRIMARY KEY, " +
  107. "name TEXT NOT NULL COLLATE NOCASE, " +
  108. "rdclass TEXT NOT NULL COLLATE NOCASE DEFAULT 'IN', " +
  109. "dnssec BOOLEAN NOT NULL DEFAULT 0)",
  110. "INSERT INTO ZONES " +
  111. "SELECT id, name, rdclass, dnssec FROM old_zones",
  112. "CREATE INDEX zones_byname ON zones (name)",
  113. "DROP TABLE old_zones",
  114. # records table
  115. "DROP INDEX records_byname",
  116. "DROP INDEX records_byrname",
  117. "ALTER TABLE records RENAME TO old_records",
  118. "CREATE TABLE records (" +
  119. "id INTEGER PRIMARY KEY, " +
  120. "zone_id INTEGER NOT NULL, " +
  121. "name TEXT NOT NULL COLLATE NOCASE, " +
  122. "rname TEXT NOT NULL COLLATE NOCASE, " +
  123. "ttl INTEGER NOT NULL, " +
  124. "rdtype TEXT NOT NULL COLLATE NOCASE, " +
  125. "sigtype TEXT COLLATE NOCASE, " +
  126. "rdata TEXT NOT NULL)",
  127. "INSERT INTO records " +
  128. "SELECT id, zone_id, name, rname, ttl, rdtype, sigtype, " +
  129. "rdata FROM old_records",
  130. "CREATE INDEX records_byname ON records (name)",
  131. "CREATE INDEX records_byrname ON records (rname)",
  132. "CREATE INDEX records_bytype_and_rname ON records (rdtype, rname)",
  133. "DROP TABLE old_records",
  134. # nsec3 table
  135. "DROP INDEX nsec3_byhash",
  136. "ALTER TABLE nsec3 RENAME TO old_nsec3",
  137. "CREATE TABLE nsec3 (" +
  138. "id INTEGER PRIMARY KEY, " +
  139. "zone_id INTEGER NOT NULL, " +
  140. "hash TEXT NOT NULL COLLATE NOCASE, " +
  141. "owner TEXT NOT NULL COLLATE NOCASE, " +
  142. "ttl INTEGER NOT NULL, " +
  143. "rdtype TEXT NOT NULL COLLATE NOCASE, " +
  144. "rdata TEXT NOT NULL)",
  145. "INSERT INTO nsec3 " +
  146. "SELECT id, zone_id, hash, owner, ttl, rdtype, rdata " +
  147. "FROM old_nsec3",
  148. "CREATE INDEX nsec3_byhash ON nsec3 (hash)",
  149. "DROP TABLE old_nsec3",
  150. # diffs table
  151. "ALTER TABLE diffs RENAME TO old_diffs",
  152. "CREATE TABLE diffs (" +
  153. "id INTEGER PRIMARY KEY, " +
  154. "zone_id INTEGER NOT NULL, " +
  155. "version INTEGER NOT NULL, " +
  156. "operation INTEGER NOT NULL, " +
  157. "name TEXT NOT NULL COLLATE NOCASE, " +
  158. "rrtype TEXT NOT NULL COLLATE NOCASE, " +
  159. "ttl INTEGER NOT NULL, " +
  160. "rdata TEXT NOT NULL)",
  161. "INSERT INTO diffs " +
  162. "SELECT id, zone_id, version, operation, name, rrtype, " +
  163. "ttl, rdata FROM old_diffs",
  164. "DROP TABLE old_diffs",
  165. # Schema table. This is updated to include a second column for
  166. # future changes. The idea is that if a version of BIND 10 is
  167. # written for schema M.N, it should be able to work for all
  168. # versions of N; if not, M must be incremented.
  169. #
  170. # For backwards compatibility, the column holding the major
  171. # version number is left named "version".
  172. "ALTER TABLE schema_version " +
  173. "ADD COLUMN minor INTEGER NOT NULL DEFAULT 0"
  174. ]
  175. },
  176. {'from': (2, 0), 'to': (2, 1),
  177. 'statements': [
  178. "CREATE INDEX nsec3_byhash_and_rdtype ON nsec3 " +
  179. "(hash, rdtype)"
  180. ]
  181. },
  182. {'from': (2, 1), 'to': (2, 2),
  183. 'statements': [
  184. "CREATE INDEX records_byrname_and_rdtype ON records (rname, rdtype)"
  185. ]
  186. }
  187. # To extend this, leave the above statements in place and add another
  188. # dictionary to the list. The "from" version should be (2, 2), the "to"
  189. # version whatever the version the update is to, and the SQL statements are
  190. # the statements required to perform the upgrade. This way, the upgrade
  191. # program will be able to upgrade both a V1.0 and a V2.0 database.
  192. ]
  193. class DbutilException(Exception):
  194. """
  195. @brief Exception class to indicate error exit
  196. """
  197. pass
  198. class Database:
  199. """
  200. @brief Database Encapsulation
  201. Encapsulates the SQL database, both the connection and the cursor. The
  202. methods will cause a program exit on any error.
  203. """
  204. def __init__(self, db_file):
  205. """
  206. @brief Constructor
  207. @param db_file Name of the database file
  208. """
  209. self.connection = None
  210. self.cursor = None
  211. self.db_file = db_file
  212. self.backup_file = None
  213. def open(self):
  214. """
  215. @brief Open Database
  216. Opens the passed file as an sqlite3 database and stores a connection
  217. and a cursor.
  218. """
  219. if not os.path.exists(self.db_file):
  220. raise DbutilException("database " + self.db_file +
  221. " does not exist");
  222. try:
  223. self.connection = sqlite3.connect(self.db_file)
  224. self.connection.isolation_level = None # set autocommit
  225. self.cursor = self.connection.cursor()
  226. except sqlite3.OperationalError as ex:
  227. raise DbutilException("unable to open " + self.db_file +
  228. " - " + str(ex))
  229. def close(self):
  230. """
  231. @brief Closes the database
  232. """
  233. if self.connection is not None:
  234. self.connection.close()
  235. def execute(self, statement):
  236. """
  237. @brief Execute Statement
  238. Executes the given statement, exiting the program on error.
  239. @param statement SQL statement to execute
  240. """
  241. logger.debug(TRACE_BASIC, DBUTIL_EXECUTE, statement)
  242. try:
  243. self.cursor.execute(statement)
  244. except Exception as ex:
  245. logger.error(DBUTIL_STATEMENT_ERROR, statement, ex)
  246. raise DbutilException(str(ex))
  247. def result(self):
  248. """
  249. @brief Return result of last execute
  250. Returns a single row that is the result of the last "execute".
  251. """
  252. return self.cursor.fetchone()
  253. def backup(self):
  254. """
  255. @brief Backup Database
  256. Attempts to copy the given database file to a backup database, the
  257. backup database file being the file name with ".backup" appended.
  258. If the ".backup" file exists, a new name is constructed by appending
  259. ".backup-n" (n starting at 1) and the action repeated until an
  260. unused filename is found.
  261. @param db_file Database file to backup
  262. """
  263. if not os.path.exists(self.db_file):
  264. raise DbutilException("database " + self.db_file +
  265. " does not exist");
  266. self.backup_file = self.db_file + ".backup"
  267. count = 0
  268. while os.path.exists(self.backup_file):
  269. count = count + 1
  270. self.backup_file = self.db_file + ".backup-" + str(count)
  271. # Do the backup
  272. shutil.copyfile(self.db_file, self.backup_file)
  273. logger.info(DBUTIL_BACKUP, self.db_file, self.backup_file)
  274. def prompt_user():
  275. """
  276. @brief Prompt the User
  277. Explains about the upgrade and requests authorisation to continue.
  278. @return True if user entered 'Yes', False if 'No'
  279. """
  280. sys.stdout.write(
  281. """You have selected the upgrade option. This will upgrade the schema of the
  282. selected BIND 10 zone database to the latest version.
  283. The utility will take a copy of the zone database file before executing so, in
  284. the event of a problem, you will be able to restore the zone database from
  285. the backup. To ensure that the integrity of this backup, please ensure that
  286. BIND 10 is not running before continuing.
  287. """)
  288. yes_entered = False
  289. no_entered = False
  290. while (not yes_entered) and (not no_entered):
  291. sys.stdout.write("Enter 'Yes' to proceed with the upgrade, " +
  292. "'No' to exit the program: \n")
  293. response = sys.stdin.readline()
  294. if response.lower() == "yes\n":
  295. yes_entered = True
  296. elif response.lower() == "no\n":
  297. no_entered = True
  298. else:
  299. sys.stdout.write("Please enter 'Yes' or 'No'\n")
  300. return yes_entered
  301. def version_string(version):
  302. """
  303. @brief Format Database Version
  304. Converts a (major, minor) tuple into a 'Vn.m' string.
  305. @param version Version tuple to convert
  306. @return Version string
  307. """
  308. return "V" + str(version[0]) + "." + str(version[1])
  309. def compare_versions(first, second):
  310. """
  311. @brief Compare Versions
  312. Compares two database version numbers.
  313. @param first First version number to check (in the form of a
  314. "(major, minor)" tuple).
  315. @param second Second version number to check (in the form of a
  316. "(major, minor)" tuple).
  317. @return -1, 0, +1 if "first" is <, ==, > "second"
  318. """
  319. if first == second:
  320. return 0
  321. elif ((first[0] < second[0]) or
  322. ((first[0] == second[0]) and (first[1] < second[1]))):
  323. return -1
  324. else:
  325. return 1
  326. def get_latest_version():
  327. """
  328. @brief Returns the version to which this utility can upgrade the database
  329. This is the 'to' version held in the last element of the upgrades list
  330. """
  331. return UPGRADES[-1]['to']
  332. def get_version(db):
  333. """
  334. @brief Return version of database
  335. @return Version of database in form (major version, minor version)
  336. """
  337. # Get the version information.
  338. db.execute("SELECT * FROM schema_version")
  339. result = db.result()
  340. if result is None:
  341. raise DbutilException("nothing in schema_version table")
  342. major = result[0]
  343. if (major == 1):
  344. # If the version number is 1, there will be no "minor" column, so
  345. # assume a minor version number of 0.
  346. minor = 0
  347. else:
  348. minor = result[1]
  349. result = db.result()
  350. if result is not None:
  351. raise DbutilException("too many rows in schema_version table")
  352. return (major, minor)
  353. def check_version(db):
  354. """
  355. @brief Check the version
  356. Checks the version of the database and the latest version, and advises if
  357. an upgrade is needed.
  358. @param db Database object
  359. returns 0 if the database is up to date
  360. returns EXIT_NEED_UPDATE if the database needs updating
  361. returns EXIT_VERSION_TOO_HIGH if the database is at a later version
  362. than this program knows about
  363. These return values are intended to be passed on to sys.exit.
  364. """
  365. current = get_version(db)
  366. latest = get_latest_version()
  367. match = compare_versions(current, latest)
  368. if match == 0:
  369. logger.info(DBUTIL_VERSION_CURRENT, version_string(current))
  370. logger.info(DBUTIL_CHECK_OK)
  371. return EXIT_SUCCESS
  372. elif match < 0:
  373. logger.info(DBUTIL_VERSION_LOW, version_string(current),
  374. version_string(latest))
  375. logger.info(DBUTIL_CHECK_UPGRADE_NEEDED)
  376. return EXIT_NEED_UPDATE
  377. else:
  378. logger.warn(DBUTIL_VERSION_HIGH, version_string(current),
  379. version_string(get_latest_version()))
  380. logger.info(DBUTIL_UPGRADE_DBUTIL)
  381. return EXIT_VERSION_TOO_HIGH
  382. def perform_upgrade(db, upgrade):
  383. """
  384. @brief Perform upgrade
  385. Performs the upgrade. At the end of the upgrade, updates the schema_version
  386. table with the expected version.
  387. @param db Database object
  388. @param upgrade Upgrade dictionary, holding "from", "to" and "statements".
  389. """
  390. logger.info(DBUTIL_UPGRADING, version_string(upgrade['from']),
  391. version_string(upgrade['to']))
  392. for statement in upgrade['statements']:
  393. db.execute(statement)
  394. # Update the version information
  395. db.execute("DELETE FROM schema_version")
  396. db.execute("INSERT INTO schema_version VALUES (" +
  397. str(upgrade['to'][0]) + "," + str(upgrade['to'][1]) + ")")
  398. def perform_all_upgrades(db):
  399. """
  400. @brief Performs all the upgrades
  401. @brief db Database object
  402. For each upgrade, checks that the database is at the expected version.
  403. If so, calls perform_upgrade to update the database.
  404. """
  405. match = compare_versions(get_version(db), get_latest_version())
  406. if match == 0:
  407. logger.info(DBUTIL_UPGRADE_NOT_NEEDED)
  408. elif match > 0:
  409. logger.warn(DBUTIL_UPGRADE_NOT_POSSIBLE)
  410. else:
  411. # Work our way through all upgrade increments
  412. count = 0
  413. for upgrade in UPGRADES:
  414. if compare_versions(get_version(db), upgrade['from']) == 0:
  415. perform_upgrade(db, upgrade)
  416. count = count + 1
  417. if count > 0:
  418. logger.info(DBUTIL_UPGRADE_SUCCESFUL)
  419. else:
  420. # Should not get here, as we established earlier that the database
  421. # was not at the latest version so we should have upgraded.
  422. raise DbutilException("internal error in upgrade tool - no " +
  423. "upgrade was performed on an old version " +
  424. "the database")
  425. def parse_command():
  426. """
  427. @brief Parse Command
  428. Parses the command line and sets the global command options.
  429. @return Tuple of parser options and parser arguments
  430. """
  431. usage = ("usage: %prog --check [options] db_file\n" +
  432. " %prog --upgrade [--noconfirm] [options] db_file")
  433. parser = OptionParser(usage = usage, version = VERSION)
  434. parser.add_option("-c", "--check", action="store_true",
  435. dest="check", default=False,
  436. help="Print database version and check if it " +
  437. "needs upgrading")
  438. parser.add_option("-n", "--noconfirm", action="store_true",
  439. dest="noconfirm", default=False,
  440. help="Do not prompt for confirmation before upgrading")
  441. parser.add_option("-u", "--upgrade", action="store_true",
  442. dest="upgrade", default=False,
  443. help="Upgrade the database file to the latest version")
  444. parser.add_option("-v", "--verbose", action="store_true",
  445. dest="verbose", default=False,
  446. help="Print SQL statements as they are executed")
  447. parser.add_option("-q", "--quiet", action="store_true",
  448. dest="quiet", default=False,
  449. help="Don't print any info, warnings or errors")
  450. (options, args) = parser.parse_args()
  451. # Set the database file on which to operate
  452. if (len(args) > 1):
  453. logger.error(DBUTIL_TOO_MANY_ARGUMENTS)
  454. parser.print_usage()
  455. sys.exit(EXIT_COMMAND_ERROR)
  456. elif len(args) == 0:
  457. logger.error(DBUTIL_NO_FILE)
  458. parser.print_usage()
  459. sys.exit(EXIT_COMMAND_ERROR)
  460. # Check for conflicting options. If some are found, output a suitable
  461. # error message and print the usage.
  462. if options.check and options.upgrade:
  463. logger.error(DBUTIL_COMMAND_UPGRADE_CHECK)
  464. elif (not options.check) and (not options.upgrade):
  465. logger.error(DBUTIL_COMMAND_NONE)
  466. elif (options.check and options.noconfirm):
  467. logger.error(DBUTIL_CHECK_NOCONFIRM)
  468. else:
  469. return (options, args)
  470. # Only get here on conflicting options
  471. parser.print_usage()
  472. sys.exit(EXIT_COMMAND_ERROR)
  473. def main():
  474. (options, args) = parse_command()
  475. global logger
  476. if options.verbose:
  477. isc.log.init("b10-dbutil", "DEBUG", 99)
  478. logger = isc.log.Logger("dbutil")
  479. elif options.quiet:
  480. # We don't use FATAL, so setting the logger to use
  481. # it should essentially make it silent.
  482. isc.log.init("b10-dbutil", "FATAL")
  483. logger = isc.log.Logger("dbutil")
  484. db = Database(args[0])
  485. exit_code = EXIT_SUCCESS
  486. logger.info(DBUTIL_FILE, args[0])
  487. if options.check:
  488. # Check database - open, report, and close
  489. try:
  490. db.open()
  491. exit_code = check_version(db)
  492. db.close()
  493. except Exception as ex:
  494. logger.error(DBUTIL_CHECK_ERROR, ex)
  495. exit_code = EXIT_READ_ERROR
  496. elif options.upgrade:
  497. # Upgrade. Check if this is what they really want to do
  498. if not options.noconfirm:
  499. proceed = prompt_user()
  500. if not proceed:
  501. logger.info(DBUTIL_UPGRADE_CANCELED)
  502. sys.exit(EXIT_SUCCESS)
  503. # It is. Do a backup then do the upgrade.
  504. in_progress = False
  505. try:
  506. db.backup()
  507. db.open()
  508. in_progress = True
  509. perform_all_upgrades(db)
  510. db.close()
  511. except Exception as ex:
  512. if in_progress:
  513. logger.error(DBUTIL_UPGRADE_FAILED, ex)
  514. logger.warn(DBUTIL_DATABASE_MAY_BE_CORRUPT, db.db_file,
  515. db.backup_file)
  516. else:
  517. logger.error(DBUTIL_UPGRADE_PREPARATION_FAILED, ex)
  518. logger.info(DBUTIL_UPGRADE_NOT_ATTEMPTED)
  519. exit_code = EXIT_UPGRADE_ERROR
  520. sys.exit(exit_code)
  521. if __name__ == "__main__":
  522. isc.util.traceback_handler.traceback_handler(main)