health_check.c 25.2 KB
Newer Older
O
overweight 已提交
1 2
/******************************************************************************
 * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. All rights reserved.
3 4 5 6
 * iSulad licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
O
overweight 已提交
7 8 9
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
10
 * See the Mulan PSL v2 for more details.
O
overweight 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Author: wujing
 * Create: 2018-11-1
 * Description: provide health check functions
 *********************************************************************************/
#define _GNU_SOURCE
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <semaphore.h>

H
haozi007 已提交
25
#include "isula_libutils/log.h"
O
overweight 已提交
26 27 28
#include "utils.h"
#include "health_check.h"
#include "callback.h"
29
#include "service_container_api.h"
H
haozi007 已提交
30 31
#include "isula_libutils/container_exec_request.h"
#include "isula_libutils/container_exec_response.h"
32
#include "log_gather_api.h"
L
lifeng68 已提交
33
#include "container_state.h"
O
overweight 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

/* container state lock */
static void container_health_check_lock(health_check_manager_t *health)
{
    if (health == NULL) {
        return;
    }
    if (pthread_mutex_lock(&health->mutex)) {
        ERROR("Failed to lock health check manager");
    }
}

/* container state unlock */
static void container_health_check_unlock(health_check_manager_t *health)
{
    if (health == NULL) {
        return;
    }
    if (pthread_mutex_unlock(&health->mutex)) {
        ERROR("Failed to unlock health check manager");
    }
}

static char *get_health_status(container_state_t *s)
{
    char *status = NULL;

    if (s->state->health->status == NULL || strlen(s->state->health->status) == 0) {
        return util_strdup_s(UNHEALTHY);
    }

    container_state_lock(s);
    status = util_strdup_s(s->state->health->status);
    container_state_unlock(s);

    return status;
}

static void set_health_status(container_state_t *s, const char *new)
{
    if (s == NULL || new == NULL) {
        return;
    }
    container_state_lock(s);
    free(s->state->health->status);
    s->state->health->status = util_strdup_s(new);
    container_state_unlock(s);
}

static void set_monitor_idle_status(health_check_manager_t *health)
{
    container_health_check_lock(health);
    health->monitor_status = MONITOR_IDLE;
    container_health_check_unlock(health);
}

static void set_monitor_stop_status(health_check_manager_t *health)
{
    container_health_check_lock(health);
    health->monitor_status = MONITOR_STOP;
    container_health_check_unlock(health);
}

static void set_monitor_interval_timeout_status(health_check_manager_t *health)
{
    container_health_check_lock(health);
    health->monitor_status = MONITOR_INTERVAL;
    container_health_check_unlock(health);
}

static health_check_monitor_status_t get_health_check_monitor_state(health_check_manager_t *health)
{
    health_check_monitor_status_t ret;

    container_health_check_lock(health);
    ret = health->monitor_status;
    container_health_check_unlock(health);

    return ret;
}

static void close_health_check_monitor(const container_t *cont)
{
    if (cont == NULL || cont->health_check == NULL) {
        return;
    }
    set_monitor_stop_status(cont->health_check);
    set_health_status(cont->state, UNHEALTHY);
}

static void open_health_check_monitor(health_check_manager_t *health)
{
    set_monitor_interval_timeout_status(health);
}

// Called when the container is being stopped (whether because the health check is
// failing or for any other reason).
void stop_health_checks(const char *container_id)
{
    container_t *cont = NULL;

    if (container_id == NULL) {
        return;
    }

    cont = containers_store_get(container_id);
    if (cont == NULL) {
        ERROR("Failed to get container info");
        return;
    }
    if (cont->state != NULL && cont->state->state != NULL && cont->state->state->health != NULL) {
        close_health_check_monitor(cont);
    }
    container_unref(cont);
}

/* health check manager free */
void health_check_manager_free(health_check_manager_t *health_check)
{
    if (health_check == NULL) {
        return;
    }
    if (health_check->init_mutex) {
        pthread_mutex_destroy(&health_check->mutex);
    }
    free(health_check);
}

/* health check manager new */
static health_check_manager_t *health_check_manager_new()
{
    int ret;
    health_check_manager_t *health_check = NULL;

    health_check = util_common_calloc_s(sizeof(health_check_manager_t));
    if (health_check == NULL) {
        ERROR("Out of memory");
        return NULL;
    }
    ret = pthread_mutex_init(&health_check->mutex, NULL);
    if (ret != 0) {
        ERROR("Failed to init mutex of health check manager");
        goto cleanup;
    }
    health_check->init_mutex = true;

    health_check->monitor_status = MONITOR_IDLE;

    return health_check;
cleanup:
    health_check_manager_free(health_check);
    return NULL;
}

static ssize_t write_to_string(void *context, const void *data, size_t len)
{
    char *dst = (char *)context;

    if (len == 0) {
        return 0;
    }

    if (len >= REV_BUF_SIZE) {
O
openeuler-iSula 已提交
197 198
        (void)strncpy(dst, data, REV_BUF_SIZE - 4);
        (void)strcpy(dst + REV_BUF_SIZE - 4, "...");
O
overweight 已提交
199
    } else {
O
openeuler-iSula 已提交
200
        (void)strncpy(dst, data, len);
O
overweight 已提交
201
    }
O
openeuler-iSula 已提交
202

O
overweight 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    return (ssize_t)len;
}

static char **get_shell()
{
    char **shell = NULL;

    if (util_array_append(&shell, "/bin/sh") || util_array_append(&shell, "-c")) {
        ERROR("Failed to add shell, out of memory");
        util_free_array(shell);
        return NULL;
    }
    return shell;
}

static char **health_check_cmds(const container_config *config)
{
    size_t i = 0;
    size_t shell_len = 0;
    char **shell = NULL;
    char **cmd_slice = NULL;

    if (config == NULL) {
        return NULL;
    }
    shell = get_shell();
    if (shell == NULL) {
        ERROR("Failed to get shell");
        goto out;
    }

Z
zhuchunyi 已提交
234
    shell_len = util_array_len((const char **)shell);
235
    if (shell_len > (SIZE_MAX / sizeof(char *)) - config->healthcheck->test_len) {
O
overweight 已提交
236 237 238
        ERROR("Invalid shell length");
        goto out;
    }
239
    cmd_slice = util_common_calloc_s((shell_len + config->healthcheck->test_len) * sizeof(char *));
O
overweight 已提交
240 241 242 243 244 245 246 247
    if (cmd_slice == NULL) {
        ERROR("out of memory");
        goto out;
    }
    for (i = 0; i < shell_len; i++) {
        cmd_slice[i] = util_strdup_s(shell[i]);
    }

248 249
    for (i = shell_len; i < (shell_len + config->healthcheck->test_len) - 1; i++) {
        cmd_slice[i] = util_strdup_s(config->healthcheck->test[(i - shell_len) + 1]);
O
overweight 已提交
250 251 252 253 254 255 256
    }

out:
    util_free_array(shell);
    return cmd_slice;
}

257
static int shift_and_store_log_result(defs_health *health, const defs_health_log_element *result)
O
overweight 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270
{
    int ret = 0;
    size_t i = 0;

    for (i = 0; i < MAX_LOG_ENTRIES; i++) {
        free(health->log[i]->start);
        free(health->log[i]->end);
        free(health->log[i]->output);

        if (i != MAX_LOG_ENTRIES - 1) {
            health->log[i]->start = util_strdup_s(health->log[i + 1]->start);
            health->log[i]->end = util_strdup_s(health->log[i + 1]->end);
            health->log[i]->exit_code = health->log[i + 1]->exit_code;
271
            health->log[i]->output = health->log[i + 1]->output != NULL ? util_strdup_s(health->log[i + 1]->output) :
L
lifeng68 已提交
272
                                                                          NULL;
O
overweight 已提交
273 274 275 276 277 278 279 280 281 282 283 284
        } else {
            health->log[i]->start = util_strdup_s(result->start);
            health->log[i]->end = util_strdup_s(result->end);
            health->log[i]->exit_code = result->exit_code;
            health->log[i]->output = result->output != NULL ? util_strdup_s(result->output) : NULL;
        }
    }
    health->log_len = MAX_LOG_ENTRIES;

    return ret;
}

285
static int append_last_log_result(defs_health *health, const defs_health_log_element *result)
O
overweight 已提交
286 287 288 289 290 291 292 293 294 295
{
    int ret = 0;
    defs_health_log_element **tmp_log = NULL;
    defs_health_log_element *log = NULL;

    if (health->log_len > (SIZE_MAX / sizeof(defs_health_log_element *)) - 1) {
        ERROR("failed to realloc memory");
        return -1;
    }

296 297
    ret = mem_realloc((void **)(&tmp_log), (health->log_len + 1) * sizeof(defs_health_log_element *), health->log,
                      health->log_len * sizeof(defs_health_log_element *));
O
overweight 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    if (ret != 0) {
        ERROR("failed to realloc memory");
        return -1;
    }
    health->log = tmp_log;
    log = util_common_calloc_s(sizeof(defs_health_log_element));
    if (log == NULL) {
        ERROR("Out of memory");
        ret = -1;
        goto out;
    }
    log->start = util_strdup_s(result->start);
    log->end = util_strdup_s(result->end);
    log->exit_code = result->exit_code;
    log->output = result->output != NULL ? util_strdup_s(result->output) : NULL;
    health->log[health->log_len++] = log;

out:
    return ret;
}

static int handle_increment_streak(container_t *cont, int retries)
{
    int ret = 0;
    defs_health *health = NULL;

    health = cont->state->state->health;
    health->failing_streak++;
    if (health->failing_streak >= retries) {
        set_health_status(cont->state, UNHEALTHY);
328
        if (cont->common_config->config->healthcheck->exit_on_unhealthy) {
O
overweight 已提交
329 330 331
            // kill container when exit on unhealthy flag is set
            ret = stop_container(cont, 3, true, false);
            if (ret != 0) {
L
LiuHao 已提交
332 333
                isulad_try_set_error_message("Could not stop running container %s, cannot remove",
                                             cont->common_config->id);
O
overweight 已提交
334 335 336 337 338 339 340 341
                ERROR("Could not stop running container %s, cannot remove", cont->common_config->id);
                ret = -1;
            }
        }
    }
    return ret;
}

342
static int handle_unhealthy_case(container_t *cont, const defs_health_log_element *result, int retries)
O
overweight 已提交
343
{
344
    int ret = 0;
O
overweight 已提交
345 346 347 348 349 350
    bool should_increment_streak = true;
    char *health_status = NULL;

    health_status = get_health_status(cont->state);

    if (strcmp(health_status, HEALTH_STARTING) == 0) {
351 352 353
        int64_t start_period = (cont->common_config->config->healthcheck->start_period == 0) ?
                                       DEFAULT_START_PERIOD :
                                       cont->common_config->config->healthcheck->start_period;
O
overweight 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        int64_t first, last;
        if (to_unix_nanos_from_str(cont->state->state->started_at, &first)) {
            ERROR("Parse container started time failed: %s", cont->state->state->started_at);
            ret = -1;
            goto out;
        }
        if (to_unix_nanos_from_str(result->start, &last)) {
            ERROR("Parse last health check start time failed: %s", result->start);
            ret = -1;
            goto out;
        }
        if (last - first < start_period) {
            should_increment_streak = false;
        }
    }
    if (should_increment_streak) {
        ret = handle_increment_streak(cont, retries);
    }
out:
    free(health_status);
    return ret;
}

static int append_health_log(container_state_t *s, const defs_health_log_element *result)
{
    int ret = 0;
    defs_health *health = NULL;

    container_state_lock(s);

    health = s->state->health;

    if (health->log_len >= MAX_LOG_ENTRIES) {
        if (shift_and_store_log_result(health, result)) {
            ERROR("failed to append last log result");
            ret = -1;
            goto out;
        }
    } else {
        if (append_last_log_result(health, result) != 0) {
            ERROR("failed to append last log result");
            ret = -1;
            goto out;
        }
    }

out:
    container_state_unlock(s);

    return ret;
}

// Update the container's Status.Health struct based on the latest probe's result.
static int handle_probe_result(const char *container_id, const defs_health_log_element *result)
{
    int ret = 0;
    int retries = 0;
    char *current = NULL;
    char *old_state = NULL;
    defs_health *health = NULL;
    container_t *cont = NULL;

    cont = containers_store_get(container_id);
    if (cont == NULL) {
        ERROR("Failed to get container info");
        return -1;
    }
421 422
    DEBUG("health check result: \n   start: %s\n    end: %s\n    output: %s\n    exit_code: %d\n", result->start,
          result->end, result->output, result->exit_code);
O
overweight 已提交
423 424 425 426
    // probe may have been cancelled while waiting on lock. Ignore result then
    if (get_health_check_monitor_state(cont->health_check) == MONITOR_STOP) {
        goto out;
    }
427
    retries = cont->common_config->config->healthcheck->retries;
O
overweight 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    if (retries <= 0) {
        retries = DEFAULT_PROBE_RETRIES;
    }
    health = cont->state->state->health;
    old_state = get_health_status(cont->state);

    ret = append_health_log(cont->state, result);
    if (ret != 0) {
        goto out;
    }

    if (result->exit_code == EXIT_STATUS_HEALTHY) {
        health->failing_streak = 0;
        set_health_status(cont->state, HEALTHY);
    } else {
        if (handle_unhealthy_case(cont, result, retries)) {
            ERROR("failed to handle unhealthy case");
            ret = -1;
            goto out;
        }
        // else we're starting or healthy. Stay in that state.
    }
    // note: replicate Health status changes
    current = get_health_status(cont->state);
    if (strcmp(old_state, current) != 0) {
        // note: event
        EVENT("EVENT: {Object: %s, health_status: %s}", cont->common_config->id, current);
    }
    if (container_to_disk(cont)) {
        ERROR("Failed to save container \"%s\" to disk", cont->common_config->id);
        ret = -1;
    }
out:
    free(old_state);
    free(current);
    container_unref(cont);

    return ret;
}
static void health_check_exec_failed_handle(const container_exec_response *container_res,
                                            defs_health_log_element *result)
{
    if (container_res != NULL) {
        if (container_res->errmsg != NULL) {
            ERROR("%s, Exit code: %d", container_res->errmsg, (int)container_res->exit_code);
            result->output = util_strdup_s(container_res->errmsg);
        } else {
            ERROR("Execution of exec failed, Exit code: %d", (int)container_res->exit_code);
            result->output = util_strdup_s("Execution of exec failed");
        }
    } else {
        ERROR("Failed to call exec container callback");
        result->output = util_strdup_s("Failed to call exec container callback");
    }
    result->exit_code = -1;
}

static void health_check_exec_success_handle(const container_exec_response *container_res,
486
                                             defs_health_log_element *result, const char *output)
O
overweight 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
{
    result->output = util_strdup_s(output);
    if (container_res != NULL) {
        result->exit_code = (int)container_res->exit_code;
    } else {
        result->exit_code = -1;
    }
}

// exec the healthcheck command in the container.
// Returns the exit code and probe output (if any)
void *health_check_run(void *arg)
{
    int ret = 0;
    char *container_id = NULL;
    char **cmd_slice = NULL;
    char output[REV_BUF_SIZE] = { 0 };
    char timebuffer[TIME_STR_SIZE] = { 0 };
505 506
    struct io_write_wrapper Stdoutctx = { 0 };
    struct io_write_wrapper Stderrctx = { 0 };
O
overweight 已提交
507
    container_t *cont = NULL;
508
    service_executor_t *cb = NULL;
O
overweight 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    container_exec_request *container_req = NULL;
    container_exec_response *container_res = NULL;
    defs_health_log_element *result = NULL;
    container_config *config = NULL;

    if (arg == NULL) {
        ERROR("Invalid input arguments");
        return NULL;
    }

    container_id = util_strdup_s((char *)arg);

    cont = containers_store_get(container_id);
    if (cont == NULL) {
        ERROR("Failed to get container info");
        goto out;
    }

    config = cont->common_config->config;

    cmd_slice = health_check_cmds(config);
    if (cmd_slice == NULL) {
        ERROR("Failed to get health check cmds");
        goto out;
    }

535
    cb = get_service_executor();
O
overweight 已提交
536 537 538 539 540 541 542 543 544 545
    if (cb == NULL || cb->container.exec == NULL) {
        ERROR("Failed to get service callback function");
        goto out;
    }

    container_req = (container_exec_request *)util_common_calloc_s(sizeof(container_exec_request));
    if (container_req == NULL) {
        ERROR("Out of memory");
        goto out;
    }
546 547 548

    // Set tty to true, compatible with busybox
    container_req->tty = true;
O
overweight 已提交
549 550
    container_req->attach_stdin = false;
    container_req->attach_stdout = true;
551
    container_req->attach_stderr = true;
552 553
    container_req->timeout =
            ((config->healthcheck->timeout == 0) ? DEFAULT_PROBE_TIMEOUT : config->healthcheck->timeout) / Time_Second;
O
overweight 已提交
554 555
    container_req->container_id = util_strdup_s(cont->common_config->id);
    container_req->argv = cmd_slice;
Z
zhuchunyi 已提交
556
    container_req->argv_len = util_array_len((const char **)cmd_slice);
O
overweight 已提交
557 558 559 560 561 562 563 564 565 566 567
    cmd_slice = NULL;
    EVENT("EVENT: {Object: %s, Type:  Health checking}", cont->common_config->id);

    (void)get_now_time_buffer(timebuffer, sizeof(timebuffer));
    result = util_common_calloc_s(sizeof(defs_health_log_element));
    if (result == NULL) {
        ERROR("Out of memory");
        goto out;
    }
    result->start = util_strdup_s(timebuffer);

568 569 570 571 572 573 574
    Stdoutctx.context = (void *)output;
    Stdoutctx.write_func = write_to_string;
    Stdoutctx.close_func = NULL;
    Stderrctx.context = (void *)output;
    Stderrctx.write_func = write_to_string;
    Stderrctx.close_func = NULL;
    ret = cb->container.exec(container_req, &container_res, -1, &Stdoutctx, &Stderrctx);
O
overweight 已提交
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    if (ret != 0) {
        health_check_exec_failed_handle(container_res, result);
    } else {
        health_check_exec_success_handle(container_res, result, output);
    }

    (void)get_now_time_buffer(timebuffer, sizeof(timebuffer));
    result->end = util_strdup_s(timebuffer);

    if (handle_probe_result(cont->common_config->id, result) != 0) {
        ERROR("Failed to handle probe result");
    }

out:
    util_free_array(cmd_slice);
    free(container_id);
    container_id = NULL;
    free_defs_health_log_element(result);
    free_container_exec_request(container_req);
    free_container_exec_response(container_res);
    container_unref(cont);
    return NULL;
}

// Get a suitable probe implementation for the container's healthcheck configuration.
// Nil will be returned if no healthcheck was configured or NONE was set.
static health_probe_t get_probe(const container_t *cont)
{
603
    defs_health_check *config = cont->common_config->config->healthcheck;
O
overweight 已提交
604 605 606 607 608 609 610 611 612 613 614 615

    if (config == NULL || config->test_len == 0) {
        return HEALTH_NONE;
    }

    if (strcmp(config->test[0], "CMD") == 0) {
        return CMD;
    } else if (strcmp(config->test[0], "CMD-SHELL") == 0) {
        return CMD_SHELL;
    } else if (strcmp(config->test[0], "NONE") == 0) {
        return HEALTH_NONE;
    } else {
616 617
        WARN("Unknown healthcheck type '%s' (expected 'CMD') in container %s", config->test[0],
             cont->common_config->id);
O
overweight 已提交
618 619 620 621
        return HEALTH_NONE;
    }
}

622
static int do_monitor_interval(const char *container_id, health_check_manager_t *health_check,
O
overweight 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
                               types_timestamp_t *start_timestamp)
{
    int ret = 0;
    pthread_t exec_tid = { 0 };

    if (pthread_create(&exec_tid, NULL, health_check_run, (void *)container_id)) {
        ERROR("Failed to create thread to exec health check");
        ret = -1;
        goto out;
    }
    if (pthread_join(exec_tid, NULL) < 0) {
        ERROR("Failed to run health check thread");
        ret = -1;
        goto out;
    }
    if (get_health_check_monitor_state(health_check) == MONITOR_STOP) {
        ret = 0;
        goto out;
    }
    set_monitor_idle_status(health_check);
    if (get_now_time_stamp(start_timestamp) == false) {
        ERROR("Failed to get time stamp");
        ret = -1;
        goto out;
    }
out:
    return ret;
}

652 653
static int do_monitor_default(int64_t probe_interval, health_check_manager_t *health_check,
                              const types_timestamp_t *start_timestamp, types_timestamp_t *last_timestamp)
O
overweight 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
{
    int64_t time_interval = 0;

    if (get_now_time_stamp(last_timestamp) == false) {
        ERROR("Failed to get time stamp");
        return -1;
    }

    if (get_time_interval(*start_timestamp, *last_timestamp, &time_interval)) {
        ERROR("Failed to get time interval");
        return -1;
    }

    if (time_interval >= probe_interval) {
        set_monitor_interval_timeout_status(health_check);
    }
    usleep_nointerupt(500);

    return 0;
}
// Run the container's monitoring thread until notified via "stop".
// There is never more than one monitor thread running per container at a time.
static void *health_check_monitor(void *arg)
{
    char *container_id = NULL;
    int64_t probe_interval = 0;
    container_t *cont = NULL;
    types_timestamp_t start_timestamp = { 0 };
    types_timestamp_t last_timestamp = { 0 };

    if ((char *)arg == NULL) {
        ERROR("Container id is empty");
        return NULL;
    }
    container_id = util_strdup_s((char *)arg);

    cont = containers_store_get(container_id);
    if (cont == NULL) {
        ERROR("Failed to get container info");
        goto out;
    }

    if (get_now_time_stamp(&start_timestamp) == false) {
        ERROR("Failed to monitor start time stamp");
        goto out;
    }
700 701 702
    probe_interval = (cont->common_config->config->healthcheck->interval == 0) ?
                             DEFAULT_PROBE_INTERVAL :
                             cont->common_config->config->healthcheck->interval;
O
overweight 已提交
703 704 705 706
    set_monitor_idle_status(cont->health_check);
    while (true) {
        switch (get_health_check_monitor_state(cont->health_check)) {
            case MONITOR_STOP:
707
                DEBUG("Stop healthcheck monitoring for container %s (received while idle)", cont->common_config->id);
O
overweight 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
                goto out;
            /* fall-through */
            case MONITOR_INTERVAL:
                if (do_monitor_interval(container_id, cont->health_check, &start_timestamp)) {
                    goto out;
                }
                break;
            case MONITOR_IDLE:
            /* fall-through */
            default:
                if (do_monitor_default(probe_interval, cont->health_check, &start_timestamp, &last_timestamp)) {
                    goto out;
                }
                break;
        }
    }
out:
    free(container_id);
    container_id = NULL;
    container_unref(cont);
    return NULL;
}

// Ensure the health-check monitor is running or not, depending on the current
// state of the container.
// Called from monitor.go, with c locked.
void update_health_monitor(const char *container_id)
{
    bool want_running = false;
    container_t *cont = NULL;
    defs_health *health = NULL;
    health_probe_t probe;

    if (container_id == NULL) {
        return;
    }
    cont = containers_store_get(container_id);
    if (cont == NULL) {
        ERROR("Failed to get container info");
        return;
    }

    health = cont->state->state->health;
    if (health == NULL) {
        goto out;
    }
    probe = get_probe(cont);
    want_running = cont->state->state->running && !cont->state->state->paused && probe != HEALTH_NONE;

    if (want_running) {
        open_health_check_monitor(cont->health_check);
        pthread_t monitor_tid = { 0 };
        if (pthread_create(&monitor_tid, NULL, health_check_monitor, (void *)container_id)) {
            ERROR("Failed to create thread to monitor health check...");
            goto out;
        }
        if (pthread_detach(monitor_tid)) {
            ERROR("Failed to detach the health check monitor thread");
            goto out;
        }
    } else {
        close_health_check_monitor(cont);
    }

out:
    container_unref(cont);
}

// Reset the health state for a newly-started, restarted or restored container.
// initHealthMonitor is called from monitor.go and we should never be running
// two instances at once.
// Note: Called with container locked.
void init_health_monitor(const char *id)
{
    container_t *cont = NULL;

    cont = containers_store_get(id);
    if (cont == NULL) {
        ERROR("Failed to get container info");
        return;
    }

790
    if (cont->common_config->config->healthcheck == NULL || cont->common_config->config->healthcheck->test == NULL) {
O
overweight 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
        goto out;
    }

    if (cont->health_check == NULL) {
        cont->health_check = health_check_manager_new();
        if (cont->health_check == NULL) {
            ERROR("Out of memory");
            goto out;
        }
    }

    // If no healthcheck is setup then don't init the monitor
    if (get_probe(cont) == HEALTH_NONE) {
        goto out;
    }
    // This is needed in case we're auto-restarting
    stop_health_checks(cont->common_config->id);
    if (cont->state == NULL || cont->state->state == NULL) {
        goto out;
    }

    if (cont->state->state->health != NULL) {
        set_health_status(cont->state, HEALTH_STARTING);
        cont->state->state->health->failing_streak = 0;
    } else {
        cont->state->state->health = util_common_calloc_s(sizeof(defs_health));
        if (cont->state->state->health == NULL) {
            ERROR("out of memory");
            goto out;
        }
        set_health_status(cont->state, HEALTH_STARTING);
    }

    if (container_to_disk(cont)) {
        ERROR("Failed to save container \"%s\" to disk", id);
        goto out;
    }

    update_health_monitor(id);

out:
    container_unref(cont);
    return;
}