util.py 3.68 KB
Newer Older
1
"""Common system utilities"""
2 3 4 5
from __future__ import absolute_import as _abs
import os
import tempfile
import shutil
6 7 8 9 10
try:
    import fcntl
except ImportError:
    fcntl = None

11 12

class TempDirectory(object):
13 14 15 16
    """Helper object to manage temp directory during testing.

    Automatically removes the directory when it went out of scope.
    """
17 18
    def __init__(self):
        self.temp_dir = tempfile.mkdtemp()
Tianqi Chen committed
19
        self._rmtree = shutil.rmtree
20

21 22 23
    def remove(self):
        """Remote the tmp dir"""
        if self.temp_dir:
Hu Shiwen committed
24
            self._rmtree(self.temp_dir, ignore_errors=True)
25 26
            self.temp_dir = None

27
    def __del__(self):
28
        self.remove()
29 30 31 32 33 34 35 36

    def relpath(self, name):
        """Relative path in temp dir

        Parameters
        ----------
        name : str
            The name of the file.
37 38 39 40 41

        Returns
        -------
        path : str
            The concatenated path.
42 43 44
        """
        return os.path.join(self.temp_dir, name)

45
    def listdir(self):
46
        """List contents in the dir.
47 48 49 50 51 52

        Returns
        -------
        names : list
            The content of directory
        """
53
        return os.listdir(self.temp_dir)
54

55

56
def tempdir():
57
    """Create temp dir which deletes the contents when exit.
58 59 60 61 62 63 64

    Returns
    -------
    temp : TempDirectory
        The temp directory object
    """
    return TempDirectory()
65 66 67 68 69 70 71 72 73 74 75 76


class FileLock(object):
    """File lock object

    Parameters
    ----------
    path : str
        The path to the lock
    """
    def __init__(self, path):
        self.lock_file = open(path, "w")
77 78
        if fcntl:
            fcntl.lockf(self.lock_file, fcntl.LOCK_EX)
79 80 81 82 83


    def release(self):
        """Release the lock"""
        if self.lock_file:
84 85
            if fcntl:
                fcntl.lockf(self.lock_file, fcntl.LOCK_UN)
86 87 88
            self.lock_file.close()
            self.lock_file = None

89

90 91 92 93 94 95 96 97 98 99 100 101 102
def filelock(path):
    """Create a file lock which locks on path

    Parameters
    ----------
    path : str
        The path to the lock

    Returns
    -------
    lock : File lock object
    """
    return FileLock(path)
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144


def is_source_path(path):
    """Check if path is source code path.

    Parameters
    ----------
    path : str
        A possible path

    Returns
    -------
    valid : bool
        Whether path is a possible source path
    """
    if os.path.exists(path):
        return True
    if path.find("\n") != -1:
        return False
    spath = path.rsplit(".", 1)
    return len(spath) == 2 and spath[1].strip() == spath[1]


def which(exec_name):
    """Try to find full path of exec_name

    Parameters
    ----------
    exec_name : str
        The executable name

    Returns
    -------
    path : str
        The full path of executable if found, otherwise returns None
    """
    base_list = ["", "/bin"] + os.environ.get("PATH", "").split(os.pathsep)
    for path in base_list:
        full_path = os.path.join(path, exec_name)
        if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
            return full_path
    return None
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

def get_lower_ir(s):
    """Get lower ir code of a schedule.
    This is useful for debug, since you don't have to find all inputs/outputs
    for a schedule in a fused subgraph.

    Parameters
    ----------
    s: Schedule

    Returns
    -------
    ir: str
        The lower ir
    """
    from .. import tensor
    from ..build_module import lower

    outputs = s.outputs

    inputs = []
    def find_all(op):
        if isinstance(op, tensor.PlaceholderOp):
            inputs.append(op.output(0))
        else:
            for x in op.input_tensors:
                find_all(x.op)

    for out in outputs:
        find_all(out)

    return lower(s, inputs, simple_mode=True)