sh_commands.py 6.7 KB
Newer Older
Y
yejianwu 已提交
1 2
import falcon_cli
import filelock
3
import re
Y
yejianwu 已提交
4
import sh
5 6
import time

L
Liangliang He 已提交
7

8 9 10 11
################################
# common
################################
def strip_invalid_utf8(str):
L
Liangliang He 已提交
12 13
    return sh.iconv(str, "-c", "-t", "UTF-8")

14 15

def make_output_processor(buff):
L
Liangliang He 已提交
16 17 18 19 20 21
    def process_output(line):
        print(line.strip())
        buff.append(line)

    return process_output

22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
def device_lock_path(serialno):
    return "/tmp/device-lock-%s" % serialno


def device_lock(serialno, timeout=3600):
    return filelock.FileLock(device_lock_path(serialno), timeout=timeout)


def is_device_locked(serialno):
    try:
        with device_lock(serialno, timeout=0.000001):
            return False
    except filelock.Timeout:
        return True


39 40 41 42
################################
# adb commands
################################
def adb_split_stdout(stdout_str):
L
Liangliang He 已提交
43 44 45 46
    stdout_str = strip_invalid_utf8(stdout_str)
    # Filter out last empty line
    return [l.strip() for l in stdout_str.split('\n') if len(l.strip()) > 0]

47 48

def adb_devices(target_socs=None):
49 50 51 52 53 54 55
    device_ids = []
    p = re.compile(r'(\w+)\s+device')
    for line in adb_split_stdout(sh.adb("devices")):
        m = p.match(line)
        if m:
            device_ids.append(m.group(1))

L
Liangliang He 已提交
56 57 58 59 60 61 62 63 64 65 66
    if target_socs is not None:
        target_socs_set = set(target_socs)
        target_devices = []
        for serialno in device_ids:
            props = adb_getprop_by_serialno(serialno)
            if props["ro.board.platform"] in target_socs_set:
                target_devices.append(serialno)
        return target_devices
    else:
        return device_ids

67 68

def adb_getprop_by_serialno(serialno):
L
Liangliang He 已提交
69 70 71
    outputs = sh.adb("-s", serialno, "shell", "getprop")
    raw_props = adb_split_stdout(outputs)
    props = {}
72
    p = re.compile(r'\[(.+)\]: \[(.+)\]')
L
Liangliang He 已提交
73 74 75 76 77 78
    for raw_prop in raw_props:
        m = p.match(raw_prop)
        if m:
            props[m.group(1)] = m.group(2)
    return props

79

80
def adb_supported_abis(serialno):
L
Liangliang He 已提交
81 82 83 84 85
    props = adb_getprop_by_serialno(serialno)
    abilist_str = props["ro.product.cpu.abilist"]
    abis = [abi.strip() for abi in abilist_str.split(',')]
    return abis

86

87
def adb_get_all_socs():
L
Liangliang He 已提交
88 89 90 91 92
    socs = []
    for d in adb_devices():
        props = adb_getprop_by_serialno(d)
        socs.append(props["ro.board.platform"])
    return set(socs)
93

L
Liangliang He 已提交
94 95 96 97

def adb_run(serialno,
            host_bin_path,
            bin_name,
98 99 100
            args="",
            opencl_profiling=1,
            vlog_level=0,
101 102
            device_bin_path="/data/local/tmp/mace",
            out_of_range_check=1):
L
Liangliang He 已提交
103 104 105 106 107 108
    host_bin_full_path = "%s/%s" % (host_bin_path, bin_name)
    device_bin_full_path = "%s/%s" % (device_bin_path, bin_name)
    props = adb_getprop_by_serialno(serialno)
    print(
        "====================================================================="
    )
109 110 111 112 113
    print("Trying to lock device", serialno)
    with device_lock(serialno):
        print("Run on device: %s, %s, %s" %
              (serialno, props["ro.board.platform"],
               props["ro.product.model"]))
Y
yejianwu 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        sh.adb("-s", serialno, "shell", "rm -rf %s" % device_bin_path)
        sh.adb("-s", serialno, "shell", "mkdir -p %s" % device_bin_path)
        print("Push %s to %s" % (host_bin_full_path, device_bin_full_path))
        sh.adb("-s", serialno, "push", host_bin_full_path,
               device_bin_full_path)
        print("Run %s" % device_bin_full_path)
        stdout_buff = []
        process_output = make_output_processor(stdout_buff)
        p = sh.adb(
            "-s",
            serialno,
            "shell",
            "MACE_OUT_OF_RANGE_CHECK=%d MACE_OPENCL_PROFILING=%d "
            "MACE_CPP_MIN_VLOG_LEVEL=%d %s %s" %
            (out_of_range_check, opencl_profiling, vlog_level,
129
             device_bin_full_path, args),
Y
yejianwu 已提交
130 131 132 133 134
            _out=process_output,
            _bg=True,
            _err_to_out=True)
        p.wait()
        return "".join(stdout_buff)
135 136 137 138 139 140


################################
# bazel commands
################################
def bazel_build(target, strip="always", abi="armeabi-v7a"):
L
Liangliang He 已提交
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
    print("Build %s with ABI %s" % (target, abi))
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
    p = sh.bazel(
        "build",
        "-c",
        "opt",
        "--strip",
        strip,
        "--verbose_failures",
        target,
        "--crosstool_top=//external:android/crosstool",
        "--host_crosstool_top=@bazel_tools//tools/cpp:toolchain",
        "--cpu=%s" % abi,
        "--copt=-std=c++11",
        "--copt=-D_GLIBCXX_USE_C99_MATH_TR1",
        "--copt=-DMACE_DISABLE_NO_TUNING_WARNING",
        "--copt=-Werror=return-type",
        "--copt=-O3",
        "--define",
        "neon=true",
        "--define",
        "openmp=true",
        _out=process_output,
        _bg=True,
        _err_to_out=True)
    p.wait()
    return "".join(stdout_buff)

170 171

def bazel_target_to_bin(target):
L
Liangliang He 已提交
172 173 174 175 176 177 178 179
    # change //mace/a/b:c to bazel-bin/mace/a/b/c
    prefix, bin_name = target.split(':')
    prefix = prefix.replace('//', '/')
    if prefix.startswith('/'):
        prefix = prefix[1:]
    host_bin_path = "bazel-bin/%s" % prefix
    return host_bin_path, bin_name

180 181 182 183 184 185

################################
# mace commands
################################
# TODO this should be refactored
def gen_encrypted_opencl_source(codegen_path="mace/codegen"):
L
Liangliang He 已提交
186 187 188 189 190 191
    sh.mkdir("-p", "%s/opencl" % codegen_path)
    sh.python(
        "mace/python/tools/encrypt_opencl_codegen.py",
        "--cl_kernel_dir=./mace/kernels/opencl/cl/",
        "--output_path=%s/opencl/opencl_encrypt_program.cc" % codegen_path)

192 193

def gen_mace_version(codegen_path="mace/codegen"):
L
Liangliang He 已提交
194 195 196 197
    sh.mkdir("-p", "%s/version" % codegen_path)
    sh.bash("mace/tools/git/gen_version_source.sh",
            "%s/version/version.cc" % codegen_path)

198

L
liuqi 已提交
199
def gen_compiled_opencl_source(codegen_path="mace/codegen"):
L
Liangliang He 已提交
200 201 202 203 204
    sh.mkdir("-p", "%s/opencl" % codegen_path)
    sh.python(
        "mace/python/tools/opencl_codegen.py",
        "--output_path=%s/opencl/opencl_compiled_program.cc" % codegen_path)

L
liuqi 已提交
205

206 207 208
################################
# falcon
################################
L
Liangliang He 已提交
209
def falcon_tags(tags_dict):
L
Liangliang He 已提交
210 211 212 213 214 215 216
    tags = ""
    for k, v in tags_dict.iteritems():
        if tags == "":
            tags = "%s=%s" % (k, v)
        else:
            tags = tags + ",%s=%s" % (k, v)
    return tags
L
Liangliang He 已提交
217

218

L
Liangliang He 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232
def falcon_push_metrics(metrics, endpoint="mace_dev", tags={}):
    cli = falcon_cli.FalconCli.connect(
        server="transfer.falcon.miliao.srv", port=8433, debug=False)
    ts = int(time.time())
    falcon_metrics = [{
        "endpoint": endpoint,
        "metric": key,
        "tags": falcon_tags(tags),
        "timestamp": ts,
        "value": value,
        "step": 86400,
        "counterType": "GAUGE"
    } for key, value in metrics.iteritems()]
    cli.update(falcon_metrics)