util.py 4.71 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 35 36 37 38
    def __init__(self, custom_path=None):
        if custom_path:
            os.mkdir(custom_path)
            self.temp_dir = custom_path
        else:
            self.temp_dir = tempfile.mkdtemp()
Tianqi Chen committed
39
        self._rmtree = shutil.rmtree
40

41 42 43
    def remove(self):
        """Remote the tmp dir"""
        if self.temp_dir:
Hu Shiwen committed
44
            self._rmtree(self.temp_dir, ignore_errors=True)
45 46
            self.temp_dir = None

47
    def __del__(self):
48
        self.remove()
49 50 51 52 53 54 55 56

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

        Parameters
        ----------
        name : str
            The name of the file.
57 58 59 60 61

        Returns
        -------
        path : str
            The concatenated path.
62 63 64
        """
        return os.path.join(self.temp_dir, name)

65
    def listdir(self):
66
        """List contents in the dir.
67 68 69 70 71 72

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

75

76
def tempdir(custom_path=None):
77
    """Create temp dir which deletes the contents when exit.
78

79 80 81 82 83
    Parameters
    ----------
    custom_path : str, optional
        Manually specify the exact temp dir path

84 85 86 87 88
    Returns
    -------
    temp : TempDirectory
        The temp directory object
    """
89
    return TempDirectory(custom_path)
90 91 92 93 94 95 96 97 98 99 100 101


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

    Parameters
    ----------
    path : str
        The path to the lock
    """
    def __init__(self, path):
        self.lock_file = open(path, "w")
102 103
        if fcntl:
            fcntl.lockf(self.lock_file, fcntl.LOCK_EX)
104 105 106 107 108


    def release(self):
        """Release the lock"""
        if self.lock_file:
109 110
            if fcntl:
                fcntl.lockf(self.lock_file, fcntl.LOCK_UN)
111 112 113
            self.lock_file.close()
            self.lock_file = None

114

115 116 117 118 119 120 121 122 123 124 125 126 127
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)
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 161 162 163 164 165 166 167 168 169


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
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

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)