#!/usr/bin/python
# Copyright (C) 2006-2007 XenSource Ltd.
# Copyright (C) 2008-2009 Citrix Ltd.
#
# 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.
#
# A plugin for synchronizing slaves when something changes on the Master

import sys
import XenAPIPlugin
sys.path.append("/opt/xensource/sm/")
import util
import lock
from lvmcache import LVMCache

def multi(session, args):
    """Perform several actions in one call (to save on round trips)"""
    util.SMlog("on-slave.multi: %s" % args)
    vgName = args["vgName"]
    lvmCache = LVMCache(vgName)
    i = 1
    while True:
        action = args.get("action%d" % i)
        if not action:
            break
        util.SMlog("on-slave.action %d: %s" % (i, action))
        if action == "activate":
            lvmCache.activate(args["ns%d" % i], args["uuid%d" % i],
                    args["lvName%d" % i], False)
        elif action == "deactivate":
            try:
                lvmCache.deactivate(args["ns%d" % i], args["uuid%d" % i],
                        args["lvName%d" % i], False)
            except util.SMException:
                util.SMlog("on-slave.deactivate failed")
        elif action == "activateNoRefcount":
            lvmCache.activateNoRefcount(args["lvName%d" % i])
        elif action == "deactivateNoRefcount":
            try:
                lvmCache.deactivateNoRefcount(args["lvName%d" % i])
            except util.SMException:
                util.SMlog("on-slave.deactivateNoRefcount failed")
        elif action == "refresh":
            lvmCache.activateNoRefcount(args["lvName%d" % i], True)
        elif action == "cleanupLock":
            lock.Lock.cleanup(args["uuid%d" % i], args["ns%d" % i])
        else:
            raise util.SMException("unrecognized action: %s" % action)
        i += 1
    return str(True)

if __name__ == "__main__":
    XenAPIPlugin.dispatch({"multi": multi})
