summaryrefslogtreecommitdiffstats
path: root/fluent-bit/src/flb_io.c
blob: 81303459cf099a6c52b3974ce006a71e35981470 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
197
198
199
200
201
202
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
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
289
290
291
292
293
294
295
296
297
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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
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
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2022 The Fluent Bit Authors
 *
 *  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
 *
 *      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.
 */

/*
 * FLB_IO
 * ======
 * This interface is used by the output plugins which needs to write over
 * the network in plain communication or through the TLS support. When dealing
 * with network operation there are a few things to keep in mind:
 *
 * - TCP hosts can be down.
 * - Network can be slow.
 * - If the amount of data to flush requires multiple 'write' operations, we
 *   should not block the main thread, instead use event-driven mechanism to
 *   write when is possible.
 *
 * Output plugins that flag themselves with FLB_OUTPUT_TCP or FLB_OUTPUT_TLS
 * can take advantage of this interface.
 *
 * The workflow to use this is the following:
 *
 * - A connection and data flow requires an flb_io_upstream context.
 * - We write/read data through the flb_io_write()/flb_io_read() interfaces.
 *
 * Note that Upstreams context may define how network operations will work,
 * basically synchronous or asynchronous (non-blocking).
 */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <assert.h>

#include <monkey/mk_core.h>
#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_config.h>
#include <fluent-bit/flb_io.h>
#include <fluent-bit/tls/flb_tls.h>
#include <fluent-bit/flb_socket.h>
#include <fluent-bit/flb_upstream.h>
#include <fluent-bit/flb_downstream.h>

#include <fluent-bit/flb_utils.h>
#include <fluent-bit/flb_macros.h>
#include <fluent-bit/flb_network.h>
#include <fluent-bit/flb_engine.h>
#include <fluent-bit/flb_coro.h>
#include <fluent-bit/flb_http_client.h>

int flb_io_net_accept(struct flb_connection *connection,
                       struct flb_coro *coro)
{
    int ret;

    if (connection->fd != FLB_INVALID_SOCKET) {
        flb_socket_close(connection->fd);

        connection->fd = FLB_INVALID_SOCKET;
        connection->event.fd = FLB_INVALID_SOCKET;
    }

    /* Accept the new connection */
    connection->fd = flb_net_accept(connection->downstream->server_fd);

    if (connection->fd == -1) {
        connection->fd = FLB_INVALID_SOCKET;

        return -1;
    }

#ifdef FLB_HAVE_TLS
    /* Check if TLS was enabled, if so perform the handshake */
    if (flb_stream_is_secure(connection->stream) &&
        connection->stream->tls_context != NULL) {
        ret = flb_tls_session_create(connection->stream->tls_context,
                                     connection,
                                     coro);

        if (ret != 0) {
            return -1;
        }
    }
#endif

    flb_trace("[io] connection OK");

    return 0;
}

int flb_io_net_connect(struct flb_connection *connection,
                       struct flb_coro *coro)
{
    int ret;
    int async = FLB_FALSE;
    flb_sockfd_t fd = -1;
    // struct flb_upstream *u = u_conn->u;

    if (connection->fd > 0) {
        flb_socket_close(connection->fd);

        connection->fd = -1;
        connection->event.fd = -1;
    }

    /* Check which connection mode must be done */
    if (coro) {
        async = flb_upstream_is_async(connection->upstream);
    }
    else {
        async = FLB_FALSE;
    }

    /* Perform TCP connection */
    fd = flb_net_tcp_connect(connection->upstream->tcp_host,
                             connection->upstream->tcp_port,
                             connection->stream->net.source_address,
                             connection->stream->net.connect_timeout,
                             async, coro, connection);
    if (fd == -1) {
        return -1;
    }

    if (connection->upstream->proxied_host) {
        ret = flb_http_client_proxy_connect(connection);

        if (ret == -1) {
            flb_debug("[http_client] flb_http_client_proxy_connect connection #%i failed to %s:%i.",
                      connection->fd,
                      connection->upstream->tcp_host,
                      connection->upstream->tcp_port);

          flb_socket_close(fd);

          return -1;
        }
        flb_debug("[http_client] flb_http_client_proxy_connect connection #%i connected to %s:%i.",
                  connection->fd,
                  connection->upstream->tcp_host,
                  connection->upstream->tcp_port);
    }

#ifdef FLB_HAVE_TLS
    /* Check if TLS was enabled, if so perform the handshake */
    if (flb_stream_is_secure(connection->stream) &&
        connection->stream->tls_context != NULL) {
        ret = flb_tls_session_create(connection->stream->tls_context,
                                     connection,
                                     coro);

        if (ret != 0) {
            return -1;
        }
    }
#endif

    flb_trace("[io] connection OK");

    return 0;
}

static void net_io_propagate_critical_error(
                struct flb_connection *connection)
{
    switch (errno) {
    case EBADF:
    case ECONNRESET:
    case EDESTADDRREQ:
    case ENOTCONN:
    case EPIPE:
    case EACCES:
    case ENOTTY:
    case ENETDOWN:
    case ENETUNREACH:
        connection->net_error = errno;
    }
}

static int fd_io_write(int fd, struct sockaddr_storage *address,
                       const void *data, size_t len, size_t *out_len);
static int net_io_write(struct flb_connection *connection,
                        const void *data, size_t len, size_t *out_len)
{
    struct sockaddr_storage *address;
    int                      ret;

    if (connection->fd <= 0) {
        if (connection->type != FLB_UPSTREAM_CONNECTION) {
            return -1;
        }

        ret = flb_io_net_connect((struct flb_connection *) connection,
                                 flb_coro_get());

        if (ret == -1) {
            return -1;
        }
    }

    address = NULL;

    if (connection->type == FLB_DOWNSTREAM_CONNECTION) {
        if (connection->stream->transport == FLB_TRANSPORT_UDP ||
            connection->stream->transport == FLB_TRANSPORT_UNIX_DGRAM) {
            address = &connection->raw_remote_host;
        }
    }

    ret = fd_io_write(connection->fd, address, data, len, out_len);

    if (ret == -1) {
        net_io_propagate_critical_error(connection);
    }

    return ret;
}

static int fd_io_write(int fd, struct sockaddr_storage *address,
                       const void *data, size_t len, size_t *out_len)
{
    int ret;
    int tries = 0;
    size_t total = 0;

    while (total < len) {
        if (address != NULL) {
            ret = sendto(fd, (char *) data + total, len - total, 0,
                         (struct sockaddr *) address,
                         flb_network_address_size(address));
        }
        else {
            ret = send(fd, (char *) data + total, len - total, 0);
        }

        if (ret == -1) {
            if (FLB_WOULDBLOCK()) {
                /*
                 * FIXME: for now we are handling this in a very lazy way,
                 * just sleep for a second and retry (for a max of 30 tries).
                 */
                sleep(1);
                tries++;

                if (tries == 30) {
                    /* Since we're aborting after 30 failures we want the
                     * caller to know how much data we were able to send
                     */

                    *out_len = total;

                    return -1;
                }

                continue;
            }

            return -1;
        }

        tries = 0;
        total += ret;
    }

    *out_len = total;

    return total;
}

static FLB_INLINE void net_io_backup_event(struct flb_connection *connection,
                                           struct mk_event *backup)
{
    if (connection != NULL && backup != NULL) {
        memcpy(backup, &connection->event, sizeof(struct mk_event));
    }
}

static FLB_INLINE void net_io_restore_event(struct flb_connection *connection,
                                            struct mk_event *backup)
{
    int result;

    if (connection != NULL && backup != NULL) {
        if (MK_EVENT_IS_REGISTERED((&connection->event))) {
            result = mk_event_del(connection->evl, &connection->event);

            assert(result == 0);
        }

        if (MK_EVENT_IS_REGISTERED(backup)) {
            connection->event.priority = backup->priority;
            connection->event.handler = backup->handler;

            result = mk_event_add(connection->evl,
                                  connection->fd,
                                  backup->type,
                                  backup->mask,
                                  &connection->event);

            assert(result == 0);
        }
    }
}

/*
 * Perform Async socket write(2) operations. This function depends on a main
 * event-loop and the co-routines interface to yield/resume once sockets are
 * ready to continue.
 *
 * Intentionally we register/de-register the socket file descriptor from
 * the event loop each time when we require to do some work.
 */
static FLB_INLINE int net_io_write_async(struct flb_coro *co,
                                         struct flb_connection *connection,
                                         const void *data, size_t len, size_t *out_len)
{
    int ret = 0;
    int error;
    uint32_t mask;
    ssize_t bytes;
    size_t total = 0;
    size_t to_send;
    char so_error_buf[256];
    struct mk_event event_backup;
    int event_restore_needed;

    event_restore_needed = FLB_FALSE;

    net_io_backup_event(connection, &event_backup);

retry:
    error = 0;

    if (len - total > 524288) {
        to_send = 524288;
    }
    else {
        to_send = (len - total);
    }

    bytes = send(connection->fd, (char *) data + total, to_send, 0);

#ifdef FLB_HAVE_TRACE
    if (bytes > 0) {
        flb_trace("[io coro=%p] [fd %i] write_async(2)=%d (%lu/%lu)",
                  co, connection->fd, bytes, total + bytes, len);
    }
    else {
        flb_trace("[io coro=%p] [fd %i] write_async(2)=%d (%lu/%lu)",
                  co, connection->fd, bytes, total, len);
    }
#endif

    if (bytes == -1) {
        if (FLB_WOULDBLOCK()) {
            event_restore_needed = FLB_TRUE;

            ret = mk_event_add(connection->evl,
                               connection->fd,
                               FLB_ENGINE_EV_THREAD,
                               MK_EVENT_WRITE,
                               &connection->event);

            connection->event.priority = FLB_ENGINE_PRIORITY_SEND_RECV;

            if (ret == -1) {
                /*
                 * If we failed here there no much that we can do, just
                 * let the caller we failed
                 */
                *out_len = total;

                net_io_restore_event(connection, &event_backup);

                return -1;
            }

            connection->coroutine = co;

            /*
             * Return the control to the parent caller, we need to wait for
             * the event loop to get back to us.
             */
            flb_coro_yield(co, FLB_FALSE);

            /* We want this field to hold NULL at all times unless we are explicitly
             * waiting to be resumed.
             */
            connection->coroutine = NULL;

            /* Save events mask since mk_event_del() will reset it */
            mask = connection->event.mask;

            /* We got a notification, remove the event registered */
            ret = mk_event_del(connection->evl, &connection->event);

            if (ret == -1) {
                *out_len = total;

                net_io_restore_event(connection, &event_backup);

                return -1;
            }

            /* Check the connection status */
            if (mask & MK_EVENT_WRITE) {
                error = flb_socket_error(connection->fd);

                if (error != 0) {
                    /* Connection is broken, not much to do here */
                    strerror_r(error, so_error_buf, sizeof(so_error_buf) - 1);

                    flb_error("[io fd=%i] error sending data to: %s (%s)",
                              connection->fd,
                              flb_connection_get_remote_address(connection),
                              so_error_buf);

                    *out_len = total;

                    net_io_restore_event(connection, &event_backup);

                    return -1;
                }

                MK_EVENT_NEW(&connection->event);

                goto retry;
            }
            else {
                *out_len = total;

                net_io_restore_event(connection, &event_backup);

                return -1;
            }

        }
        else {
            *out_len = total;

            net_io_restore_event(connection, &event_backup);
            net_io_propagate_critical_error(connection);

            return -1;
        }
    }

    /* Update counters */
    total += bytes;
    if (total < len) {
        if ((connection->event.mask & MK_EVENT_WRITE) == 0) {
            ret = mk_event_add(connection->evl,
                               connection->fd,
                               FLB_ENGINE_EV_THREAD,
                               MK_EVENT_WRITE,
                               &connection->event);

            connection->event.priority = FLB_ENGINE_PRIORITY_SEND_RECV;

            if (ret == -1) {
                /*
                 * If we failed here there no much that we can do, just
                 * let the caller we failed
                 */
                *out_len = total;

                net_io_restore_event(connection, &event_backup);

                return -1;
            }
        }

        connection->coroutine = co;

        flb_coro_yield(co, MK_FALSE);

        /* We want this field to hold NULL at all times unless we are explicitly
         * waiting to be resumed.
         */
        connection->coroutine = NULL;

        goto retry;
    }

    if (event_restore_needed) {
        /* If we enter here it means we registered this connection
         * in the event loop, in which case we need to unregister it
         * and restore the original registration if there was one.
         *
         * We do it conditionally because in those cases in which
         * send succeeds on the first try we don't touch the event
         * and it wouldn't make sense to unregister and register for
         * the same event.
         */

        net_io_restore_event(connection, &event_backup);
    }

    *out_len = total;

    return bytes;
}

static ssize_t fd_io_read(int fd, struct sockaddr_storage *address,
                          void *buf, size_t len);
static ssize_t net_io_read(struct flb_connection *connection,
                           void *buf, size_t len)
{
    struct sockaddr_storage *address;
    int                      ret;

    address = NULL;

    if (connection->type == FLB_DOWNSTREAM_CONNECTION) {
        if (connection->stream->transport == FLB_TRANSPORT_UDP ||
            connection->stream->transport == FLB_TRANSPORT_UNIX_DGRAM) {
            address = &connection->raw_remote_host;
        }
    }

    ret = fd_io_read(connection->fd, address, buf, len);

    if (ret == -1) {
        ret = FLB_WOULDBLOCK();
        if (ret) {
            /* timeout caused error */
            flb_warn("[net] sync io_read #%i timeout after %i seconds from: %s",
                     connection->fd,
                     connection->net->io_timeout,
                     flb_connection_get_remote_address(connection));
        }
        else {
            net_io_propagate_critical_error(connection);
        }

        return -1;
    }

    return ret;
}

static ssize_t fd_io_read(int fd, struct sockaddr_storage *address,
                          void *buf, size_t len)
{
    socklen_t address_size;
    int       ret;

    if (address != NULL) {
        address_size = sizeof(struct sockaddr_storage);
        ret = recvfrom(fd, buf, len, 0,
                       (struct sockaddr *) address,
                       &address_size);
    }
    else {
        ret = recv(fd, buf, len, 0);
    }

    if (ret == -1) {
        return -1;
    }

    return ret;
}

static FLB_INLINE ssize_t net_io_read_async(struct flb_coro *co,
                                            struct flb_connection *connection,
                                            void *buf, size_t len)
{
    struct mk_event event_backup;
    int event_restore_needed;
    int ret;

    event_restore_needed = FLB_FALSE;

    net_io_backup_event(connection, &event_backup);

 retry_read:
    ret = recv(connection->fd, buf, len, 0);

    if (ret == -1) {
        if (FLB_WOULDBLOCK()) {
            event_restore_needed = FLB_TRUE;

            ret = mk_event_add(connection->evl,
                               connection->fd,
                               FLB_ENGINE_EV_THREAD,
                               MK_EVENT_READ,
                               &connection->event);

            connection->event.priority = FLB_ENGINE_PRIORITY_SEND_RECV;

            if (ret == -1) {
                /*
                 * If we failed here there no much that we can do, just
                 * let the caller we failed
                 */
                net_io_restore_event(connection, &event_backup);

                return -1;
            }

            connection->coroutine = co;

            flb_coro_yield(co, MK_FALSE);

            /* We want this field to hold NULL at all times unless we are explicitly
             * waiting to be resumed.
             */
            connection->coroutine = NULL;

            goto retry_read;
        }
        else {
            net_io_propagate_critical_error(connection);
        }

        ret = -1;
    }
    else if (ret <= 0) {
        ret = -1;
    }

    if (event_restore_needed) {
        /* If we enter here it means we registered this connection
         * in the event loop, in which case we need to unregister it
         * and restore the original registration if there was one.
         *
         * We do it conditionally because in those cases in which
         * send succeeds on the first try we don't touch the event
         * and it wouldn't make sense to unregister and register for
         * the same event.
         */

        net_io_restore_event(connection, &event_backup);
    }

    return ret;
}

/* Write data to fd. For unix socket. */
int flb_io_fd_write(int fd, const void *data, size_t len, size_t *out_len)
{
    /* TODO: support async mode */
    return fd_io_write(fd, NULL, data, len, out_len);
}

/* Write data to an upstream connection/server */
int flb_io_net_write(struct flb_connection *connection, const void *data,
                     size_t len, size_t *out_len)
{
    int              flags;
    struct flb_coro *coro;
    int              ret;

    ret  = -1;
    coro = flb_coro_get();
    flags = flb_connection_get_flags(connection);

    flb_trace("[io coro=%p] [net_write] trying %zd bytes", coro, len);

    if (connection->tls_session == NULL) {
        if (flags & FLB_IO_ASYNC) {
            ret = net_io_write_async(coro, connection, data, len, out_len);
        }
        else {
            ret = net_io_write(connection, data, len, out_len);
        }
    }
#ifdef FLB_HAVE_TLS
    else if (flags & FLB_IO_TLS) {
        if (flags & FLB_IO_ASYNC) {
            ret = flb_tls_net_write_async(coro, connection->tls_session, data, len, out_len);
        }
        else {
            ret = flb_tls_net_write(connection->tls_session, data, len, out_len);
        }
    }
#endif

    if (ret > 0) {
        flb_connection_reset_io_timeout(connection);
    }

    flb_trace("[io coro=%p] [net_write] ret=%i total=%lu/%lu",
              coro, ret, *out_len, len);

    return ret;
}

ssize_t flb_io_fd_read(int fd, void *buf, size_t len)
{
    /* TODO: support async mode */
    return fd_io_read(fd, NULL, buf, len);
}

ssize_t flb_io_net_read(struct flb_connection *connection, void *buf, size_t len)
{
    int ret;
    int flags;
    struct flb_coro *coro;

    ret = -1;
    coro = flb_coro_get();

    flb_trace("[io coro=%p] [net_read] try up to %zd bytes", coro, len);

    flags = flb_connection_get_flags(connection);

    if (!connection->tls_session) {
        if (flags & FLB_IO_ASYNC) {
            ret = net_io_read_async(coro, connection, buf, len);
        }
        else {
            ret = net_io_read(connection, buf, len);
        }
    }
#ifdef FLB_HAVE_TLS
    else if (flags & FLB_IO_TLS) {
        if (flags & FLB_IO_ASYNC) {
            ret = flb_tls_net_read_async(coro, connection->tls_session, buf, len);
        }
        else {
            ret = flb_tls_net_read(connection->tls_session, buf, len);
        }
    }
#endif

    if (ret > 0) {
        flb_connection_reset_io_timeout(connection);
    }

    flb_trace("[io coro=%p] [net_read] ret=%i", coro, ret);

    return ret;
}