-
Notifications
You must be signed in to change notification settings - Fork 107
/
server.c
1727 lines (1578 loc) · 43.6 KB
/
server.c
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
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
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
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
946
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2013-2022 Fabian Groffen
*
* 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.
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <pthread.h>
#include <poll.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/resource.h>
#include <assert.h>
#include "relay.h"
#include "queue.h"
#include "dispatcher.h"
#include "collector.h"
#include "server.h"
#ifdef HAVE_GZIP
#include <zlib.h>
#endif
#ifdef HAVE_LZ4
#include <lz4.h>
#include <lz4frame.h>
#endif
#ifdef HAVE_SNAPPY
#include <snappy-c.h>
#endif
#ifdef HAVE_SSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif
#define FAIL_WAIT_TIME 6 /* 6 * 250ms = 1.5s */
#define DISCONNECT_WAIT_TIME 12 /* 12 * 250ms = 3s */
#define LEN_CRITICAL(Q) (queue_free(Q) < self->bsize)
typedef struct _z_strm {
ssize_t (*strmwrite)(struct _z_strm *, const void *, size_t);
int (*strmflush)(struct _z_strm *);
int (*strmclose)(struct _z_strm *);
const char *(*strmerror)(struct _z_strm *, int); /* get last err str */
struct _z_strm *nextstrm; /* set when chained */
#if defined(HAVE_LZ4) || defined(HAVE_SNAPPY) || defined(HAVE_GZIP)
char obuf[METRIC_BUFSIZ];
int obuflen;
#endif
#ifdef HAVE_SSL
SSL_CTX *ctx;
#endif
union {
#ifdef HAVE_GZIP
z_streamp gz;
#endif
#ifdef HAVE_LZ4
struct {
void *cbuf;
size_t cbuflen;
} z;
#endif
#ifdef HAVE_SSL
SSL *ssl;
#endif
int sock;
} hdl;
} z_strm;
struct _server {
const char *ip;
unsigned short port;
char *instance;
struct addrinfo *saddr;
struct addrinfo *hint;
int fd;
z_strm *strm;
queue *queue;
size_t bsize;
short iotimeout;
unsigned int sockbufsize;
unsigned char maxstalls:SERVER_STALL_BITS;
const char **batch;
con_type type;
con_trnsp transport;
char *mtlspemcert;
char *mtlspemkey;
con_proto ctype;
pthread_t tid;
struct _server **secondaries;
size_t secondariescnt;
unsigned char reresolve:1;
unsigned char failover:1;
char failure; /* full byte for atomic access */
char running; /* full byte for atomic access */
char keep_running; /* full byte for atomic access */
char reopen_con; /* full byte for atomic access */
unsigned char stallseq; /* full byte for atomic access */
size_t metrics;
size_t dropped;
size_t stalls;
size_t ticks;
size_t prevmetrics;
size_t prevdropped;
size_t prevstalls;
size_t prevticks;
};
/* connection specific writers and closers */
/* ordinary socket */
static inline ssize_t
sockwrite(z_strm *strm, const void *buf, size_t sze)
{
return write(strm->hdl.sock, buf, sze);
}
static inline int
sockflush(z_strm *strm)
{
/* noop, we don't use a stream in the normal case */
(void)strm;
return 0;
}
static inline int
sockclose(z_strm *strm)
{
return close(strm->hdl.sock);
}
static inline const char *
sockerror(z_strm *strm, int rval)
{
(void)strm;
(void)rval;
return strerror(errno);
}
#ifdef HAVE_GZIP
/* gzip wrapped socket */
static inline int gzipflush(z_strm *strm);
static inline ssize_t
gzipwrite(z_strm *strm, const void *buf, size_t sze)
{
/* ensure we have space available */
if (strm->obuflen + sze > METRIC_BUFSIZ)
if (gzipflush(strm) != 0)
return -1;
/* append metric to buf */
memcpy(strm->obuf + strm->obuflen, buf, sze);
strm->obuflen += sze;
return sze;
}
static inline int
gzipflush(z_strm *strm)
{
int cret;
char cbuf[METRIC_BUFSIZ];
size_t cbuflen;
char *cbufp;
int oret;
strm->hdl.gz->next_in = (Bytef *)strm->obuf;
strm->hdl.gz->avail_in = strm->obuflen;
strm->hdl.gz->next_out = (Bytef *)cbuf;
strm->hdl.gz->avail_out = sizeof(cbuf);
do {
cret = deflate(strm->hdl.gz, Z_PARTIAL_FLUSH);
if (cret == Z_OK && strm->hdl.gz->avail_out == 0) {
/* too large output block, unlikely given the input, discard */
/* TODO */
break;
}
if (cret == Z_OK) {
cbufp = cbuf;
cbuflen = sizeof(cbuf) - strm->hdl.gz->avail_out;
while (cbuflen > 0) {
oret = strm->nextstrm->strmwrite(strm->nextstrm,
cbufp, cbuflen);
if (oret < 0)
return -1; /* failure is failure */
/* update counters to possibly retry the remaining bit */
cbufp += oret;
cbuflen -= oret;
}
if (strm->hdl.gz->avail_in == 0)
break;
strm->hdl.gz->next_out = (Bytef *)cbuf;
strm->hdl.gz->avail_out = sizeof(cbuf);
} else {
/* discard */
break;
}
} while (1);
/* flush whatever we wrote */
strm->nextstrm->strmflush(strm->nextstrm);
/* reset the write position, from this point it will always need to
* restart */
strm->obuflen = 0;
if (cret != Z_OK)
return -1; /* we must reset/free gzip */
return 0;
}
static inline int
gzipclose(z_strm *strm)
{
int ret = strm->nextstrm->strmclose(strm->nextstrm);
deflateEnd(strm->hdl.gz);
free(strm->hdl.gz);
return ret;
}
static inline const char *
gziperror(z_strm *strm, int rval)
{
return strm->nextstrm->strmerror(strm->nextstrm, rval);
}
#endif
#ifdef HAVE_LZ4
/* lz4 wrapped socket */
static inline int lzflush(z_strm *strm);
static inline ssize_t
lzwrite(z_strm *strm, const void *buf, size_t sze)
{
size_t towrite = sze;
/* use the same strategy as gzip: fill the buffer until space
runs out. we completely fill the output buffer before flushing */
while (towrite > 0) {
size_t avail = METRIC_BUFSIZ - strm->obuflen;
size_t copysize = towrite > avail ? avail : towrite;
/* copy into the output buffer as much as we can */
if (copysize > 0) {
memcpy(strm->obuf + strm->obuflen, buf, copysize);
strm->obuflen += copysize;
towrite -= copysize;
buf += copysize;
}
/* if output buffer is full & still have bytes to write, flush now */
if (strm->obuflen == METRIC_BUFSIZ && towrite > 0 && lzflush(strm) != 0) {
logerr("Failed to flush LZ4 data to make space\n");
return -1;
}
}
return sze;
}
static inline int
lzflush(z_strm *strm)
{
int oret;
size_t ret;
/* anything to do? */
if (strm->obuflen == 0)
return 0;
/* the buffered data goes out as a single frame */
ret = LZ4F_compressFrame(strm->hdl.z.cbuf, strm->hdl.z.cbuflen, strm->obuf, strm->obuflen, NULL);
if (LZ4F_isError(ret)) {
logerr("Failed to compress %d LZ4 bytes into a frame: %d\n",
strm->obuflen, (int)ret);
return -1;
}
/* write and flush */
if ((oret = strm->nextstrm->strmwrite(strm->nextstrm,
strm->hdl.z.cbuf, ret)) < 0) {
logerr("Failed to write %lu bytes of compressed LZ4 data: %d\n",
ret, oret);
return oret;
}
strm->nextstrm->strmflush(strm->nextstrm);
/* the buffer is gone. reset the write position */
strm->obuflen = 0;
return 0;
}
static inline int
lzclose(z_strm *strm)
{
lzflush(strm);
free(strm->hdl.z.cbuf);
return strm->nextstrm->strmclose(strm->nextstrm);
}
static inline const char *
lzerror(z_strm *strm, int rval)
{
return strm->nextstrm->strmerror(strm->nextstrm, rval);
}
#endif
#ifdef HAVE_SNAPPY
/* snappy wrapped socket */
static inline int snappyflush(z_strm *strm);
static inline ssize_t
snappywrite(z_strm *strm, const void *buf, size_t sze)
{
/* ensure we have space available */
if (strm->obuflen + sze > METRIC_BUFSIZ)
if (snappyflush(strm) != 0)
return -1;
/* append metric to buf */
memcpy(strm->obuf + strm->obuflen, buf, sze);
strm->obuflen += sze;
return sze;
}
static inline int
snappyflush(z_strm *strm)
{
int cret;
char cbuf[METRIC_BUFSIZ];
size_t cbuflen = sizeof(cbuf);
char *cbufp = cbuf;
int oret;
cret = snappy_compress(strm->obuf, strm->obuflen, cbuf, &cbuflen);
/* reset the write position, from this point it will always need to
* restart */
strm->obuflen = 0;
if (cret != SNAPPY_OK)
return -1; /* we must reset/free snappy */
while (cbuflen > 0) {
oret = strm->nextstrm->strmwrite(strm->nextstrm, cbufp, cbuflen);
if (oret < 0)
return -1; /* failure is failure */
strm->nextstrm->strmflush(strm->nextstrm);
/* update counters to possibly retry the remaining bit */
cbufp += oret;
cbuflen -= oret;
}
return 0;
}
static inline int
snappyclose(z_strm *strm)
{
int ret = strm->nextstrm->strmclose(strm->nextstrm);
return ret;
}
static inline const char *
snappyerror(z_strm *strm, int rval)
{
return strm->nextstrm->strmerror(strm->nextstrm, rval);
}
#endif
#ifdef HAVE_SSL
/* (Open|Libre)SSL wrapped socket */
static inline ssize_t
sslwrite(z_strm *strm, const void *buf, size_t sze)
{
return (ssize_t)SSL_write(strm->hdl.ssl, buf, (int)sze);
}
static inline int
sslflush(z_strm *strm)
{
/* noop */
(void)strm;
return 0;
}
static inline int
sslclose(z_strm *strm)
{
int sock = SSL_get_fd(strm->hdl.ssl);
SSL_free(strm->hdl.ssl);
return close(sock);
}
static char _sslerror_buf[256];
static inline const char *
sslerror(z_strm *strm, int rval)
{
int err = SSL_get_error(strm->hdl.ssl, rval);
switch (err) {
case SSL_ERROR_NONE:
snprintf(_sslerror_buf, sizeof(_sslerror_buf),
"%d: SSL_ERROR_NONE", err);
break;
case SSL_ERROR_ZERO_RETURN:
snprintf(_sslerror_buf, sizeof(_sslerror_buf),
"%d: TLS/SSL connection has been closed", err);
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
snprintf(_sslerror_buf, sizeof(_sslerror_buf),
"%d: the read or write operation did not complete", err);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
snprintf(_sslerror_buf, sizeof(_sslerror_buf),
"%d: call callback via SSL_CTX_set_client_cert_cb()", err);
break;
#ifdef SSL_ERROR_WANT_ASYNC
case SSL_ERROR_WANT_ASYNC:
snprintf(_sslerror_buf, sizeof(_sslerror_buf),
"%d: asynchronous engine is still processing data", err);
break;
#endif
#ifdef SSL_ERROR_WANT_ASYNC_JOB
case SSL_ERROR_WANT_ASYNC_JOB:
snprintf(_sslerror_buf, sizeof(_sslerror_buf),
"%d: no async jobs available in the pool", err);
break;
#endif
case SSL_ERROR_SYSCALL:
snprintf(_sslerror_buf, sizeof(_sslerror_buf),
"%d: I/O error: %s", err, strerror(errno));
break;
case SSL_ERROR_SSL:
ERR_error_string_n(ERR_get_error(),
_sslerror_buf, sizeof(_sslerror_buf));
break;
}
return _sslerror_buf;
}
#endif
/**
* Reads from the queue and sends items to the remote server. This
* function is designed to be a thread. Data sending is attempted to be
* batched, but sent one by one to reduce loss on sending failure.
* A connection with the server is maintained for as long as there is
* data to be written. As soon as there is none, the connection is
* dropped if a timeout of DISCONNECT_WAIT_TIME exceeds.
*/
static void *
server_queuereader(void *d)
{
server *self = (server *)d;
size_t len;
ssize_t slen;
const char **metric = self->batch;
struct timeval start, stop;
struct timeval timeout;
queue *squeue;
char idle = 0;
size_t *secpos = NULL;
unsigned char cnt;
const char *p;
*metric = NULL;
self->running = 1;
while (1) {
/* close connection when we're asked to reopen */
if (__sync_bool_compare_and_swap(&(self->reopen_con), 1, 0)) {
self->strm->strmclose(self->strm);
self->fd = -1;
}
if (queue_len(self->queue) == 0) {
/* if we're idling, close the TCP connection, this allows us
* to reduce connections, while keeping the connection alive
* if we're writing a lot */
gettimeofday(&start, NULL);
if (self->ctype == CON_TCP && self->fd >= 0 &&
idle++ > DISCONNECT_WAIT_TIME)
{
self->strm->strmclose(self->strm);
self->fd = -1;
}
if (idle == 1)
/* ensure blocks are pushed out as soon as we're idling,
* this allows compressors to benefit from a larger
* stream of data to gain better compression */
self->strm->strmflush(self->strm);
gettimeofday(&stop, NULL);
__sync_add_and_fetch(&(self->ticks), timediff(start, stop));
if (__sync_bool_compare_and_swap(&(self->keep_running), 0, 0))
break;
/* nothing to do, so slow down for a bit */
usleep((200 + (rand() % 100)) * 1000); /* 200ms - 300ms */
/* if we are in failure mode, keep checking if we can
* connect, this avoids unnecessary queue moves */
if (__sync_bool_compare_and_swap(&(self->failure), 0, 0))
/* it makes no sense to try and do something, so skip */
continue;
} else if (self->secondariescnt > 0 &&
(__sync_add_and_fetch(&(self->failure), 0) >= FAIL_WAIT_TIME ||
(!self->failover && LEN_CRITICAL(self->queue))))
{
size_t i;
gettimeofday(&start, NULL);
if (self->secondariescnt > 0) {
if (secpos == NULL) {
secpos = malloc(sizeof(size_t) * self->secondariescnt);
if (secpos == NULL) {
logerr("server: failed to allocate memory "
"for secpos\n");
gettimeofday(&stop, NULL);
__sync_add_and_fetch(&(self->ticks),
timediff(start, stop));
continue;
}
for (i = 0; i < self->secondariescnt; i++)
secpos[i] = i;
}
if (!self->failover) {
/* randomise the failover list such that in the
* grand scheme of things we don't punish the first
* working server in the list to deal with all
* traffic meant for a now failing server */
for (i = 0; i < self->secondariescnt; i++) {
size_t n = rand() % (self->secondariescnt - i);
if (n != i) {
size_t t = secpos[n];
secpos[n] = secpos[i];
secpos[i] = t;
}
}
}
}
/* offload data from our queue to our secondaries
* when doing so, observe the following:
* - avoid nodes that are in failure mode
* - avoid nodes which queues are >= critical_len
* when no nodes remain given the above
* - send to nodes which queue size < critical_len
* where there are no such nodes
* - do nothing (we will overflow, since we can't send
* anywhere) */
*metric = NULL;
squeue = NULL;
for (i = 0; i < self->secondariescnt; i++) {
/* both conditions below make sure we skip ourself */
if (__sync_add_and_fetch(
&(self->secondaries[secpos[i]]->failure), 0))
continue;
squeue = self->secondaries[secpos[i]]->queue;
if (!self->failover && LEN_CRITICAL(squeue)) {
squeue = NULL;
continue;
}
if (*metric == NULL) {
/* send up to batch size of our queue to this queue */
len = queue_dequeue_vector(
self->batch, self->queue, self->bsize);
self->batch[len] = NULL;
metric = self->batch;
}
for (; *metric != NULL; metric++)
if (!queue_putback(squeue, *metric))
break;
/* try to put back stuff that didn't fit */
for (; *metric != NULL; metric++)
if (!queue_putback(self->queue, *metric))
break;
}
for (; *metric != NULL; metric++) {
if (mode & MODE_DEBUG)
logerr("dropping metric: %s", *metric);
free((char *)*metric);
__sync_add_and_fetch(&(self->dropped), 1);
}
gettimeofday(&stop, NULL);
__sync_add_and_fetch(&(self->ticks),
timediff(start, stop));
if (squeue == NULL) {
/* we couldn't do anything, take it easy for a bit */
if (__sync_add_and_fetch(&(self->failure), 0) > 1) {
/* This is a compound because I can't seem to figure
* out how to atomically just "set" a variable.
* It's not bad when in the middle there is a ++,
* all that counts is that afterwards its > 0. */
__sync_and_and_fetch(&(self->failure), 0);
__sync_add_and_fetch(&(self->failure), 1);
}
if (__sync_bool_compare_and_swap(&(self->keep_running), 0, 0))
break;
usleep((200 + (rand() % 100)) * 1000); /* 200ms - 300ms */
}
} else if (__sync_add_and_fetch(&(self->failure), 0) > 0) {
if (__sync_bool_compare_and_swap(&(self->keep_running), 0, 0))
break;
usleep((200 + (rand() % 100)) * 1000); /* 200ms - 300ms */
/* avoid overflowing */
if (__sync_add_and_fetch(&(self->failure), 0) > FAIL_WAIT_TIME)
__sync_sub_and_fetch(&(self->failure), 1);
}
/* at this point we've got work to do, if we're instructed to
* shut down, however, try to get everything out of the door
* (until we fail, see top of this loop) */
gettimeofday(&start, NULL);
/* try to connect */
if (self->fd < 0) {
if (self->reresolve) { /* can only be CON_UDP/CON_TCP */
struct addrinfo *saddr;
char sport[8];
/* re-lookup the address info, if it fails, stay with
* whatever we have such that resolution errors incurred
* after starting the relay won't make it fail */
if (self->saddr)
freeaddrinfo(self->saddr);
snprintf(sport, sizeof(sport), "%u", self->port);
if (getaddrinfo(self->ip, sport, self->hint, &saddr) == 0) {
self->saddr = saddr;
} else {
if (__sync_fetch_and_add(&(self->failure), 1) == 0)
logerr("failed to resolve %s:%u, server unavailable\n",
self->ip, self->port);
self->saddr = NULL;
/* this will break out below */
}
}
if (self->ctype == CON_PIPE) {
int intconn[2];
if (pipe(intconn) < 0) {
if (__sync_fetch_and_add(&(self->failure), 1) == 0)
logerr("failed to create pipe: %s\n", strerror(errno));
continue;
}
dispatch_addconnection(intconn[0], NULL);
self->fd = intconn[1];
} else if (self->ctype == CON_FILE) {
if ((self->fd = open(self->ip,
O_WRONLY | O_APPEND | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
{
if (__sync_fetch_and_add(&(self->failure), 1) == 0)
logerr("failed to open file '%s': %s\n",
self->ip, strerror(errno));
continue;
}
} else if (self->ctype == CON_UDP) {
struct addrinfo *walk;
for (walk = self->saddr; walk != NULL; walk = walk->ai_next) {
if ((self->fd = socket(walk->ai_family,
walk->ai_socktype,
walk->ai_protocol)) < 0)
{
if (walk->ai_next == NULL &&
__sync_fetch_and_add(&(self->failure), 1) == 0)
logerr("failed to create udp socket: %s\n",
strerror(errno));
continue;
}
if (connect(self->fd, walk->ai_addr, walk->ai_addrlen) < 0)
{
if (walk->ai_next == NULL &&
__sync_fetch_and_add(&(self->failure), 1) == 0)
logerr("failed to connect udp socket: %s\n",
strerror(errno));
close(self->fd);
self->fd = -1;
continue;
}
/* we made it up here, so this connection is usable */
break;
}
/* if this didn't resolve to anything, treat as failure */
if (self->saddr == NULL)
__sync_add_and_fetch(&(self->failure), 1);
/* if all addrinfos failed, try again later */
if (self->fd < 0)
continue;
} else { /* CON_TCP */
int ret;
int args;
struct addrinfo *walk;
for (walk = self->saddr; walk != NULL; walk = walk->ai_next) {
if ((self->fd = socket(walk->ai_family,
walk->ai_socktype,
walk->ai_protocol)) < 0)
{
if (walk->ai_next == NULL &&
__sync_fetch_and_add(&(self->failure), 1) == 0)
logerr("failed to create socket: %s\n",
strerror(errno));
continue;
}
/* put socket in non-blocking mode such that we can
* poll() (time-out) on the connect() call */
args = fcntl(self->fd, F_GETFL, NULL);
if (fcntl(self->fd, F_SETFL, args | O_NONBLOCK) < 0) {
logerr("failed to set socket non-blocking mode: %s\n",
strerror(errno));
close(self->fd);
self->fd = -1;
continue;
}
ret = connect(self->fd, walk->ai_addr, walk->ai_addrlen);
if (ret < 0 && errno == EINPROGRESS) {
/* wait for connection to succeed if the OS thinks
* it can succeed */
struct pollfd ufds[1];
ufds[0].fd = self->fd;
ufds[0].events = POLLIN | POLLOUT;
ret = poll(ufds, 1, self->iotimeout + (rand() % 100));
if (ret == 0) {
/* time limit expired */
if (walk->ai_next == NULL &&
__sync_fetch_and_add(
&(self->failure), 1) == 0)
logerr("failed to connect() to "
"%s:%u: Operation timed out\n",
self->ip, self->port);
close(self->fd);
self->fd = -1;
continue;
} else if (ret < 0) {
/* some select error occurred */
if (walk->ai_next &&
__sync_fetch_and_add(
&(self->failure), 1) == 0)
logerr("failed to poll() for %s:%u: %s\n",
self->ip, self->port, strerror(errno));
close(self->fd);
self->fd = -1;
continue;
} else {
if (ufds[0].revents & POLLHUP) {
if (walk->ai_next == NULL &&
__sync_fetch_and_add(
&(self->failure), 1) == 0)
logerr("failed to connect() for %s:%u: "
"Connection refused\n",
self->ip, self->port);
close(self->fd);
self->fd = -1;
continue;
}
}
} else if (ret < 0) {
if (walk->ai_next == NULL &&
__sync_fetch_and_add(&(self->failure), 1) == 0)
{
logerr("failed to connect() to %s:%u: %s\n",
self->ip, self->port, strerror(errno));
dispatch_check_rlimit_and_warn();
}
close(self->fd);
self->fd = -1;
continue;
}
/* make socket blocking again */
if (fcntl(self->fd, F_SETFL, args) < 0) {
logerr("failed to remove socket non-blocking "
"mode: %s\n", strerror(errno));
close(self->fd);
self->fd = -1;
continue;
}
/* disable Nagle's algorithm, issue #208 */
args = 1;
if (setsockopt(self->fd, IPPROTO_TCP, TCP_NODELAY,
&args, sizeof(args)) != 0)
; /* ignore */
#ifdef TCP_USER_TIMEOUT
/* break out of connections when no ACK is being
* received for +- 10 seconds instead of
* retransmitting for +- 15 minutes available on
* linux >= 2.6.37
* the 10 seconds is in line with the SO_SNDTIMEO
* set on the socket below */
args = 10000 + (rand() % 300);
if (setsockopt(self->fd, IPPROTO_TCP, TCP_USER_TIMEOUT,
&args, sizeof(args)) != 0)
; /* ignore */
#endif
/* if we reached up here, we're good to go, so don't
* continue with the other addrinfos */
break;
}
/* if this didn't resolve to anything, treat as failure */
if (self->saddr == NULL)
__sync_add_and_fetch(&(self->failure), 1);
/* all available addrinfos failed on us */
if (self->fd < 0)
continue;
}
/* ensure we will break out of connections being stuck more
* quickly than the kernel would give up */
timeout.tv_sec = 10;
timeout.tv_usec = (rand() % 300) * 1000;
if (setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO,
&timeout, sizeof(timeout)) != 0)
; /* ignore */
if (self->sockbufsize > 0)
if (setsockopt(self->fd, SOL_SOCKET, SO_SNDBUF,
&self->sockbufsize, sizeof(self->sockbufsize)) != 0)
; /* ignore */
#ifdef SO_NOSIGPIPE
if (self->ctype == CON_TCP || self->ctype == CON_UDP) {
int enable = 1;
if (setsockopt(self->fd, SOL_SOCKET, SO_NOSIGPIPE,
(void *)&enable, sizeof(enable)) != 0)
logout("warning: failed to ignore SIGPIPE on socket: %s\n",
strerror(errno));
}
#endif
#ifdef HAVE_GZIP
if ((self->transport & 0xFFFF) == W_GZIP) {
self->strm->hdl.gz = malloc(sizeof(z_stream));
if (self->strm->hdl.gz != NULL) {
self->strm->hdl.gz->zalloc = Z_NULL;
self->strm->hdl.gz->zfree = Z_NULL;
self->strm->hdl.gz->opaque = Z_NULL;
self->strm->hdl.gz->next_in = Z_NULL;
}
if (self->strm->hdl.gz == NULL ||
deflateInit2(self->strm->hdl.gz,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
15 + 16,
8,
Z_DEFAULT_STRATEGY) != Z_OK)
{
logerr("failed to open gzip stream: out of memory\n");
close(self->fd);
self->fd = -1;
continue;
}
self->strm->obuflen = 0;
}
#endif
#ifdef HAVE_LZ4
if ((self->transport & 0xFFFF) == W_LZ4) {
self->strm->obuflen = 0;
/* get the maximum size that should ever be required and allocate for it */
self->strm->hdl.z.cbuflen = LZ4F_compressFrameBound(sizeof(self->strm->obuf), NULL);
if ((self->strm->hdl.z.cbuf = malloc(self->strm->hdl.z.cbuflen)) == NULL) {
logerr("Failed to allocate %lu bytes for compressed LZ4 data\n", self->strm->hdl.z.cbuflen);
close(self->fd);
self->fd = -1;
continue;
}
}
#endif
#ifdef HAVE_SNAPPY
if ((self->transport & 0xFFFF) == W_SNAPPY) {
self->strm->obuflen = 0;
}
#endif
#ifdef HAVE_SSL
if (self->transport & W_SSL) {
int rv;
z_strm *sstrm;
if ((self->transport & 0xFFFF) == W_PLAIN) {
/* just SSL, nothing else */
sstrm = self->strm;
} else {
sstrm = self->strm->nextstrm;
}
sstrm->hdl.ssl = SSL_new(sstrm->ctx);
SSL_set_tlsext_host_name(sstrm->hdl.ssl, self->ip);
if (SSL_set_fd(sstrm->hdl.ssl, self->fd) == 0) {
logerr("failed to SSL_set_fd: %s\n",
ERR_reason_error_string(ERR_get_error()));
sstrm->strmclose(sstrm);
self->fd = -1;
continue;
}
if (self->transport & W_MTLS) {
int ret;
/* issue #444 */
ret = SSL_use_certificate_chain_file(sstrm->hdl.ssl, self->mtlspemcert);
if (ret == 1) {
ret = SSL_use_PrivateKey_file(sstrm->hdl.ssl,
self->mtlspemkey,
SSL_FILETYPE_PEM);
}
if (ret != 1) {
logerr("failed to enable mTLS: %s\n",
sslerror(sstrm, ret));
sstrm->strmclose(sstrm);
self->fd = -1;
continue;
}
}
if ((rv = SSL_connect(sstrm->hdl.ssl)) != 1) {
logerr("failed to connect ssl stream: %s\n",
sslerror(sstrm, rv));
sstrm->strmclose(sstrm);
self->fd = -1;
continue;
}
if ((rv = SSL_get_verify_result(sstrm->hdl.ssl)) != X509_V_OK) {
logerr("failed to verify ssl certificate: %s\n",
sslerror(sstrm, rv));
sstrm->strmclose(sstrm);
self->fd = -1;
continue;
}
} else
#endif
{
z_strm *pstrm;
if (self->transport == W_PLAIN) { /* just plain socket */
pstrm = self->strm;
} else {
pstrm = self->strm->nextstrm;
}
pstrm->hdl.sock = self->fd;
}
}
/* send up to batch size */
len = queue_dequeue_vector(self->batch, self->queue, self->bsize);
self->batch[len] = NULL;
metric = self->batch;
if (len != 0 &&
__sync_bool_compare_and_swap(&(self->keep_running), 0, 0))
{
/* be noisy during shutdown so we can track any slowing down
* servers, possibly preventing us to shut down */
logerr("shutting down %s:%u: waiting for %zu metrics\n",
self->ip, self->port, len + queue_len(self->queue));
}
if (len == 0 && __sync_add_and_fetch(&(self->failure), 0)) {
/* if we don't have anything to send, we have at least a