|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +:file: db_backup.py |
| 6 | +:language: python3 |
| 7 | +:author: Peter Bailie (Systems Programmer, Dept. of Computer Science, RPI) |
| 8 | +:date: May 22 2018 |
| 9 | +
|
| 10 | +This script will take backup dumps of each individual Submitty course |
| 11 | +database. This should be set up by a sysadmin to be run on the Submitty |
| 12 | +server as a cron job by root. Recommend that this is run nightly. |
| 13 | +
|
| 14 | +The term code can be specified as a command line argument "-t". |
| 15 | +The "-g" argument will guess the semester by the current month and year. |
| 16 | +Either -t or -g must be specified. |
| 17 | +
|
| 18 | +Dumpfile expiration can be specified as a command line argument "-e". This |
| 19 | +indicates the number of days of dumps to keep. Older dumps will be purged. |
| 20 | +Only old dumps of the semester being processed will be purged. Argument value |
| 21 | +must be an unsigned integer 0 - 999 or an error will be issued. "No expiration" |
| 22 | +(no files are purged regardless of age) is indicated by a value of 0, or when |
| 23 | +this argument is ommitted. |
| 24 | +
|
| 25 | +WARNING: Backup data contains sensitive information protected by FERPA, and |
| 26 | +as such should have very strict access permissions. |
| 27 | +
|
| 28 | +Change values under CONFIGURATION to match access properties of your |
| 29 | +university's Submitty database and file system. |
| 30 | +""" |
| 31 | + |
| 32 | +import argparse |
| 33 | +import datetime |
| 34 | +import os |
| 35 | +import re |
| 36 | +import subprocess |
| 37 | +import sys |
| 38 | + |
| 39 | +# CONFIGURATION |
| 40 | +DB_HOST = 'submitty.cs.myuniversity.edu' |
| 41 | +DB_USER = 'hsdbu' |
| 42 | +DB_PASS = 'DB.p4ssw0rd' # CHANGE THIS! DO NOT USE 'DB.p4ssw0rd' |
| 43 | +DUMP_PATH = '/var/local/submitty-dumps' |
| 44 | + |
| 45 | +def delete_obsolete_dumps(working_path, expiration_stamp): |
| 46 | + """ |
| 47 | + Recurse through folders/files and delete any obsolete dump files |
| 48 | +
|
| 49 | + :param working_path: path to recurse through |
| 50 | + :param expiration_stamp: date to begin purging old dump files |
| 51 | + :type working_path: string |
| 52 | + :type expiration_stamp: string |
| 53 | + """ |
| 54 | + |
| 55 | + # Filter out '.', '..', and any "hidden" files/directories. |
| 56 | + # Prepend full path to all directory list elements |
| 57 | + regex = re.compile('^(?!\.)') |
| 58 | + files_list = filter(regex.match, [working_path + '/{}'.format(x) for x in os.listdir(working_path)]) |
| 59 | + re.purge() |
| 60 | + |
| 61 | + for file in files_list: |
| 62 | + if os.path.isdir(file): |
| 63 | + # If the file is a folder, recurse |
| 64 | + delete_obsolete_dumps(file, expiration_stamp) |
| 65 | + else: |
| 66 | + # File date was concat'ed into the file's name. Use regex to isolate date from full path. |
| 67 | + # e.g. "/var/local/submitty-dumps/s18/cs1000/180424_s18_cs1000.dbdump" |
| 68 | + # The date substring can be located with high confidence by looking for: |
| 69 | + # - final token of the full path (the actual file name) |
| 70 | + # - file name consists of three tokens delimited by '_' chars |
| 71 | + # - first token is exactly 6 digits, the date stamp. |
| 72 | + # - second token is the semester code, at least one 'word' char |
| 73 | + # - third token is the course code, at least one 'word' char |
| 74 | + # - filename always ends in ".dbdump" |
| 75 | + # - then take substring [0:6] to get "180424". |
| 76 | + match = re.search('(\d{6}_\w+_\w+\.dbdump)$', file) |
| 77 | + if match is not None: |
| 78 | + file_date_stamp = match.group(0)[0:6] |
| 79 | + if file_date_stamp <= expiration_stamp: |
| 80 | + os.remove(file) |
| 81 | + |
| 82 | +def main(): |
| 83 | + """ Main """ |
| 84 | + |
| 85 | + # ROOT REQUIRED |
| 86 | + if os.getuid() != 0: |
| 87 | + raise SystemExit('Root required. Please contact your sysadmin for assistance.') |
| 88 | + |
| 89 | + # READ COMMAND LINE ARGUMENTS |
| 90 | + # Note that -t and -g are different args and mutually exclusive |
| 91 | + parser = argparse.ArgumentParser(description='Dump all Submitty databases for a particular academic term.') |
| 92 | + parser.add_argument('-e', action='store', nargs='?', type=int, default=0, help='Set number of days expiration of older dumps (default: no expiration).', metavar='days') |
| 93 | + group = parser.add_mutually_exclusive_group(required=True) |
| 94 | + group.add_argument('-t', action='store', nargs='?', type=str, help='Set the term code.', metavar='term code') |
| 95 | + group.add_argument('-g', action='store_true', help='Guess term code based on calender month and year.') |
| 96 | + args = parser.parse_args() |
| 97 | + |
| 98 | + # Get current date -- needed throughout the script, but also used when guessing default term code. |
| 99 | + # (today.year % 100) determines the two digit year. e.g. '2017' -> '17' |
| 100 | + today = datetime.date.today() |
| 101 | + year = str(today.year % 100) |
| 102 | + today_stamp = '{:0>2}{:0>2}{:0>2}'.format(year, today.month, today.day) |
| 103 | + |
| 104 | + # PARSE COMMAND LINE ARGUMENTS |
| 105 | + expiration = args.e |
| 106 | + if args.g is True: |
| 107 | + # Guess the term code by calendar month and year |
| 108 | + # Jan - May = (s)pring, Jun - July = s(u)mmer, Aug - Dec = (f)all |
| 109 | + # if month <= 5: ... elif month >=8: ... else: ... |
| 110 | + semester = 's' + year if today.month <= 5 else ('f' + year if today.month >= 8 else 'u' + year) |
| 111 | + else: |
| 112 | + semester = args.t |
| 113 | + |
| 114 | + # GET ACTIVE COURSES FROM 'MASTER' DB |
| 115 | + try: |
| 116 | + sql = "select course from courses where semester='{}'".format(semester) |
| 117 | + # psql postgresql://user:password@host/dbname?sslmode=prefer -c "COPY (SQL code) TO STDOUT" |
| 118 | + process = "psql postgresql://{}:{}@{}/submitty?sslmode=prefer -c \"COPY ({}) TO STDOUT\"".format(DB_USER, DB_PASS, DB_HOST, sql) |
| 119 | + result = list(subprocess.check_output(process, shell=True).decode('utf-8').split(os.linesep))[:-1] |
| 120 | + except subprocess.CalledProcessError: |
| 121 | + raise SystemExit("Communication error with Submitty 'master' DB") |
| 122 | + |
| 123 | + if len(result) < 1: |
| 124 | + raise SystemExit("No registered courses found for semester '{}'.".format(semester)) |
| 125 | + |
| 126 | + # BUILD LIST OF DBs TO BACKUP |
| 127 | + # Initial entry is the submitty 'master' database |
| 128 | + # All other entries are submitty course databases |
| 129 | + course_list = ['submitty'] + result |
| 130 | + |
| 131 | + # MAKE/VERIFY BACKUP FOLDERS FOR EACH DB |
| 132 | + for course in course_list: |
| 133 | + dump_path = '{}/{}/{}/'.format(DUMP_PATH, semester, course) |
| 134 | + try: |
| 135 | + os.makedirs(dump_path, mode=0o700, exist_ok=True) |
| 136 | + os.chown(dump_path, uid=0, gid=0) |
| 137 | + except OSError as e: |
| 138 | + if not os.path.isdir(dump_path): |
| 139 | + raise SystemExit("Failed to prepare DB dump path '{}'{}OS error: '{}'".format(e.filename, os.linesep, e.strerror)) |
| 140 | + |
| 141 | + # BUILD DB LISTS |
| 142 | + # Initial entry is the submitty 'master' database |
| 143 | + # All other entries are submitty course databases |
| 144 | + db_list = ['submitty'] |
| 145 | + dump_list = ['{}_{}_submitty.dbdump'.format(today_stamp, semester)] |
| 146 | + |
| 147 | + for course in course_list[1:]: |
| 148 | + db_list.append('submitty_{}_{}'.format(semester, course)) |
| 149 | + dump_list.append('{}_{}_{}.dbdump'.format(today_stamp, semester, course)) |
| 150 | + |
| 151 | + # DUMP |
| 152 | + for i in range(len(course_list)): |
| 153 | + try: |
| 154 | + # pg_dump postgresql://user:password@host/dbname?sslmode=prefer > /var/local/submitty-dump/semester/course/dump_file.dbdump |
| 155 | + process = 'pg_dump postgresql://{}:{}@{}/{}?sslmode=prefer > {}/{}/{}/{}'.format(DB_USER, DB_PASS, DB_HOST, db_list[i], DUMP_PATH, semester, course_list[i], dump_list[i]) |
| 156 | + return_code = subprocess.check_call(process, shell=True) |
| 157 | + except subprocess.CalledProcessError as e: |
| 158 | + print("Error while dumping {}".format(db_list[i])) |
| 159 | + print(e.output.decode('utf-8')) |
| 160 | + |
| 161 | + # DETERMINE EXPIRATION DATE (to delete obsolete dump files) |
| 162 | + # (do this BEFORE recursion so it is not calculated recursively n times) |
| 163 | + if expiration > 0: |
| 164 | + expiration_date = datetime.date.fromordinal(today.toordinal() - expiration) |
| 165 | + expiration_stamp = '{:0>2}{:0>2}{:0>2}'.format(expiration_date.year % 100, expiration_date.month, expiration_date.day) |
| 166 | + working_path = "{}/{}".format(DUMP_PATH, semester) |
| 167 | + |
| 168 | + # RECURSIVELY CULL OBSOLETE DUMPS |
| 169 | + delete_obsolete_dumps(working_path, expiration_stamp) |
| 170 | + |
| 171 | +if __name__ == "__main__": |
| 172 | + main() |
0 commit comments