collector.c 27.8 KB
Newer Older
O
overweight 已提交
1 2
/******************************************************************************
 * Copyright (c) Huawei Technologies Co., Ltd. 2017-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 25 26 27 28
 * Author: tanyifeng
 * Create: 2017-11-22
 * Description: provide container collector functions
 ******************************************************************************/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <poll.h>
#include <sys/prctl.h>
#include <regex.h>
#include <errno.h>

#include "error.h"
H
haozi007 已提交
29
#include "isula_libutils/log.h"
O
overweight 已提交
30
#include "collector.h"
31
#include "monitord.h"
L
LiuHao 已提交
32 33
#include "isulad_config.h"
#include "libisulad.h"
L
lifeng68 已提交
34
#include "container_api.h"
35
#include "event_type.h"
L
lifeng68 已提交
36
#include "container_events_handler.h"
O
overweight 已提交
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

static struct context_lists g_context_lists;

struct events_lists {
    unsigned int size;
    pthread_mutex_t event_mutex;
    struct linked_list event_list;
};
static struct events_lists g_events_buffer;

#define EVENTSLIMIT 64

struct context_elem {
    stream_func_wrapper stream;
    char *name;
    sem_t context_sem;
    const types_timestamp_t *since;
    const types_timestamp_t *until;
};

/* get idreg */
static bool get_idreg(regex_t *preg, const char *id)
{
    char *regexp = NULL;
    size_t len = 0;
    int nret = 0;
    bool ret = false;

    if (id == NULL) {
        ERROR("Invalid event id");
        return false;
    }

    len = strlen(id) + 3;
    regexp = util_common_calloc_s(len);
    if (regexp == NULL) {
        ERROR("failed to allocate memory");
        return false;
    }

O
openeuler-iSula 已提交
77 78
    nret = snprintf(regexp, len, "^%s$", id);
    if ((size_t)nret >= len || nret < 0) {
O
overweight 已提交
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
        ERROR("Failed to print string");
        goto error;
    }

    if (regcomp(preg, regexp, REG_NOSUB | REG_EXTENDED)) {
        ERROR("failed to compile the regex '%s'", id);
        goto error;
    }

    ret = true;

error:
    free(regexp);
    return ret;
}

static container_events_type_t lcrsta2Evetype(int value)
{
    container_events_type_t et = EVENTS_TYPE_EXIT;

    switch (value) {
        case STOPPED:
            et = EVENTS_TYPE_STOPPED1;
            break;
        case STARTING:
            et = EVENTS_TYPE_STARTING;
            break;
        case RUNNING:
            et = EVENTS_TYPE_RUNNING1;
            break;
        case STOPPING:
            et = EVENTS_TYPE_STOPPING;
            break;
        case ABORTING:
            et = EVENTS_TYPE_ABORTING;
            break;
        case FREEZING:
            et = EVENTS_TYPE_FREEZING;
            break;
        case FROZEN:
            et = EVENTS_TYPE_FROZEN;
            break;
        case THAWED:
            et = EVENTS_TYPE_THAWED;
            break;
        default:
            et = EVENTS_TYPE_EXIT;
            break;
    }
    return et;
}

L
lifeng68 已提交
131
static const char *const g_isulad_event_strtype[] = {
132 133 134 135
    "exit",     "die",     "starting", "running", "stopping", "aborting",     "freezing",       "frozen",
    "thawed",   "oom",     "create",   "start",   "restart",  "stop",         "exec_create",    "exec_start",
    "exec_die", "attach",  "kill",     "top",     "reanme",   "archive-path", "extract-to-dir", "update",
    "pause",    "unpause", "export",   "resize",  "paused1",
W
wujing 已提交
136 137 138 139 140 141 142 143 144 145 146 147
};

/* isulad event sta2str */
static const char *isulad_event_sta2str(container_events_type_t sta)
{
    if (sta > EVENTS_TYPE_PAUSED1) {
        return NULL;
    }

    return g_isulad_event_strtype[sta];
}

L
lifeng68 已提交
148
static const char *const g_isulad_image_event_strtype[] = { "load", "remove", "pull", "login", "logout" };
W
wujing 已提交
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

static const char *isulad_image_event_sta2str(image_events_type_t sta)
{
    if (sta > EVENTS_TYPE_IMAGE_LOGOUT) {
        return NULL;
    }

    return g_isulad_image_event_strtype[sta];
}

static void supplement_msg_for_events_handler(const struct monitord_msg *msg, struct isulad_events_format *format_msg)
{
    if (msg->pid != -1) {
        format_msg->has_pid = true;
        format_msg->pid = (uint32_t)msg->pid;
    }

    format_msg->has_type = true;
    format_msg->type = lcrsta2Evetype(msg->value);
    if (format_msg->type == EVENTS_TYPE_STOPPED1) {
        format_msg->has_exit_status = true;
        if (msg->exit_code >= 0) {
            format_msg->exit_status = (uint32_t)msg->exit_code;
        } else {
            format_msg->exit_status = 125;
        }
    }
}

static int supplement_operator_for_container_msg(const struct monitord_msg *msg,
                                                 struct isulad_events_format *format_msg)
{
W
wujing 已提交
181
#define CONTAINER_OPERATOR_MAX_LEN 300
W
wujing 已提交
182
    int nret = 0;
183
    char opt[CONTAINER_OPERATOR_MAX_LEN] = { 0x00 };
W
wujing 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

    if (strlen(msg->args) != 0) {
        nret = snprintf(opt, sizeof(opt), "container %s: %s", isulad_event_sta2str(msg->value), msg->args);
    } else {
        nret = snprintf(opt, sizeof(opt), "container %s", isulad_event_sta2str(msg->value));
    }
    if (nret < 0 || nret >= sizeof(opt)) {
        return -1;
    }

    free(format_msg->opt);
    format_msg->opt = util_strdup_s(opt);

    return 0;
}

static int supplement_pid_for_container_msg(const container_t *cont, const struct monitord_msg *msg,
                                            struct isulad_events_format *format_msg)
{
    int nret = 0;
L
lifeng68 已提交
204
    char info[EVENT_EXTRA_ANNOTATION_MAX] = { 0x00 };
W
wujing 已提交
205

206
    if (cont->state == NULL || cont->state->state == NULL || cont->state->state->pid <= 0) {
W
wujing 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        return 0;
    }

    nret = snprintf(info, sizeof(info), "pid=%u", cont->state->state->pid);
    if (nret < 0 || nret >= sizeof(info)) {
        return -1;
    }

    if (util_array_append(&format_msg->annotations, info) != 0) {
        ERROR("Out of memory");
        return -1;
    }

    return 0;
}

static int supplement_exitcode_for_container_msg(const container_t *cont, const struct monitord_msg *msg,
                                                 struct isulad_events_format *format_msg)
{
    int nret = 0;
    int exit_code = 0;
L
lifeng68 已提交
228
    char info[EVENT_EXTRA_ANNOTATION_MAX] = { 0x00 };
W
wujing 已提交
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

    if (format_msg->exit_status != 0) {
        exit_code = format_msg->exit_status;
    } else if (cont->state != NULL && cont->state->state != NULL && cont->state->state->exit_code != 0) {
        exit_code = cont->state->state->exit_code;
    }

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

    nret = snprintf(info, sizeof(info), "exitCode=%u", exit_code);
    if (nret < 0 || nret >= sizeof(info)) {
        return -1;
    }

    if (util_array_append(&format_msg->annotations, info) != 0) {
        ERROR("Out of memory");
        return -1;
    }

    return 0;
}

static int supplement_image_for_container_msg(const container_t *cont, const struct monitord_msg *msg,
                                              struct isulad_events_format *format_msg)
{
    int nret = 0;
L
lifeng68 已提交
257
    char info[EVENT_EXTRA_ANNOTATION_MAX] = { 0x00 };
W
wujing 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

    if (cont->common_config == NULL || cont->common_config->image == NULL) {
        return 0;
    }

    nret = snprintf(info, sizeof(info), "image=%s", cont->common_config->image);
    if (nret < 0 || nret >= sizeof(info)) {
        return -1;
    }

    if (util_array_append(&format_msg->annotations, info) != 0) {
        ERROR("Out of memory");
        return -1;
    }

    return 0;
}

static int supplement_name_for_container_msg(const container_t *cont, const struct monitord_msg *msg,
                                             struct isulad_events_format *format_msg)
{
    int nret = 0;
L
lifeng68 已提交
280
    char info[EVENT_EXTRA_ANNOTATION_MAX] = { 0x00 };
W
wujing 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

    if (cont->common_config == NULL || cont->common_config->name == NULL) {
        return 0;
    }

    nret = snprintf(info, sizeof(info), "name=%s", cont->common_config->name);
    if (nret < 0 || nret >= sizeof(info)) {
        return -1;
    }

    if (util_array_append(&format_msg->annotations, info) != 0) {
        ERROR("Out of memory");
        return -1;
    }

    return 0;
}

static int supplement_labels_for_container_msg(const container_t *cont, const struct monitord_msg *msg,
                                               struct isulad_events_format *format_msg)
{
    size_t i;

304
    if (cont->common_config == NULL || cont->common_config->config->labels == NULL ||
W
wujing 已提交
305 306 307 308 309
        cont->common_config->config->labels->len == 0) {
        return 0;
    }

    for (i = 0; i < cont->common_config->config->labels->len; i++) {
L
lifeng68 已提交
310
        char info[EVENT_EXTRA_ANNOTATION_MAX] = { 0x00 };
W
wujing 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 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
        int nret = snprintf(info, sizeof(info), "%s=%s", cont->common_config->config->labels->keys[i],
                            cont->common_config->config->labels->values[i]);
        if (nret < 0 || nret >= sizeof(info)) {
            return -1;
        }

        if (util_array_append(&format_msg->annotations, info) != 0) {
            ERROR("Out of memory");
            return -1;
        }
    }

    return 0;
}

static int supplement_annotations_for_container_msg(const container_t *cont, const struct monitord_msg *msg,
                                                    struct isulad_events_format *format_msg)
{
    if (supplement_pid_for_container_msg(cont, msg, format_msg) != 0) {
        ERROR("Failed to supplement pid info");
        return -1;
    }

    if (supplement_exitcode_for_container_msg(cont, msg, format_msg) != 0) {
        ERROR("Failed to supplement exitCode info");
        return -1;
    }

    if (supplement_image_for_container_msg(cont, msg, format_msg) != 0) {
        ERROR("Failed to supplement image info");
        return -1;
    }

    if (supplement_name_for_container_msg(cont, msg, format_msg) != 0) {
        ERROR("Failed to supplement name info");
        return -1;
    }

    if (supplement_labels_for_container_msg(cont, msg, format_msg) != 0) {
        ERROR("Failed to supplement label info");
        return -1;
    }

    if (strlen(msg->extra_annations) != 0) {
        if (util_array_append(&format_msg->annotations, msg->extra_annations) != 0) {
            ERROR("Failed to supplement extra annations info");
            return -1;
        }
    }

    format_msg->annotations_len = util_array_len((const char **)format_msg->annotations);

    return 0;
}

static int supplement_msg_for_container(struct monitord_msg *msg, struct isulad_events_format *format_msg)
{
    int ret = 0;
    container_t *cont = containers_store_get(msg->name);
    if (cont == NULL) {
        ERROR("No such container:%s", msg->name);
        ret = -1;
        goto out;
    }

    // pid & exit_status parameter for events handler
    supplement_msg_for_events_handler(msg, format_msg);

    if (cont->common_config != NULL && cont->common_config->id != NULL) {
        format_msg->id = util_strdup_s(cont->common_config->id);
    }

    if (supplement_operator_for_container_msg(msg, format_msg) != 0) {
        ERROR("Failed to supplement operator info");
        ret = -1;
        goto out;
    }

    if (supplement_annotations_for_container_msg(cont, msg, format_msg) != 0) {
        ERROR("Failed to supplement annotations info");
        ret = -1;
        goto out;
    }

out:
    container_unref(cont);
    return ret;
}

static int supplement_msg_for_image(struct monitord_msg *msg, struct isulad_events_format *format_msg)
{
W
wujing 已提交
402
#define IMAGE_OPERATOR_MAX_LEN 50
W
wujing 已提交
403 404
    int ret = 0;
    int nret = 0;
405
    char opt[IMAGE_OPERATOR_MAX_LEN] = { 0x00 };
W
wujing 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

    format_msg->id = util_strdup_s(msg->name);

    nret = snprintf(opt, sizeof(opt), "image %s", isulad_image_event_sta2str(msg->value));
    if (nret < 0 || nret >= sizeof(opt)) {
        ERROR("Get operator operator info failed");
        ret = -1;
        goto out;
    }
    format_msg->opt = util_strdup_s(opt);

out:
    return ret;
}

O
overweight 已提交
421
/* format_msg */
L
LiuHao 已提交
422
static bool format_msg(struct isulad_events_format *r, struct monitord_msg *msg)
O
overweight 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
{
    bool ret = false;
    int err = 0;
    struct timespec ts;

    err = clock_gettime(CLOCK_REALTIME, &ts);
    if (err != 0) {
        ERROR("failed to get time");
        return false;
    }
    r->timestamp.has_seconds = true;
    r->timestamp.seconds = (int64_t)ts.tv_sec;
    r->timestamp.has_nanos = true;
    r->timestamp.nanos = (int32_t)ts.tv_nsec;

    msg->name[sizeof(msg->name) - 1] = '\0';

    r->has_pid = false;
    switch (msg->type) {
W
wujing 已提交
442 443 444 445 446
        case MONITORD_MSG_STATE:
            if (msg->event_type == CONTAINER_EVENT) {
                supplement_msg_for_container(msg, r);
            } else if (msg->event_type == IMAGE_EVENT) {
                supplement_msg_for_image(msg, r);
O
overweight 已提交
447 448 449
            }
            ret = true;
            break;
W
wujing 已提交
450 451
        case MONITORD_MSG_PRIORITY:
        case MONITORD_MSG_EXIT_CODE:
O
overweight 已提交
452 453 454 455 456 457 458 459 460
        default:
            /* ignore garbage */
            ret = false;
            DEBUG("Ignore received %d event", msg->type);
            break;
    }
    return ret;
}

W
wujing 已提交
461 462 463 464 465 466 467 468 469 470 471 472 473
static int calculate_annaotation_info_len(const struct isulad_events_format *events)
{
    size_t i;
    size_t len = 0;
    for (i = 0; i < events->annotations_len; i++) {
        len += strlen(events->annotations[i]);
    }
    len += events->annotations_len * 2; // length of ", " and "()"
    len += 1; // length of '\0'

    return len;
}

O
overweight 已提交
474
/* write events log */
L
LiuHao 已提交
475
static int write_events_log(const struct isulad_events_format *events)
O
overweight 已提交
476 477
{
    int ret = 0;
W
wujing 已提交
478 479 480
    size_t i;
    char *annotation = NULL;
    size_t len = 0;
O
overweight 已提交
481 482 483 484
    if (events == NULL) {
        goto out;
    }

W
wujing 已提交
485 486 487 488 489 490 491
    len = calculate_annaotation_info_len(events);
    if (len == 1) {
        EVENT("Event: {Object: %s, Type: %s}", events->id, events->opt);
    } else {
        annotation = (char *)util_common_calloc_s(len);
        if (annotation == NULL) {
            ERROR("Out of memory");
O
overweight 已提交
492 493 494 495
            ret = -1;
            goto out;
        }

W
wujing 已提交
496 497 498 499 500 501
        (void)strcat(annotation, "(");
        for (i = 0; i < events->annotations_len; i++) {
            (void)strcat(annotation, events->annotations[i]);
            if (i != events->annotations_len - 1) {
                (void)strcat(annotation, ", ");
            }
O
overweight 已提交
502
        }
W
wujing 已提交
503
        (void)strcat(annotation, ")");
O
overweight 已提交
504

W
wujing 已提交
505 506
        EVENT("Event: {Object: %s, Type: %s %s}", events->id, events->opt, annotation);
    }
O
overweight 已提交
507 508

out:
W
wujing 已提交
509
    free(annotation);
O
overweight 已提交
510 511 512 513
    return ret;
}

/* events append */
L
LiuHao 已提交
514
static void events_append(const struct isulad_events_format *event)
O
overweight 已提交
515
{
L
LiuHao 已提交
516
    struct isulad_events_format *tmpevent = NULL;
O
overweight 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    struct linked_list *newnode = NULL;
    struct linked_list *firstnode = NULL;

    if (pthread_mutex_lock(&g_events_buffer.event_mutex)) {
        WARN("Failed to lock");
        return;
    }

    if (g_events_buffer.size < EVENTSLIMIT) {
        newnode = util_common_calloc_s(sizeof(struct linked_list));
        if (newnode == NULL) {
            CRIT("Memory allocation error.");
            goto unlock;
        }

L
LiuHao 已提交
532
        tmpevent = util_common_calloc_s(sizeof(struct isulad_events_format));
O
overweight 已提交
533 534 535 536 537 538
        if (tmpevent == NULL) {
            CRIT("Memory allocation error.");
            free(newnode);
            goto unlock;
        }

W
wujing 已提交
539 540 541 542 543 544
        if (event_copy(event, tmpevent) != 0) {
            CRIT("Failed to copy event.");
            isulad_events_format_free(tmpevent);
            free(newnode);
            goto unlock;
        }
O
overweight 已提交
545 546 547 548 549 550 551 552 553

        linked_list_add_elem(newnode, tmpevent);
        linked_list_add_tail(&g_events_buffer.event_list, newnode);
        g_events_buffer.size++;
    } else {
        firstnode = linked_list_first_node(&g_events_buffer.event_list);
        if (firstnode != NULL) {
            linked_list_del(firstnode);

L
LiuHao 已提交
554
            tmpevent = (struct isulad_events_format *)firstnode->elem;
W
wujing 已提交
555 556 557 558
            if (event_copy(event, tmpevent) != 0) {
                CRIT("Failed to copy event.");
                goto unlock;
            }
O
overweight 已提交
559 560 561 562 563 564 565 566 567 568 569 570

            linked_list_add_tail(&g_events_buffer.event_list, firstnode);
        }
    }

unlock:
    if (pthread_mutex_unlock(&g_events_buffer.event_mutex)) {
        WARN("Failed to unlock");
        return;
    }
}

L
LiuHao 已提交
571
static int do_write_events(const stream_func_wrapper *stream, struct isulad_events_format *event)
O
overweight 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
{
    int ret = 0;

    if (stream->write_func == NULL || stream->writer == NULL) {
        ERROR("Unimplemented write function");
        ret = -1;
        goto out;
    }
    if (!stream->write_func(stream->writer, event)) {
        ERROR("Failed to send exit event for 'events' client");
        ret = -1;
        goto out;
    }
out:
    return ret;
}

L
LiuHao 已提交
589
static int check_since_time(const types_timestamp_t *since, const struct isulad_events_format *event)
O
overweight 已提交
590 591 592 593 594 595 596 597 598
{
    if (since != NULL && (since->has_seconds || since->has_nanos)) {
        if (types_timestamp_cmp(&event->timestamp, since) < 0) {
            return -1;
        }
    }
    return 0;
}

L
LiuHao 已提交
599
static int check_util_time(const types_timestamp_t *until, const struct isulad_events_format *event)
O
overweight 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
{
    if (until != NULL && (until->has_seconds || until->has_nanos)) {
        if (types_timestamp_cmp(&event->timestamp, until) > 0) {
            return -1;
        }
    }
    return 0;
}

static int do_subscribe(const char *name, const types_timestamp_t *since, const types_timestamp_t *until,
                        const stream_func_wrapper *stream)
{
    bool regflag = false;
    int ret = 0;
    regex_t preg;
    regmatch_t regmatch = { 0 };
    struct linked_list *it = NULL;
    struct linked_list *next = NULL;
L
LiuHao 已提交
618
    struct isulad_events_format *c_event = NULL;
O
overweight 已提交
619 620 621 622 623 624

    if (pthread_mutex_lock(&g_events_buffer.event_mutex)) {
        WARN("Failed to lock");
        return -1;
    }

L
lifeng68 已提交
625
    linked_list_for_each_safe (it, &g_events_buffer.event_list, next) {
L
LiuHao 已提交
626
        c_event = (struct isulad_events_format *)it->elem;
O
overweight 已提交
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 652 653 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

        if (check_since_time(since, c_event) != 0) {
            continue;
        }

        if (check_util_time(until, c_event) != 0) {
            break;
        }

        if (regflag) {
            regfree(&preg);
        }
        regflag = get_idreg(&preg, c_event->id);

        if (name != NULL && regflag) {
            if (regexec(&preg, name, 1, &regmatch, 0)) {
                continue;
            }
        }

        ret = do_write_events(stream, c_event);
        if (ret != 0) {
            break;
        }
    }

    if (pthread_mutex_unlock(&g_events_buffer.event_mutex)) {
        WARN("Failed to unlock");
    }
    if (regflag) {
        regfree(&preg);
    }

    return ret;
}

/* events subscribe */
int events_subscribe(const char *name, const types_timestamp_t *since, const types_timestamp_t *until,
                     const stream_func_wrapper *stream)
{
    if (stream == NULL) {
        ERROR("Invalid input arguments");
        return -1;
    }

    if (since == NULL && until == NULL) {
        return 0;
    }

    if (since != NULL && (since->has_seconds || since->has_nanos) && until != NULL &&
        (until->has_seconds || until->has_nanos)) {
        if (types_timestamp_cmp(since, until) > 0) {
            ERROR("'since' time cannot be after 'until' time");
            return -1;
        }
    }

    return do_subscribe(name, since, until, stream);
}

/* events forward */
L
LiuHao 已提交
688
static void events_forward(struct isulad_events_format *r)
O
overweight 已提交
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
{
    struct linked_list *it = NULL;
    struct linked_list *next = NULL;
    struct context_elem *context_info = NULL;
    char *name = NULL;
    regex_t preg;
    bool regflag = false;
    regmatch_t regmatch = { 0 };

    events_append(r);
    regflag = get_idreg(&preg, r->id);

    if (pthread_mutex_lock(&g_context_lists.context_mutex)) {
        WARN("Failed to lock");
        return;
    }

L
lifeng68 已提交
706
    linked_list_for_each_safe (it, &g_context_lists.context_list, next) {
O
overweight 已提交
707 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
        context_info = (struct context_elem *)it->elem;
        name = context_info->name;

        if (context_info->since != NULL) {
            if (types_timestamp_cmp(&r->timestamp, context_info->since) < 0) {
                continue;
            }
        }

        if (name != NULL && regflag) {
            if (regexec(&preg, name, 1, &regmatch, 0)) {
                continue;
            }
        }

        if (context_info->stream.write_func == NULL || context_info->stream.writer == NULL) {
            INFO("Unimplemented write function");
            goto delete_and_continue;
        }
        if (!context_info->stream.write_func(context_info->stream.writer, r)) {
            INFO("Failed to send exit event for 'events' client");
            goto delete_and_continue;
        }

        continue;

L
lifeng68 已提交
733
    delete_and_continue:
O
overweight 已提交
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
        linked_list_del(it);
        sem_post(&context_info->context_sem);
        continue;
    }

    if (pthread_mutex_unlock(&g_context_lists.context_mutex)) {
        WARN("Failed to unlock");
    }

    if (regflag) {
        regfree(&preg);
    }
}

/* event should exit */
static void *event_should_exit(void *arg)
{
    int res = 0;
    int err = 0;

    res = pthread_detach(pthread_self());
    if (res != 0) {
        CRIT("Set thread detach fail");
        goto error;
    }

    prctl(PR_SET_NAME, "Clients_checker");

    struct linked_list *it = NULL;
    struct linked_list *next = NULL;
    struct context_elem *context_info = NULL;
    struct timespec ts_now = { 0 };
    types_timestamp_t t_now = { 0 };

    for (;;) {
        if (pthread_mutex_lock(&g_context_lists.context_mutex)) {
            WARN("Failed to lock");
            continue;
        }

L
lifeng68 已提交
774
        linked_list_for_each_safe (it, &g_context_lists.context_list, next) {
O
overweight 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 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
            context_info = (struct context_elem *)it->elem;

            if (context_info->stream.is_cancelled(context_info->stream.context)) {
                DEBUG("Client has exited, stop sending events");
                linked_list_del(it);
                sem_post(&context_info->context_sem);
                continue;
            }

            if (context_info->until == NULL ||
                (context_info->until->has_seconds == 0 && context_info->until->has_nanos == 0)) {
                continue;
            }

            err = clock_gettime(CLOCK_REALTIME, &ts_now);
            if (err != 0) {
                ERROR("Failed to get time");
                continue;
            }

            t_now.has_seconds = true;
            t_now.seconds = ts_now.tv_sec;
            t_now.has_nanos = true;
            t_now.nanos = (int32_t)ts_now.tv_nsec;

            if (types_timestamp_cmp(&t_now, context_info->until) > 0) {
                INFO("Finish response for RPC, client should exit");
                linked_list_del(it);
                sem_post(&context_info->context_sem);
                continue;
            }
        }

        if (pthread_mutex_unlock(&g_context_lists.context_mutex)) {
            WARN("Failed to unlock");
        }

        sleep(1);
    }
error:
    return NULL;
}

/* post event to events hander */
L
LiuHao 已提交
819
static int post_event_to_events_hander(const struct isulad_events_format *events)
O
overweight 已提交
820 821 822 823 824 825 826
{
    int ret = 0;

    if (events == NULL || events->id == NULL) {
        return -1;
    }

D
dogsheng 已提交
827
    /* only post STOPPED event to events_hander */
O
overweight 已提交
828 829 830 831
    if (events->type != EVENTS_TYPE_STOPPED1) {
        return 0;
    }

832
    if (container_events_handler_post_events(events)) {
O
overweight 已提交
833 834 835 836 837 838 839 840 841 842 843 844
        ERROR("Failed to post events to events handler:%s", events->id);
        ret = -1;
        goto out;
    }

out:
    return ret;
}

/* events handler */
void events_handler(struct monitord_msg *msg)
{
W
wujing 已提交
845
    struct isulad_events_format *events = NULL;
O
overweight 已提交
846 847 848 849 850 851

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

W
wujing 已提交
852 853 854
    events = (struct isulad_events_format *)util_common_calloc_s(sizeof(struct isulad_events_format));
    if (events == NULL) {
        ERROR("Out of memory");
O
overweight 已提交
855 856 857
        return;
    }

W
wujing 已提交
858 859 860 861 862
    if (format_msg(events, msg) != true) {
        ERROR("Failed to format massage");
        goto out;
    }

O
overweight 已提交
863
    /* post events to events handler */
W
wujing 已提交
864 865 866
    if (post_event_to_events_hander(events)) {
        ERROR("Failed to handle %s STOPPED events with pid %d", events->id, msg->pid);
        goto out;
O
overweight 已提交
867 868 869
    }

    /* forward events to grpc clients */
W
wujing 已提交
870
    events_forward(events);
O
overweight 已提交
871

L
LiuHao 已提交
872
    /* log event into isulad.log */
W
wujing 已提交
873 874 875 876
    (void)write_events_log(events);

out:
    isulad_events_format_free(events);
O
overweight 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
}

/* add monitor client */
int add_monitor_client(char *name, const types_timestamp_t *since, const types_timestamp_t *until,
                       const stream_func_wrapper *stream)
{
    int ret = 0;
    struct linked_list *newnode = NULL;
    struct context_elem *context_info = NULL;

    if (stream == NULL) {
        CRIT("Should provide stream functions");
        return -1;
    }

    newnode = util_common_calloc_s(sizeof(struct linked_list));
    if (newnode == NULL) {
        CRIT("Memory allocation error.");
        return -1;
    }

    context_info = util_common_calloc_s(sizeof(struct context_elem));
    if (context_info == NULL) {
        CRIT("Memory allocation error.");
        ret = -1;
        goto free_out;
    }

    if (sem_init(&context_info->context_sem, 0, 0)) {
        ERROR("Semaphore initialization failed");
        ret = -1;
        goto free_out;
    }

    context_info->name = name;
    context_info->since = since;
    context_info->until = until;
    context_info->stream.is_cancelled = stream->is_cancelled;
    context_info->stream.context = stream->context;
    context_info->stream.write_func = stream->write_func;
    context_info->stream.writer = stream->writer;

    if (pthread_mutex_lock(&g_context_lists.context_mutex)) {
        ERROR("Failed to lock");
        ret = -1;
        goto sem_free;
    }

    linked_list_add_elem(newnode, context_info);
    linked_list_add_tail(&g_context_lists.context_list, newnode);

    if (pthread_mutex_unlock(&g_context_lists.context_mutex)) {
        WARN("Failed to unlock");
        ret = -1;
        goto sem_free;
    }

    sem_wait(&context_info->context_sem);

sem_free:
    sem_destroy(&context_info->context_sem);

free_out:
    free(context_info);
    free(newnode);
    return ret;
}

/* newcollector */
946
static int newcollector()
O
overweight 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
{
    int ret = -1;
    pthread_t exit_thread;

    linked_list_init(&(g_context_lists.context_list));
    linked_list_init(&(g_events_buffer.event_list));
    g_events_buffer.size = 0;

    ret = pthread_mutex_init(&(g_context_lists.context_mutex), NULL);
    if (ret != 0) {
        CRIT("Mutex initialization failed");
        goto out;
    }

    ret = pthread_mutex_init(&(g_events_buffer.event_mutex), NULL);
    if (ret != 0) {
        CRIT("Mutex initialization failed");
        pthread_mutex_destroy(&(g_context_lists.context_mutex));
        goto out;
    }

    INFO("Starting collector...");
    ret = pthread_create(&exit_thread, NULL, event_should_exit, NULL);
    if (ret != 0) {
        CRIT("Thread creation failed");
        pthread_mutex_destroy(&(g_context_lists.context_mutex));
        pthread_mutex_destroy(&(g_events_buffer.event_mutex));
        goto out;
    }

    ret = 0;
out:
    return ret;
}
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

static int start_monitord()
{
    int ret = 0;
    int monitord_exitcode = 0;
    sem_t monitord_sem;
    struct monitord_sync_data msync = { 0 };

    msync.monitord_sem = &monitord_sem;
    msync.exit_code = &monitord_exitcode;
    if (sem_init(msync.monitord_sem, 0, 0)) {
        isulad_set_error_message("Failed to init monitor sem");
        ret = -1;
        goto out;
    }

    if (new_monitord(&msync)) {
        isulad_set_error_message("Create monitord thread failed");
        ret = -1;
        sem_destroy(msync.monitord_sem);
        goto out;
    }

    sem_wait(msync.monitord_sem);
    sem_destroy(msync.monitord_sem);
    if (monitord_exitcode) {
        isulad_set_error_message("Monitord start failed");
        ret = -1;
        goto out;
    }

out:
    return ret;
}

int events_module_init(char **msg)
{
    int ret = 0;

    if (newcollector()) {
        *msg = "Create collector thread failed";
        ret = -1;
        goto out;
    }

    if (start_monitord()) {
        *msg = g_isulad_errmsg ? g_isulad_errmsg : "Failed to init cgroups path";
        ret = -1;
        goto out;
    }

out:
    return ret;
}