util.py 4.45 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
17
"""Common system utilities"""
18 19 20 21
from __future__ import absolute_import as _abs
import os
import tempfile
import shutil
22 23 24 25 26
try:
    import fcntl
except ImportError:
    fcntl = None

27 28

class TempDirectory(object):
29 30 31 32
    """Helper object to manage temp directory during testing.

    Automatically removes the directory when it went out of scope.
    """
33 34
    def __init__(self):
        self.temp_dir = tempfile.mkdtemp()
Tianqi Chen committed
35
        self._rmtree = shutil.rmtree
36

37 38 39
    def remove(self):
        """Remote the tmp dir"""
        if self.temp_dir:
Hu Shiwen committed
40
            self._rmtree(self.temp_dir, ignore_errors=True)
41 42
            self.temp_dir = None

43
    def __del__(self):
44
        self.remove()
45 46 47 48 49 50 51 52

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

        Parameters
        ----------
        name : str
            The name of the file.
53 54 55 56 57

        Returns
        -------
        path : str
            The concatenated path.
58 59 60
        """
        return os.path.join(self.temp_dir, name)

61
    def listdir(self):
62
        """List contents in the dir.
63 64 65 66 67 68

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

71

72
def tempdir():
73
    """Create temp dir which deletes the contents when exit.
74 75 76 77 78 79 80

    Returns
    -------
    temp : TempDirectory
        The temp directory object
    """
    return TempDirectory()
81 82 83 84 85 86 87 88 89 90 91 92


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

    Parameters
    ----------
    path : str
        The path to the lock
    """
    def __init__(self, path):
        self.lock_file = open(path, "w")
93 94
        if fcntl:
            fcntl.lockf(self.lock_file, fcntl.LOCK_EX)
95 96 97 98 99


    def release(self):
        """Release the lock"""
        if self.lock_file:
100 101
            if fcntl:
                fcntl.lockf(self.lock_file, fcntl.LOCK_UN)
102 103 104
            self.lock_file.close()
            self.lock_file = None

105

106 107 108 109 110 111 112 113 114 115 116 117 118
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)
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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160


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
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

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)