clonedb.py 22 KB

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