-
Notifications
You must be signed in to change notification settings - Fork 860
Expand file tree
/
Copy pathHostDB.cc
More file actions
1737 lines (1538 loc) · 57 KB
/
HostDB.cc
File metadata and controls
1737 lines (1538 loc) · 57 KB
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
/** @file
A brief file description
@section license License
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 "iocore/hostdb/HostDBProcessor.h"
#include "swoc/swoc_file.h"
#include "tscore/Regression.h"
#include "tsutil/ts_bw_format.h"
#include "P_HostDB.h"
// Gross
#include "../dns/P_SplitDNSProcessor.h"
#include "tscore/MgmtDefs.h" // MgmtInt, MgmtFloat, etc
#include "iocore/hostdb/HostFile.h"
#include <utility>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
#include <shared_mutex>
using std::chrono::duration_cast;
using swoc::round_down;
using swoc::round_up;
using swoc::TextView;
HostDBProcessor hostDBProcessor;
int HostDBProcessor::hostdb_strict_round_robin = 0;
int HostDBProcessor::hostdb_timed_round_robin = 0;
HostDBProcessor::Options const HostDBProcessor::DEFAULT_OPTIONS;
HostDBContinuation::Options const HostDBContinuation::DEFAULT_OPTIONS;
int hostdb_enable = true;
int hostdb_migrate_on_demand = true;
int hostdb_lookup_timeout = 30;
int hostdb_re_dns_on_reload = false;
int hostdb_ttl_mode = TTL_OBEY;
unsigned int hostdb_round_robin_max_count = 16;
unsigned int hostdb_ip_stale_interval = HOST_DB_IP_STALE;
unsigned int hostdb_ip_timeout_interval = HOST_DB_IP_TIMEOUT;
unsigned int hostdb_ip_fail_timeout_interval = HOST_DB_IP_FAIL_TIMEOUT;
unsigned int hostdb_serve_stale_but_revalidate = 0;
static ts_seconds hostdb_hostfile_check_interval{std::chrono::hours(24)};
// Epoch timestamp of the current hosts file check. This also functions as a
// cached version of ts_clock::now().
std::atomic<ts_time> hostdb_current_timestamp{TS_TIME_ZERO};
// Epoch timestamp of the last time we actually checked for a hosts file update.
static ts_time hostdb_last_timestamp{TS_TIME_ZERO};
// Epoch timestamp when we updated the hosts file last.
static ts_time hostdb_hostfile_update_timestamp{TS_TIME_ZERO};
int hostdb_max_count = DEFAULT_HOST_DB_SIZE;
static swoc::file::path hostdb_hostfile_path;
int hostdb_disable_reverse_lookup = 0;
int hostdb_max_iobuf_index = BUFFER_SIZE_INDEX_32K;
ClassAllocator<HostDBContinuation, false> hostDBContAllocator("hostDBContAllocator");
namespace
{
DbgCtl dbg_ctl_hostdb{"hostdb"};
DbgCtl dbg_ctl_dns_srv{"dns_srv"};
unsigned int
HOSTDB_CLIENT_IP_HASH(sockaddr const *lhs, IpAddr const &rhs)
{
unsigned int zret = ~static_cast<unsigned int>(0);
if (lhs->sa_family == rhs.family()) {
if (rhs.isIp4()) {
in_addr_t ip1 = ats_ip4_addr_cast(lhs);
in_addr_t ip2 = rhs._addr._ip4;
zret = (ip1 >> 16) ^ ip1 ^ ip2 ^ (ip2 >> 16);
} else if (rhs.isIp6()) {
uint32_t const *ip1 = ats_ip_addr32_cast(lhs);
uint32_t const *ip2 = rhs._addr._u32;
for (int i = 0; i < 4; ++i, ++ip1, ++ip2) {
zret ^= (*ip1 >> 16) ^ *ip1 ^ *ip2 ^ (*ip2 >> 16);
}
}
}
return zret & 0xFFFF;
}
} // namespace
// Static configuration information
HostDBCache hostDB;
void UpdateHostsFile(swoc::file::path const &path, ts_seconds interval);
static inline bool
is_addr_valid(uint8_t af, ///< Address family (format of data)
void *ptr ///< Raw address data (not a sockaddr variant!)
)
{
return (AF_INET == af && INADDR_ANY != *(reinterpret_cast<in_addr_t *>(ptr))) ||
(AF_INET6 == af && !IN6_IS_ADDR_UNSPECIFIED(reinterpret_cast<in6_addr *>(ptr)));
}
inline void
hostdb_cont_free(HostDBContinuation *cont)
{
if (cont->timeout) {
cont->timeout->cancel();
cont->timeout = nullptr;
}
cont->mutex = nullptr;
cont->action.mutex = nullptr;
hostDBContAllocator.free(cont);
}
/* Check whether a resolution fail should lead to a retry.
The @a mark argument is updated if appropriate.
@return @c true if @a mark was updated, @c false if no retry should be done.
*/
static inline bool
check_for_retry(HostDBMark &mark, HostResStyle style)
{
bool zret = true;
if (HOSTDB_MARK_IPV4 == mark && HOST_RES_IPV4 == style) {
mark = HOSTDB_MARK_IPV6;
} else if (HOSTDB_MARK_IPV6 == mark && HOST_RES_IPV6 == style) {
mark = HOSTDB_MARK_IPV4;
} else {
zret = false;
}
return zret;
}
//
// Function Prototypes
//
HostDBHash &
HostDBHash::set_host(TextView name)
{
host_name = name;
if (!host_name.empty() && SplitDNSConfig::isSplitDNSEnabled()) {
if (TS_SUCCESS != ip.load(host_name)) {
// config is released in the destructor, because we must make sure values we
// get out of it don't evaporate while @a this is still around.
if (!pSD) {
pSD = SplitDNSConfig::acquire();
}
if (pSD) {
dns_server = static_cast<DNSServer *>(pSD->getDNSRecord(host_name));
}
} else {
dns_server = nullptr;
}
}
return *this;
}
void
HostDBHash::refresh()
{
CryptoContext ctx;
if (host_name) {
const char *server_line = dns_server ? dns_server->x_dns_ip_line : nullptr;
uint8_t m = static_cast<uint8_t>(db_mark); // be sure of the type.
ctx.update(host_name.data(), host_name.size());
ctx.update(reinterpret_cast<uint8_t *>(&port), sizeof(port));
ctx.update(&m, sizeof(m));
if (server_line) {
ctx.update(server_line, strlen(server_line));
}
} else {
// CryptoHash the ip, pad on both sizes with 0's
// so that it does not intersect the string space
//
char buff[TS_IP6_SIZE + 4];
int n = ip.isIp6() ? sizeof(in6_addr) : sizeof(in_addr_t);
memset(buff, 0, 2);
memcpy(buff + 2, ip._addr._byte, n);
memset(buff + 2 + n, 0, 2);
ctx.update(buff, n + 4);
}
ctx.finalize(hash);
}
HostDBHash::~HostDBHash()
{
if (pSD) {
SplitDNSConfig::release(pSD);
}
}
HostDBCache::HostDBCache() {}
bool
HostDBCache::is_pending_dns_for_hash(const CryptoHash &hash)
{
ts::shared_mutex &bucket_lock = hostDB.refcountcache->lock_for_key(hash.fold());
std::shared_lock<ts::shared_mutex> lock{bucket_lock};
bool retval = false;
Queue<HostDBContinuation> &q = pending_dns_for_hash(hash);
for (HostDBContinuation *c = q.head; c; c = static_cast<HostDBContinuation *>(c->link.next)) {
if (hash == c->hash.hash) {
retval = true;
break;
}
}
return retval;
}
bool
HostDBCache::remove_from_pending_dns_for_hash(const CryptoHash &hash, HostDBContinuation *c)
{
bool retval = false;
ts::shared_mutex &bucket_lock = hostDB.refcountcache->lock_for_key(hash.fold());
std::unique_lock<ts::shared_mutex> lock{bucket_lock};
Queue<HostDBContinuation> &q = pending_dns_for_hash(hash);
if (q.in(c)) {
q.remove(c);
retval = true;
}
return retval;
}
std::shared_ptr<HostFile>
HostDBCache::acquire_host_file()
{
std::shared_lock lock(host_file_mutex);
auto zret = host_file;
return zret;
}
HostDBCache *
HostDBProcessor::cache()
{
return &hostDB;
}
int
HostDBCache::start(int flags)
{
(void)flags; // unused
MgmtInt hostdb_max_size = 0;
int hostdb_partitions = 64;
// Read configuration
// Command line overrides manager configuration.
//
hostdb_enable = RecGetRecordInt("proxy.config.hostdb.enabled").value_or(0);
// Max number of items
hostdb_max_count = RecGetRecordInt("proxy.config.hostdb.max_count").value_or(0);
// max size allowed to use
hostdb_max_size = RecGetRecordInt("proxy.config.hostdb.max_size").value_or(0);
// number of partitions
hostdb_partitions = RecGetRecordInt("proxy.config.hostdb.partitions").value_or(0);
RecEstablishStaticConfigInt32(hostdb_max_iobuf_index, "proxy.config.hostdb.io.max_buffer_index");
if (hostdb_max_size == 0) {
Fatal("proxy.config.hostdb.max_size must be a non-zero number");
}
// Setup the ref-counted cache (this must be done regardless of syncing or not).
this->refcountcache =
new RefCountCache<HostDBRecord>(hostdb_partitions, hostdb_max_size, hostdb_max_count, "proxy.process.hostdb.cache.");
this->pending_dns = new Queue<HostDBContinuation, Continuation::Link_link>[hostdb_partitions];
this->remoteHostDBQueue = new Queue<HostDBContinuation, Continuation::Link_link>[hostdb_partitions];
return 0;
}
// Start up the Host Database processor.
// Load configuration, register configuration and statistics and
// open the cache. This doesn't create any threads, so those
// parameters are ignored.
//
int
HostDBProcessor::start(int, size_t)
{
if (hostDB.start(0) < 0) {
return -1;
}
return init();
}
int
HostDBProcessor::init()
{
//
// Register configuration callback, and establish configuration links
//
RecEstablishStaticConfigInt32(hostdb_ttl_mode, "proxy.config.hostdb.ttl_mode");
RecEstablishStaticConfigInt32(hostdb_disable_reverse_lookup, "proxy.config.cache.hostdb.disable_reverse_lookup");
RecEstablishStaticConfigInt32(hostdb_re_dns_on_reload, "proxy.config.hostdb.re_dns_on_reload");
RecEstablishStaticConfigInt32(hostdb_migrate_on_demand, "proxy.config.hostdb.migrate_on_demand");
RecEstablishStaticConfigInt32(hostdb_strict_round_robin, "proxy.config.hostdb.strict_round_robin");
RecEstablishStaticConfigInt32(hostdb_timed_round_robin, "proxy.config.hostdb.timed_round_robin");
RecEstablishStaticConfigInt32(hostdb_lookup_timeout, "proxy.config.hostdb.lookup_timeout");
RecEstablishStaticConfigUInt32(hostdb_ip_timeout_interval, "proxy.config.hostdb.timeout");
RecEstablishStaticConfigUInt32(hostdb_ip_stale_interval, "proxy.config.hostdb.verify_after");
RecEstablishStaticConfigUInt32(hostdb_ip_fail_timeout_interval, "proxy.config.hostdb.fail.timeout");
RecEstablishStaticConfigUInt32(hostdb_serve_stale_but_revalidate, "proxy.config.hostdb.serve_stale_for");
RecEstablishStaticConfigUInt32(hostdb_round_robin_max_count, "proxy.config.hostdb.round_robin_max_count");
const char *interval_config = "proxy.config.hostdb.host_file.interval";
{
RecInt tmp_interval{};
tmp_interval = RecGetRecordInt(interval_config).value_or(0);
hostdb_hostfile_check_interval = std::chrono::seconds(tmp_interval);
}
RecRegisterConfigUpdateCb(
interval_config,
[&](const char *, RecDataT, RecData data, void *) {
hostdb_hostfile_check_interval = std::chrono::seconds(data.rec_int);
return REC_ERR_OKAY;
},
nullptr);
//
// Initialize hostdb_current_timestamp which is our cached version of
// ts_clock::now().
//
hostdb_current_timestamp = ts_clock::now();
HostDBContinuation *b = hostDBContAllocator.alloc();
SET_CONTINUATION_HANDLER(b, &HostDBContinuation::backgroundEvent);
b->mutex = new_ProxyMutex();
eventProcessor.schedule_every(b, HRTIME_SECONDS(1), ET_DNS);
return 0;
}
void
HostDBContinuation::init(HostDBHash const &the_hash, Options const &opt)
{
hash = the_hash;
hash.host_name = hash.host_name.prefix(static_cast<int>(sizeof(hash_host_name_store) - 1));
if (!hash.host_name.empty()) {
// copy to backing store.
memcpy(hash_host_name_store, hash.host_name);
}
hash_host_name_store[hash.host_name.size()] = 0;
hash.host_name.assign(hash_host_name_store, hash.host_name.size());
host_res_style = opt.host_res_style;
dns_lookup_timeout = opt.timeout;
mutex = new_ProxyMutex();
timeout = nullptr;
if (opt.cont) {
action = opt.cont;
} else {
// ink_assert(!"this sucks");
ink_zero(action);
action.mutex = mutex;
}
}
void
HostDBContinuation::refresh_hash()
{
// We're not pending DNS anymore.
remove_and_trigger_pending_dns();
hash.refresh();
}
static bool
reply_to_cont(Continuation *cont, HostDBRecord *r, bool is_srv = false)
{
if (r == nullptr || r->is_srv() != is_srv || r->is_failed()) {
cont->handleEvent(is_srv ? EVENT_SRV_LOOKUP : EVENT_HOST_DB_LOOKUP, nullptr);
return false;
}
if (r->record_type != HostDBType::HOST) {
if (!r->name()) {
ink_assert(!"missing hostname");
cont->handleEvent(is_srv ? EVENT_SRV_LOOKUP : EVENT_HOST_DB_LOOKUP, nullptr);
Warning("bogus entry deleted from HostDB: missing hostname");
hostDB.refcountcache->erase(r->key);
return false;
}
Dbg(dbg_ctl_hostdb, "hostname = %s", r->name());
}
cont->handleEvent(is_srv ? EVENT_SRV_LOOKUP : EVENT_HOST_DB_LOOKUP, r);
return true;
}
inline HostResStyle
host_res_style_for(HostDBMark mark)
{
return HOSTDB_MARK_IPV4 == mark ? HOST_RES_IPV4_ONLY : HOSTDB_MARK_IPV6 == mark ? HOST_RES_IPV6_ONLY : HOST_RES_NONE;
}
inline HostDBMark
db_mark_for(HostResStyle style)
{
HostDBMark zret = HOSTDB_MARK_GENERIC;
if (HOST_RES_IPV4 == style || HOST_RES_IPV4_ONLY == style) {
zret = HOSTDB_MARK_IPV4;
} else if (HOST_RES_IPV6 == style || HOST_RES_IPV6_ONLY == style) {
zret = HOSTDB_MARK_IPV6;
}
return zret;
}
HostDBRecord::Handle
probe_ip(HostDBHash const &hash)
{
HostDBRecord::Handle result;
if (hash.is_byname()) {
Dbg(dbg_ctl_hostdb, "DNS %.*s", int(hash.host_name.size()), hash.host_name.data());
IpAddr tip;
if (0 == tip.load(hash.host_name)) {
result = HostDBRecord::Handle{HostDBRecord::alloc(hash.host_name, 1, 0, hash.port)};
result->af_family = tip.family();
auto &info = result->rr_info()[0];
info.assign(tip);
}
}
return result;
}
HostDBRecord::Handle
probe_hostfile(HostDBHash const &hash)
{
HostDBRecord::Handle result;
// Check if this can be fulfilled by the host file
//
if (auto static_hosts = hostDB.acquire_host_file(); static_hosts) {
result = static_hosts->lookup(hash);
}
return result;
}
HostDBRecord::Handle
probe(HostDBHash const &hash, bool ignore_timeout)
{
static const Ptr<HostDBRecord> NO_RECORD;
// If hostdb is disabled, don't return anything
if (!hostdb_enable) {
return NO_RECORD;
}
// Otherwise HostDB is enabled, so we'll do our thing
uint64_t folded_hash = hash.hash.fold();
ts::shared_mutex &bucket_lock = hostDB.refcountcache->lock_for_key(folded_hash);
Ptr<HostDBRecord> record;
{
std::shared_lock<ts::shared_mutex> lock{bucket_lock};
// get the record from cache
record = hostDB.refcountcache->get(folded_hash);
// If there was nothing in the cache-- this is a miss
if (record.get() == nullptr) {
record = probe_ip(hash);
if (!record) {
record = probe_hostfile(hash);
}
return record;
}
// If the dns response was failed, and we've hit the failed timeout, lets stop returning it
if (record->is_failed() && record->is_ip_fail_timeout()) {
return NO_RECORD;
// if we aren't ignoring timeouts, and we are past it-- then remove the record
} else if (!ignore_timeout && record->is_ip_timeout() && !record->serve_stale_but_revalidate()) {
Metrics::Counter::increment(hostdb_rsb.ttl_expires);
return NO_RECORD;
}
}
// If the record is stale, but we want to revalidate-- lets start that up
if ((!ignore_timeout && record->is_ip_configured_stale() && record->record_type != HostDBType::HOST) ||
(record->is_ip_timeout() && record->serve_stale_but_revalidate())) {
Metrics::Counter::increment(hostdb_rsb.total_serve_stale);
if (hostDB.is_pending_dns_for_hash(hash.hash)) {
Dbg(dbg_ctl_hostdb, "%s",
swoc::bwprint(ts::bw_dbg, "stale {} {} {}, using with pending refresh", record->ip_age(),
record->ip_timestamp.time_since_epoch(), record->ip_timeout_interval)
.c_str());
return record;
}
Dbg(dbg_ctl_hostdb, "%s",
swoc::bwprint(ts::bw_dbg, "stale {} {} {}, using while refresh", record->ip_age(), record->ip_timestamp.time_since_epoch(),
record->ip_timeout_interval)
.c_str());
HostDBContinuation *c = hostDBContAllocator.alloc();
HostDBContinuation::Options copt;
copt.host_res_style = record->af_family == AF_INET6 ? HOST_RES_IPV6_ONLY : HOST_RES_IPV4_ONLY;
c->init(hash, copt);
SCOPED_MUTEX_LOCK(lock, c->mutex, this_ethread());
c->do_dns();
}
return record;
}
//
// Get an entry by either name or IP
//
Action *
HostDBProcessor::getby(Continuation *cont, cb_process_result_pfn cb_process_result, HostDBHash &hash, Options const &opt)
{
bool force_dns = false;
bool delay_reschedule = false;
EThread *thread = this_ethread();
Ptr<ProxyMutex> mutex = thread->mutex;
ip_text_buffer ipb;
if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS) {
force_dns = true;
} else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
force_dns = hostdb_re_dns_on_reload;
if (force_dns) {
Metrics::Counter::increment(hostdb_rsb.re_dns_on_reload);
}
}
Metrics::Counter::increment(hostdb_rsb.total_lookups);
if (!hostdb_enable || // if the HostDB is disabled,
(hash.host_name && !*hash.host_name) || // or host_name is empty string
(hostdb_disable_reverse_lookup && hash.ip.isValid())) { // or try to lookup by ip address when the reverse lookup disabled
if (cb_process_result) {
(cont->*cb_process_result)(nullptr);
} else {
MUTEX_TRY_LOCK(lock, cont->mutex, thread);
if (!lock.is_locked()) {
delay_reschedule = true;
goto Lretry;
}
cont->handleEvent(EVENT_HOST_DB_LOOKUP, nullptr);
}
return ACTION_RESULT_DONE;
}
// Attempt to find the result in-line, for level 1 hits
if (!force_dns) {
MUTEX_TRY_LOCK(lock, cont->mutex, thread);
bool loop = lock.is_locked();
while (loop) {
loop = false; // Only loop on explicit set for retry.
// find the partition lock
ts::shared_mutex &bucket_lock = hostDB.refcountcache->lock_for_key(hash.hash.fold());
// If we can get the lock and a level 1 probe succeeds, return
HostDBRecord::Handle r = probe(hash, false);
std::shared_lock<ts::shared_mutex> lock{bucket_lock};
if (r) {
// fail, see if we should retry with alternate
if (hash.db_mark != HOSTDB_MARK_SRV && r->is_failed() && hash.host_name) {
loop = check_for_retry(hash.db_mark, opt.host_res_style);
}
if (!loop) {
// No retry -> final result. Return it.
if (hash.db_mark == HOSTDB_MARK_SRV) {
Dbg(dbg_ctl_hostdb, "immediate SRV answer for %.*s from hostdb", int(hash.host_name.size()), hash.host_name.data());
Dbg(dbg_ctl_dns_srv, "immediate SRV answer for %.*s from hostdb", int(hash.host_name.size()), hash.host_name.data());
} else if (hash.host_name) {
Dbg(dbg_ctl_hostdb, "immediate answer for %.*s", int(hash.host_name.size()), hash.host_name.data());
} else {
Dbg(dbg_ctl_hostdb, "immediate answer for %s", hash.ip.isValid() ? hash.ip.toString(ipb, sizeof ipb) : "<null>");
}
Metrics::Counter::increment(hostdb_rsb.total_hits);
if (cb_process_result) {
(cont->*cb_process_result)(r.get());
} else {
reply_to_cont(cont, r.get());
}
return ACTION_RESULT_DONE;
}
hash.refresh(); // only on reloop, because we've changed the family.
}
}
}
if (hash.db_mark == HOSTDB_MARK_SRV) {
Dbg(dbg_ctl_hostdb, "delaying (force=%d) SRV answer for %.*s [timeout = %d]", force_dns, int(hash.host_name.size()),
hash.host_name.data(), opt.timeout);
Dbg(dbg_ctl_dns_srv, "delaying (force=%d) SRV answer for %.*s [timeout = %d]", force_dns, int(hash.host_name.size()),
hash.host_name.data(), opt.timeout);
} else if (hash.host_name) {
Dbg(dbg_ctl_hostdb, "delaying (force=%d) answer for %.*s [timeout %d]", force_dns, int(hash.host_name.size()),
hash.host_name.data(), opt.timeout);
} else {
Dbg(dbg_ctl_hostdb, "delaying (force=%d) answer for %s [timeout %d]", force_dns,
hash.ip.isValid() ? hash.ip.toString(ipb, sizeof ipb) : "<null>", opt.timeout);
}
Lretry:
// Otherwise, create a continuation to do a deeper probe in the background
//
HostDBContinuation *c = hostDBContAllocator.alloc();
HostDBContinuation::Options copt;
copt.timeout = opt.timeout;
copt.force_dns = force_dns;
copt.cont = cont;
copt.host_res_style = (hash.db_mark == HOSTDB_MARK_SRV) ? HOST_RES_NONE : opt.host_res_style;
c->init(hash, copt);
SET_CONTINUATION_HANDLER(c, &HostDBContinuation::probeEvent);
if (delay_reschedule) {
c->timeout = thread->schedule_in(c, MUTEX_RETRY_DELAY);
} else {
thread->schedule_imm(c);
}
return &c->action;
}
// Wrapper from getbyname to getby
//
Action *
HostDBProcessor::getbyname_re(Continuation *cont, const char *ahostname, int len, Options const &opt)
{
HostDBHash hash;
ink_assert(nullptr != ahostname);
// Load the hash data.
hash.set_host({ahostname, ahostname ? (len ? len : strlen(ahostname)) : 0});
// Leave hash.ip invalid
hash.port = 0;
hash.db_mark = db_mark_for(opt.host_res_style);
hash.refresh();
return getby(cont, nullptr, hash, opt);
}
Action *
HostDBProcessor::getbynameport_re(Continuation *cont, const char *ahostname, int len, Options const &opt)
{
HostDBHash hash;
ink_assert(nullptr != ahostname);
// Load the hash data.
hash.set_host({ahostname, ahostname ? (len ? len : strlen(ahostname)) : 0});
// Leave hash.ip invalid
hash.port = opt.port;
hash.db_mark = db_mark_for(opt.host_res_style);
hash.refresh();
return getby(cont, nullptr, hash, opt);
}
// Lookup Hostinfo by addr
Action *
HostDBProcessor::getbyaddr_re(Continuation *cont, sockaddr const *aip)
{
HostDBHash hash;
ink_assert(nullptr != aip);
HostDBProcessor::Options opt;
opt.host_res_style = HOST_RES_NONE;
// Leave hash.host_name as nullptr
hash.ip.assign(aip);
hash.port = ats_ip_port_host_order(aip);
hash.db_mark = db_mark_for(opt.host_res_style);
hash.refresh();
return getby(cont, nullptr, hash, opt);
}
/* Support SRV records */
Action *
HostDBProcessor::getSRVbyname_imm(Continuation *cont, cb_process_result_pfn process_srv_info, const char *hostname, int len,
Options const &opt)
{
ink_assert(cont->mutex->thread_holding == this_ethread());
HostDBHash hash;
ink_assert(nullptr != hostname);
hash.set_host({hostname, len ? len : strlen(hostname)});
// Leave hash.ip invalid
hash.port = 0;
hash.db_mark = HOSTDB_MARK_SRV;
hash.refresh();
return getby(cont, process_srv_info, hash, opt);
}
// Wrapper from getbyname to getby
//
Action *
HostDBProcessor::getbyname_imm(Continuation *cont, cb_process_result_pfn process_hostdb_info, const char *hostname, int len,
Options const &opt)
{
ink_assert(cont->mutex->thread_holding == this_ethread());
HostDBHash hash;
ink_assert(nullptr != hostname);
hash.set_host({hostname, len ? len : strlen(hostname)});
// Leave hash.ip invalid
// TODO: May I rename the wrapper name to getbynameport_imm ? - oknet
// By comparing getbyname_re and getbynameport_re, the hash.port should be 0 if only get hostinfo by name.
hash.port = opt.port;
hash.db_mark = db_mark_for(opt.host_res_style);
hash.refresh();
return getby(cont, process_hostdb_info, hash, opt);
}
// Lookup done, insert into the local table, return data to the
// calling continuation.
// NOTE: if "i" exists it means we already allocated the space etc, just return
//
Ptr<HostDBRecord>
HostDBContinuation::lookup_done(TextView query_name, ts_seconds answer_ttl, SRVHosts *srv, Ptr<HostDBRecord> record)
{
ink_assert(record);
if (query_name.empty()) {
if (hash.is_byname()) {
Dbg(dbg_ctl_hostdb, "lookup_done() failed for '%.*s'", int(hash.host_name.size()), hash.host_name.data());
record->record_type = HostDBType::ADDR;
} else if (hash.is_srv()) {
Dbg(dbg_ctl_dns_srv, "SRV failed for '%.*s'", int(hash.host_name.size()), hash.host_name.data());
record->record_type = HostDBType::SRV;
} else {
ip_text_buffer b;
Dbg(dbg_ctl_hostdb, "failed for %s", hash.ip.toString(b, sizeof b));
record->record_type = HostDBType::HOST;
}
record->ip_timestamp = hostdb_current_timestamp;
record->ip_timeout_interval = ts_seconds(std::clamp(hostdb_ip_fail_timeout_interval, 1u, HOST_DB_MAX_TTL));
record->set_failed();
} else {
switch (hostdb_ttl_mode) {
default:
ink_assert(!"bad TTL mode");
case TTL_OBEY:
break;
case TTL_IGNORE:
answer_ttl = ts_seconds(hostdb_ip_timeout_interval);
break;
case TTL_MIN:
if (ts_seconds(hostdb_ip_timeout_interval) < answer_ttl) {
answer_ttl = ts_seconds(hostdb_ip_timeout_interval);
}
break;
case TTL_MAX:
if (ts_seconds(hostdb_ip_timeout_interval) > answer_ttl) {
answer_ttl = ts_seconds(hostdb_ip_timeout_interval);
}
break;
}
Metrics::Counter::increment(hostdb_rsb.ttl, answer_ttl.count());
// update the TTL
record->ip_timestamp = hostdb_current_timestamp;
record->ip_timeout_interval = std::clamp(answer_ttl, ts_seconds(1), ts_seconds(HOST_DB_MAX_TTL));
if (hash.is_byname()) {
Dbg_bw(dbg_ctl_hostdb, "done {} TTL {}", hash.host_name, answer_ttl);
record->record_type = HostDBType::ADDR;
} else if (hash.is_srv()) {
ink_assert(srv && srv->hosts.size() && srv->hosts.size() <= hostdb_round_robin_max_count);
record->record_type = HostDBType::SRV;
} else {
Dbg_bw(dbg_ctl_hostdb, "done {} TTL {}", hash.host_name, answer_ttl);
record->record_type = HostDBType::HOST;
}
}
return record;
}
int
HostDBContinuation::dnsPendingEvent(int event, Event *e)
{
if (timeout) {
timeout->cancel(this);
timeout = nullptr;
}
if (event == EVENT_INTERVAL) {
// we timed out, return a failure to the user
MUTEX_TRY_LOCK(lock, action.mutex, ((Event *)e)->ethread);
if (!lock.is_locked()) {
timeout = eventProcessor.schedule_in(this, HOST_DB_RETRY_PERIOD);
return EVENT_CONT;
}
if (!action.cancelled && action.continuation) {
action.continuation->handleEvent(EVENT_HOST_DB_LOOKUP, nullptr);
}
if (hostDB.remove_from_pending_dns_for_hash(hash.hash, this)) {
hostdb_cont_free(this);
}
return EVENT_DONE;
} else {
SET_HANDLER(&HostDBContinuation::probeEvent);
return probeEvent(EVENT_INTERVAL, nullptr);
}
}
// DNS lookup result state
int
HostDBContinuation::dnsEvent(int event, HostEnt *e)
{
if (timeout) {
timeout->cancel(this);
timeout = nullptr;
}
EThread *thread = mutex->thread_holding;
if (event != DNS_EVENT_LOOKUP) {
// Event should be immediate or interval.
if (!action.continuation) {
// Nothing to do, give up.
if (event == EVENT_INTERVAL) {
// Timeout - clear all queries queued up for this FQDN because none of the other ones have sent an
// actual DNS query. If the request rate is high enough this can cause a persistent queue where the
// DNS query is never sent and all requests timeout, even if it was a transient error.
// See issue #8417.
remove_and_trigger_pending_dns();
} else {
// "local" signal to give up, usually due this being one of those "other" queries.
// That generally means @a this has already been removed from the queue, but just in case...
hostDB.pending_dns_for_hash(hash.hash).remove(this);
}
if (hostDB.remove_from_pending_dns_for_hash(hash.hash, this)) {
hostdb_cont_free(this);
}
return EVENT_DONE;
}
MUTEX_TRY_LOCK(lock, action.mutex, thread);
if (!lock.is_locked()) {
timeout = thread->schedule_in(this, HOST_DB_RETRY_PERIOD);
return EVENT_CONT;
}
// [amc] Callback to client to indicate a failure due to timeout.
// We don't try a different family here because a timeout indicates
// a server issue that won't be fixed by asking for a different
// address family.
if (!action.cancelled && action.continuation) {
action.continuation->handleEvent(EVENT_HOST_DB_LOOKUP, nullptr);
}
action = nullptr;
return EVENT_DONE;
} else {
bool failed = !e || !e->good;
pending_action = nullptr;
ttl = ts_seconds(failed ? 0 : e->ttl);
Ptr<HostDBRecord> old_r = probe(hash, false);
// If the DNS lookup failed with NXDOMAIN, remove the old record
if (e && e->isNameError() && old_r) {
hostDB.refcountcache->erase(old_r->key);
old_r = nullptr;
Dbg(dbg_ctl_hostdb, "Removing the old record when the DNS lookup failed with NXDOMAIN");
}
int valid_records = 0;
void *first_record = nullptr;
sa_family_t af = e ? e->ent.h_addrtype : AF_UNSPEC; // address family
// Find the first record and total number of records.
if (!failed) {
if (hash.is_srv()) {
valid_records = e->srv_hosts.hosts.size();
} else {
void *ptr; // tmp for current entry.
for (int total_records = 0;
total_records < static_cast<int>(hostdb_round_robin_max_count) && nullptr != (ptr = e->ent.h_addr_list[total_records]);
++total_records) {
if (is_addr_valid(af, ptr)) {
if (!first_record) {
first_record = ptr;
}
// If we have found some records which are invalid, lets just shuffle around them.
// This way we'll end up with e->ent.h_addr_list with all the valid responses at
// the first `valid_records` slots
if (valid_records != total_records) {
e->ent.h_addr_list[valid_records] = e->ent.h_addr_list[total_records];
}
++valid_records;
} else {
Warning("Invalid address removed for '%.*s'", int(hash.host_name.size()), hash.host_name.data());
}
}
if (!first_record) {
failed = true;
}
}
} // else first is nullptr
// In the event that the lookup failed (SOA response-- for example) we want to use hash.host_name, since it'll be ""
TextView query_name = (failed || !hash.host_name.empty()) ? hash.host_name : TextView{e->ent.h_name, strlen(e->ent.h_name)};
HostDBRecord::Handle r{HostDBRecord::alloc(query_name, valid_records, failed ? 0 : e->srv_hosts.srv_hosts_length, hash.port)};
r->key = hash.hash.fold(); // always set the key
r->af_family = af;
r->flags.f.failed_p = failed;
// If the DNS lookup failed (errors such as SERVFAIL, etc.) but we have an old record
// which is okay with being served stale-- lets continue to serve the stale record as long as
// the record is willing to be served.
bool serve_stale = false;
if (failed && old_r && old_r->serve_stale_but_revalidate()) {
r = old_r;
serve_stale = true;
} else if (hash.is_byname()) {
lookup_done(hash.host_name, ttl, failed ? nullptr : &e->srv_hosts, r);
} else if (hash.is_srv()) {
lookup_done(hash.host_name, /* hostname */
ttl, /* ttl in seconds */
failed ? nullptr : &e->srv_hosts, r);
} else if (failed) {
lookup_done(hash.host_name, ttl, nullptr, r);
} else {
lookup_done(e->ent.h_name, ttl, &e->srv_hosts, r);
}
if (!failed) { // implies r != old_r
auto rr_info = r->rr_info();
// Fill in record type specific data.
if (hash.is_srv()) {
char *pos = rr_info.rebind<char>().end();
SRV *q[valid_records];
ink_assert(valid_records <= static_cast<int>(hostdb_round_robin_max_count));
for (int i = 0; i < valid_records; ++i) {
q[i] = &e->srv_hosts.hosts[i];
}
std::sort(q, q + valid_records, [](SRV *lhs, SRV *rhs) -> bool { return *lhs < *rhs; });
SRV **cur_srv = q;
for (auto &item : rr_info) {
auto t = *cur_srv++; // get next SRV record pointer.
memcpy(pos, t->host, t->host_len); // Append the name to the overall record.
item.assign(t, pos);
pos += t->host_len;
if (old_r) { // migrate as needed.
for (auto &old_item : old_r->rr_info()) {
if (item.data.srv.key == old_item.data.srv.key && 0 == strcmp(item.srvname(), old_item.srvname())) {
item.migrate_from(old_item);
break;
}
}
}
// Archetypical example - "%zd" doesn't work on FreeBSD, "%ld" doesn't work on Ubuntu, "%lld" doesn't work on Fedora.
Dbg_bw(dbg_ctl_dns_srv, "inserted SRV RR record [{}] into HostDB with TTL: {} seconds", item.srvname(), ttl);
}
} else { // Otherwise this is a regular dns response
unsigned idx = 0;
for (auto &item : rr_info) {
item.assign(af, e->ent.h_addr_list[idx++]);
if (old_r) { // migrate as needed.
for (auto &old_item : old_r->rr_info()) {
if (item.data.ip == old_item.data.ip) {
item.migrate_from(old_item);
break;
}
}
}
}
}
}
if (!serve_stale) { // implies r != old_r
ts::shared_mutex &bucket_lock = hostDB.refcountcache->lock_for_key(hash.hash.fold());
std::unique_lock<ts::shared_mutex> lock{bucket_lock};
auto const duration_till_revalidate = r->expiry_time().time_since_epoch();
auto const seconds_till_revalidate = duration_cast<ts_seconds>(duration_till_revalidate).count();
hostDB.refcountcache->put(r->key, r.get(), r->_record_size, seconds_till_revalidate);
} else {
Warning("Fallback to serving stale record, skip re-update of hostdb for %.*s", int(query_name.size()), query_name.data());
}