clonedb.py 18 KB

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