#!/usr/bin/env python
#
# Copyright (C) 2020  Vates SAS - ronan.abhamon@vates.fr
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# We must modify default import path, we don't want to import modules
# installed in plugins folder and instead we must import from LINSTOR driver
# folder.
import sys
sys.path[0] = '/opt/xensource/sm/'

import base64
import distutils.util
import time
import subprocess
import XenAPIPlugin

from linstorjournaler import LinstorJournaler
from linstorvolumemanager import get_controller_uri, LinstorVolumeManager
from lock import Lock
import json
import LinstorSR
import util
import vhdutil


FIREWALL_PORT_SCRIPT = '/etc/xapi.d/plugins/firewall-port'
LINSTOR_PORTS = [3366, 3370, 3376, 3377, '7000:8000']


def update_port(port, open):
    fn = 'open' if open else 'close'
    args = (
        FIREWALL_PORT_SCRIPT, fn, str(port), 'tcp'
    )

    (ret, out, err) = util.doexec(args)
    if ret == 0:
        return
    raise Exception('Failed to {} port: {} {}'.format(fn, out, err))


def update_all_ports(open):
    for port in LINSTOR_PORTS:
        update_port(port, open)


def enable_and_start_service(name, start):
    attempt = 0
    while True:
        attempt += 1
        fn = 'enable' if start else 'disable'
        args = ('systemctl', fn, '--now', name)
        (ret, out, err) = util.doexec(args)
        if ret == 0:
            return
        elif attempt >= 3:
            raise Exception(
                'Failed to {} {}: {} {}'.format(fn, name, out, err)
            )
        time.sleep(1)


def restart_service(name):
    attempt = 0
    while True:
        attempt += 1
        util.SMlog('linstor-manager:restart service {} {}...'.format(name, attempt))
        args = ('systemctl', 'restart', name)
        (ret, out, err) = util.doexec(args)
        if ret == 0:
            return
        elif attempt >= 3:
            util.SMlog('linstor-manager:restart service FAILED {} {}'.format(name, attempt))
            raise Exception(
                'Failed to restart {}: {} {}'.format(name, out, err)
            )
        time.sleep(1)


def stop_service(name):
    args = ('systemctl', 'stop', name)
    (ret, out, err) = util.doexec(args)
    if ret == 0:
        return
    raise Exception('Failed to stop {}: {} {}'.format(name, out, err))


def update_linstor_satellite_service(start):
    enable_and_start_service('linstor-satellite', start)


def update_minidrbdcluster_service(start):
    enable_and_start_service('minidrbdcluster', start)


def prepare_sr(session, args):
    try:
        update_all_ports(open=True)
        # We don't want to enable and start minidrbdcluster daemon during
        # SR creation.
        update_minidrbdcluster_service(start=False)
        update_linstor_satellite_service(start=True)
        return str(True)
    except Exception as e:
        util.SMlog('linstor-manager:prepare_sr error: {}'.format(e))
    return str(False)


def release_sr(session, args):
    try:
        update_linstor_satellite_service(start=False)
        update_minidrbdcluster_service(start=False)
        update_all_ports(open=False)
        return str(True)
    except Exception as e:
        util.SMlog('linstor-manager:release_sr error: {}'.format(e))
    return str(False)


def update_minidrbdcluster(session, args):
    try:
        enabled = distutils.util.strtobool(args['enabled'])
        update_minidrbdcluster_service(start=enabled)
        return str(True)
    except Exception as e:
        util.SMlog(
            'linstor-manager:update_minidrbdcluster error: {}'.format(e)
        )
    return str(False)


def attach(session, args):
    try:
        sr_uuid = args['srUuid']
        vdi_uuid = args['vdiUuid']
        group_name = args['groupName']

        controller_uri = get_controller_uri()
        journaler = LinstorJournaler(
            controller_uri, group_name, logger=util.SMlog
        )
        linstor = LinstorVolumeManager(
            controller_uri,
            group_name,
            logger=util.SMlog
        )
        LinstorSR.attach_thin(session, journaler, linstor, sr_uuid, vdi_uuid)
        return str(True)
    except Exception as e:
        util.SMlog('linstor-manager:attach error: {}'.format(e))
    return str(False)


def detach(session, args):
    try:
        sr_uuid = args['srUuid']
        vdi_uuid = args['vdiUuid']
        group_name = args['groupName']

        linstor = LinstorVolumeManager(
            get_controller_uri(),
            group_name,
            logger=util.SMlog
        )
        LinstorSR.detach_thin(session, linstor, sr_uuid, vdi_uuid)
        return str(True)
    except Exception as e:
        util.SMlog('linstor-manager:detach error: {}'.format(e))
    return str(False)


def destroy(session, args):
    try:
        group_name = args['groupName']

        # When destroy is called, there are no running minidrbdcluster daemons.
        # So the controllers are stopped too, we must start an instance.
        restart_service('var-lib-linstor.service')
        restart_service('linstor-controller')

        linstor = LinstorVolumeManager(
            'linstor://localhost',
            group_name,
            logger=util.SMlog
        )
        linstor.destroy()
        return str(True)
    except Exception as e:
        stop_service('linstor-controller')
        stop_service('var-lib-linstor.service')
        util.SMlog('linstor-manager:destroy error: {}'.format(e))
    return str(False)


def check(session, args):
    try:
        device_path = args['devicePath']
        ignore_missing_footer = args['ignoreMissingFooter']
        fast = args['fast']
        return str(vhdutil.check(device_path, ignore_missing_footer, fast))
    except Exception as e:
        util.SMlog('linstor-manager:check error: {}'.format(e))
        raise


def get_vhd_info(session, args):
    try:
        device_path = args['devicePath']
        group_name = args['groupName']
        include_parent = distutils.util.strtobool(args['includeParent'])

        linstor = LinstorVolumeManager(
            get_controller_uri(),
            group_name,
            logger=util.SMlog
        )

        def extract_uuid(device_path):
            # TODO: Remove new line in the vhdutil module. Not here.
            return linstor.get_volume_uuid_from_device_path(
                device_path.rstrip('\n')
            )

        vhd_info = vhdutil.getVHDInfo(
            device_path, extract_uuid, include_parent
        )
        return json.dumps(vhd_info.__dict__)
    except Exception as e:
        util.SMlog('linstor-manager:get_vhd_info error: {}'.format(e))
        raise


def has_parent(session, args):
    try:
        device_path = args['devicePath']
        return str(vhdutil.hasParent(device_path))
    except Exception as e:
        util.SMlog('linstor-manager:has_parent error: {}'.format(e))
        raise


def get_parent(session, args):
    try:
        device_path = args['devicePath']
        group_name = args['groupName']

        linstor = LinstorVolumeManager(
            get_controller_uri(),
            group_name,
            logger=util.SMlog
        )

        def extract_uuid(device_path):
            # TODO: Remove new line in the vhdutil module. Not here.
            return linstor.get_volume_uuid_from_device_path(
                device_path.rstrip('\n')
            )

        return vhdutil.getParent(device_path, extract_uuid)
    except Exception as e:
        util.SMlog('linstor-manager:get_parent error: {}'.format(e))
        raise


def get_size_virt(session, args):
    try:
        device_path = args['devicePath']
        return str(vhdutil.getSizeVirt(device_path))
    except Exception as e:
        util.SMlog('linstor-manager:get_size_virt error: {}'.format(e))
        raise


def get_size_phys(session, args):
    try:
        device_path = args['devicePath']
        return str(vhdutil.getSizePhys(device_path))
    except Exception as e:
        util.SMlog('linstor-manager:get_size_phys error: {}'.format(e))
        raise


def get_depth(session, args):
    try:
        device_path = args['devicePath']
        return str(vhdutil.getDepth(device_path))
    except Exception as e:
        util.SMlog('linstor-manager:get_depth error: {}'.format(e))
        raise


def get_key_hash(session, args):
    try:
        device_path = args['devicePath']
        return vhdutil.getKeyHash(device_path) or ''
    except Exception as e:
        util.SMlog('linstor-manager:get_key_hash error: {}'.format(e))
        raise


def get_block_bitmap(session, args):
    try:
        device_path = args['devicePath']
        return base64.b64encode(vhdutil.getBlockBitmap(device_path)) or ''
    except Exception as e:
        util.SMlog('linstor-manager:get_block_bitmap error: {}'.format(e))
        raise


def lock_vdi(session, args):
    lock = None
    try:
        sr_uuid = args['srUuid']
        vdi_uuid = args['vdiUuid']
        group_name = args['groupName']
        locked = distutils.util.strtobool(args['locked'])

        # We must lock to mark the VDI.
        lock = Lock(vhdutil.LOCK_TYPE_SR, sr_uuid)
        if locked:
            lock.acquire()

        linstor = LinstorVolumeManager(
            get_controller_uri(),
            group_name,
            logger=util.SMlog
        )
        linstor.lock_volume(vdi_uuid, locked)

        return str(True)
    except Exception as e:
        util.SMlog('linstor-manager:lock_vdi error: {}'.format(e))
    finally:
        if locked and lock:
            lock.release()
    return str(False)


def lsof_resource(session, args):
    try:
        drbd_path = args['drbdPath']
        (ret, stdout, stderr) = util.doexec(['lsof', drbd_path])
        if ret == 0:
            return 'DRBD resource `{}` is open: {}'.format(
                drbd_path, stdout
            )
        return '`lsof` on DRBD resource `{}` returned {}: {}'.format(
            drbd_path, ret, stderr
        )
    except Exception as e:
        util.SMlog('linstor-manager:lsof_drbd error: {}'.format(e))
        raise


def has_controller_running(session, args):
    (ret, stdout, stderr) = util.doexec([
        'systemctl', 'is-active', '--quiet', 'linstor-controller'
    ])
    return str(ret == 0)


if __name__ == '__main__':
    XenAPIPlugin.dispatch({
        'prepareSr': prepare_sr,
        'releaseSr': release_sr,
        'updateMinidrbdcluster': update_minidrbdcluster,
        'attach': attach,
        'detach': detach,
        'destroy': destroy,
        'check': check,
        'getVHDInfo': get_vhd_info,
        'hasParent': has_parent,
        'getParent': get_parent,
        'getSizeVirt': get_size_virt,
        'getSizePhys': get_size_phys,
        'getDepth': get_depth,
        'getKeyHash': get_key_hash,
        'getBlockBitmap': get_block_bitmap,
        'lockVdi': lock_vdi,
        'lsofResource': lsof_resource,
        'hasControllerRunning': has_controller_running
    })
