dbutil.py.in 22 KB

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