#!/usr/bin/python3
#
# Copyright (C) Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU Lesser General Public License as published 
# by the Free Software Foundation; version 2.1 only.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# A plugin for inflating/deflating LVHD VDI's centrally on the master when 
# using thin provisioning

import sys
import XenAPIPlugin
from sm.core import util
from sm import lvhdutil
from sm.lvmcache import LVMCache
from sm.journaler import Journaler
from sm import lvutil
import os

def attach(session, args):
    if util.is_master(session):
        os.environ['LVM_SYSTEM_DIR'] = lvutil.MASTER_LVM_CONF
    srUuid = args["srUuid"]
    vdiUuid = args["vdiUuid"]
    vgName = "%s%s" % (lvhdutil.VG_PREFIX, srUuid)
    lvmCache = LVMCache(vgName)
    journaler = Journaler(lvmCache)
    try:
        lvhdutil.attachThin(journaler, srUuid, vdiUuid)
        return str(True)
    except Exception as e:
        util.logException("lvhd-thin:attach %s" % e)
    return str(False)

def detach(session, args):
    if util.is_master(session):
        os.environ['LVM_SYSTEM_DIR'] = lvutil.MASTER_LVM_CONF
    srUuid = args["srUuid"]
    vdiUuid = args["vdiUuid"]
    vgName = "%s%s" % (lvhdutil.VG_PREFIX, srUuid)
    lvmCache = LVMCache(vgName)
    try:
        lvhdutil.detachThin(session, lvmCache, args["srUuid"], args["vdiUuid"])
        return str(True)
    except Exception as e:
        util.logException("lvhd-thin:detach %s" % e)
    return str(False)

if __name__ == "__main__":
    XenAPIPlugin.dispatch({"attach": attach, "detach": detach})
