mysql主從日誌的定期清理

mysql主從的binlog定時刪除是很重要的,一般是通過expire_logs_days = 10來設置binlog保留的天數(mysql5.0一下版本不支持),但有時這還不夠,假如有幾天的日誌量非常大,硬盤可能會滿,所以不但要設置保留的天數,還要監控硬盤的空間使用情況。寫了一個腳本,適合各個版本的mysql,保留3天的日誌,當存放日誌的硬盤使用率超過80%,則保留2天,但至少會保留一天的binlog日誌文件。

  1. #!/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ##############################################################
  4. #查看存在binlog的目錄位置並找出3天前的最後一個bin-log文件名字
  5. #刪除3天以前的binlog文件,刪除之後data1目錄掛載的硬盤使用率超
  6. #過的80%的話,繼續刪除2天前的日誌文件,至少保留一天的日誌。
  7. ##############################################################
  8. import os,sys,time,MySQLdb
  9. def log_w(text):
  10. logfile = "/usr/local/zabbix/bin/delet.log"
  11. now = time.strftime("%Y-%m-%d %H:%M:%S")
  12. tt = now + "\t" + str(text) + "\n"
  13. f = open(logfile,'a+')
  14. f.write(tt)
  15. f.close()
  16. def mysql_conn(port,lastlog,days):
  17. try:
  18. center_ip = '127.0.0.1'
  19. center_user = 'repl_monitor'
  20. center_passwd = 'VQMQLGwTaw3k0UV8'
  21. sql = "PURGE MASTER LOGS TO '%s';" % lastlog
  22. conn = MySQLdb.connect(host = center_ip,port = int(port),user = center_user,passwd = center_passwd,connect_timeout=5)
  23. cursor = conn.cursor()
  24. cursor.execute(sql)
  25. alldata = cursor.fetchall()
  26. cursor.close()
  27. conn.close()
  28. text = "Deltet before %s days binlog,deltet %s before !" % (days,lastlog)
  29. log_w(text)
  30. except Exception,e:
  31. log_w(e)
  32. def find_logdir():
  33. conn = "find / -name binlog|grep -v usr"
  34. logdir_list = os.popen(conn).readlines()
  35. if len(logdir_list) != 0:
  36. for logdir in logdir_list:
  37. datadir = logdir.strip().split("/")[1]
  38. if "mysql_log" in logdir.strip():
  39. port = 3306
  40. else:
  41. port = logdir.strip().split("/")[3].split("-")[-1]
  42. days = 3
  43. while 1:
  44. conn = "find %s -mtime %s|sort" % (logdir.strip(),days)
  45. count = os.popen(conn).readlines()
  46. if len(count) != 0:
  47. lastlog = count[-1].strip().split("/")[-1]
  48. mysql_conn(port,lastlog,days)
  49. df = "df -h|grep -e '%s$'|awk '{print $5}'|awk -F '%%' '{print $1}'" % datadir
  50. disk = os.popen(df).read().strip()
  51. if not disk:
  52. break
  53. else:
  54. if int(disk) < 80:
  55. break
  56. else:
  57. days = days - 1
  58. if days == 1:
  59. break
  60. else:
  61. sys.exit()
  62. if __name__ == "__main__":
  63. find_logdir()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章