#!/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.  "Isilon IQ" is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.

import errno
import getopt
import os
import sys
import time
import traceback

import isi.misc as imisc
import isi.fs.diskpool as fsdp
import isi.smartpools.diskpools as spdp
import isi.sys.version as sysver
import isi.fs.diskpool as fsdp
from isi.app.lib import safelockfile
from isi.fs.diskpool import Logger

NUM_ATTEMPTS = 10
RETRY_DELAY = 2
DRIVE_PROVISION_LOCK_FILE = "/ifs/.ifsvar/drive_provision.lock"

def infox(msg):
    log_and_print(msg)
    sys.exit(0)

def errx(msg):
    print >> sys.stderr, msg
    Logger().logger.error(msg)
    sys.exit(1)

def usagex(msg):
    print >> sys.stdout, msg
    print >> sys.stdout, \
            "usage: isi_evaluate_provision_drive [-l] [-s]"
    sys.exit(2)

def log_and_print(msg):
    print >> sys.stdout, msg
    Logger().log(msg)

def update_node_info_cache(force):
    err_msg = "Error updating node info cache"
    try:
        updated_cache = sysver.update_cache(skip_if_current=not force)
    except Exception, e:
        err_msg += ":" + traceback.format_exc()
        updated_cache = False
    if not updated_cache:
        errx(err_msg)

def main(argv):
    global log

    try:
        opts, args = getopt.getopt(argv, "sl")
    except getopt.GetoptError, e:
        usagex(str(e))

    log = False
    ident = None
    for o, a in opts:
        if o == "-s":
            log = True
        elif o == '-l':
            log = True
            log_and_print("Debug logging enabled, check " + \
                  "/var/log/diskpools.log for debugging output.")
            fsdp.set_debug(True)
        else:
            assert False, "unhandled option"

    if log:
        log_and_print("isi_evaluate_provision_drive running")

    update_node_info_cache(False)

    # There may be other entities writing to the diskpools DB, rendering
    # our in-memory copy stale. Since we're provisioning a specific drive,
    # we'll try up to NUM_ATTEMPTS, delaying RETRY_DELAY in between each
    # attempt.
    attempts = 0
    cache_update_attempted = False
    while attempts < NUM_ATTEMPTS:
        try:
            lockfile = safelockfile(DRIVE_PROVISION_LOCK_FILE, "w")
        except IOError as e:
            errx("Error obtaining lock on %s: %s" %
                    (DRIVE_PROVISION_LOCK_FILE, str(e)))
        try:
            dp_cfg = spdp.open_config()
            if not dp_cfg.fully_upgraded():
                log_and_print("Postponing provisioning of unassigned drives "
                        "until after SmartPools is upgraded")
                return
            if not dp_cfg.purposedb_fully_populated():
                log_and_print("Postponing provisioning of unassigned drives "
                        "until the purpose db is fully populated (should occur "
                        "after all nodes come up")
                return

            dp_cfg.autoprov_unassigned()

            if dp_cfg.list_unassigned_drives() and not cache_update_attempted:
                # Autoprov failed, Once: force an update of node info caches and
                # try again
                update_node_info_cache(True)
                cache_update_attempted = True
                continue

            dp_cfg.save(ignore_underprovisioned=False)
            break
        except OSError, e:
            if e.errno in [errno.ESTALE, errno.EAGAIN, errno.ENOENT]:
                # Sleep for a couple seconds before trying again.
                time.sleep(RETRY_DELAY)
                attempts += 1
                # and enable debugging to /var/log/diskpools.log
                continue
            else:
                errx("Error updating diskpool config: %s" %
                        traceback.format_exc())
        except spdp.UnderprovisionedError, e:
            # Provisioning all drives will leave one of more disk pools in
            # the underprovisioned state (most commonly encountered when
            # /ifs is first mounted and the cluster is transitioning from
            # the bootstrap provisioning to user-managed provisioning) so
            # we simply log a message and skip this provisioning action.
            infox("Postponed provisioning: %s" % traceback.format_exc())
            break
        except spdp.ProvisioningError, e:
            # TODO: Generate CELOG alert/event
            errx("Error provisioning: %s" % traceback.format_exc())
        except:
            e_type, e_val, e_tb = sys.exc_info()
            msg = ''.join(traceback.format_exception(e_type, e_val, e_tb))
            log_and_print("Unhandled exception: %s" % msg)
        finally:
            lockfile.close()

    if attempts >= NUM_ATTEMPTS:
        errx("Error provisioning: failed %d attempts" % attempts)

    return 0

if __name__ == "__main__":
    imisc.setproctitle(os.path.basename(sys.argv[0]))
    sys.exit(main(sys.argv[1:]))

