
from __future__ import absolute_import
from __future__ import division
import errno
import os
import select

from vdsm.common import time


def close_fd(fd):
    try:
        os.close(fd)
    except EnvironmentError as e:
        if e.errno != errno.EINTR:
            raise


def uninterruptible(func, *args, **kwargs):
    while True:
        try:
            return func(*args, **kwargs)
        except EnvironmentError as e:
            if e.errno != errno.EINTR:
                raise


def uninterruptible_poll(pollfun, timeout=-1):
    endtime = None if timeout < 0 else time.monotonic_time() + timeout

    while True:
        try:
            return pollfun(timeout)
        except (IOError, select.error) as e:
            if e.args[0] != errno.EINTR:
                raise

        if endtime is not None:
            timeout = max(0, endtime - time.monotonic_time())
