
from __future__ import absolute_import

import functools

import six

from vdsm.common import compat
from vdsm.storage import constants as sc


def compat_4k(func):

    @functools.wraps(func)
    def decorator(*args, **kwargs):
        sector = kwargs.pop("sector", sc.BLOCK_SIZE_512)
        if sector != sc.BLOCK_SIZE_512:
            raise ValueError("Wrong sector size %d" % sector)

        align = kwargs.pop("align", sc.ALIGNMENT_1M)
        if align != sc.ALIGNMENT_1M:
            raise ValueError("Wrong alignment %d" % align)

        return func(*args, **kwargs)

    return decorator


try:
    import sanlock

    if not hasattr(sanlock, "SECTOR_SIZE"):
        sanlock.read_lockspace = compat_4k(sanlock.read_lockspace)
        sanlock.write_lockspace = compat_4k(sanlock.write_lockspace)
        sanlock.read_resource = compat_4k(sanlock.read_resource)
        sanlock.read_resource_owners = compat_4k(sanlock.read_resource_owners)
        sanlock.write_resource = compat_4k(sanlock.write_resource)

        sanlock.SECTOR_SIZE = (sc.BLOCK_SIZE_512,)
        sanlock.ALINGN_SIZE = (sc.ALIGNMENT_1M,)

except ImportError:
    if six.PY2:
        raise


    class SanlockModule(compat.MissingModule):

        HOST_UNKNOWN = 1
        HOST_FREE = 2
        HOST_LIVE = 3
        HOST_FAIL = 4
        HOST_DEAD = 5

    sanlock = SanlockModule("sanlock is not available in python 3")

try:
    import ioprocess
except ImportError:
    if six.PY2:
        raise
    ioprocess = compat.MissingModule("ioprocess is not available in python 3")
