blob: f57127ca838fd8878bf10fd1fcac47adec9e8fbb [file] [log] [blame]
Scott Baker6bd238f2019-04-16 16:28:52 -07001# Copyright 2017-present Open Networking Foundation
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15""" BackupHandler
16
17 This file contains code to interface with various backends (django, postgres, etc) for creating
18 and restoring backups. Backend-specific code is isolated here to make it easier to port and easier
19 to use.
20"""
21
22import os
23
24from xosconfig import Config
25from multistructlog import create_logger
26
27# TODO(smbaker): Write a django BackupHandler that uses dumpdata and loaddata
28
29
30class BackupHandler_postgres(object):
31 """ This backuphandler uses postgres pg_dump and psql """
32 def __init__(self):
33 self.db_name = Config().get("database.name")
34 self.db_username = Config().get("database.username")
35 self.db_password = Config().get("database.password")
36 self.db_host = "xos-db"
37 self.db_port = "5432"
38 self.log = create_logger(Config().get("logging"))
39
40 def backup(self, filename):
41 cmd = "PGPASSWORD=\"%s\" pg_dump -h %s -p %s -U %s -c %s > %s" % \
42 (self.db_password, self.db_host, self.db_port, self.db_username, self.db_name, filename)
43 self.log.info("Shell execute: %s" % cmd)
44 result = os.system(cmd)
45 self.log.info("Shell result", result=result)
46 if result != 0:
47 raise Exception("pgdump failed")
48
49 def restore(self, filename):
50 cmd = "PGPASSWORD=\"%s\" psql -h %s -p %s -U %s %s < %s > /dev/null" % \
51 (self.db_password, self.db_host, self.db_port, self.db_username, self.db_name, filename)
52 self.log.info("Shell execute: %s" % cmd)
53 result = os.system(cmd)
54 self.log.info("Shell result", result=result)
55 if result != 0:
56 raise Exception("psql failed")
57
58
59BackupHandler = BackupHandler_postgres