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
|
/** @file
Outbound connection tracking support.
@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 <algorithm>
#include <deque>
#include <records/P_RecDefs.h>
#include <HttpConfig.h>
#include "HttpConnectionCount.h"
#include "tscore/bwf_std_format.h"
#include "tscore/BufferWriter.h"
using namespace std::literals;
extern int http_config_cb(const char *, RecDataT, RecData, void *);
OutboundConnTrack::Imp OutboundConnTrack::_imp;
OutboundConnTrack::GlobalConfig *OutboundConnTrack::_global_config{nullptr};
const MgmtConverter OutboundConnTrack::MAX_CONV(
[](const void *data) -> MgmtInt { return static_cast<MgmtInt>(*static_cast<const decltype(TxnConfig::max) *>(data)); },
[](void *data, MgmtInt i) -> void { *static_cast<decltype(TxnConfig::max) *>(data) = static_cast<decltype(TxnConfig::max)>(i); });
const MgmtConverter OutboundConnTrack::MIN_CONV(
[](const void *data) -> MgmtInt { return static_cast<MgmtInt>(*static_cast<const decltype(TxnConfig::min) *>(data)); },
[](void *data, MgmtInt i) -> void { *static_cast<decltype(TxnConfig::min) *>(data) = static_cast<decltype(TxnConfig::min)>(i); });
// Do integer and string conversions.
const MgmtConverter OutboundConnTrack::MATCH_CONV{
[](const void *data) -> MgmtInt { return static_cast<MgmtInt>(*static_cast<const decltype(TxnConfig::match) *>(data)); },
[](void *data, MgmtInt i) -> void {
// Problem - the InkAPITest requires being able to set an arbitrary value, so this can either
// correctly clamp or pass the regression tests. Currently it passes the tests.
// *static_cast<decltype(TxnConfig::match) *>(data) = std::clamp(static_cast<decltype(TxnConfig::match)>(i), MATCH_IP,
// MATCH_BOTH);
*static_cast<decltype(TxnConfig::match) *>(data) = static_cast<decltype(TxnConfig::match)>(i);
},
nullptr,
nullptr,
[](const void *data) -> std::string_view {
auto t = *static_cast<const OutboundConnTrack::MatchType *>(data);
return t < 0 || t > OutboundConnTrack::MATCH_BOTH ? "Invalid"sv : OutboundConnTrack::MATCH_TYPE_NAME[t];
},
[](void *data, std::string_view src) -> void {
OutboundConnTrack::MatchType t;
if (OutboundConnTrack::lookup_match_type(src, t)) {
*static_cast<OutboundConnTrack::MatchType *>(data) = t;
} else {
OutboundConnTrack::Warning_Bad_Match_Type(src);
}
}};
const std::array<std::string_view, static_cast<int>(OutboundConnTrack::MATCH_BOTH) + 1> OutboundConnTrack::MATCH_TYPE_NAME{
{"ip"sv, "port"sv, "host"sv, "both"sv}};
// Make sure the clock is millisecond resolution or finer.
static_assert(OutboundConnTrack::Group::Clock::period::num == 1);
static_assert(OutboundConnTrack::Group::Clock::period::den >= 1000);
// Configuration callback functions.
namespace
{
bool
Config_Update_Conntrack_Min(const char *name, RecDataT dtype, RecData data, void *cookie)
{
auto config = static_cast<OutboundConnTrack::TxnConfig *>(cookie);
if (RECD_INT == dtype) {
config->min = data.rec_int;
return true;
}
return false;
}
bool
Config_Update_Conntrack_Max(const char *name, RecDataT dtype, RecData data, void *cookie)
{
auto config = static_cast<OutboundConnTrack::TxnConfig *>(cookie);
if (RECD_INT == dtype) {
config->max = data.rec_int;
return true;
}
return false;
}
bool
Config_Update_Conntrack_Queue_Size(const char *name, RecDataT dtype, RecData data, void *cookie)
{
auto config = static_cast<OutboundConnTrack::GlobalConfig *>(cookie);
if (RECD_INT == dtype) {
config->queue_size = data.rec_int;
return true;
}
return false;
}
bool
Config_Update_Conntrack_Queue_Delay(const char *name, RecDataT dtype, RecData data, void *cookie)
{
auto config = static_cast<OutboundConnTrack::GlobalConfig *>(cookie);
if (RECD_INT == dtype && data.rec_int > 0) {
config->queue_delay = std::chrono::milliseconds(data.rec_int);
return true;
}
return false;
}
bool
Config_Update_Conntrack_Match(const char *name, RecDataT dtype, RecData data, void *cookie)
{
auto config = static_cast<OutboundConnTrack::TxnConfig *>(cookie);
if (RECD_STRING == dtype) {
OutboundConnTrack::MatchType match_type;
std::string_view tag{data.rec_string};
if (OutboundConnTrack::lookup_match_type(tag, match_type)) {
config->match = match_type;
return true;
} else {
OutboundConnTrack::Warning_Bad_Match_Type(tag);
}
} else {
Warning("Invalid type for '%s' - must be 'INT'", OutboundConnTrack::CONFIG_VAR_MATCH.data());
}
return false;
}
bool
Config_Update_Conntrack_Alert_Delay(const char *name, RecDataT dtype, RecData data, void *cookie)
{
auto config = static_cast<OutboundConnTrack::GlobalConfig *>(cookie);
if (RECD_INT == dtype && data.rec_int >= 0) {
config->alert_delay = std::chrono::seconds(data.rec_int);
return true;
}
return false;
}
} // namespace
void
OutboundConnTrack::config_init(GlobalConfig *global, TxnConfig *txn)
{
_global_config = global; // remember this for later retrieval.
// Per transaction lookup must be done at call time because it changes.
Enable_Config_Var(CONFIG_VAR_MIN, &Config_Update_Conntrack_Min, txn);
Enable_Config_Var(CONFIG_VAR_MAX, &Config_Update_Conntrack_Max, txn);
Enable_Config_Var(CONFIG_VAR_MATCH, &Config_Update_Conntrack_Match, txn);
Enable_Config_Var(CONFIG_VAR_QUEUE_SIZE, &Config_Update_Conntrack_Queue_Size, global);
Enable_Config_Var(CONFIG_VAR_QUEUE_DELAY, &Config_Update_Conntrack_Queue_Delay, global);
Enable_Config_Var(CONFIG_VAR_ALERT_DELAY, &Config_Update_Conntrack_Alert_Delay, global);
}
OutboundConnTrack::TxnState
OutboundConnTrack::obtain(TxnConfig const &txn_cnf, std::string_view fqdn, IpEndpoint const &addr)
{
TxnState zret;
CryptoHash hash;
CryptoContext().hash_immediate(hash, fqdn.data(), fqdn.size());
Group::Key key{addr, hash, txn_cnf.match};
std::lock_guard<std::mutex> lock(_imp._mutex); // Table lock
auto loc = _imp._table.find(key);
if (loc != _imp._table.end()) {
zret._g = loc;
} else {
zret._g = new Group(key, fqdn, txn_cnf.min);
_imp._table.insert(zret._g);
}
return zret;
}
bool
OutboundConnTrack::Group::equal(const Key &lhs, const Key &rhs)
{
bool zret = false;
if (lhs._match_type == rhs._match_type) {
switch (lhs._match_type) {
case MATCH_IP:
zret = ats_ip_addr_eq(&lhs._addr.sa, &rhs._addr.sa);
break;
case MATCH_PORT:
zret = ats_ip_addr_port_eq(&lhs._addr.sa, &rhs._addr.sa);
break;
case MATCH_HOST:
zret = lhs._hash == rhs._hash;
break;
case MATCH_BOTH:
zret = (lhs._hash == rhs._hash && ats_ip_addr_port_eq(&lhs._addr.sa, &rhs._addr.sa));
break;
}
}
if (is_debug_tag_set(DEBUG_TAG)) {
ts::LocalBufferWriter<256> w;
w.print("Comparing {} to {} -> {}\0", lhs, rhs, zret ? "match" : "fail");
Debug(DEBUG_TAG, "%s", w.data());
}
return zret;
}
bool
OutboundConnTrack::Group::should_alert(std::time_t *lat)
{
bool zret = false;
// This is a bit clunky because the goal is to store just the tick count as an atomic.
// Might check to see if an atomic time_point is really atomic and avoid this.
Ticker last_tick{_last_alert}; // Load the most recent alert time in ticks.
TimePoint last{TimePoint::duration{last_tick}}; // Most recent alert time in a time_point.
TimePoint now = Clock::now(); // Current time_point.
if (last + _global_config->alert_delay <= now) {
// it's been long enough, swap out our time for the last time. The winner of this swap
// does the actual alert, leaving its current time as the last alert time.
zret = _last_alert.compare_exchange_strong(last_tick, now.time_since_epoch().count());
if (zret && lat) {
*lat = Clock::to_time_t(last);
}
}
return zret;
}
std::time_t
OutboundConnTrack::Group::get_last_alert_epoch_time() const
{
return Clock::to_time_t(TimePoint{TimePoint::duration{Ticker{_last_alert}}});
}
void
OutboundConnTrack::get(std::vector<Group const *> &groups)
{
std::lock_guard<std::mutex> lock(_imp._mutex); // TABLE LOCK
groups.resize(0);
groups.reserve(_imp._table.count());
for (Group const &g : _imp._table) {
groups.push_back(&g);
}
}
std::string
OutboundConnTrack::to_json_string()
{
std::string text;
size_t extent = 0;
static const ts::BWFormat header_fmt{R"({{"count": {}, "list": [
)"};
static const ts::BWFormat item_fmt{
R"( {{"type": "{}", "ip": "{}", "fqdn": "{}", "current": {}, "max": {}, "blocked": {}, "queued": {}, "alert": {}}},
)"};
static const std::string_view trailer{" \n]}"};
static const auto printer = [](ts::BufferWriter &w, Group const *g) -> ts::BufferWriter & {
w.print(item_fmt, g->_match_type, g->_addr, g->_fqdn, g->_count.load(), g->_count_max.load(), g->_blocked.load(),
g->_rescheduled.load(), g->get_last_alert_epoch_time());
return w;
};
ts::FixedBufferWriter null_bw{nullptr}; // Empty buffer for sizing work.
std::vector<Group const *> groups;
self_type::get(groups);
null_bw.print(header_fmt, groups.size()).extent();
for (auto g : groups) {
printer(null_bw, g);
}
extent = null_bw.extent() + trailer.size() - 2; // 2 for the trailing comma newline that will get clipped.
text.resize(extent);
ts::FixedBufferWriter w(const_cast<char *>(text.data()), text.size());
w.clip(trailer.size());
w.print(header_fmt, groups.size());
for (auto g : groups) {
printer(w, g);
}
w.extend(trailer.size());
w.write(trailer);
return text;
}
void
OutboundConnTrack::dump(FILE *f)
{
std::vector<Group const *> groups;
self_type::get(groups);
if (groups.size()) {
fprintf(f, "\nUpstream Connection Tracking\n%7s | %5s | %10s | %24s | %33s | %8s |\n", "Current", "Block", "Queue", "Address",
"Hostname Hash", "Match");
fprintf(f, "------|-------|---------|--------------------------|-----------------------------------|----------|\n");
for (Group const *g : groups) {
ts::LocalBufferWriter<128> w;
w.print("{:7} | {:5} | {:5} | {:24} | {:33} | {:8} |\n", g->_count.load(), g->_blocked.load(), g->_rescheduled.load(),
g->_addr, g->_hash, g->_match_type);
fwrite(w.data(), w.size(), 1, f);
}
fprintf(f, "------|-------|-------|--------------------------|-----------------------------------|----------|\n");
}
}
struct ShowConnectionCount : public ShowCont {
ShowConnectionCount(Continuation *c, HTTPHdr *h) : ShowCont(c, h) { SET_HANDLER(&ShowConnectionCount::showHandler); }
int
showHandler(int event, Event *e)
{
CHECK_SHOW(show(OutboundConnTrack::to_json_string().c_str()));
return completeJson(event, e);
}
};
Action *
register_ShowConnectionCount(Continuation *c, HTTPHdr *h)
{
ShowConnectionCount *s = new ShowConnectionCount(c, h);
this_ethread()->schedule_imm(s);
return &s->action;
}
bool
OutboundConnTrack::lookup_match_type(std::string_view tag, OutboundConnTrack::MatchType &type)
{
// Search the array for the tag.
for (OutboundConnTrack::MatchType idx :
{OutboundConnTrack::MATCH_IP, OutboundConnTrack::MATCH_PORT, OutboundConnTrack::MATCH_HOST, OutboundConnTrack::MATCH_BOTH}) {
if (tag == MATCH_TYPE_NAME[idx]) {
type = idx;
return true;
}
}
return false;
}
void
OutboundConnTrack::Warning_Bad_Match_Type(std::string_view tag)
{
ts::LocalBufferWriter<256> w;
w.print("Invalid value '{}' for '{}' - must be one of", tag, CONFIG_VAR_MATCH);
for (auto n : MATCH_TYPE_NAME) {
w.write(" '"sv);
w.write(n);
w.write("',"sv);
}
w.auxBuffer()[-1] = '\0'; // clip trailing comma and null terminate.
Warning("%s", w.data());
}
void
OutboundConnTrack::TxnState::Note_Unblocked(const TxnConfig *config, int count, sockaddr const *addr)
{
time_t lat; // last alert time (epoch seconds)
if ((_g->_blocked > 0 || _g->_rescheduled > 0) && _g->should_alert(&lat)) {
auto blocked = _g->_blocked.exchange(0);
auto rescheduled = _g->_rescheduled.exchange(0);
ts::LocalBufferWriter<256> w;
w.print("upstream unblocked: [{}] count={} limit={} group=({}) blocked={} queued={} upstream={}\0",
ts::bwf::Date(lat, "%b %d %H:%M:%S"sv), count, config->max, *_g, blocked, rescheduled, addr);
Debug(DEBUG_TAG, "%s", w.data());
Note("%s", w.data());
}
}
void
OutboundConnTrack::TxnState::Warn_Blocked(const TxnConfig *config, int64_t sm_id, int count, sockaddr const *addr,
char const *debug_tag)
{
bool alert_p = _g->should_alert();
auto blocked = alert_p ? _g->_blocked.exchange(0) : _g->_blocked.load();
auto rescheduled = alert_p ? _g->_rescheduled.exchange(0) : _g->_rescheduled.load();
if (alert_p || debug_tag) {
ts::LocalBufferWriter<256> w;
w.print("[{}] too many connections: count={} limit={} group=({}) blocked={} queued={} upstream={}\0", sm_id, count, config->max,
*_g, blocked, rescheduled, addr);
if (debug_tag) {
Debug(debug_tag, "%s", w.data());
}
if (alert_p) {
Warning("%s", w.data());
}
}
}
namespace ts
{
BufferWriter &
bwformat(BufferWriter &w, BWFSpec const &spec, OutboundConnTrack::MatchType type)
{
if (spec.has_numeric_type()) {
bwformat(w, spec, static_cast<unsigned int>(type));
} else {
bwformat(w, spec, OutboundConnTrack::MATCH_TYPE_NAME[type]);
}
return w;
}
BufferWriter &
bwformat(BufferWriter &w, BWFSpec const &spec, OutboundConnTrack::Group::Key const &key)
{
switch (key._match_type) {
case OutboundConnTrack::MATCH_BOTH:
w.print("{:s} {},{}", key._match_type, key._addr, key._hash);
break;
case OutboundConnTrack::MATCH_HOST:
w.print("{:s} {}", key._match_type, key._hash);
break;
case OutboundConnTrack::MATCH_PORT:
w.print("{:s} {}", key._match_type, key._addr);
break;
case OutboundConnTrack::MATCH_IP:
w.print("{:s} {::a}", key._match_type, key._addr);
break;
}
return w;
}
BufferWriter &
bwformat(BufferWriter &w, BWFSpec const &spec, OutboundConnTrack::Group const &g)
{
switch (g._match_type) {
case OutboundConnTrack::MATCH_BOTH:
w.print("{:s} {},{}", g._match_type, g._addr, g._fqdn);
break;
case OutboundConnTrack::MATCH_HOST:
w.print("{:s} {}", g._match_type, g._fqdn);
break;
case OutboundConnTrack::MATCH_PORT:
w.print("{:s} {}", g._match_type, g._addr);
break;
case OutboundConnTrack::MATCH_IP:
w.print("{:s} {::a}", g._match_type, g._addr);
break;
}
return w;
}
} // namespace ts
|