Add scheduled database backups

This commit is contained in:
JonnyWong16 2016-02-17 18:41:55 -08:00
parent 3926d97fc6
commit 85b3f081bf
4 changed files with 31 additions and 29 deletions

View file

@ -333,7 +333,7 @@ def initialize_scheduler():
schedule_job(pmsconnect.refresh_libraries, 'Refresh libraries list', schedule_job(pmsconnect.refresh_libraries, 'Refresh libraries list',
hours=hours, minutes=0, seconds=0) hours=hours, minutes=0, seconds=0)
schedule_job(database.make_backup, 'Backup PlexPy database', hours=6, minutes=0, seconds=0, args=(True,)) schedule_job(database.make_backup, 'Backup PlexPy database', hours=6, minutes=0, seconds=0, args=(True, True))
# Start scheduler # Start scheduler
if start_jobs and len(SCHED.get_jobs()): if start_jobs and len(SCHED.get_jobs()):

View file

@ -275,22 +275,6 @@ class API2:
self.data = rows self.data = rows
return rows return rows
def backupdb(self, cleanup=False):
""" Makes a backup of the db, removes all but the 3 last backups
Args:
cleanup: (bool, optional)
"""
data = database.make_backup(cleanup=cleanup)
if data:
self.result_type = 'success'
else:
self.result_type = 'failed'
return data
def restart(self, **kwargs): def restart(self, **kwargs):
""" Restarts plexpy """ """ Restarts plexpy """

View file

@ -13,11 +13,11 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with PlexPy. If not, see <http://www.gnu.org/licenses/>. # along with PlexPy. If not, see <http://www.gnu.org/licenses/>.
import arrow
import os import os
import sqlite3 import sqlite3
import shutil import shutil
import threading import threading
import time
import logger import logger
import plexpy import plexpy
@ -46,16 +46,19 @@ def db_filename(filename="plexpy.db"):
return os.path.join(plexpy.DATA_DIR, filename) return os.path.join(plexpy.DATA_DIR, filename)
def make_backup(cleanup=False): def make_backup(cleanup=False, scheduler=False):
""" Makes a backup of db, removes all but the last 5 backups """ """ Makes a backup of db, removes all but the last 5 backups """
backupfolder = plexpy.CONFIG.BACKUP_DIR if scheduler:
backup_file = 'plexpy.backup-%s.db' % int(time.time()) backup_file = 'plexpy.backup-%s.sched.db' % arrow.now().format('YYYYMMDDHHmmss')
backup_file_fp = os.path.join(backupfolder, backup_file) else:
backup_file = 'plexpy.backup-%s.db' % arrow.now().format('YYYYMMDDHHmmss')
backup_folder = plexpy.CONFIG.BACKUP_DIR
backup_file_fp = os.path.join(backup_folder, backup_file)
# In case the user has deleted it manually # In case the user has deleted it manually
if not os.path.exists(backupfolder): if not os.path.exists(backup_folder):
os.makedirs(backupfolder) os.makedirs(backup_folder)
db = MonitorDatabase() db = MonitorDatabase()
db.connection.execute('begin immediate') db.connection.execute('begin immediate')
@ -63,9 +66,9 @@ def make_backup(cleanup=False):
db.connection.rollback() db.connection.rollback()
if cleanup: if cleanup:
# Delete all backup files except from the last 5. # Delete all scheduled backup files except from the last 5.
for root, dirs, files in os.walk(backupfolder): for root, dirs, files in os.walk(backup_folder):
db_files = [os.path.join(root, f) for f in files if f.endswith('.db')] db_files = [os.path.join(root, f) for f in files if f.endswith('.sched.db')]
if len(db_files) > 5: if len(db_files) > 5:
backups_sorted_on_age = sorted(db_files, key=os.path.getctime, reverse=True) backups_sorted_on_age = sorted(db_files, key=os.path.getctime, reverse=True)
for file_ in backups_sorted_on_age[5:]: for file_ in backups_sorted_on_age[5:]:
@ -74,7 +77,7 @@ def make_backup(cleanup=False):
except OSError as e: except OSError as e:
logger.error(u"PlexPy Database :: Failed to delete %s from the backup folder: %s" % (file_, e)) logger.error(u"PlexPy Database :: Failed to delete %s from the backup folder: %s" % (file_, e))
if backup_file in os.listdir(backupfolder): if backup_file in os.listdir(backup_folder):
logger.debug(u"PlexPy Database :: Successfully backed up %s to %s" % (db_filename(), backup_file)) logger.debug(u"PlexPy Database :: Successfully backed up %s to %s" % (db_filename(), backup_file))
return True return True
else: else:

View file

@ -13,7 +13,7 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with PlexPy. If not, see <http://www.gnu.org/licenses/>. # along with PlexPy. If not, see <http://www.gnu.org/licenses/>.
from plexpy import logger, notifiers, plextv, pmsconnect, common, log_reader, datafactory, graphs, users, libraries from plexpy import logger, notifiers, plextv, pmsconnect, common, log_reader, datafactory, graphs, users, libraries, database
from plexpy.helpers import checked, addtoapi, get_ip, create_https_certificates from plexpy.helpers import checked, addtoapi, get_ip, create_https_certificates
from mako.lookup import TemplateLookup from mako.lookup import TemplateLookup
@ -1339,6 +1339,21 @@ class WebInterface(object):
def get_scheduler_table(self, **kwargs): def get_scheduler_table(self, **kwargs):
return serve_template(templatename="scheduler_table.html") return serve_template(templatename="scheduler_table.html")
@cherrypy.expose
@addtoapi()
def backup_db(self):
""" Creates a manual backup of the plexpy.db file """
result = database.make_backup(scheduler=False)
if result:
cherrypy.response.headers['Content-type'] = 'application/json'
return json.dumps({'message': 'Database backup successful.'})
else:
cherrypy.response.headers['Content-type'] = 'application/json'
return json.dumps({'message': 'Database backup failed.'})
@cherrypy.expose @cherrypy.expose
def get_notification_agent_config(self, agent_id, **kwargs): def get_notification_agent_config(self, agent_id, **kwargs):
if agent_id.isdigit(): if agent_id.isdigit():