clonedb.py 17 KB

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