説明なし

backup.py 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # IRIS Core Code
  2. # contact@dfir-iris.org
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU Lesser General Public
  6. # License as published by the Free Software Foundation; either
  7. # version 3 of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # Lesser General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Lesser General Public License
  15. # along with this program; if not, write to the Free Software Foundation,
  16. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. import subprocess
  18. from datetime import datetime
  19. from pathlib import Path
  20. from app import app
  21. log = app.logger
  22. def backup_iris_db():
  23. logs = []
  24. backup_dir = Path(app.config.get('BACKUP_PATH')) / "database"
  25. try:
  26. if not backup_dir.is_dir():
  27. backup_dir.mkdir()
  28. except Exception as e:
  29. logs.append('Unable to create backup directory')
  30. logs.append(str(e))
  31. return True, logs
  32. backup_file = Path(app.config.get('BACKUP_PATH')) / "database" / "backup-{}.sql.gz".format(
  33. datetime.now().strftime("%Y-%m-%d_%H%M%S"))
  34. try:
  35. logs.append('Saving database')
  36. with open(backup_file, 'w') as backup:
  37. completed_process = subprocess.run(
  38. [f'{app.config.get("PG_CLIENT_PATH")}/pg_dump', '-h',
  39. app.config.get('PG_SERVER'), '-p',
  40. app.config.get('PG_PORT'),
  41. '-U', app.config.get('PGA_ACCOUNT'),
  42. '--compress=9', '-c', '-O', '--if-exists', app.config.get('PG_DB')],
  43. stdout=backup,
  44. env={'PGPASSWORD': app.config.get('PGA_PASSWD')},
  45. check=True
  46. )
  47. except Exception as e:
  48. logs.append('Something went wrong backing up DB')
  49. logs.append(str(e))
  50. return True, logs
  51. try:
  52. completed_process.check_returncode()
  53. except subprocess.CalledProcessError as e:
  54. logs.append('Something went wrong backing up DB')
  55. logs.append(str(e))
  56. return True, logs
  57. if backup_file.is_file() and backup_file.stat().st_size != 0:
  58. logs.append(f'Backup completed in {backup_file}')
  59. return False, logs