utils.cpp 8.1 KB
Newer Older
W
wenjun 已提交
1
/*
M
mamingshuai 已提交
2
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
W
wenjun 已提交
3 4 5 6
 * Licensed 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
 *
M
mamingshuai 已提交
7
 * http://www.apache.org/licenses/LICENSE-2.0
W
wenjun 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * 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.
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include "utils.h"
#include <gtest/gtest.h>
#include "log.h"

// init rand seed at startup
__attribute__((constructor)) static void Initialize(void)
{
    LOGD("srand(time(0)) is called.");
M
mamingshuai 已提交
28
    srand(time(nullptr));
W
wenjun 已提交
29 30 31 32 33
}

int CheckValueClose(double target, double actual, double accuracy)
{
    double diff = actual - target;
M
mamingshuai 已提交
34
    double pct;
W
wenjun 已提交
35 36 37
    if (diff < 0) {
        diff = -diff;
    }
M
mamingshuai 已提交
38 39 40 41 42
    if(actual == 0) {
        return 0;
    }else {
        pct = diff / actual;
    }
W
wenjun 已提交
43 44 45 46 47 48 49 50 51 52 53 54
    LOGD("diff=%f, pct=%f\n", diff, pct);
    return (pct <= accuracy);
}

const int SYS_US_PER_MS = 1000;
void Msleep(int msec)
{
    usleep(msec * SYS_US_PER_MS);
}

int KeepRun(int msec)
{
M
mamingshuai 已提交
55 56
    struct timespec time1 = { 0, 0 };
    struct timespec time2 = { 0, 0 };
W
wenjun 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70
    clock_gettime(CLOCK_MONOTONIC, &time1);
    LOGD("KeepRun start : tv_sec=%ld, tv_nsec=%ld\n", time1.tv_sec, time1.tv_nsec);
    int loop = 0;
    int runned = 0;
    while (runned < msec) {
        ++loop;
        clock_gettime(CLOCK_MONOTONIC, &time2);
        runned = (time2.tv_sec - time1.tv_sec) * 1000 + (time2.tv_nsec - time1.tv_nsec) / 1000000;
    }
    LOGD("KeepRun end : tv_sec=%ld, tv_nsec=%ld\n", time2.tv_sec, time2.tv_nsec);
    return loop;
}

// check process state use 'waitpid'
M
mamingshuai 已提交
71
int CheckProcStatus(pid_t pid, int *code, int flag)
W
wenjun 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
{
    int status;
    int rt = waitpid(pid, &status, flag);
    errno = 0;
    if (rt == -1) {
        LOGE("waitpid return -1, errno=%d:%s\n", errno, strerror(errno));
        return -1;
    } else if (rt == 0) {
        return 0;
    } else if (rt != pid) { // waitpid return error
        if (errno) {
            LOGE("waitpid return error, rt=%d, errno=%d:%s\n", rt, errno, strerror(errno));
        } else {
            LOGE("waitpid return error, errno is not set(no more info)\n");
        }
        return -2;
    }
M
mamingshuai 已提交
89 90 91
    if (code == nullptr) {
        return -1;
    }
W
wenjun 已提交
92 93

    if (WIFEXITED(status)) {
M
mamingshuai 已提交
94
        *code = WEXITSTATUS(status);
W
wenjun 已提交
95 96
        return 1;
    } else if (WIFSIGNALED(status)) {
M
mamingshuai 已提交
97
        *code = WTERMSIG(status);
W
wenjun 已提交
98 99 100 101 102 103 104 105 106
        return 2;
    } else if (WIFSTOPPED(status)) {
        *code = WSTOPSIG(status);
        return 3;
    }
    return 4;
}

// start a elf, only check if execve success or not
M
mamingshuai 已提交
107
static int StartElf(const char *fname, char * const argv[], char * const envp[])
W
wenjun 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
{
    int pid = fork();
    if (pid == -1) {
        LOGE("ERROR: Fork Error, errno=%d, err=%s\n", errno, strerror(errno));
        return -1;
    } else if (pid == 0) { // child
        errno = 0;
        int rt = execve(fname, argv, envp);
        if (rt == -1) {
            LOGE("ERROR: execve return -1, errno=%d, err=%s\n", errno, strerror(errno));
            exit(EXECVE_RETURN_ERROR);
        }
        LOGE("ERROR: execve should never return on success. rt=%d, errno=%d, err=%s\n", rt, errno, strerror(errno));
        exit(EXECVE_RETURN_OK);
    }
    return pid;
}

M
mamingshuai 已提交
126
int RunElf(const char *fname, char * const argv[], char * const envp[], int timeoutSec)
W
wenjun 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139
{
    int isTimeout = 0;
    int exitCode;
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);

    int pid = StartElf(fname, argv, envp);
    if (pid == -1) { // fork error
        return -1;
    }

    if (timeoutSec > 0) {
M
mamingshuai 已提交
140 141
        struct timespec time1 = { timeoutSec, 0 };
        if (sigtimedwait(&set, nullptr, &time1) == -1) {
W
wenjun 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
            if (errno == EAGAIN) {
                isTimeout = 1;
            } else {
                LOGE("ERROR: sigtimedwait FAIL: %s\n", strerror(errno));
                return -1;
            }
            if (kill(pid, SIGKILL) == -1) {
                LOGE("ERROR: kill child FAIL: %s\n", strerror(errno));
                return -1;
            }
        }
        // else: sigtimedwait return ok, child has exited already, nothing else to do
    }
    int rt = CheckProcStatus(pid, &exitCode, 0);
    if ((rt <= 0) || (exitCode == EXECVE_RETURN_OK) || (exitCode == EXECVE_RETURN_ERROR)) {
        return -1;
    }
    if (isTimeout) {
        LOGE("ERROR: child execute timed out!\n");
        return -2;
    }
    return exitCode;
}

M
mamingshuai 已提交
166
int StartExecveError(const char *fname, char * const argv[], char * const envp[])
W
wenjun 已提交
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 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
{
    pid_t pid = fork();
    if (pid == -1) {
        LOGE("ERROR: Fork Error, errno=%d, err=%s\n", errno, strerror(errno));
        return -1;
    } else if (pid == 0) { // child
        int rt = execve(fname, argv, envp);
        if (rt == -1) {
            LOG("ERROR: execve return -1, errno=%d, err=%s\n", errno, strerror(errno));
            exit(errno);
        }
        LOGE("ERROR: execve should never return on success. rt=%d, errno=%d, err=%s\n", rt, errno, strerror(errno));
        exit(EXECVE_RETURN_OK);
    }
    // parent
    Msleep(30);
    int exitCode;
    int procStat = CheckProcStatus(pid, &exitCode);
    LOG("procStat=%d, exitCode=%d\n", procStat, exitCode);
    if (procStat != 1) {
        return -3;
    } else if (exitCode == EXECVE_RETURN_OK) {
        return -2;
    } else {
        return exitCode;
    }
}

// Get a pid number that currently not exist
// by creat a child process and exit.
pid_t GetNonExistPid()
{
    pid_t pid = fork();
    if (pid < 0) {
        LOG("fork error, wait 5 seconds than try angain...");
        sleep(5);
        pid = fork();
        if (pid < 0) {
            LOG("still fork error!");
            return -1;
        }
    }
    if (pid > 0) { // parent
        Msleep(20);
M
mamingshuai 已提交
211
        if (waitpid(pid, nullptr, 0) != pid) {
W
wenjun 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            LOG("waitpid failed, errno = %d", errno);
            return -1;
        }
    } else { // child
        exit(0);
    }
    return pid;
}

// return n: 0 < n <= max
uint32_t GetRandom(uint32_t max)
{
    if (max == 0 || max == 1) {
        return 1;
    }
    return (rand() % max) + 1;
}
M
mamingshuai 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

// get cur-time plus ms
void GetDelayedTime(struct timespec *ts, unsigned int ms)
{
    const unsigned int nsecPerSec = 1000000000;
    unsigned int setTimeNs = ms * 1000000;
    struct timespec tsNow = { 0 };
    clock_gettime(CLOCK_REALTIME, &tsNow);
    ts->tv_sec = tsNow.tv_sec + (tsNow.tv_nsec + setTimeNs) / nsecPerSec;
    ts->tv_nsec = (tsNow.tv_nsec + setTimeNs) % nsecPerSec;
}

// calculate time difference, in ms
int GetTimeDiff(struct timespec ts1, struct timespec ts2)
{
    const unsigned int nsecPerSec = 1000000000;
    int ms = (ts1.tv_sec - ts2.tv_sec) * nsecPerSec + (ts1.tv_nsec - ts2.tv_nsec);
    ms = ms / 1000000;
    return ms;
}

int GetCpuCount(void)
{
    cpu_set_t cpuset;

    CPU_ZERO(&cpuset);
    int temp = sched_getaffinity(getpid(), sizeof(cpu_set_t), &cpuset);
    if (temp != 0) {
        printf("%s %d Error : %d\n", __FUNCTION__, __LINE__, temp);
    }

    return CPU_COUNT(&cpuset);
}

int FixCurProcessToOneCpu(int cpuIndex, cpu_set_t *pOldMask)
{
    int ret;
    cpu_set_t setMask;
    CPU_ZERO(pOldMask);
    ret = sched_getaffinity(0, sizeof(cpu_set_t), pOldMask);
    if (ret != 0) {
        LOG("sched_getaffinity failed, ret = %d", ret);
        return -1;
    }
    if (CPU_ISSET(0, pOldMask)) {
        LOG("before affinity cpu is 0");
    }
    if (CPU_ISSET(1, pOldMask)) {
        LOG("before affinity cpu is 1");
    }
    CPU_ZERO(&setMask);
    CPU_SET(cpuIndex, &setMask);
    LOG("fix cpu to %d", cpuIndex);
    ret = sched_setaffinity(0, sizeof(setMask), &setMask);
    if (ret != 0) {
        LOG("sched_setaffinity failed, ret = %d", ret);
        return -1;
    }
    return 0;
}