-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
socket.cpp
3021 lines (2762 loc) · 103 KB
/
socket.cpp
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "butil/compat.h" // OS_MACOSX
#include "butil/ssl_compat.h" // BIO_fd_non_fatal_error
#include <openssl/ssl.h>
#include <openssl/err.h>
#ifdef USE_MESALINK
#include <mesalink/openssl/ssl.h>
#include <mesalink/openssl/err.h>
#include <mesalink/openssl/x509.h>
#endif
#include <netinet/tcp.h> // getsockopt
#include <gflags/gflags.h>
#include "bthread/unstable.h" // bthread_timer_del
#include "butil/fd_utility.h" // make_non_blocking
#include "butil/fd_guard.h" // fd_guard
#include "butil/time.h" // cpuwide_time_us
#include "butil/object_pool.h" // get_object
#include "butil/logging.h" // CHECK
#include "butil/macros.h"
#include "butil/class_name.h" // butil::class_name
#include "butil/memory/scope_guard.h"
#include "brpc/log.h"
#include "brpc/reloadable_flags.h" // BRPC_VALIDATE_GFLAG
#include "brpc/errno.pb.h"
#include "brpc/event_dispatcher.h" // RemoveConsumer
#include "brpc/socket.h"
#include "brpc/describable.h" // Describable
#include "brpc/circuit_breaker.h" // CircuitBreaker
#include "brpc/input_messenger.h"
#include "brpc/details/sparse_minute_counter.h"
#include "brpc/stream_impl.h"
#include "brpc/shared_object.h"
#include "brpc/policy/rtmp_protocol.h" // FIXME
#include "brpc/periodic_task.h"
#include "brpc/details/health_check.h"
#include "brpc/rdma/rdma_endpoint.h"
#include "brpc/rdma/rdma_helper.h"
#if defined(OS_MACOSX)
#include <sys/event.h>
#endif
namespace bthread {
size_t __attribute__((weak))
get_sizes(const bthread_id_list_t* list, size_t* cnt, size_t n);
}
namespace brpc {
// NOTE: This flag was true by default before r31206. Connected to somewhere
// is not an important event now, we can check the connection in /connections
// if we're in doubt.
DEFINE_bool(log_connected, false, "Print log when a connection is established");
BRPC_VALIDATE_GFLAG(log_connected, PassValidate);
DEFINE_bool(log_idle_connection_close, false,
"Print log when an idle connection is closed");
BRPC_VALIDATE_GFLAG(log_idle_connection_close, PassValidate);
DEFINE_int32(socket_recv_buffer_size, -1,
"Set the recv buffer size of socket if this value is positive");
// Default value of SNDBUF is 2500000 on most machines.
DEFINE_int32(socket_send_buffer_size, -1,
"Set send buffer size of sockets if this value is positive");
DEFINE_int32(ssl_bio_buffer_size, 16*1024, "Set buffer size for SSL read/write");
DEFINE_int64(socket_max_unwritten_bytes, 64 * 1024 * 1024,
"Max unwritten bytes in each socket, if the limit is reached,"
" Socket.Write fails with EOVERCROWDED");
DEFINE_int64(socket_max_streams_unconsumed_bytes, 0,
"Max stream receivers' unconsumed bytes in one socket,"
" it used in stream for receiver buffer control.");
DEFINE_int32(max_connection_pool_size, 100,
"Max number of pooled connections to a single endpoint");
BRPC_VALIDATE_GFLAG(max_connection_pool_size, PassValidate);
DEFINE_int32(connect_timeout_as_unreachable, 3,
"If the socket failed to connect due to ETIMEDOUT for so many "
"times *continuously*, the error is changed to ENETUNREACH which "
"fails the main socket as well when this socket is pooled.");
DECLARE_int32(health_check_timeout_ms);
DECLARE_bool(usercode_in_coroutine);
static bool validate_connect_timeout_as_unreachable(const char*, int32_t v) {
return v >= 2 && v < 1000/*large enough*/;
}
BRPC_VALIDATE_GFLAG(connect_timeout_as_unreachable,
validate_connect_timeout_as_unreachable);
const int WAIT_EPOLLOUT_TIMEOUT_MS = 50;
class BAIDU_CACHELINE_ALIGNMENT SocketPool {
friend class Socket;
public:
explicit SocketPool(const SocketOptions& opt);
~SocketPool();
// Get an address-able socket. If the pool is empty, create one.
// Returns 0 on success.
int GetSocket(SocketUniquePtr* ptr);
// Return a socket (which was returned by GetSocket) back to the pool,
// if the pool is full, setfail the socket directly.
void ReturnSocket(Socket* sock);
// Get all pooled sockets inside.
void ListSockets(std::vector<SocketId>* list, size_t max_count);
private:
// options used to create this instance
SocketOptions _options;
butil::Mutex _mutex;
std::vector<SocketId> _pool;
butil::EndPoint _remote_side;
butil::atomic<int> _numfree; // #free sockets in all sub pools.
butil::atomic<int> _numinflight; // #inflight sockets in all sub pools.
};
// NOTE: sizeof of this class is 1200 bytes. If we have 10K sockets, total
// memory is 12MB, not lightweight, but acceptable.
struct ExtendedSocketStat : public SocketStat {
// For computing stat.
size_t last_in_size;
size_t last_in_num_messages;
size_t last_out_size;
size_t last_out_num_messages;
struct Sampled {
uint32_t in_size_s;
uint32_t in_num_messages_s;
uint32_t out_size_s;
uint32_t out_num_messages_s;
};
SparseMinuteCounter<Sampled> _minute_counter;
ExtendedSocketStat()
: last_in_size(0)
, last_in_num_messages(0)
, last_out_size(0)
, last_out_num_messages(0) {
memset((SocketStat*)this, 0, sizeof(SocketStat));
}
};
// Shared by main socket and derivative sockets.
class Socket::SharedPart : public SharedObject {
public:
// A pool of sockets on which only a request can be sent, corresponding
// to CONNECTION_TYPE_POOLED. When RPC begins, it picks one socket from
// this pool and send the request, when the RPC ends, it returns the
// socket back to this pool.
// Before rev <= r32136, the pool is managed globally in socket_map.cpp
// which has the disadvantage that accesses to different pools contend
// with each other.
butil::atomic<SocketPool*> socket_pool;
// The socket newing this object.
SocketId creator_socket_id;
// Counting number of continuous ETIMEDOUT
butil::atomic<int> num_continuous_connect_timeouts;
// _in_size, _in_num_messages, _out_size, _out_num_messages of pooled
// sockets are counted into the corresponding fields in their _main_socket.
butil::atomic<size_t> in_size;
butil::atomic<size_t> in_num_messages;
butil::atomic<size_t> out_size;
butil::atomic<size_t> out_num_messages;
// For computing stats.
ExtendedSocketStat* extended_stat;
CircuitBreaker circuit_breaker;
butil::atomic<uint64_t> recent_error_count;
explicit SharedPart(SocketId creator_socket_id);
~SharedPart();
// Call this method every second (roughly)
void UpdateStatsEverySecond(int64_t now_ms);
};
Socket::SharedPart::SharedPart(SocketId creator_socket_id2)
: socket_pool(NULL)
, creator_socket_id(creator_socket_id2)
, num_continuous_connect_timeouts(0)
, in_size(0)
, in_num_messages(0)
, out_size(0)
, out_num_messages(0)
, extended_stat(NULL)
, recent_error_count(0) {
}
Socket::SharedPart::~SharedPart() {
delete extended_stat;
extended_stat = NULL;
delete socket_pool.exchange(NULL, butil::memory_order_relaxed);
}
void Socket::SharedPart::UpdateStatsEverySecond(int64_t now_ms) {
ExtendedSocketStat* stat = extended_stat;
if (stat == NULL) {
stat = new (std::nothrow) ExtendedSocketStat;
if (stat == NULL) {
return;
}
extended_stat = stat;
}
// Save volatile counters.
const size_t in_sz = in_size.load(butil::memory_order_relaxed);
const size_t in_nmsg = in_num_messages.load(butil::memory_order_relaxed);
const size_t out_sz = out_size.load(butil::memory_order_relaxed);
const size_t out_nmsg = out_num_messages.load(butil::memory_order_relaxed);
// Notice that we don't normalize any data, mainly because normalization
// often make data inaccurate and confuse users. This assumes that this
// function is called exactly every second. This may not be true when the
// running machine gets very busy. TODO(gejun): Figure out a method to
// selectively normalize data when the calling interval is far from 1 second.
stat->in_size_s = in_sz - stat->last_in_size;
stat->in_num_messages_s = in_nmsg - stat->last_in_num_messages;
stat->out_size_s = out_sz - stat->last_out_size;
stat->out_num_messages_s = out_nmsg - stat->last_out_num_messages;
stat->last_in_size = in_sz;
stat->last_in_num_messages = in_nmsg;
stat->last_out_size = out_sz;
stat->last_out_num_messages = out_nmsg;
ExtendedSocketStat::Sampled popped;
if (stat->in_size_s |/*bitwise or*/
stat->in_num_messages_s |
stat->out_size_s |
stat->out_num_messages_s) {
ExtendedSocketStat::Sampled s = {
stat->in_size_s, stat->in_num_messages_s,
stat->out_size_s, stat->out_num_messages_s
};
stat->in_size_m += s.in_size_s;
stat->in_num_messages_m += s.in_num_messages_s;
stat->out_size_m += s.out_size_s;
stat->out_num_messages_m += s.out_num_messages_s;
if (stat->_minute_counter.Add(now_ms, s, &popped)) {
stat->in_size_m -= popped.in_size_s;
stat->in_num_messages_m -= popped.in_num_messages_s;
stat->out_size_m -= popped.out_size_s;
stat->out_num_messages_m -= popped.out_num_messages_s;
}
}
while (stat->_minute_counter.TryPop(now_ms, &popped)) {
stat->in_size_m -= popped.in_size_s;
stat->in_num_messages_m -= popped.in_num_messages_s;
stat->out_size_m -= popped.out_size_s;
stat->out_num_messages_m -= popped.out_num_messages_s;
}
}
SocketVarsCollector* g_vars = NULL;
static pthread_once_t s_create_vars_once = PTHREAD_ONCE_INIT;
static void CreateVars() {
g_vars = new SocketVarsCollector;
}
void Socket::CreateVarsOnce() {
CHECK_EQ(0, pthread_once(&s_create_vars_once, CreateVars));
}
// Used by ConnectionService
int64_t GetChannelConnectionCount() {
if (g_vars) {
return g_vars->channel_conn.get_value();
}
return 0;
}
bool Socket::CreatedByConnect() const {
return _user == static_cast<SocketUser*>(get_client_side_messenger());
}
SocketMessage* const DUMMY_USER_MESSAGE = (SocketMessage*)0x1;
const uint32_t MAX_PIPELINED_COUNT = 16384;
struct BAIDU_CACHELINE_ALIGNMENT Socket::WriteRequest {
static WriteRequest* const UNCONNECTED;
butil::IOBuf data;
WriteRequest* next;
bthread_id_t id_wait;
void clear_and_set_control_bits(bool notify_on_success,
bool shutdown_write) {
_socket_and_control_bits.set_extra(
(uint16_t)notify_on_success << 1 | (uint16_t)shutdown_write);
}
void set_socket(Socket* s) {
_socket_and_control_bits.set(s);
}
// If this field is set to true, notify when write successfully.
bool is_notify_on_success() const {
return _socket_and_control_bits.extra() & ((uint16_t)1 << 1);
}
// Whether shutdown write of the socket after this write complete.
bool need_shutdown_write() const {
return _socket_and_control_bits.extra() & (uint16_t)1;
}
Socket* get_socket() const {
return _socket_and_control_bits.get();
}
uint32_t pipelined_count() const {
return _pc_and_udmsg.extra() & 0x3FFF;
}
uint32_t get_auth_flags() const {
return (_pc_and_udmsg.extra() >> 14) & 0x03;
}
void clear_pipelined_count_and_auth_flags() {
_pc_and_udmsg.reset_extra();
}
SocketMessage* user_message() const {
return _pc_and_udmsg.get();
}
void clear_user_message() {
_pc_and_udmsg.reset();
}
void set_pipelined_count_and_user_message(
uint32_t pc, SocketMessage* msg, uint32_t auth_flags) {
if (auth_flags) {
pc |= (auth_flags & 0x03) << 14;
}
_pc_and_udmsg.set_ptr_and_extra(msg, pc);
}
bool reset_pipelined_count_and_user_message() {
SocketMessage* msg = user_message();
if (msg) {
if (msg != DUMMY_USER_MESSAGE) {
butil::IOBuf dummy_buf;
// We don't care about the return value since the request
// is already failed.
(void)msg->AppendAndDestroySelf(&dummy_buf, NULL);
}
set_pipelined_count_and_user_message(0, NULL, 0);
return true;
}
return false;
}
// Register pipelined_count and user_message
void Setup(Socket* s);
private:
// Socket pointer and some control bits.
PackedPtr<Socket> _socket_and_control_bits;
// User message pointer, pipelined count auth flag.
PackedPtr<SocketMessage> _pc_and_udmsg;
};
void Socket::WriteRequest::Setup(Socket* s) {
SocketMessage* msg = user_message();
if (msg) {
clear_user_message();
if (msg != DUMMY_USER_MESSAGE) {
butil::Status st = msg->AppendAndDestroySelf(&data, s);
if (!st.ok()) {
// Abandon the request.
data.clear();
bthread_id_error2(id_wait, st.error_code(), st.error_cstr());
return;
}
}
const int64_t before_write =
s->_unwritten_bytes.fetch_add(data.size(), butil::memory_order_relaxed);
if (before_write + (int64_t)data.size() >= FLAGS_socket_max_unwritten_bytes) {
s->_overcrowded = true;
}
}
const uint32_t pc = pipelined_count();
if (pc) {
// For positional correspondence between responses and requests,
// which is common in cache servers: memcache, redis...
// The struct will be popped when reading a message from the socket.
PipelinedInfo pi;
pi.count = pc;
pi.auth_flags = get_auth_flags();
pi.id_wait = id_wait;
clear_pipelined_count_and_auth_flags(); // avoid being pushed again
s->PushPipelinedInfo(pi);
}
}
Socket::WriteRequest* const Socket::WriteRequest::UNCONNECTED =
(Socket::WriteRequest*)(intptr_t)-1;
class Socket::EpollOutRequest : public SocketUser {
public:
EpollOutRequest() : fd(-1), timer_id(0)
, on_epollout_event(NULL), data(NULL) {}
~EpollOutRequest() override {
// Remove the timer at last inside destructor to avoid
// race with the place that registers the timer
if (timer_id) {
bthread_timer_del(timer_id);
timer_id = 0;
}
}
void BeforeRecycle(Socket*) override {
// Recycle itself.
delete this;
}
int fd;
bthread_timer_t timer_id;
int (*on_epollout_event)(int fd, int err, void* data);
void* data;
};
static const uint64_t AUTH_FLAG = (1ul << 32);
Socket::Socket(Forbidden f)
// must be even because Address() relies on evenness of version
: VersionedRefWithId<Socket>(f)
, _shared_part(NULL)
, _nevent(0)
, _keytable_pool(NULL)
, _fd(-1)
, _tos(0)
, _reset_fd_real_us(-1)
, _on_edge_triggered_events(NULL)
, _user(NULL)
, _conn(NULL)
, _preferred_index(-1)
, _hc_count(0)
, _last_msg_size(0)
, _avg_msg_size(0)
, _last_readtime_us(0)
, _parsing_context(NULL)
, _correlation_id(0)
, _health_check_interval_s(-1)
, _is_hc_related_ref_held(false)
, _hc_started(false)
, _ninprocess(1)
, _auth_flag_error(0)
, _auth_id(INVALID_BTHREAD_ID)
, _auth_context(NULL)
, _ssl_state(SSL_UNKNOWN)
, _ssl_session(NULL)
, _rdma_ep(NULL)
, _rdma_state(RDMA_OFF)
, _connection_type_for_progressive_read(CONNECTION_TYPE_UNKNOWN)
, _controller_released_socket(false)
, _overcrowded(false)
, _fail_me_at_server_stop(false)
, _logoff_flag(false)
, _error_code(0)
, _pipeline_q(NULL)
, _last_writetime_us(0)
, _unwritten_bytes(0)
, _epollout_butex(NULL)
, _write_head(NULL)
, _is_write_shutdown(false)
, _stream_set(NULL)
, _total_streams_unconsumed_size(0)
, _ninflight_app_health_check(0)
, _http_request_method(HTTP_METHOD_GET) {
CreateVarsOnce();
pthread_mutex_init(&_id_wait_list_mutex, NULL);
_epollout_butex = bthread::butex_create_checked<butil::atomic<int> >();
}
Socket::~Socket() {
pthread_mutex_destroy(&_id_wait_list_mutex);
bthread::butex_destroy(_epollout_butex);
}
void Socket::ReturnSuccessfulWriteRequest(Socket::WriteRequest* p) {
DCHECK(p->data.empty());
AddOutputMessages(1);
const bthread_id_t id_wait = p->id_wait;
butil::return_object(p);
if (id_wait != INVALID_BTHREAD_ID) {
if (p->is_notify_on_success() && !Failed()) {
bthread_id_error(id_wait, 0);
} else {
NotifyOnFailed(id_wait);
}
}
}
void Socket::ReturnFailedWriteRequest(Socket::WriteRequest* p, int error_code,
const std::string& error_text) {
if (!p->reset_pipelined_count_and_user_message()) {
CancelUnwrittenBytes(p->data.size());
}
p->data.clear(); // data is probably not written.
const bthread_id_t id_wait = p->id_wait;
butil::return_object(p);
if (id_wait != INVALID_BTHREAD_ID) {
bthread_id_error2(id_wait, error_code, error_text);
}
}
Socket::WriteRequest* Socket::ReleaseWriteRequestsExceptLast(
Socket::WriteRequest* req, int error_code, const std::string& error_text) {
WriteRequest* p = req;
while (p->next != NULL) {
WriteRequest* const saved_next = p->next;
ReturnFailedWriteRequest(p, error_code, error_text);
p = saved_next;
}
return p;
}
void Socket::ReleaseAllFailedWriteRequests(Socket::WriteRequest* req) {
CHECK(Failed() || IsWriteShutdown());
int error_code;
std::string error_text;
if (Failed()) {
pthread_mutex_lock(&_id_wait_list_mutex);
error_code = non_zero_error_code();
error_text = _error_text;
pthread_mutex_unlock(&_id_wait_list_mutex);
} else {
error_code = ESHUTDOWNWRITE;
error_text = "Shutdown write of the socket";
}
// Notice that `req' is not tail if Address after IsWriteComplete fails.
do {
req = ReleaseWriteRequestsExceptLast(req, error_code, error_text);
if (!req->reset_pipelined_count_and_user_message()) {
CancelUnwrittenBytes(req->data.size());
}
req->data.clear(); // MUST, otherwise IsWriteComplete is false
} while (!IsWriteComplete(req, true, NULL));
ReturnFailedWriteRequest(req, error_code, error_text);
}
int Socket::ResetFileDescriptor(int fd) {
// Reset message sizes when fd is changed.
_last_msg_size = 0;
_avg_msg_size = 0;
// MUST store `_fd' before adding itself into epoll device to avoid
// race conditions with the callback function inside epoll
_fd.store(fd, butil::memory_order_release);
_reset_fd_real_us = butil::gettimeofday_us();
if (!ValidFileDescriptor(fd)) {
return 0;
}
if (_remote_side == butil::EndPoint()) {
// OK to fail, non-socket fd does not support this.
butil::get_remote_side(fd, &_remote_side);
}
// OK to fail, non-socket fd does not support this.
if (butil::get_local_side(fd, &_local_side) != 0) {
_local_side = butil::EndPoint();
}
// FIXME : close-on-exec should be set by new syscalls or worse: set right
// after fd-creation syscall. Setting at here has higher probabilities of
// race condition.
butil::make_close_on_exec(fd);
// Make the fd non-blocking.
if (butil::make_non_blocking(fd) != 0) {
PLOG(ERROR) << "Fail to set fd=" << fd << " to non-blocking";
_fd.store(-1, butil::memory_order_release);
return -1;
}
// turn off nagling.
// OK to fail, namely unix domain socket does not support this.
butil::make_no_delay(fd);
if (_tos > 0 &&
setsockopt(fd, IPPROTO_IP, IP_TOS, &_tos, sizeof(_tos)) != 0) {
PLOG(ERROR) << "Fail to set tos of fd=" << fd << " to " << _tos;
}
if (FLAGS_socket_send_buffer_size > 0) {
int buff_size = FLAGS_socket_send_buffer_size;
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buff_size, sizeof(buff_size)) != 0) {
PLOG(ERROR) << "Fail to set sndbuf of fd=" << fd << " to "
<< buff_size;
}
}
if (FLAGS_socket_recv_buffer_size > 0) {
int buff_size = FLAGS_socket_recv_buffer_size;
if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buff_size, sizeof(buff_size)) != 0) {
PLOG(ERROR) << "Fail to set rcvbuf of fd=" << fd << " to "
<< buff_size;
}
}
EnableKeepaliveIfNeeded(fd);
if (_on_edge_triggered_events) {
if (_io_event.AddConsumer(fd) != 0) {
PLOG(ERROR) << "Fail to add SocketId=" << id()
<< " into EventDispatcher";
_fd.store(-1, butil::memory_order_release);
return -1;
}
}
return 0;
}
void Socket::EnableKeepaliveIfNeeded(int fd) {
if (!_keepalive_options) {
return;
}
int keepalive = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive,
sizeof(keepalive)) != 0) {
PLOG(ERROR) << "Fail to set keepalive of fd=" << fd;
return;
}
#if defined(OS_LINUX)
if (_keepalive_options->keepalive_idle_s > 0) {
if (setsockopt(fd, SOL_TCP, TCP_KEEPIDLE,
&_keepalive_options->keepalive_idle_s,
sizeof(_keepalive_options->keepalive_idle_s)) != 0) {
PLOG(ERROR) << "Fail to set keepidle of fd=" << fd;
}
}
if (_keepalive_options->keepalive_interval_s > 0) {
if (setsockopt(fd, SOL_TCP, TCP_KEEPINTVL,
&_keepalive_options->keepalive_interval_s,
sizeof(_keepalive_options->keepalive_interval_s)) != 0) {
PLOG(ERROR) << "Fail to set keepintvl of fd=" << fd;
}
}
if (_keepalive_options->keepalive_count > 0) {
if (setsockopt(fd, SOL_TCP, TCP_KEEPCNT,
&_keepalive_options->keepalive_count,
sizeof(_keepalive_options->keepalive_count)) != 0) {
PLOG(ERROR) << "Fail to set keepcnt of fd=" << fd;
}
}
#elif defined(OS_MACOSX)
if (_keepalive_options->keepalive_idle_s > 0) {
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE,
&_keepalive_options->keepalive_idle_s,
sizeof(_keepalive_options->keepalive_idle_s)) != 0) {
PLOG(ERROR) << "Fail to set keepidle of fd=" << fd;
}
}
if (_keepalive_options->keepalive_interval_s > 0) {
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
&_keepalive_options->keepalive_interval_s,
sizeof(_keepalive_options->keepalive_interval_s)) != 0) {
PLOG(ERROR) << "Fail to set keepintvl of fd=" << fd;
}
}
if (_keepalive_options->keepalive_count > 0) {
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
&_keepalive_options->keepalive_count,
sizeof(_keepalive_options->keepalive_count)) != 0) {
PLOG(ERROR) << "Fail to set keepcnt of fd=" << fd;
}
}
#endif
}
// SocketId = 32-bit version + 32-bit slot.
// version: from version part of _versioned_nref, must be an EVEN number.
// slot: designated by ResourcePool.
int Socket::Create(const SocketOptions& options, SocketId* id) {
return VersionedRefWithId<Socket>::Create(id, options);
}
int Socket::OnCreated(const SocketOptions& options) {
if (_io_event.Init((void*)id()) != 0) {
LOG(ERROR) << "Fail to init IOEvent";
SetFailed(ENOMEM, "%s", "Fail to init IOEvent");
return -1;
}
_io_event.set_bthread_tag(options.bthread_tag);
auto guard = butil::MakeScopeGuard([this] {
_io_event.Reset();
});
g_vars->nsocket << 1;
CHECK(NULL == _shared_part.load(butil::memory_order_relaxed));
_nevent.store(0, butil::memory_order_relaxed);
_keytable_pool = options.keytable_pool;
_tos = 0;
_remote_side = options.remote_side;
_on_edge_triggered_events = options.on_edge_triggered_events;
_user = options.user;
_conn = options.conn;
_app_connect = options.app_connect;
_preferred_index = -1;
_hc_count = 0;
CHECK(_read_buf.empty());
const int64_t cpuwide_now = butil::cpuwide_time_us();
_last_readtime_us.store(cpuwide_now, butil::memory_order_relaxed);
reset_parsing_context(options.initial_parsing_context);
_correlation_id = 0;
_health_check_interval_s = options.health_check_interval_s;
_is_hc_related_ref_held = false;
_hc_started.store(false, butil::memory_order_relaxed);
_ninprocess.store(1, butil::memory_order_relaxed);
_auth_flag_error.store(0, butil::memory_order_relaxed);
const int rc2 = bthread_id_create(&_auth_id, NULL, NULL);
if (rc2) {
LOG(ERROR) << "Fail to create auth_id: " << berror(rc2);
SetFailed(rc2, "Fail to create auth_id: %s", berror(rc2));
return -1;
}
_force_ssl = options.force_ssl;
// Disable SSL check if there is no SSL context
_ssl_state = (options.initial_ssl_ctx == NULL ? SSL_OFF : SSL_UNKNOWN);
_ssl_session = NULL;
_ssl_ctx = options.initial_ssl_ctx;
#if BRPC_WITH_RDMA
CHECK(_rdma_ep == NULL);
if (options.use_rdma) {
_rdma_ep = new (std::nothrow)rdma::RdmaEndpoint(m);
if (!_rdma_ep) {
const int saved_errno = errno;
PLOG(ERROR) << "Fail to create RdmaEndpoint";
SetFailed(saved_errno, "Fail to create RdmaEndpoint: %s",
berror(saved_errno));
return -1;
}
_rdma_state = RDMA_UNKNOWN;
} else {
_rdma_state = RDMA_OFF;
}
#endif
_connection_type_for_progressive_read = CONNECTION_TYPE_UNKNOWN;
_controller_released_socket.store(false, butil::memory_order_relaxed);
_overcrowded = false;
// Maybe non-zero for RTMP connections.
_fail_me_at_server_stop = false;
_logoff_flag.store(false, butil::memory_order_relaxed);
_error_code = 0;
_agent_socket_id.store(INVALID_SOCKET_ID, butil::memory_order_relaxed);
_total_streams_unconsumed_size.store(0, butil::memory_order_relaxed);
_ninflight_app_health_check.store(0, butil::memory_order_relaxed);
// NOTE: last two params are useless in bthread > r32787
const int rc = bthread_id_list_init(&_id_wait_list, 512, 512);
if (rc) {
LOG(ERROR) << "Fail to init _id_wait_list: " << berror(rc);
SetFailed(rc, "Fail to init _id_wait_list: %s", berror(rc));
return -1;
}
_last_writetime_us.store(cpuwide_now, butil::memory_order_relaxed);
_unwritten_bytes.store(0, butil::memory_order_relaxed);
_keepalive_options = options.keepalive_options;
CHECK(NULL == _write_head.load(butil::memory_order_relaxed));
_is_write_shutdown = false;
int fd = options.fd;
if (!ValidFileDescriptor(fd) && options.connect_on_create) {
// Connect on create.
fd = DoConnect(options.connect_abstime, NULL, NULL);
if (fd < 0) {
PLOG(ERROR) << "Fail to connect to " << options.remote_side;
int error_code = errno != 0 ? errno : EHOSTDOWN;
SetFailed(error_code, "Fail to connect to %s: %s",
butil::endpoint2str(options.remote_side).c_str(),
berror(error_code));
return -1;
}
}
// Must be the last one! Internal fields of this Socket may be accessed
// just after calling ResetFileDescriptor.
if (ResetFileDescriptor(options.fd) != 0) {
const int saved_errno = errno;
PLOG(ERROR) << "Fail to ResetFileDescriptor";
SetFailed(saved_errno, "Fail to ResetFileDescriptor: %s",
berror(saved_errno));
return -1;
}
HoldHCRelatedRef();
guard.dismiss();
return 0;
}
void Socket::BeforeRecycled() {
const bool create_by_connect = CreatedByConnect();
if (_app_connect) {
std::shared_ptr<AppConnect> tmp;
_app_connect.swap(tmp);
tmp->StopConnect(this);
}
if (_conn) {
SocketConnection* const saved_conn = _conn;
_conn = NULL;
saved_conn->BeforeRecycle(this);
}
if (_user) {
SocketUser* const saved_user = _user;
_user = NULL;
saved_user->BeforeRecycle(this);
}
SharedPart* sp = _shared_part.exchange(NULL, butil::memory_order_acquire);
if (sp) {
sp->RemoveRefManually();
}
const int prev_fd = _fd.exchange(-1, butil::memory_order_relaxed);
if (ValidFileDescriptor(prev_fd)) {
if (_on_edge_triggered_events != NULL) {
_io_event.RemoveConsumer(prev_fd);
}
close(prev_fd);
if (create_by_connect) {
g_vars->channel_conn << -1;
}
}
_io_event.Reset();
#if BRPC_WITH_RDMA
if (_rdma_ep) {
delete _rdma_ep;
_rdma_ep = NULL;
_rdma_state = RDMA_UNKNOWN;
}
#endif
reset_parsing_context(NULL);
_read_buf.clear();
_auth_flag_error.store(0, butil::memory_order_relaxed);
bthread_id_error(_auth_id, 0);
bthread_id_list_destroy(&_id_wait_list);
if (_ssl_session) {
SSL_free(_ssl_session);
_ssl_session = NULL;
}
_ssl_ctx = NULL;
delete _pipeline_q;
_pipeline_q = NULL;
delete _auth_context;
_auth_context = NULL;
delete _stream_set;
_stream_set = NULL;
const SocketId asid = _agent_socket_id.load(butil::memory_order_relaxed);
if (asid != INVALID_SOCKET_ID) {
SocketUniquePtr ptr;
if (Socket::Address(asid, &ptr) == 0) {
ptr->ReleaseAdditionalReference();
}
}
g_vars->nsocket << -1;
}
void Socket::OnFailed(int error_code, const std::string& error_text) {
// Update _error_text
pthread_mutex_lock(&_id_wait_list_mutex);
_error_code = error_code;
_error_text = error_text;
pthread_mutex_unlock(&_id_wait_list_mutex);
// Do health-checking even if we're not connected before, needed
// by Channel to revive never-connected socket when server side
// comes online.
if (HCEnabled()) {
bool expect = false;
if (_hc_started.compare_exchange_strong(expect,
true,
butil::memory_order_relaxed,
butil::memory_order_relaxed)) {
GetOrNewSharedPart()->circuit_breaker.MarkAsBroken();
StartHealthCheck(id(),
GetOrNewSharedPart()->circuit_breaker.isolation_duration_ms());
} else {
// No need to run 2 health checking at the same time.
RPC_VLOG << "There is already a health checking running "
"for SocketId=" << id();
}
}
// Wake up all threads waiting on EPOLLOUT when closing fd
_epollout_butex->fetch_add(1, butil::memory_order_relaxed);
bthread::butex_wake_all(_epollout_butex);
// Wake up all unresponded RPC.
CHECK_EQ(0, bthread_id_list_reset2_pthreadsafe(
&_id_wait_list, error_code, error_text,
&_id_wait_list_mutex));
ResetAllStreams(error_code, error_text);
// _app_connect shouldn't be set to NULL in SetFailed otherwise
// HC is always not supported.
// FIXME: Design a better interface for AppConnect
// if (_app_connect) {
// AppConnect* const saved_app_connect = _app_connect;
// _app_connect = NULL;
// saved_app_connect->StopConnect(this);
// }
}
void Socket::AfterRevived() {
if (_user) {
_user->AfterRevived(this);
} else {
LOG(INFO) << "Revived " << description() << " (Connectable)";
}
}
std::string Socket::OnDescription() const {
// NOTE: The output of `description()' should be consistent with operator<<()
std::string result;
result.reserve(64);
const int saved_fd = fd();
if (saved_fd >= 0) {
butil::string_appendf(&result, "fd=%d", saved_fd);
}
butil::string_appendf(&result, " addr=%s",
butil::endpoint2str(remote_side()).c_str());
const int local_port = local_side().port;
if (local_port > 0) {
butil::string_appendf(&result, ":%d", local_port);
}
return result;
}
void Socket::HoldHCRelatedRef() {
if (_health_check_interval_s > 0) {
_is_hc_related_ref_held = true;
AddReference();
}
}
void Socket::ReleaseHCRelatedReference() {
if (_health_check_interval_s > 0) {
_is_hc_related_ref_held = false;
Dereference();
}
}
int Socket::WaitAndReset(int32_t expected_nref) {
const uint32_t id_ver = VersionOfVRefId(id());
uint64_t vref;
// Wait until nref == expected_nref.
while (true) {
// The acquire fence pairs with release fence in Dereference to avoid
// inconsistent states to be seen by others.
vref = versioned_ref();
if (VersionOfVRef(vref) != id_ver + 1) {
LOG(WARNING) << "SocketId=" << id() << " is already alive or recycled";
return -1;
}
if (NRefOfVRef(vref) > expected_nref) {
if (bthread_usleep(1000L/*FIXME*/) < 0) {
PLOG_IF(FATAL, errno != ESTOP) << "Fail to sleep";
return -1;
}
} else if (NRefOfVRef(vref) < expected_nref) {
RPC_VLOG << "SocketId=" << id()
<< " was abandoned during health checking";
return -1;
} else {
// nobody holds a health-checking-related reference,
// so no need to do health checking.
if (!_is_hc_related_ref_held) {