clonedb.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. #!/usr/bin/python3
  2. """
  3. Script de clonage des bases de données MariaDb 10.*
  4. (requiert python 3.6+)
  5. > Configuration: settings.yml
  6. Usage:
  7. clonedb.py [-v] [-y] [<opname>...]
  8. clonedb.py (-h | --help)
  9. clonedb.py --version
  10. Options:
  11. -y, --yes Do not ask for confirmation
  12. -h --help Show this screen.
  13. --version Show version.
  14. @author: olivier.massot, 05-2020
  15. """
  16. import logging
  17. import re
  18. import subprocess
  19. from subprocess import Popen, PIPE, CalledProcessError
  20. import sys
  21. import pymysql
  22. import yaml
  23. from docopt import docopt
  24. from path import Path
  25. from core import logging_
  26. from core.docker import resolve_docker_ip
  27. from core.locker import Lockfile
  28. from core.pipe_handler import PipeHandler
  29. from core.ssh import SshTunnel
  30. from core.prompt import ask_confirmation
  31. __VERSION__ = "0.2"
  32. HERE = Path(__file__).parent
  33. # Start logger
  34. LOG_DIR = HERE / 'log'
  35. LOG_DIR.mkdir_p()
  36. logger = logging.getLogger('clonedb')
  37. logging_.start("clonedb", filename=LOG_DIR / 'clonedb.log', replace=True)
  38. # FIX the default ascii encoding on some linux dockers...
  39. sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
  40. # Options
  41. SHOW_PROGRESSION = True
  42. LOG_PIPES_OUTPUT = True
  43. LOG_MYSQL_QUERIES = True
  44. MAX_ALLOWED_PACKET = 1073741824
  45. # Utilities
  46. def load_settings():
  47. """ Load the settings from the 'settings.yml' file
  48. If there is no such file, the base settings.yml file is created
  49. """
  50. settings_file = HERE / 'settings.yml'
  51. if not settings_file.exists():
  52. Path(HERE / 'settings.yml.dist').copy(HERE / 'settings.yml')
  53. with open(settings_file, 'r') as f:
  54. return yaml.load(f, Loader=yaml.FullLoader)
  55. def _print(msg, end=False):
  56. msg = msg.ljust(80)
  57. print(f'\r{msg}', end='' if not end else '\n', flush=True)
  58. def fetch_mysqldump_version():
  59. p = subprocess.run('mysqldump --version', shell=True, capture_output=True)
  60. out, err = p.stdout.decode('utf-8'), p.stderr.decode('utf-8')
  61. if err:
  62. raise RuntimeError('mysqldump can not be found, is it installed on this machine?')
  63. fork = "mariadb" if "MariaDB" in out else "mysql"
  64. match = re.search(r"Ver ((?:\d+\.?)+)", out)
  65. version = match.group(1) if match else "0"
  66. return fork, version
  67. class MysqldumpHandler(PipeHandler):
  68. """ Handle and process the stdout / stderr output from a mysqldump process
  69. """
  70. _rx_prog = re.compile(r'Retrieving table structure for table (\w+)')
  71. _log_all = LOG_PIPES_OUTPUT
  72. def __init__(self, logger_name, level, total_prog):
  73. super().__init__(logger_name, level)
  74. self.total_prog = total_prog
  75. self.prog = 0
  76. self._last_logged = ""
  77. def process(self, line):
  78. """ Process the last line that was read
  79. """
  80. line = line.strip('\n')
  81. if SHOW_PROGRESSION:
  82. match = self._rx_prog.search(line)
  83. if match:
  84. self.log_new_table(match.group(1), "dumping")
  85. if self._log_all:
  86. logger.debug(line)
  87. def log_new_table(self, tname, action_name=""):
  88. if tname == self._last_logged:
  89. return
  90. self.prog += 1
  91. logger.debug('... %s %s', action_name, tname)
  92. _print(f'{action_name} `{tname}` [{self.prog} / {self.total_prog}]')
  93. self._last_logged = tname
  94. def log_end(self):
  95. _print(f'\r-- done --', end=True)
  96. def close(self):
  97. """ Close the write end of the pipe.
  98. """
  99. super().close()
  100. class MysqlHandler(MysqldumpHandler):
  101. """ Handle and process the stdout / stderr output from a mysql process
  102. """
  103. _rx_prog = re.compile(r'^((?:CREATE TABLE )|(?:INSERT INTO ))`(\w+)`')
  104. _log_all = LOG_PIPES_OUTPUT
  105. _action_name = "restoring"
  106. def process(self, line):
  107. """ Process the last line that was read
  108. """
  109. line = line.strip('\n')
  110. if SHOW_PROGRESSION:
  111. match = self._rx_prog.search(line)
  112. if match:
  113. action_name = "restoring {}".format('structure of'
  114. if 'CREATE' in match.group(1)
  115. else 'data of')
  116. self.log_new_table(match.group(2), action_name)
  117. if self._log_all:
  118. logger.debug(line)
  119. class MySqlServer:
  120. """ A server hosting a Mysql instance
  121. """
  122. def __init__(self, host, port, username, password, description="", ssh_tunnel=None):
  123. self.host = host
  124. self.port = port
  125. self.username = username
  126. self.password = password
  127. self.description = description[:30]
  128. self.ssh_tunnel = ssh_tunnel
  129. self.cnn = None
  130. self.active_db = ""
  131. def __repr__(self):
  132. s = f"{self.host}:{self.port} as {self.username}"
  133. if self.description:
  134. s = f"{self.description} ({s})"
  135. return s
  136. def connect(self, autocommit=True):
  137. """ Establish the connection to the Mysql server
  138. @see https://pymysql.readthedocs.io/en/latest/modules/connections.html
  139. """
  140. if self.ssh_tunnel:
  141. self.ssh_tunnel.start()
  142. host, port = self.ssh_tunnel.LOCAL_ADRESS
  143. else:
  144. host, port = self.host, self.port
  145. self.cnn = pymysql.connect(host=host,
  146. port=port,
  147. user=self.username,
  148. password=self.password,
  149. autocommit=autocommit,
  150. max_allowed_packet=MAX_ALLOWED_PACKET,
  151. )
  152. if not self.cnn.open:
  153. raise RuntimeError(f'Unable to connect to {self}')
  154. return self.cnn
  155. def set_active_db(self, dbname):
  156. """ set the active database
  157. """
  158. self.cnn.select_db(dbname)
  159. self.active_db = dbname
  160. def close(self):
  161. """ Close the connection to the database
  162. and the ssh tunnel if one is opened
  163. """
  164. if self.cnn:
  165. self.cnn.close()
  166. if self.ssh_tunnel:
  167. self.ssh_tunnel.stop()
  168. logger.debug(f'{self} - connection closed')
  169. def exec_query(self, sql):
  170. """ Execute the sql code and return the resulting cursor
  171. @see https://pymysql.readthedocs.io/en/latest/modules/cursors.html
  172. """
  173. self.cnn.ping(reconnect=True)
  174. cursor = self.cnn.cursor()
  175. if LOG_MYSQL_QUERIES:
  176. logger.debug(sql)
  177. cursor.execute(sql)
  178. return cursor
  179. def db_exists(self, dbname):
  180. """ Return True if the database exists
  181. """
  182. cursor = self.exec_query(f"""SELECT SCHEMA_NAME
  183. FROM INFORMATION_SCHEMA.SCHEMATA
  184. WHERE SCHEMA_NAME = '{dbname}'""")
  185. row = cursor.fetchone()
  186. return row is not None
  187. def get_db_charset(self, dbname):
  188. """ return the charset (encoding) of the mysql database """
  189. cursor = self.exec_query(f"""SELECT default_character_set_name
  190. FROM information_schema.SCHEMATA S
  191. WHERE schema_name = '{dbname}';""")
  192. return cursor.fetchone()[0]
  193. def list_tables(self, dbname=""):
  194. """ Return a list of tables (but not views!)
  195. for either the currently selected database,
  196. or the one given as a parameter"""
  197. cursor = self.exec_query(
  198. "SHOW FULL TABLES{} WHERE Table_type='BASE TABLE';".format(f" FROM {dbname}" if dbname else ""))
  199. return (row[0] for row in cursor.fetchall())
  200. def list_views(self, dbname=""):
  201. """ Return a list of views
  202. for either the currently selected database,
  203. or the one given as a parameter"""
  204. cursor = self.exec_query(
  205. "SHOW FULL TABLES{} WHERE Table_type='VIEW';".format(f" FROM {dbname}" if dbname else ""))
  206. return (row[0] for row in cursor.fetchall())
  207. def get_view_definition(self, view_name, set_definer=""):
  208. """ Return the SQL create statement for the view
  209. If 'set_definer' is not empty, the username in the 'SET DEFINER' part
  210. of the create statement is replaced by the one given
  211. """
  212. cursor = self.exec_query(f"show create view {view_name}")
  213. definition = cursor.fetchone()[1]
  214. if set_definer:
  215. # force a new definer
  216. definition = re.sub(r'DEFINER=`\w+`@`[\w\-.]+`',
  217. f"DEFINER=`{set_definer}`@`\1`",
  218. definition)
  219. return definition
  220. class MysqlUser:
  221. def __init__(self, username, pwd, host='localhost'):
  222. self.username = username
  223. self.pwd = pwd
  224. self.host = host
  225. # Operation status
  226. UNKNOWN = 0
  227. SUCCESS = 1
  228. FAILURE = 2
  229. # Behaviors for the tables cloning
  230. IGNORE = 0
  231. STRUCTURE_ONLY = 1
  232. STRUCTURE_AND_DATA = 2 # -> default behavior
  233. class CloningOperation:
  234. """ A database cloning operation between two Mysql servers
  235. """
  236. def __init__(self, name, dbname, from_server, to_server, grant=None,
  237. is_default=True, ignore_tables=None, structure_only=None,
  238. filter_tables=None, ignore_views=None, compress=True):
  239. self.name = name
  240. self.dbname = dbname
  241. self.from_server = from_server
  242. self.to_server = to_server
  243. self.grant = grant if grant is not None else []
  244. self.is_default = is_default
  245. self.compress = compress
  246. self.ignore_tables = [re.compile(f"^{r}$") for r in ignore_tables] if ignore_tables else []
  247. self.structure_only = [re.compile(f"^{r}$") for r in structure_only] if structure_only else []
  248. self.filter_tables = [re.compile(f"^{r}$") for r in filter_tables] if filter_tables else []
  249. self.ignore_views = [re.compile(f"^{r}$") for r in ignore_views] if ignore_views else []
  250. self.status = UNKNOWN
  251. def __repr__(self):
  252. return f"Cloning {self.dbname} from {self.from_server} to {self.to_server}"
  253. def _build_dump_command(self, dump_options=None, tables=None):
  254. """ Build a mysqldump command line and return it as a
  255. ready-to-consume list for Popen
  256. @see https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#mysqldump-option-summary
  257. """
  258. tables = tables or []
  259. dump_options = dump_options or []
  260. mysqldump_version = fetch_mysqldump_version()
  261. base_cmd = ["mysqldump",
  262. "--single-transaction",
  263. "-u", self.from_server.username,
  264. f"--password={self.from_server.password}",
  265. f"--max-allowed-packet={MAX_ALLOWED_PACKET}",
  266. "--skip-add-drop-table",
  267. "--skip-add-locks",
  268. "--skip-comments"
  269. ]
  270. # <-- fix the occasional 'Unknown table 'COLUMN_STATISTICS' in information_schema' bug
  271. # https://stackoverflow.com/questions/52423595/mysqldump-couldnt-execute-unknown-table-column-statistics-in-information-sc
  272. if mysqldump_version[0] == 'mysql' and mysqldump_version[1] >= "8":
  273. try:
  274. self.from_server.exec_query("SELECT COLUMN_NAME FROM information_schema.COLUMN_STATISTICS;")
  275. except pymysql.err.OperationalError:
  276. base_cmd.append("--column-statistics=0")
  277. except pymysql.err.MySQLError:
  278. pass
  279. # -->
  280. if self.compress:
  281. base_cmd.append("--compress")
  282. if SHOW_PROGRESSION:
  283. base_cmd.append("--verbose")
  284. if self.from_server.ssh_tunnel:
  285. host, port = self.from_server.ssh_tunnel.LOCAL_ADRESS
  286. base_cmd += ["--host", host,
  287. "--port", str(port)]
  288. return base_cmd + dump_options + [self.dbname] + tables
  289. def _build_restore_command(self):
  290. """ Build a mysql command line and return it as a
  291. ready-to-consume list for Popen
  292. @see https://dev.mysql.com/doc/refman/8.0/en/mysql-command-options.html#option_mysql_quick
  293. """
  294. init_command = f"set global max_allowed_packet={MAX_ALLOWED_PACKET};" \
  295. "set global wait_timeout=28800;" \
  296. "set global interactive_timeout=28800;"
  297. cmd = ["mysql",
  298. "-h", self.to_server.host,
  299. "-P", str(self.to_server.port),
  300. "-u", self.to_server.username,
  301. f"--password={self.to_server.password}",
  302. f"--init-command={init_command}",
  303. "--reconnect",
  304. "--quick",
  305. "--unbuffered",
  306. "--wait",
  307. "--verbose",
  308. "-D", self.dbname
  309. ]
  310. # if LOG_PIPES_OUTPUT:
  311. # cmd.append("--verbose")
  312. if self.compress:
  313. cmd.append("--compress")
  314. return cmd
  315. @staticmethod
  316. def _run_piped_processes(
  317. dump_cmd,
  318. restore_cmd,
  319. tbl_count):
  320. """ Run the dump and the restore commands by piping them
  321. The output of the mysqldump process is piped into the input of the mysql one
  322. """
  323. logger.debug(">>> Dump command: %s", " ".join(map(str, dump_cmd)))
  324. logger.debug(">>> Piped into: %s", " ".join(map(str, restore_cmd)))
  325. mysqldump_handler = MysqldumpHandler(logger.name, logging.INFO, tbl_count)
  326. mysql_handler = MysqlHandler(logger.name, logging.INFO, tbl_count)
  327. try:
  328. # noinspection PyTypeChecker
  329. with Popen(restore_cmd, stdin=PIPE, stdout=mysql_handler, stderr=mysql_handler) as mysql:
  330. # noinspection PyTypeChecker
  331. with Popen(dump_cmd, stdout=PIPE, stderr=mysqldump_handler) as mysqldump:
  332. mysql.stdin.write(mysqldump.stdout.read())
  333. if mysqldump.returncode:
  334. raise RuntimeError('mysqldump returned a non zero code')
  335. if mysql.returncode:
  336. raise RuntimeError('mysql returned a non zero code')
  337. mysql_handler.log_end()
  338. except (OSError, RuntimeError, CalledProcessError) as e:
  339. logger.error("Execution failed: %s", e)
  340. raise RuntimeError(f"An error happened at runtime: {e}")
  341. finally:
  342. mysqldump_handler.close()
  343. mysql_handler.close()
  344. def run(self):
  345. """ Run the cloning op
  346. """
  347. logger.info(f"*** Cloning {self.dbname} ***")
  348. logger.info(f"> From {self.from_server}")
  349. logger.info(f"> To {self.to_server}")
  350. try:
  351. self.from_server.connect()
  352. self.from_server.set_active_db(self.dbname)
  353. logger.debug('Connected to %s', self.from_server)
  354. self.to_server.connect()
  355. logger.debug('Connected to %s', self.to_server)
  356. # Create admin users if not exist
  357. for user in self.grant:
  358. exists = self.to_server.exec_query(
  359. f"SELECT count(*) FROM mysql.user WHERE User = '{user.username}' and Host='{user.host}';"
  360. ).fetchone()[0] > 0
  361. if not exists:
  362. logger.info(f'Create user %s@%s on %s', user.username, user.host, self.to_server)
  363. self.to_server.exec_query(
  364. f"CREATE USER '{user.username}'@'{user.host}' IDENTIFIED BY '{user.pwd}';")
  365. # List tables
  366. tables = {}
  367. for tname in self.from_server.list_tables():
  368. if any(rx.match(tname) for rx in self.ignore_tables):
  369. tables[tname] = IGNORE
  370. elif self.filter_tables and not any(rx.match(tname) for rx in self.filter_tables):
  371. tables[tname] = IGNORE
  372. elif any(rx.match(tname) for rx in self.structure_only):
  373. tables[tname] = STRUCTURE_ONLY
  374. else:
  375. tables[tname] = STRUCTURE_AND_DATA
  376. restore_cmd = self._build_restore_command()
  377. # Dump structure: --single-transaction --no-data --routines {dbname} tbname1 tname2 ...
  378. dump_structure_for = [t for t, s in tables.items() if s != IGNORE]
  379. dump_structure_cmd = self._build_dump_command(["--no-data", "--routines"],
  380. dump_structure_for)
  381. # Dump data: --no-create-info --skip-triggers {dbname} tbname1 tname2 ...
  382. dump_data_for = [t for t, s in tables.items() if s == STRUCTURE_AND_DATA]
  383. dump_data_cmd = self._build_dump_command(["--no-create-info", "--skip-triggers"],
  384. dump_data_for)
  385. if tables and not dump_structure_for and not dump_data_for:
  386. logging.warning('No table will be cloned')
  387. # Recreate the target DB
  388. logger.info("(Re)create the database")
  389. self.to_server.exec_query(f"DROP DATABASE IF EXISTS `{self.dbname}`;")
  390. self.to_server.exec_query(f"CREATE SCHEMA `{self.dbname}`;")
  391. self.to_server.set_active_db(self.dbname)
  392. # Grant admin users if any
  393. for user in self.grant:
  394. self.to_server.exec_query(
  395. f"GRANT ALL ON {self.dbname}.* TO '{user.username}'@'{user.host}';"
  396. )
  397. # Run mysqldump
  398. try:
  399. if dump_structure_for:
  400. logger.info(f"Cloning structure for {len(dump_structure_for)} tables (on {len(tables)})...")
  401. self._run_piped_processes(
  402. dump_structure_cmd,
  403. restore_cmd,
  404. len(dump_structure_for)
  405. )
  406. if dump_data_for:
  407. logger.info(f"Cloning data for {len(dump_data_for)} tables (on {len(tables)})...")
  408. self._run_piped_processes(
  409. dump_data_cmd,
  410. restore_cmd,
  411. len(dump_data_for)
  412. )
  413. logger.info(f"Cloning views...")
  414. self.from_server.set_active_db(self.dbname)
  415. self.to_server.set_active_db(self.dbname)
  416. for v in self.from_server.list_views(self.dbname):
  417. if any(rx.match(v) for rx in self.ignore_views):
  418. continue
  419. logger.debug('* cloning view %s', v)
  420. definition = self.from_server.get_view_definition(v, self.to_server.username)
  421. try:
  422. self.to_server.exec_query(definition)
  423. except (pymysql.err.ProgrammingError, pymysql.err.InternalError) as e:
  424. logger.error('Unable to create the internal view %s: %s', v, e)
  425. self.status = SUCCESS
  426. logger.info("> the database was successfully cloned")
  427. except RuntimeError:
  428. self.status = FAILURE
  429. logger.error("<!> An error happened while cloning the '%s' database", self.dbname)
  430. finally:
  431. self.from_server.close()
  432. self.to_server.close()
  433. def main(settings, arguments):
  434. prompt = not arguments["--yes"]
  435. logger.info("Start db cloning utility...")
  436. logger.debug(f"Settings: %s", str(settings).replace('\r', '').replace('\n', ''))
  437. logger.debug(f"Arguments: %s", str(arguments).replace('\r', '').replace('\n', ''))
  438. # Load the servers' configuration
  439. servers = {}
  440. if 'servers' not in settings:
  441. raise RuntimeError(f'Missing section in settings.yml: {servers}')
  442. for server_name, server_settings in settings['servers'].items():
  443. hostname = server_settings['host']
  444. match = re.search(r"^docker:(\w+)$", hostname)
  445. if match:
  446. logger.debug("resolve IP for docker %s", match.group(1))
  447. ip = resolve_docker_ip(match.group(1))
  448. logger.debug("substitute '%s' to '%s' as hostname", ip, hostname)
  449. hostname = ip
  450. if 'ssh' in server_settings:
  451. ssh_tunnel = SshTunnel(hostname, server_settings['mysql']['port'], **server_settings['ssh'])
  452. else:
  453. ssh_tunnel = None
  454. server = MySqlServer(hostname,
  455. **server_settings['mysql'],
  456. description=server_settings['description'],
  457. ssh_tunnel=ssh_tunnel)
  458. servers[server_name] = server
  459. # Load the users' configuration
  460. users = {}
  461. for username, args in settings.get('users', {}).items():
  462. host = args.get('host', 'localhost')
  463. pwd = args.get('pwd', '')
  464. users[username] = MysqlUser(username, pwd, host)
  465. # Load the cloning ops' configuration
  466. ops = {}
  467. if 'operations' not in settings:
  468. raise RuntimeError(f'Missing section in settings.yml: {servers}')
  469. for name, args in settings['operations'].items():
  470. dbname = args['dbname']
  471. from_server = servers[args['from_server']]
  472. to_server = servers[args['to_server']]
  473. grant = args.get('grant', [])
  474. admins = [user for username, user in users.items() if username in grant]
  475. kwargs = {k: v for k, v in args.items() \
  476. if k not in ('dbname', 'from_server', 'to_server', 'grant')}
  477. op = CloningOperation(name, dbname, from_server, to_server, admins, **kwargs)
  478. ops[name] = op
  479. # Operations to launch
  480. if arguments.get('<opname>', None):
  481. selected_ops = []
  482. for opname in arguments['<opname>']:
  483. try:
  484. selected_ops.append(ops[opname])
  485. except KeyError:
  486. logger.error('No operation found with name %s', opname)
  487. else:
  488. selected_ops = [op for op in ops.values() if op.is_default]
  489. if not selected_ops:
  490. logger.error('No operations to launch')
  491. return
  492. # Ask for confirmation (except if '--yes' is in arguments)
  493. if prompt:
  494. logger.debug('Ask for confirmation...')
  495. msg = "The following operations will be launched:\n{}\n" \
  496. "WARNING: the existing local databases will be replaced" \
  497. "".format("\n".join(f"* {op}" for op in selected_ops))
  498. if not ask_confirmation(msg):
  499. logger.info("-- Operation cancelled by user --")
  500. return
  501. logger.debug('> User confirmed')
  502. # Run the cloning operations
  503. for op in selected_ops:
  504. op.run()
  505. failures = [op.name for op in selected_ops if op.status == FAILURE]
  506. if failures:
  507. logger.error("WARNING! the following operations failed: %s", ', '.join(failures))
  508. if __name__ == '__main__':
  509. # load settings from settings.yml file
  510. settings = load_settings()
  511. # parse CLI arguments
  512. arguments = docopt(__doc__, help=__doc__, version=__VERSION__)
  513. with Lockfile(path=HERE / '.clonedb.lock',
  514. on_error=lambda: logger.critical("A cloning process is already running, please wait...")):
  515. main(settings, arguments)