update_backup_copy_stats.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # $Id: btrfs-diskusage.py,v 1.1 2022/10/17 07:53:20 springm Exp springm $
  4. # $Revision: 1.1 $
  5. # $Date: 2022/10/17 07:53:20 $
  6. # $Log: btrfs-diskusage.py,v $
  7. # Revision 1.1 2022/10/17 07:53:20 springm
  8. # Initial revision
  9. '''
  10. * (shell) Lokaler Mount der Backup-Kopie
  11. * backup_the_backup.sh muss als root laufen.
  12. * rsync-kopiere repository von hermes (backup_the_backup.sh)
  13. /var/lib/restic und /var/lib/restic/backupcopies.json auf hermes
  14. müssen für springm beschreibbar sein
  15. * Hole json-file per scp von hermes
  16. * update json-file lokal
  17. * Eintrag mit aktuellem Datum
  18. * __summary updaten
  19. * kopiere json-file per scp auf hermes
  20. * umount der Backup-Kopie
  21. '''
  22. # ------------------------------------------- start script variables ---
  23. remotehost = 'hermes'
  24. ssh_username = 'root'
  25. remoterepo = '/backupdisk/backupdisk/restic-repo'
  26. #json_remotefile = '/var/lib/restic/backupcopies.json'
  27. json_localfile = '/tmp/backupcopies.json'
  28. # UUID ermitteln mit blkid
  29. snapcolors = { 'a0942a33-911d-429f-9e7d-cf38f3730525' : 'blau',
  30. '1faf4622-fd5d-4cde-8d6a-8c9e9b0c7c5b' : 'violett' }
  31. # --------------------------------------------- end script variables ---
  32. import argparse
  33. import datetime
  34. from datetime import datetime, timedelta, timezone
  35. import json
  36. import re
  37. import socket
  38. import subprocess
  39. import sys
  40. from paramiko import SSHClient
  41. from scp import SCPClient
  42. jso = {}
  43. def load_jsonfile( ):
  44. try:
  45. with open(json_localfile, 'r') as openfile:
  46. jso = json.load(openfile)
  47. except:
  48. print(f"Warning: could not open {json_localfile}. Exiting.")
  49. sys.exit(1)
  50. # try:
  51. # with SCPClient(ssh.get_transport()) as scp:
  52. # scp.get(json_remotefile, local_path=json_localfile)
  53. # with open(json_localfile, 'r') as openfile:
  54. # jso = json.load(openfile)
  55. # except:
  56. # print(f"Warning: could not get {json_remotefile} from {remotehost}")
  57. def disc_free ( mountpoint, host ):
  58. if host != False: # remote host
  59. cmd = [ 'ssh', host, 'bash', '-c', f"df | grep {mountpoint} | cut -b 52-61,64-68" ]
  60. s = subprocess.check_output( cmd ).decode('utf-8').strip().split(' ')
  61. else: # local host
  62. cmd = [ 'bash', '-c', f"df | grep {mountpoint} | cut -b 57-66,69-72" ]
  63. s = subprocess.check_output( cmd ).decode('utf-8').strip().split(' ')
  64. print("#".join(s))
  65. return( { 'fill_level' : s[1], 'bytes_free' : s[0] } )
  66. def disc_blkid ( mapperdev, host ):
  67. if host != False:
  68. cmd = [ 'ssh', host, f"""lsblk -n -o UUID {mapperdev}"""]
  69. s = subprocess.check_output( cmd ).decode('utf-8')
  70. else:
  71. cmd = [ 'bash', '-c', f"""lsblk -n -o UUID {mapperdev}"""]
  72. s = subprocess.check_output( cmd ).decode('utf-8')
  73. s = s.strip("\n")
  74. return(s)
  75. def nextcolor ( blkid ):
  76. for key in snapcolors:
  77. if key != blkid:
  78. return snapcolors[key]
  79. def update_json ():
  80. now = str(datetime.fromisoformat(args.repolastupdate))
  81. jso[now] = {}
  82. r_blkid = disc_blkid('/dev/mapper/backupdisk', remotehost)
  83. jso[now][r_blkid] = {}
  84. jso[now][r_blkid]['backup_server'] = remotehost
  85. jso[now][r_blkid]['bytes_free'] = disc_free('/backupdisk', remotehost)['bytes_free']
  86. jso[now][r_blkid]['fill_level'] = disc_free('/backupdisk', remotehost)['fill_level']
  87. print(jso[now][r_blkid]['fill_level'])
  88. localdevice = subprocess.check_output(['/usr/bin/grep', args.localrepobasedir, '/proc/mounts']).decode('utf-8').split()[0]
  89. blkid = disc_blkid(localdevice, False) # localhost
  90. jso[now][blkid] = {}
  91. jso[now][blkid]['bytes_free'] = disc_free(args.localrepobasedir, False)['bytes_free']
  92. jso[now][blkid]['fill_level'] = disc_free(args.localrepobasedir, False)['fill_level']
  93. print(jso[now][blkid]['fill_level'])
  94. jso[now][blkid]['color'] = snapcolors[blkid]
  95. jso['__summary'] = { 'last_backup_copy' : now,
  96. 'last_backup_blkid' : blkid,
  97. 'last_backup_color' : snapcolors[blkid],
  98. 'last_remotefreebytes' : jso[now][r_blkid]['bytes_free'],
  99. 'last_localfreebytes' : jso[now][blkid]['bytes_free'],
  100. 'last_remotefilllevel' : jso[now][r_blkid]['fill_level'],
  101. 'last_localfilllevel' : jso[now][blkid]['fill_level'],
  102. 'next_backup_color' : nextcolor(blkid) }
  103. def write_json():
  104. with open(json_localfile, 'w', encoding='utf-8') as f:
  105. json.dump(jso, f, ensure_ascii=False, indent=4)
  106. # try:
  107. # with SCPClient(ssh.get_transport()) as scp:
  108. # scp.put(json_localfile, json_remotefile)
  109. # except:
  110. # print(f"Error: could not copy {json_localfile} to {remotehost}:{json_remotefile}")
  111. def rewrite_snapshots_json(host):
  112. cmd = [ 'ssh', f"""{ssh_username}@{host}""", 'bash', '-c', "/usr/local/sbin/restic_json.sh" ]
  113. print(cmd)
  114. s = subprocess.check_output( cmd ).decode('utf-8').strip().split(' ')
  115. print(" ".join(s))
  116. # ------------------------------------------------------------- main ---
  117. parser = argparse.ArgumentParser(
  118. prog = sys.argv[0],
  119. description = 'Update json file of backup-of-backup stats',
  120. epilog = 'Markus ist ein cooler Hund')
  121. parser.add_argument('--localrepobasedir', help='local basedir of restic repo', required=True)
  122. parser.add_argument('--repolastupdate', help='last update timestamp of repo in full iso format', required=True)
  123. args = parser.parse_args()
  124. ssh = SSHClient()
  125. ssh.load_system_host_keys()
  126. ssh.connect(remotehost, username=ssh_username)
  127. load_jsonfile()
  128. update_json()
  129. #print(json.dumps(jso, sort_keys=True, indent=4))
  130. write_json()
  131. rewrite_snapshots_json(remotehost)