summaryrefslogtreecommitdiff
path: root/Code/backup_files.py
blob: 6105525fc6ba8ac528373b9dab542c71146228ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Usage: use the copy_and_backup_file() as a utility function for backing up a file.
#
# Purpose: the function copy_and_backup_file(src, dest_dir) copies file src to destination directory (if exists) and compress
#          the copied file in the destination directory (to save space).
#          
#
# Created on 7 December 2019 by Hui Lan (lanhui@zjnu.edu.cn)

import os, sys
from configure import UPDATE_NETWORK_LOG_FILE
from datetime import datetime

MINIMUM_SPACE_REQUIREMENT = 1 # Gigabytes

def write_log_file(s, fname):
    if not os.path.exists(fname):
        return None
    f = open(fname, 'a')
    curr_time = datetime.now().strftime('%Y-%m-%d %H:%M')
    s = '[' + curr_time + ']: ' + s
    if not '\n' in s:
        s += '\n'
    f.write(s)
    f.close()


def make_paths(s):
    if not os.path.isdir(s):
        os.makedirs(s)


def disk_has_enough_space():
    available_G = 4 * os.statvfs('/home').f_bavail / (1024*1024) # compute available space (in Gigabytes).  Each block has 4k bytes, work for Linux/UNIX systems only
    if available_G < MINIMUM_SPACE_REQUIREMENT:
        print('[backup_files.py] home directory does not have enough space (only %4.1f G is available) ' % (available_G))
        write_log_file('[backup_files.py] WARNING: home directory does not have enough space (only %4.1f G is available)!  No backup is carried out.' % (available_G), UPDATE_NETWORK_LOG_FILE)        
        sys.exit()


def copy_and_backup_file(src_file, dest_dir):
    disk_has_enough_space() # make sure we have enough space first
    if not os.path.exists(src_file):
        sys.exit()
    make_paths(dest_dir) # if dest_dir does not exist, create it.
    curr_date = datetime.now().strftime('%Y%m%d')
    dest_file = os.path.join(dest_dir, os.path.basename(src_file) + '.' + curr_date)
    cmd = 'cp %s %s && gzip -f %s' % (src_file, dest_file, dest_file)
    os.system(cmd)
    write_log_file('[backup_files.py] File %s has been backed up to %s and zipped (.gz)' % (src_file, dest_file), UPDATE_NETWORK_LOG_FILE)            


## main
if __name__ == '__main__':
    copy_and_backup_file('../Data/temp/edges.txt', '../Analysis')