#!/usr/bin/env python

# Copyright C 2002-2010 by Isilon Systems, Inc. All rights not expressly
# granted herein are reserved.
# Created in the United States of America.
# 
# This digital media is protected by U.S. and international copyright and
# intellectual property laws. Unless otherwise specified, all information
# and screens appearing as part of this digital medium, including
# software, services, documents, text, images, icons, and logos design;
# the selection, assembly, arrangement, and design thereof; and the code
# that enables its presentation, are the sole property of Isilon Systems,
# Inc.
# 
# Except as otherwise required by applicable law, no part of any
# copyrighted material may be reproduced, modified, translated,
# distributed, published, or transmitted by any means, electronic or
# mechanical, for any purpose, without the prior written consent of Isilon
# Systems. 
#  
# Isilon and Isilon Systems are registered trademarks of Isilon Systems,
# Inc.  Legion is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.

'''
Cluster-aware Tardis Namespace Backup Coordinator Script
'''

import os
import sys
import glob
import errno
import subprocess
import datetime
import time

import isi.config.tardis as tardis

# Global constants
MAX_NUM_BACKUPS = 4
# TODO: this path must be exposed from Tardis Python API (in-turn from
# isi_tardis/constants.h)
IFS_BACKUPS_PATH = '/ifs/.ifsvar/modules/tardis/backups'
BKP_EXT = '.tardis.bak'
BKP_LOCK_FILE = os.path.join(IFS_BACKUPS_PATH, 'bkp.lck')
MIN_TIME_DELTA_BETWEEN_BACKUPS = datetime.timedelta(seconds=300)
EX_CODE = os.EX_OK

def run_backup_checks(force=False):
    '''
    run checks to make sure we can backup or simply exist
    '''
    # make sure that we are the only one backing up currently, otherwise, exit
    # because we do not want to start another backup just now
    # NOTE: we block if are forced to backup right now
    try:
        os.open(BKP_LOCK_FILE, os.O_CREAT | os.O_EXLOCK |
                (0 if force else os.O_NONBLOCK), 0600)
        print "acquired backup lock"
    except OSError as err:
        if err.errno != errno.EWOULDBLOCK:
            raise
        print 'another backup is in progress, exiting'
        sys.exit()


def push_rotate_backup(bkp_base_path, old_bkp_fpath, nmspc, push_at_index):
    '''
    Use this function to recursively rotate the backup files of a namespace
    while pushing the temporary file to the top on the list (lowest backup
    index).

    NOTE: this function doesn't expect the MAX_NUM_BACKUPS to change or it'll
    not cleanup the files which have greater indexes if it is ever made
    smaller.
    '''
    # ignore if we have reached the max index (stopping condition)
    if push_at_index >= MAX_NUM_BACKUPS:
        return

    # generate the new path name based upon the given index
    new_fpath = os.path.join(bkp_base_path,
            '%s%s.%d' % (nmspc, BKP_EXT, push_at_index))
    # if this path still exists then push it to the next index
    if os.path.exists(new_fpath):
        push_rotate_backup(bkp_base_path, new_fpath, nmspc, push_at_index + 1)

    # we do not care if the file exists anymore because if it is still there
    # then we can overwrite it
    os.rename(old_bkp_fpath, new_fpath)


# run checks, we can exit inside this function
run_backup_checks(force='now' in sys.argv[1:])

# list all the namespaces and back then up using tha tardis CLI
# NOTE: list of the namespaces might become obsolete, so, we want to ignore any
# errors
for nmspc in tardis.list_namespaces():
    # backup patch contains the namespace name as a leaf directory
    bkp_base_path = os.path.join(IFS_BACKUPS_PATH, nmspc)
    try:
        os.mkdir(bkp_base_path)
    except OSError as err:
        # raise if the directory does not already exist
        if err.errno != errno.EEXIST:
            raise

    # prepare temporary backup file path based upon bkp_base_path
    tmp_bkp_fpath = os.path.join(bkp_base_path, '%s%s.tmp' % (nmspc, BKP_EXT))

    # if this temporary file already exists then we probably failed rotating
    # backups the last time, so, we'll do it now
    if os.path.exists(tmp_bkp_fpath):
        print 'Detected incomplete rotation for namespace<%s> from previous ' \
                'run, finishing it' % nmspc
        push_rotate_backup(bkp_base_path, tmp_bkp_fpath, nmspc, 0)

    # try to backup this namespace and rotate on success
    try:
        subprocess.check_call(['/usr/bin/isi_tardis', '--backup', nmspc,
                tmp_bkp_fpath])
    except subprocess.CalledProcessError as err:
        print 'failed to backup the namespace <%s>: %s' % (nmspc, str(err))
        # NOTE: DO NOT ROTATE if backups are failing on this namespace
        # Set the return code for the backup coordinator, note that this will
        # get overwritten later
        EX_CODE = err.returncode
    else:
        # rotate the namespace backups ONLY if we got a successful backup just
        # now. Otherwise, we'll rotate everything out and will be left with
        # nothing to restore from in a corruption scenario
        print 'Rotating backups for namespace<%s>' % nmspc
        push_rotate_backup(bkp_base_path, tmp_bkp_fpath, nmspc, 0)

# ensure the other nodes have time to wake up and fail to acquire the lock
# to prevent them from running
if not 'now' in sys.argv[1:]:
    time.sleep(300)

sys.exit(EX_CODE)
