forked from SpamapS/gearmand
-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathgearmand.cc
1338 lines (1132 loc) · 35.4 KB
/
gearmand.cc
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
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011-2013 Data Differential, http://datadifferential.com/
* Copyright (C) 2008 Brian Aker, Eric Day
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* @file
* @brief Gearmand Definitions
*/
#include "gear_config.h"
#include "libgearman-server/common.h"
#include <cerrno>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <set>
#include <string>
#include <vector>
#include <libgearman-server/gearmand.h>
#include "libgearman-server/struct/port.h"
#include "libgearman-server/plugins.h"
#include "libgearman-server/timer.h"
#include "libgearman-server/queue.h"
#include "util/memory.h"
using namespace org::tangent;
using namespace gearmand;
#ifndef SOCK_NONBLOCK
# define SOCK_NONBLOCK 0
#endif
#ifndef SOL_TCP
# define SOL_TCP 0
#endif
#ifndef TCP_KEEPIDLE
# define TCP_KEEPIDLE 0
#endif
#ifndef TCP_KEEPINTVL
# define TCP_KEEPINTVL 0
#endif
#ifndef TCP_KEEPCNT
# define TCP_KEEPCNT 0
#endif
/*
* Private declarations
*/
/**
* @addtogroup gearmand_private Private Gearman Daemon Functions
* @ingroup gearmand
* @{
*/
static gearmand_error_t _listen_init(gearmand_st *gearmand);
static void _listen_close(gearmand_st *gearmand);
static gearmand_error_t _listen_watch(gearmand_st *gearmand);
static void _listen_clear(gearmand_st *gearmand);
static void _listen_event(int fd, short events, void *arg);
static gearmand_error_t _wakeup_init(gearmand_st *gearmand);
static void _wakeup_close(gearmand_st *gearmand);
static gearmand_error_t _wakeup_watch(gearmand_st *gearmand);
static void _wakeup_clear(gearmand_st *gearmand);
static void _wakeup_event(int fd, short events, void *arg);
static gearmand_error_t _watch_events(gearmand_st *gearmand);
static void _clear_events(gearmand_st *gearmand);
static void _close_events(gearmand_st *gearmand);
static bool gearman_server_create(gearman_server_st& server,
const uint32_t job_retries,
const char *job_handle_prefix,
uint8_t worker_wakeup,
bool round_robin,
uint32_t hashtable_buckets);
static void gearmand_set_log_fn(gearmand_st *gearmand, gearmand_log_fn *function,
void *context, const gearmand_verbose_t verbose);
static void gearman_server_free(gearman_server_st& server)
{
/* All threads should be cleaned up before calling this. */
assert(server.thread_list == NULL);
for (uint32_t key= 0; key < server.hashtable_buckets; key++)
{
while (server.job_hash[key] != NULL)
{
gearman_server_save_job(server, server.job_hash[key]);
gearman_server_job_free(server.job_hash[key]);
}
}
gearman_queue_flush(&server);
for (uint32_t function_key= 0; function_key < GEARMAND_DEFAULT_HASH_SIZE;
function_key++)
{
while(server.function_hash[function_key] != NULL)
{
gearman_server_function_free(&server, server.function_hash[function_key]);
}
}
while (server.free_packet_list != NULL)
{
gearman_server_packet_st *packet= server.free_packet_list;
server.free_packet_list= packet->next;
delete packet;
}
while (server.free_job_list != NULL)
{
gearman_server_job_st* job= server.free_job_list;
server.free_job_list= job->next;
delete job;
}
while (server.free_client_list != NULL)
{
gearman_server_client_st* client= server.free_client_list;
server.free_client_list= client->con_next;
delete client;
}
while (server.free_worker_list != NULL)
{
gearman_server_worker_st* worker= server.free_worker_list;
server.free_worker_list= worker->con_next;
delete worker;
}
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "removing queue: %s", (server.queue_version == QUEUE_VERSION_CLASS) ? "CLASS" : "FUNCTION");
if (server.queue_version == QUEUE_VERSION_CLASS)
{
delete server.queue.object;
assert(server.queue.functions == NULL);
}
else if (server.queue_version == QUEUE_VERSION_FUNCTION)
{
delete server.queue.functions;
assert(server.queue.object == NULL);
}
else
{
gearmand_debug("Unknown queue type in removal");
}
free(server.job_hash);
free(server.unique_hash);
free(server.function_hash);
}
/** @} */
#pragma GCC diagnostic push
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
/*
* Public definitions
*/
static gearmand_st *_global_gearmand= NULL;
gearmand_st *Gearmand(void)
{
if (_global_gearmand == NULL)
{
assert_msg(false, "Gearmand() was called before it was allocated");
gearmand_error("Gearmand() was called before it was allocated");
}
assert(_global_gearmand);
return _global_gearmand;
}
gearmand_st *gearmand_create(gearmand_config_st *config,
const char *host_arg,
uint32_t threads_arg,
int backlog_arg,
const uint32_t job_retries,
const char *job_handle_prefix,
uint8_t worker_wakeup,
gearmand_log_fn *log_function, void *log_context, const gearmand_verbose_t verbose_arg,
bool round_robin,
bool exceptions_,
uint32_t hashtable_buckets)
{
assert(_global_gearmand == NULL);
if (_global_gearmand)
{
gearmand_error("You have called gearmand_create() twice within your application.");
_exit(EXIT_FAILURE);
}
#ifdef HAVE_LIBEVENT2_PTHREADS
evthread_use_pthreads();
#else
#warn "HAVE_LIBEVENT2_PTHREADS not defined, can't initialize thread-support. This build will emit warnings and disable threads."
if (threads_arg > 0)
{
threads_arg= 0;
gearmand_log_warning("Threads disabled because this build could not locate libevent2 or its pthreads support.");
}
#endif
gearmand_st* gearmand= new (std::nothrow) gearmand_st(host_arg, threads_arg, backlog_arg, verbose_arg, exceptions_);
if (gearmand == NULL)
{
gearmand_perror(errno, "Failed to new() gearmand_st");
return NULL;
}
_global_gearmand= gearmand;
gearmand->socketopt()= config->config.sockopt();
if (gearman_server_create(gearmand->server, job_retries,
job_handle_prefix, worker_wakeup,
round_robin, hashtable_buckets) == false)
{
delete gearmand;
_global_gearmand= NULL;
return NULL;
}
gearmand_set_log_fn(gearmand, log_function, log_context, verbose_arg);
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "THREADS: %u", threads_arg);
return gearmand;
}
void gearmand_free(gearmand_st *gearmand)
{
if (gearmand)
{
_close_events(gearmand);
if (gearmand->threads > 0)
{
gearmand_debug("Shutting down all threads");
}
while (gearmand->thread_list != NULL)
{
gearmand_thread_free(gearmand->thread_list);
}
while (gearmand->free_dcon_list != NULL)
{
gearmand_con_st* dcon= gearmand->free_dcon_list;
gearmand->free_dcon_list= dcon->next;
delete dcon;
}
if (gearmand->base != NULL)
{
event_base_free(gearmand->base);
gearmand->base= NULL;
}
gearman_server_free(gearmand->server);
gearmand_info("Shutdown complete");
delete gearmand;
}
}
static void gearmand_set_log_fn(gearmand_st *gearmand, gearmand_log_fn *function,
void *context, const gearmand_verbose_t verbose)
{
gearmand->log_fn= function;
gearmand->log_context= context;
gearmand->verbose= verbose;
}
bool gearmand_exceptions(gearmand_st *gearmand)
{
return gearmand->exceptions();
}
gearmand_error_t gearmand_port_add(gearmand_st *gearmand, const char *port,
gearmand_connection_add_fn *function,
gearmand_connection_remove_fn* remove_)
{
assert(gearmand);
gearmand->_port_list.resize(gearmand->_port_list.size() +1);
memcpy(gearmand->_port_list.back().port, port, NI_MAXSERV);
gearmand->_port_list.back().port[NI_MAXSERV -1]= '\0';
gearmand->_port_list.back().add_fn(function);
gearmand->_port_list.back().remove_fn(remove_);
return GEARMAND_SUCCESS;
}
gearman_server_st *gearmand_server(gearmand_st *gearmand)
{
return &gearmand->server;
}
gearmand_error_t gearmand_run(gearmand_st *gearmand)
{
libgearman::server::Epoch epoch;
/* Initialize server components. */
if (gearmand->base == NULL)
{
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "Starting up with pid %lu, verbose is set to %s",
(unsigned long)(getpid()),
gearmand_verbose_name(gearmand->verbose));
if (gearmand->threads > 0)
{
/* Set the number of free connection structures each thread should keep
around before the main thread is forced to take them. We compute this
here so we don't need to on every new connection. */
gearmand->max_thread_free_dcon_count= ((GEARMAND_MAX_FREE_SERVER_CON /
gearmand->threads) / 2);
}
gearmand->base= static_cast<struct event_base *>(event_base_new());
if (gearmand->base == NULL)
{
gearmand_fatal("event_base_new(NULL)");
return GEARMAND_EVENT;
}
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "Method for libevent: %s", event_base_get_method(gearmand->base));
gearmand->ret= _listen_init(gearmand);
if (gearmand->ret != GEARMAND_SUCCESS)
{
return gearmand->ret;
}
gearmand->ret= _wakeup_init(gearmand);
if (gearmand->ret != GEARMAND_SUCCESS)
{
return gearmand->ret;
}
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "Creating %u threads", gearmand->threads);
/* If we have 0 threads we still need to create a fake one for context. */
uint32_t x= 0;
do
{
gearmand->ret= gearmand_thread_create(*gearmand);
if (gearmand->ret != GEARMAND_SUCCESS)
return gearmand->ret;
x++;
}
while (x < gearmand->threads);
gearmand_debug("replaying queue: begin");
gearmand->ret= gearman_server_queue_replay(gearmand->server);
if (gearmand_failed(gearmand->ret))
{
return gearmand_gerror("failed to reload queue", gearmand->ret);
}
gearmand_debug("replaying queue: end");
}
gearmand->ret= _watch_events(gearmand);
if (gearmand_failed(gearmand->ret))
{
return gearmand->ret;
}
gearmand_debug("Entering main event loop");
if (event_base_loop(gearmand->base, 0) == -1)
{
gearmand_fatal("event_base_loop(-1)");
return GEARMAND_EVENT;
}
gearmand_debug("Exited main event loop");
return gearmand->ret;
}
void gearmand_wakeup(gearmand_st *gearmand, gearmand_wakeup_t wakeup)
{
/*
If this fails, there is not much we can really do. This should never fail though if the main gearmand thread is still active.
*/
if (gearmand->wakeup_fd[1] != -1)
{
int limit= 5;
while (--limit) // limit is for EINTR
{
ssize_t written;
uint8_t buffer= wakeup;
if ((written= write(gearmand->wakeup_fd[1], &buffer, 1)) != 1)
{
if (written < 0)
{
switch (errno)
{
case EINTR:
continue;
default:
break;
}
gearmand_perror(errno, gearmand_strwakeup(wakeup));
}
else
{
gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM,
"gearmand_wakeup() incorrectly wrote %lu bytes of data.", (unsigned long)written);
}
}
return;
}
}
}
/*
* Private definitions
*/
gearmand_error_t set_socket(gearmand_st* gearmand, int& fd, struct addrinfo *addrinfo_next)
{
/* Call to socket() can fail for some getaddrinfo results, try another. */
fd= socket(addrinfo_next->ai_family, addrinfo_next->ai_socktype,
addrinfo_next->ai_protocol);
if (fd == -1)
{
return gearmand_perror(errno, "socket()");
}
#ifdef IPV6_V6ONLY
{
int flags= 1;
if (addrinfo_next->ai_family == AF_INET6)
{
flags= 1;
if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &flags, sizeof(flags)) == -1)
{
return gearmand_perror(errno, "setsockopt(IPV6_V6ONLY)");
}
}
}
#endif
if (0) // Add in when we have server working as a library again.
{
if (FD_CLOEXEC)
{
int flags;
do
{
flags= fcntl(fd, F_GETFD, 0);
} while (flags == -1 and (errno == EINTR or errno == EAGAIN));
if (flags != -1)
{
int rval;
do
{
rval= fcntl (fd, F_SETFD, flags | FD_CLOEXEC);
} while (rval == -1 && (errno == EINTR or errno == EAGAIN));
// we currently ignore the case where rval is -1
}
}
}
{
int flags= 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags)) == -1)
{
return gearmand_perror(errno, "setsockopt(SO_REUSEADDR)");
}
}
if (gearmand->socketopt().keepalive())
{
int flags= 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags)) == -1)
{
return gearmand_perror(errno, "setsockopt(SO_KEEPALIVE)");
}
if (SOL_TCP)
{
#if defined(TCP_KEEPIDLE) && TCP_KEEPIDLE
if (TCP_KEEPIDLE and gearmand->socketopt().keepalive_idle() != -1)
{
int optval= gearmand->socketopt().keepalive_idle();
if (setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &optval, sizeof(optval)) == -1)
{
return gearmand_perror(errno, "setsockopt(TCP_KEEPIDLE)");
}
}
#endif
#if defined(TCP_KEEPINTVL) && TCP_KEEPINTVL
if (TCP_KEEPINTVL and gearmand->socketopt().keepalive_interval() != -1)
{
int optval= gearmand->socketopt().keepalive_interval();
if (setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &optval, sizeof(optval)) == -1)
{
return gearmand_perror(errno, "setsockopt(TCP_KEEPINTVL)");
}
}
#endif
#if defined(TCP_KEEPCNT) && TCP_KEEPCNT
if (TCP_KEEPCNT and gearmand->socketopt().keepalive_count() != -1)
{
int optval= gearmand->socketopt().keepalive_count();
if (setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &optval, sizeof(optval)) == -1)
{
return gearmand_perror(errno, "setsockopt(TCP_KEEPCNT)");
}
}
#endif
}
}
{
struct linger ling= {0, 0};
if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) == -1)
{
return gearmand_perror(errno, "setsockopt(SO_LINGER)");
}
}
{
int flags= 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags)) == -1)
{
return gearmand_perror(errno, "setsockopt(TCP_NODELAY)");
}
}
return GEARMAND_SUCCESS;
}
static const uint32_t bind_timeout= 20; // Number is not special, but look at INFO messages if you decide to change it.
typedef std::pair<std::string, std::string> host_port_t;
static gearmand_error_t _listen_init(gearmand_st *gearmand)
{
for (uint32_t x= 0; x < gearmand->_port_list.size(); ++x)
{
struct addrinfo hints;
struct addrinfo *addrinfo= NULL;
gearmand_port_st *port= &gearmand->_port_list[x];
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags= AI_PASSIVE;
hints.ai_socktype= SOCK_STREAM;
{
int ret= getaddrinfo(gearmand->host, port->port, &hints, &addrinfo);
if (ret != 0)
{
char buffer[1024];
int length= snprintf(buffer, sizeof(buffer), "%s:%s", gearmand->host ? gearmand->host : "<any>", port->port);
if (length <= 0 or size_t(length) >= sizeof(buffer))
{
buffer[0]= 0;
}
if (addrinfo)
{
freeaddrinfo(addrinfo);
}
return gearmand_gai_error(buffer, ret);
}
}
std::set<host_port_t> unique_hosts;
for (struct addrinfo *addrinfo_next= addrinfo; addrinfo_next != NULL;
addrinfo_next= addrinfo_next->ai_next)
{
char host[NI_MAXHOST];
{
int ret= getnameinfo(addrinfo_next->ai_addr, addrinfo_next->ai_addrlen, host,
NI_MAXHOST, port->port, NI_MAXSERV,
NI_NUMERICHOST | NI_NUMERICSERV);
if (ret != 0)
{
gearmand_gai_error("getaddrinfo", ret);
strncpy(host, "-", sizeof(host));
strncpy(port->port, "-", sizeof(port->port));
}
}
std::string host_string(host);
std::string port_string(port->port);
host_port_t check= std::make_pair(host_string, port_string);
if (unique_hosts.find(check) != unique_hosts.end())
{
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "Already listening on %s:%s", host, port->port);
continue;
}
unique_hosts.insert(check);
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "Trying to listen on %s:%s", host, port->port);
/*
@note logic for this pulled from Drizzle.
Sometimes the port is not released fast enough when stopping and
restarting the server. This happens quite often with the test suite
on busy Linux systems. Retry to bind the address at these intervals:
Sleep intervals: 1, 2, 4, 6, 9, 13, 17, 22, ...
Retry at second: 1, 3, 7, 13, 22, 35, 52, 74, ...
Limit the sequence by drizzled_bind_timeout.
*/
uint32_t waited;
uint32_t this_wait;
uint32_t retry;
int ret= -1;
int fd;
for (waited= 0, retry= 1; ; retry++, waited+= this_wait)
{
{
gearmand_error_t socket_ret;
if (gearmand_failed(socket_ret= set_socket(gearmand, fd, addrinfo_next)))
{
gearmand_sockfd_close(fd);
freeaddrinfo(addrinfo);
return socket_ret;
}
}
errno= 0;
if ((ret= bind(fd, addrinfo_next->ai_addr, addrinfo_next->ai_addrlen)) == 0)
{
// Success
break;
}
// Protect our error
ret= errno;
gearmand_sockfd_close(fd);
if (waited >= bind_timeout)
{
freeaddrinfo(addrinfo);
return gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM, "Timeout occurred when calling bind() for %s:%s", host, port->port);
}
if (ret != EADDRINUSE)
{
freeaddrinfo(addrinfo);
return gearmand_perror(ret, "bind");
}
this_wait= retry * retry / 3 + 1;
// We are in single user threads, so strerror() is fine.
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "Retrying bind(%s) on %s:%s %u + %u >= %u",
strerror(ret), host, port->port,
waited, this_wait, bind_timeout);
struct timespec requested;
requested.tv_sec= this_wait;
requested.tv_nsec= 0;
nanosleep(&requested, NULL);
}
if (listen(fd, gearmand->backlog) == -1)
{
gearmand_perror(errno, "listen");
gearmand_sockfd_close(fd);
freeaddrinfo(addrinfo);
return GEARMAND_ERRNO;
}
// Scoping note for eventual transformation
{
int* fd_list= (int *)realloc(port->listen_fd, sizeof(int) * (port->listen_count + 1));
if (fd_list == NULL)
{
gearmand_perror(errno, "realloc");
gearmand_sockfd_close(fd);
freeaddrinfo(addrinfo);
return GEARMAND_ERRNO;
}
port->listen_fd= fd_list;
}
port->listen_fd[port->listen_count]= fd;
port->listen_count++;
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "Listening on %s:%s (%d)", host, port->port, fd);
}
freeaddrinfo(addrinfo);
/* Report last socket() error if we couldn't find an address to bind. */
if (port->listen_fd == NULL)
{
return gearmand_log_fatal(GEARMAN_DEFAULT_LOG_PARAM, "Could not bind/listen to any addresses");
}
assert(port->listen_event == NULL);
port->listen_event= (struct event *)malloc(sizeof(struct event) * port->listen_count); // libevent POD
if (port->listen_event == NULL)
{
return gearmand_merror("malloc(sizeof(struct event) * port->listen_count)", struct event, port->listen_count);
}
for (uint32_t y= 0; y < port->listen_count; ++y)
{
event_set(&(port->listen_event[y]), port->listen_fd[y], EV_READ | EV_PERSIST, _listen_event, port);
if (event_base_set(gearmand->base, &(port->listen_event[y])) == -1)
{
return gearmand_perror(errno, "event_base_set()");
}
}
}
return GEARMAND_SUCCESS;
}
static void _listen_close(gearmand_st *gearmand)
{
_listen_clear(gearmand);
for (uint32_t x= 0; x < gearmand->_port_list.size(); ++x)
{
for (uint32_t y= 0; y < gearmand->_port_list[x].listen_count; ++y)
{
if (gearmand->_port_list[x].listen_fd[y] >= 0)
{
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "Closing listening socket (%d)", gearmand->_port_list[x].listen_fd[y]);
gearmand_sockfd_close(gearmand->_port_list[x].listen_fd[y]);
gearmand->_port_list[x].listen_fd[y]= -1;
}
}
}
}
static gearmand_error_t _listen_watch(gearmand_st *gearmand)
{
if (gearmand->is_listen_event)
{
return GEARMAND_SUCCESS;
}
for (uint32_t x= 0; x < gearmand->_port_list.size(); ++x)
{
for (uint32_t y= 0; y < gearmand->_port_list[x].listen_count; y++)
{
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "Adding event for listening socket (%d)",
gearmand->_port_list[x].listen_fd[y]);
if (event_add(&(gearmand->_port_list[x].listen_event[y]), NULL) < 0)
{
gearmand_perror(errno, "event_add");
return GEARMAND_EVENT;
}
}
}
gearmand->is_listen_event= true;
return GEARMAND_SUCCESS;
}
static void _listen_clear(gearmand_st *gearmand)
{
if (gearmand->is_listen_event)
{
for (uint32_t x= 0; x < gearmand->_port_list.size(); ++x)
{
for (uint32_t y= 0; y < gearmand->_port_list[x].listen_count; y++)
{
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM,
"Clearing event for listening socket (%d)",
gearmand->_port_list[x].listen_fd[y]);
if (event_del(&(gearmand->_port_list[x].listen_event[y])) == -1)
{
gearmand_perror(errno, "We tried to event_del() an event which no longer existed");
assert_msg(false, "We tried to event_del() an event which no longer existed");
}
}
}
gearmand->is_listen_event= false;
}
}
static void _listen_event(int event_fd, short events __attribute__ ((unused)), void *arg)
{
gearmand_port_st *port= (gearmand_port_st *)arg;
struct sockaddr sa;
socklen_t sa_len= sizeof(sa);
#if defined(HAVE_ACCEPT4) && HAVE_ACCEPT4
int fd= accept4(event_fd, &sa, &sa_len, SOCK_NONBLOCK); // SOCK_NONBLOCK);
#else
int fd= accept(event_fd, &sa, &sa_len);
#endif
if (fd == -1)
{
int local_error= errno;
switch (local_error)
{
case EINTR:
case EMFILE:
return;
case ECONNABORTED:
gearmand_perror(local_error, "accept");
return;
default:
break;
}
_clear_events(Gearmand());
Gearmand()->ret= gearmand_perror(local_error, "accept");
return;
}
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "accept() fd:%d", fd);
/*
Since this is numeric, it should never fail. Even if it did we don't want to really error from it.
*/
char host[NI_MAXHOST];
char port_str[NI_MAXSERV];
int error= getnameinfo(&sa, sa_len, host, NI_MAXHOST, port_str, NI_MAXSERV,
NI_NUMERICHOST | NI_NUMERICSERV);
if (error != 0)
{
gearmand_gai_error("getnameinfo", error);
strncpy(host, "-", sizeof(host));
strncpy(port_str, "-", sizeof(port_str));
}
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "Accepted connection from %s:%s", host, port_str);
{
int flags= 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags)) == -1)
{
gearmand_log_perror(GEARMAN_DEFAULT_LOG_PARAM, errno, "%s:%s setsockopt(SO_KEEPALIVE)", host, port_str);
}
}
gearmand_error_t ret= gearmand_con_create(Gearmand(), fd, host, port_str, port);
if (ret == GEARMAND_MEMORY_ALLOCATION_FAILURE)
{
gearmand_sockfd_close(fd);
return;
}
else if (ret != GEARMAND_SUCCESS)
{
Gearmand()->ret= ret;
_clear_events(Gearmand());
}
}
static gearmand_error_t _wakeup_init(gearmand_st *gearmand)
{
gearmand_debug("Creating wakeup pipe");
#if defined(HAVE_PIPE2) && HAVE_PIPE2
if (pipe2(gearmand->wakeup_fd, O_NONBLOCK) == -1)
{
return gearmand_fatal_perror(errno, "pipe2(gearmand->wakeup_fd)");
}
#else
if (pipe(gearmand->wakeup_fd) == -1)
{
return gearmand_fatal_perror(errno, "pipe(gearmand->wakeup_fd)");
}
gearmand_error_t local_ret;
if ((local_ret= gearmand_sockfd_nonblock(gearmand->wakeup_fd[0])))
{
return local_ret;
}
#endif
event_set(&(gearmand->wakeup_event), gearmand->wakeup_fd[0],
EV_READ | EV_PERSIST, _wakeup_event, gearmand);
if (event_base_set(gearmand->base, &(gearmand->wakeup_event)) == -1)
{
gearmand_perror(errno, "event_base_set");
}
return GEARMAND_SUCCESS;
}
static void _wakeup_close(gearmand_st *gearmand)
{
_wakeup_clear(gearmand);
if (gearmand->wakeup_fd[0] >= 0)
{
gearmand_debug("Closing wakeup pipe");
gearmand_pipe_close(gearmand->wakeup_fd[0]);
gearmand->wakeup_fd[0]= -1;
gearmand_pipe_close(gearmand->wakeup_fd[1]);
gearmand->wakeup_fd[1]= -1;
}
}
static gearmand_error_t _wakeup_watch(gearmand_st *gearmand)
{
if (gearmand->is_wakeup_event)
{
return GEARMAND_SUCCESS;
}
gearmand_debug("Adding event for wakeup pipe");
if (event_add(&(gearmand->wakeup_event), NULL) < 0)
{
gearmand_perror(errno, "event_add");
return GEARMAND_EVENT;
}
gearmand->is_wakeup_event= true;
return GEARMAND_SUCCESS;
}
static void _wakeup_clear(gearmand_st *gearmand)
{
if (gearmand->is_wakeup_event)
{
gearmand_debug("Clearing event for wakeup pipe");
if (event_del(&(gearmand->wakeup_event)) < 0)
{
gearmand_perror(errno, "We tried to event_del() an event which no longer existed");
assert_msg(false, "We tried to event_del() an event which no longer existed");
}
gearmand->is_wakeup_event= false;