mysqldume.py代码分析

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

 可以根据实际需求修改,先来看看

 
  1. #!/usr/bin/env python 
  2. # -*- coding: utf-8 -*- 
  3. __title__ = "mysqlpdump" 
  4. __version__ = "0.5" 
  5. __author__= "Carles Amigo" 
  6. __email__= "fr3nd at fr3nd dot net" 
  7. __website__= "http://www.fr3nd.net/projects/mysqlpdump" 
  8.  
  9. import threading, Queue 
  10. import MySQLdb 
  11. from optparse import OptionParser 
  12. import commands 
  13. import sys 
  14. import os 
  15. import gzip 
  16.  
  17. class Log: 
  18.     """Simple class for logging""" 
  19.     def __init__(self, verbose): 
  20.         self.verbose = verbose 
  21.  
  22.     def log(self, line): 
  23.         """Logs an especified line""" 
  24.         if self.verbose: 
  25.             sys.stderr.write (" - " + str(line) + "\n"
  26.  
  27. class Database: 
  28.     """Class to handle database connection""" 
  29.     def __init__(self, log, mysqluser, mysqlpass, mysqlhost): 
  30.         self.user = mysqluser 
  31.         self.password = mysqlpass 
  32.         self.host = mysqlhost 
  33.         self.log = log 
  34.         self.log.log("Connecting to database"
  35.         self.db=MySQLdb.connect(user=mysqluser,passwd=mysqlpass,host=mysqlhost) 
  36.         self.cursor = self.db.cursor() 
  37.  
  38.     def close(self): 
  39.         self.log.log("Closing database connection"
  40.         self.db.close() 
  41.  
  42.     def lock(self): 
  43.         """Locks all tables for read/write""" 
  44.         self.log.log("Locking all tables"
  45.         self.cursor.execute("FLUSH TABLES WITH READ LOCK;"
  46.  
  47.     def unlock(self): 
  48.         """Unlocks all tables in the database""" 
  49.         self.log.log("Unlocking all tables"
  50.         self.cursor.execute("UNLOCK TABLES"
  51.  
  52.     def get_databases(self, included, excluded): 
  53.         """Return all the databases. Included and excluded databases can be specified""" 
  54.         self.cursor.execute("show databases;"
  55.         result = self.cursor.fetchall() 
  56.         databases = [] 
  57.         for database in result: 
  58.             if len(included) == 0
  59.                 if database[0not in excluded: 
  60.                     databases.append(database[0]) 
  61.             else
  62.                 if (database[0in included) and (database[0not in excluded): 
  63.                     databases.append(database[0]) 
  64.         return databases 
  65.  
  66.     def get_tables(self, database): 
  67.         """Return all tables for a given database""" 
  68.         self.cursor.execute("show tables from " + str(database) + ";"
  69.         result = self.cursor.fetchall() 
  70.         tables = [] 
  71.         for table in result: 
  72.             tables.append(table[0]) 
  73.         return tables 
  74.  
  75.     def get_slave_status(self): 
  76.         """Return slave status""" 
  77.         self.cursor.execute("show slave status;"
  78.         result = self.cursor.fetchall() 
  79.         return result 
  80.  
  81.     def get_change_master_to(self, slave_status): 
  82.         try
  83.             return "CHANGE MASTER TO MASTER_HOST=\'" + slave_status[0][1] + "\', MASTER_LOG_FILE=\'" + slave_status[0][5] + "\', MASTER_LOG_POS=" + str(slave_status[0][6]) + ";" 
  84.         except
  85.             return "" 
  86.  
  87.     def mysqldump(self, database, table, destination, custom_parameters="", stdout=False, gzip=False, mysqldump="/usr/bin/mysqldump"): 
  88.         """Dumps a specified table. 
  89.         It can dump it to a file or just return all the dumped data. 
  90.         It can waste a lot of memory if its returning a big table.""" 
  91.  
  92.         default_parameters = "--skip-lock-tables" 
  93.  
  94.         cmd=mysqldump + " " + default_parameters 
  95.         if custom_parameters != "": 
  96.             cmd = cmd + " " + custom_parameters 
  97.         cmd = cmd + " -u" + self.user + " -p" + self.password + " -h" + self.host + " " + database + " " + table 
  98.         if stdout: 
  99.             return commands.getstatusoutput(cmd) 
  100.         else
  101.             file = destination + "/" + database + "-" + table + ".sql" 
  102.             if gzip: 
  103.                 cmd = cmd + " | gzip -c > " + file + ".gz" 
  104.             else
  105.                 cmd = cmd + " > " + file 
  106.             os.system(cmd) 
  107.             return (NoneNone
  108.  
  109.  
  110. class Worker(threading.Thread): 
  111.     def __init__(self, queue, log, db, event_dict, destination, custom_parameters="", stdout=False, gzip=False, ): 
  112.         threading.Thread.__init__(self
  113.         self.queue = queue 
  114.         self.log = log 
  115.         self.db = db 
  116.         self.event_dict = event_dict 
  117.         self.stdout = stdout 
  118.         self.gzip = gzip 
  119.         self.destination = destination 
  120.         self.custom_parameters = custom_parameters 
  121.  
  122.     def run(self): 
  123.         self.log.log("Worker " + self.getName() + " started"
  124.         while True
  125.             try
  126.                 num, database, table = self.queue.get(True1
  127.             except Queue.Empty: 
  128.                 break 
  129.             self.event_dict[num] = threading.Event() 
  130.             self.event_dict[num].clear() 
  131.             self.log.log(self.getName() + " dumping " + database + " " + table) 
  132.             status, output = self.db.mysqldump(database, table, custom_parameters=self.custom_parameters, stdout=self.stdout, gzip=self.gzip, destination=self.destination) 
  133.             if self.stdout: 
  134.                 if num > 0
  135.                     while not self.event_dict[num-1].isSet(): 
  136.                         self.event_dict[num-1].wait() 
  137.             self.log.log(self.getName() + " dumped " + database + " " + table) 
  138.             if output: 
  139.                 print output 
  140.             self.event_dict[num].set() 
  141.  
  142. def main(): 
  143.     try
  144.         current_user = os.getlogin() 
  145.     except
  146.         current_user = "nobody" 
  147.  
  148.     usage = "usage: %prog [options]\n Run mysqldump in paralel" 
  149.     parser = OptionParser(usage, version=__version__) 
  150.     parser.add_option("-v""--verbose", action="store_true", dest="verbose", default=False, help="verbose output."
  151.     parser.add_option("-u""--user", action="store", dest="user", type="string", default=current_user, help="User for login."
  152.     parser.add_option("-p""--password", action="store", dest="password", type="string", default='', help="Password for login."
  153.     parser.add_option("-H""--host", action="store", dest="host", type="string", default='localhost', help="Connect to host."
  154.     parser.add_option("-t""--threads", action="store", dest="threads", type="int", default=5, help="Threads used. Default = 5"
  155.     parser.add_option("-s""--stdout", action="store_true", dest="stdout", default=False, help="Output dumps to stdout instead to files. WARNING: It can exaust all your memory!"
  156.     parser.add_option("-g""--gzip", action="store_true", dest="gzip", default=False, help="Add gzip compression to files."
  157.     parser.add_option("-m""--master-data", action="store_true", dest="master_data", default=False, help="This causes the binary log position and filename to be written to the file 00_master_data.sql."
  158.     parser.add_option("-d""--destination", action="store", dest="destination", type="string", default=".", help="Path where to store generated dumps."
  159.     parser.add_option("-P""--parameters", action="store", dest="parameters", type="string", default="", help="Pass parameters directly to mysqldump.") 
  160.     parser.add_option("-i""--include_database", action="append", dest="included_databases", default=[], help="Databases to be dumped. By default, all databases are dumped. Can be called more than one time."
  161.     parser.add_option("-e""--exclude_database", action="append", dest="excluded_databases", default=[], help="Databases to be excluded from the dump. No database is excluded by default. Can be called more than one time."
  162.  
  163.  
  164.     (options, args) = parser.parse_args() 
  165.  
  166.     log = Log(options.verbose) 
  167.     try
  168.         db = Database(log, options.user, options.password, options.host) 
  169.     except
  170.         parser.error("Cannot connect to database"
  171.     db.lock() 
  172.     queue = Queue.Queue() 
  173.  
  174.     x = 0 
  175.  
  176.     if options.master_data: 
  177.         if options.gzip: 
  178.             f=gzip.open(options.destination + '/00_master_data.sql.gz''w'
  179.         else
  180.             f=open(options.destination + '/00_master_data.sql''w'
  181.         f.write(db.get_change_master_to(db.get_slave_status())) 
  182.         f.write('\n'
  183.         f.close() 
  184.  
  185.     for database in db.get_databases(options.included_databases, options.excluded_databases): 
  186.         for table in db.get_tables(database): 
  187.             queue.put([x,database,table]) 
  188.             x = x + 1 
  189.  
  190.     event_dict = {} 
  191.     threads = [] 
  192.     x = 0 
  193.     for i in range(options.threads): 
  194.         threads.append(Worker(queue, log, db, event_dict, custom_parameters=options.parameters, stdout=options.stdout, gzip=options.gzip, destination=options.destination)) 
  195.         threads[x].setDaemon(True
  196.         threads[x].start() 
  197.         x = x + 1 
  198.  
  199.     # Wait for all threads to finish 
  200.     for thread in threads: 
  201.         thread.join() 
  202.  
  203.     db.unlock() 
  204.     db.close() 
  205.  
  206. if __name__ == "__main__"
  207.     main() 

 



     本文转自 珏石头 51CTO博客,原文链接:http://blog.51cto.com/gavinshaw/574638,如需转载请自行联系原作者




相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5月前
|
测试技术 Python
关于python3 unittest 调用unittest.main() 执行多个测试函数并没有顺次执行的探讨。
在学习Python的单元测试的时候,扩展了一下,本来是想用setup和tearDown做一个简单的编号记录。然而,发现了问题。
31 0
|
5月前
|
Python
Python 关于模块的几点介绍 。和。。和__all__和__main___和__file__
用来定义我们导出的内容可以有哪些的一个编码方式
20 0
|
9月前
|
程序员 开发者 Python
#PY小贴士# py2 和 py3 的差别到底有多大?
虽然结论已经很明确,但我还是想客观地说一句:对于学习者来说,学 py2 还是 py3,真的没有太大差别。之所以这会成为一个问题
|
6月前
|
测试技术 Python
python之测试代码
python之测试代码
|
7月前
|
测试技术 数据库连接 Python
conftest.py是什么?该怎么用?
conftest.py是什么?该怎么用?
99 0
|
测试技术
基于UIAutomation+Python+Unittest+Beautifulreport的WindowsGUI自动化测试框架主入口main解析
基于UIAutomation+Python+Unittest+Beautifulreport的WindowsGUI自动化测试框架主入口main解析
158 0
|
测试技术
pytest学习和使用9-fixture中conftest.py如何使用?
pytest学习和使用9-fixture中conftest.py如何使用?
104 0
pytest学习和使用9-fixture中conftest.py如何使用?
|
Python
接口自动化框架(Python)之 三,base.py的配置
接口自动化框架(Python)之 三,base.py的配置
93 0
【pytest】(四) pytest的一些其他的运行用法
【pytest】(四) pytest的一些其他的运行用法
|
数据采集 存储 Shell
[oeasy]教您玩转python - 0003 - 编写 py 文件
​ [oeasy]python3-用vim编辑python文件 [点击并拖拽以移动] 编写 py 文件 🥊 回忆上次内容 上次在解释器里玩耍 了解到字符串就是给一堆字符两边加引号 可以是单引号 也可以是双引号 这样游乐场就知道 这个不是一个名字 而是一个字符串 字符串可以用print函数进行输出 但是print千万不要打错 就连大小写都不能错 我们在游乐场玩了这么久 能否写一个真正的python文件啊?🤔 编辑
178 0
 [oeasy]教您玩转python - 0003 - 编写 py 文件