# Copyright (c) 2015 The New Mexico Consortium
#
# {{{NMC-LICENSE
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# }}}

from nmc_probe.lun_clone_job import LUNCloneJob
from nmc_probe.target_manager import TargetManager
from nmc_probe.zfs import ZFS
from nmc_probe.log import Log

import traceback


class LUNQueue:
    '''Processes the LUN clone queue'''
    def create_clone(self, zfs, args):
        created_clone = None
        # Create the ZFS clone
        created_clone = zfs.clone(args)

        if created_clone is not None:
            return True
        return None

    def create_target(self, mgr, args):
        created = None
        # Create the iSCSI target
        args['device'] = '/dev/zvol/%s' % args['dst']
        created = mgr.create_iscsi_target(args)

        if created is not None:
            return True
        return None

    def remove_target(self, mgr, args):
        mgr.delete_target_and_block_store(args)

    def remove_clone(self, task, zfs, args):
        # If deleteClones = true, then the dst parameter is also required.
        deleteClones = args.get('deleteClones', None)

        if deleteClones:
            if args.get('dst', None) is None:
                message = {'message': 'deleteClones parameter requires dst '
                                      'parameter'}
                return message

            zfs.destroy(args)
        else:
            Log.info('Delete task %s did not specify deleteClones param for %s'
                     % (task.id, args[u'dst']))

    def create_clones(self, task):
        # Set up ZFS and Target management
        zfs = ZFS()
        mgr = TargetManager()
        num_created = 0

        task.set_status_start_creating_clones()

        for arg in task.details['clones']:
            self.create_clone(zfs, arg)
            task.increment_num_clones()

        task.set_status_done_creating_clones()

        # Give udevd a chance to settle down and create associated devices
        task.set_status_start_waiting_udevd()
        zfs.udevd_settle_down()
        task.set_status_done_waiting_udevd()

        task.set_status_start_creating_targets()

        for arg in task.details['clones']:
            self.create_target(mgr, arg)
            task.increment_num_targets()
            task.increment_num_completed()

        task.set_status_done_creating_targets()
        mgr.save()

    def delete_clones(self, task):
        # Set up ZFS and Target management
        zfs = ZFS()
        mgr = TargetManager()

        task.set_status_start_deleting_targets()

        for arg in task.details['clones']:
            self.remove_target(mgr, arg)
            task.increment_num_clones()

        task.set_status_done_deleting_targets()

        task.set_status_start_deleting_clones()

        for arg in task.details['clones']:
            self.remove_clone(task, zfs, arg)
            task.increment_num_targets()
            task.increment_num_completed()

        task.set_status_done_deleting_clones()
        mgr.save()

    def process(self):
        try:
            errors = []
            for task in LUNCloneJob.pending():
                try:
                    Log.info('%s job %s started' %
                             (task.job_type.code, task.id))
                    task.set_status_start_job()

                    if task.is_create():
                        self.create_clones(task)
                    else:
                        self.delete_clones(task)

                    task.set_status_complete()
                    Log.info('%s job %s completed' %
                             (task.job_type.code, task.id))

                except (Exception), e:
                    error = u'%s:\n%s' % (str(e), traceback.format_exc())
                    Log.error('%s job %s failed' %
                              (task.job_type.code, task.id))
                    Log.error(error)
                    task.set_status_failed(error)
                    errors.append(task.error)

            if len(errors) > 0:
                message = {'message': errors}
                return {'status': 'error',
                        'errors': errors}

        except (Exception), e:
            error = u'%s:\n%s' % (str(e), traceback.format_exc())
            Log.error(error)
            return {'status': 'error',
                    'message': error}
