dbutil.py.in 22 KB

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