http.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. #include "http.h"
  2. #include "abortable_http_response.h"
  3. #include "core.h"
  4. #include "helpers.h"
  5. #include <yt/cpp/mapreduce/common/helpers.h>
  6. #include <yt/cpp/mapreduce/common/retry_lib.h>
  7. #include <yt/cpp/mapreduce/common/wait_proxy.h>
  8. #include <yt/cpp/mapreduce/interface/config.h>
  9. #include <yt/cpp/mapreduce/interface/errors.h>
  10. #include <yt/cpp/mapreduce/interface/error_codes.h>
  11. #include <yt/cpp/mapreduce/interface/logging/yt_log.h>
  12. #include <yt/yt/core/http/http.h>
  13. #include <library/cpp/json/json_writer.h>
  14. #include <library/cpp/string_utils/base64/base64.h>
  15. #include <library/cpp/string_utils/quote/quote.h>
  16. #include <util/generic/singleton.h>
  17. #include <util/generic/algorithm.h>
  18. #include <util/stream/mem.h>
  19. #include <util/string/builder.h>
  20. #include <util/string/cast.h>
  21. #include <util/string/escape.h>
  22. #include <util/string/printf.h>
  23. #include <util/system/byteorder.h>
  24. #include <util/system/getpid.h>
  25. #include <exception>
  26. namespace NYT {
  27. ////////////////////////////////////////////////////////////////////////////////
  28. std::exception_ptr WrapSystemError(
  29. const TRequestContext& context,
  30. const std::exception& ex)
  31. {
  32. if (auto errorResponse = dynamic_cast<const TErrorResponse*>(&ex); errorResponse != nullptr) {
  33. return std::make_exception_ptr(errorResponse);
  34. }
  35. auto message = NYT::Format("Request %qv to %qv failed", context.RequestId, context.HostName + context.Method);
  36. TYtError outer(1, message, {TYtError(NClusterErrorCodes::Generic, ex.what())}, {
  37. {"request_id", context.RequestId},
  38. {"host", context.HostName},
  39. {"method", context.Method},
  40. });
  41. TTransportError errorResponse(std::move(outer));
  42. return std::make_exception_ptr(errorResponse);
  43. }
  44. ////////////////////////////////////////////////////////////////////////////////
  45. class THttpRequest::TRequestStream
  46. : public IOutputStream
  47. {
  48. public:
  49. TRequestStream(THttpRequest* httpRequest, const TSocket& s)
  50. : HttpRequest_(httpRequest)
  51. , SocketOutput_(s)
  52. , HttpOutput_(static_cast<IOutputStream*>(&SocketOutput_))
  53. {
  54. HttpOutput_.EnableKeepAlive(true);
  55. }
  56. private:
  57. void DoWrite(const void* buf, size_t len) override
  58. {
  59. WrapWriteFunc([&] {
  60. HttpOutput_.Write(buf, len);
  61. });
  62. }
  63. void DoWriteV(const TPart* parts, size_t count) override
  64. {
  65. WrapWriteFunc([&] {
  66. HttpOutput_.Write(parts, count);
  67. });
  68. }
  69. void DoWriteC(char ch) override
  70. {
  71. WrapWriteFunc([&] {
  72. HttpOutput_.Write(ch);
  73. });
  74. }
  75. void DoFlush() override
  76. {
  77. WrapWriteFunc([&] {
  78. HttpOutput_.Flush();
  79. });
  80. }
  81. void DoFinish() override
  82. {
  83. WrapWriteFunc([&] {
  84. HttpOutput_.Finish();
  85. });
  86. }
  87. void WrapWriteFunc(std::function<void()> func)
  88. {
  89. CheckErrorState();
  90. try {
  91. func();
  92. } catch (const std::exception& ex) {
  93. HandleWriteException(ex);
  94. }
  95. }
  96. // In many cases http proxy stops reading request and resets connection
  97. // if error has happend. This function tries to read error response
  98. // in such cases.
  99. void HandleWriteException(const std::exception& ex) {
  100. Y_ABORT_UNLESS(WriteError_ == nullptr);
  101. WriteError_ = WrapSystemError(HttpRequest_->Context_, ex);
  102. Y_ABORT_UNLESS(WriteError_ != nullptr);
  103. try {
  104. HttpRequest_->GetResponseStream();
  105. } catch (const TErrorResponse &) {
  106. throw;
  107. } catch (...) {
  108. }
  109. std::rethrow_exception(WriteError_);
  110. }
  111. void CheckErrorState()
  112. {
  113. if (WriteError_) {
  114. std::rethrow_exception(WriteError_);
  115. }
  116. }
  117. private:
  118. THttpRequest* const HttpRequest_;
  119. TSocketOutput SocketOutput_;
  120. THttpOutput HttpOutput_;
  121. std::exception_ptr WriteError_;
  122. };
  123. ////////////////////////////////////////////////////////////////////////////////
  124. THttpHeader::THttpHeader(const TString& method, const TString& command, bool isApi)
  125. : Method_(method)
  126. , Command_(command)
  127. , IsApi_(isApi)
  128. { }
  129. void THttpHeader::AddParameter(const TString& key, TNode value, bool overwrite)
  130. {
  131. auto it = Parameters_.find(key);
  132. if (it == Parameters_.end()) {
  133. Parameters_.emplace(key, std::move(value));
  134. } else {
  135. if (overwrite) {
  136. it->second = std::move(value);
  137. } else {
  138. ythrow yexception() << "Duplicate key: " << key;
  139. }
  140. }
  141. }
  142. void THttpHeader::MergeParameters(const TNode& newParameters, bool overwrite)
  143. {
  144. for (const auto& p : newParameters.AsMap()) {
  145. AddParameter(p.first, p.second, overwrite);
  146. }
  147. }
  148. void THttpHeader::RemoveParameter(const TString& key)
  149. {
  150. Parameters_.erase(key);
  151. }
  152. TNode THttpHeader::GetParameters() const
  153. {
  154. return Parameters_;
  155. }
  156. void THttpHeader::AddTransactionId(const TTransactionId& transactionId, bool overwrite)
  157. {
  158. if (transactionId) {
  159. AddParameter("transaction_id", GetGuidAsString(transactionId), overwrite);
  160. } else {
  161. RemoveParameter("transaction_id");
  162. }
  163. }
  164. void THttpHeader::AddPath(const TString& path, bool overwrite)
  165. {
  166. AddParameter("path", path, overwrite);
  167. }
  168. void THttpHeader::AddOperationId(const TOperationId& operationId, bool overwrite)
  169. {
  170. AddParameter("operation_id", GetGuidAsString(operationId), overwrite);
  171. }
  172. TMutationId THttpHeader::AddMutationId()
  173. {
  174. TGUID guid;
  175. // Some users use `fork()' with yt wrapper
  176. // (actually they use python + multiprocessing)
  177. // and CreateGuid is not resistant to `fork()', so spice it a little bit.
  178. //
  179. // Check IGNIETFERRO-610
  180. CreateGuid(&guid);
  181. guid.dw[2] = GetPID() ^ MicroSeconds();
  182. AddParameter("mutation_id", GetGuidAsString(guid), true);
  183. return guid;
  184. }
  185. bool THttpHeader::HasMutationId() const
  186. {
  187. return Parameters_.contains("mutation_id");
  188. }
  189. void THttpHeader::SetMutationId(TMutationId mutationId)
  190. {
  191. AddParameter("mutation_id", GetGuidAsString(mutationId), /*overwrite*/ true);
  192. }
  193. void THttpHeader::SetToken(const TString& token)
  194. {
  195. Token_ = token;
  196. }
  197. void THttpHeader::SetProxyAddress(const TString& proxyAddress)
  198. {
  199. ProxyAddress_ = proxyAddress;
  200. }
  201. void THttpHeader::SetHostPort(const TString& hostPort)
  202. {
  203. HostPort_ = hostPort;
  204. }
  205. void THttpHeader::SetImpersonationUser(const TString& impersonationUser)
  206. {
  207. ImpersonationUser_ = impersonationUser;
  208. }
  209. void THttpHeader::SetServiceTicket(const TString& ticket)
  210. {
  211. ServiceTicket_ = ticket;
  212. }
  213. void THttpHeader::SetInputFormat(const TMaybe<TFormat>& format)
  214. {
  215. InputFormat_ = format;
  216. }
  217. void THttpHeader::SetOutputFormat(const TMaybe<TFormat>& format)
  218. {
  219. OutputFormat_ = format;
  220. }
  221. TMaybe<TFormat> THttpHeader::GetOutputFormat() const
  222. {
  223. return OutputFormat_;
  224. }
  225. void THttpHeader::SetRequestCompression(const TString& compression)
  226. {
  227. RequestCompression_ = compression;
  228. }
  229. void THttpHeader::SetResponseCompression(const TString& compression)
  230. {
  231. ResponseCompression_ = compression;
  232. }
  233. TString THttpHeader::GetCommand() const
  234. {
  235. return Command_;
  236. }
  237. TString THttpHeader::GetUrl(bool needProxy) const
  238. {
  239. TStringStream url;
  240. if (needProxy && !ProxyAddress_.empty()) {
  241. url << ProxyAddress_ << "/";
  242. return url.Str();
  243. }
  244. if (!ProxyAddress_.empty()) {
  245. url << HostPort_;
  246. }
  247. if (IsApi_) {
  248. url << "/api/" << TConfig::Get()->ApiVersion << "/" << Command_;
  249. } else {
  250. url << "/" << Command_;
  251. }
  252. return url.Str();
  253. }
  254. bool THttpHeader::ShouldAcceptFraming() const
  255. {
  256. return TConfig::Get()->CommandsWithFraming.contains(Command_);
  257. }
  258. TString THttpHeader::GetHeaderAsString(const TString& hostName, const TString& requestId, bool includeParameters) const
  259. {
  260. TStringStream result;
  261. result << Method_ << " " << GetUrl() << " HTTP/1.1\r\n";
  262. GetHeader(HostPort_.empty() ? hostName : HostPort_, requestId, includeParameters).Get()->WriteTo(&result);
  263. if (ShouldAcceptFraming()) {
  264. result << "X-YT-Accept-Framing: 1\r\n";
  265. }
  266. result << "\r\n";
  267. return result.Str();
  268. }
  269. NHttp::THeadersPtrWrapper THttpHeader::GetHeader(const TString& hostName, const TString& requestId, bool includeParameters) const
  270. {
  271. auto headers = New<NHttp::THeaders>();
  272. headers->Add("Host", hostName);
  273. headers->Add("User-Agent", TProcessState::Get()->ClientVersion);
  274. if (!Token_.empty()) {
  275. headers->Add("Authorization", "OAuth " + Token_);
  276. }
  277. if (!ServiceTicket_.empty()) {
  278. headers->Add("X-Ya-Service-Ticket", ServiceTicket_);
  279. }
  280. if (!ImpersonationUser_.empty()) {
  281. headers->Add("X-Yt-User-Name", ImpersonationUser_);
  282. }
  283. if (Method_ == "PUT" || Method_ == "POST") {
  284. headers->Add("Transfer-Encoding", "chunked");
  285. }
  286. headers->Add("X-YT-Correlation-Id", requestId);
  287. headers->Add("X-YT-Header-Format", "<format=text>yson");
  288. headers->Add("Content-Encoding", RequestCompression_);
  289. headers->Add("Accept-Encoding", ResponseCompression_);
  290. auto printYTHeader = [&headers] (const char* headerName, const TString& value) {
  291. static const size_t maxHttpHeaderSize = 64 << 10;
  292. if (!value) {
  293. return;
  294. }
  295. if (value.size() <= maxHttpHeaderSize) {
  296. headers->Add(headerName, value);
  297. return;
  298. }
  299. TString encoded;
  300. Base64Encode(value, encoded);
  301. auto ptr = encoded.data();
  302. auto finish = encoded.data() + encoded.size();
  303. size_t index = 0;
  304. do {
  305. auto end = Min(ptr + maxHttpHeaderSize, finish);
  306. headers->Add(Format("%v%v", headerName, index++), TString(ptr, end));
  307. ptr = end;
  308. } while (ptr != finish);
  309. };
  310. if (InputFormat_) {
  311. printYTHeader("X-YT-Input-Format", NodeToYsonString(InputFormat_->Config));
  312. }
  313. if (OutputFormat_) {
  314. printYTHeader("X-YT-Output-Format", NodeToYsonString(OutputFormat_->Config));
  315. }
  316. if (includeParameters) {
  317. printYTHeader("X-YT-Parameters", NodeToYsonString(Parameters_));
  318. }
  319. return NHttp::THeadersPtrWrapper(std::move(headers));
  320. }
  321. const TString& THttpHeader::GetMethod() const
  322. {
  323. return Method_;
  324. }
  325. ////////////////////////////////////////////////////////////////////////////////
  326. TAddressCache* TAddressCache::Get()
  327. {
  328. return Singleton<TAddressCache>();
  329. }
  330. bool ContainsAddressOfRequiredVersion(const TAddressCache::TAddressPtr& address)
  331. {
  332. if (!TConfig::Get()->ForceIpV4 && !TConfig::Get()->ForceIpV6) {
  333. return true;
  334. }
  335. for (auto i = address->Begin(); i != address->End(); ++i) {
  336. const auto& addressInfo = *i;
  337. if (TConfig::Get()->ForceIpV4 && addressInfo.ai_family == AF_INET) {
  338. return true;
  339. }
  340. if (TConfig::Get()->ForceIpV6 && addressInfo.ai_family == AF_INET6) {
  341. return true;
  342. }
  343. }
  344. return false;
  345. }
  346. TAddressCache::TAddressPtr TAddressCache::Resolve(const TString& hostName)
  347. {
  348. auto address = FindAddress(hostName);
  349. if (address) {
  350. return address;
  351. }
  352. TString host(hostName);
  353. ui16 port = 80;
  354. auto colon = hostName.find(':');
  355. if (colon != TString::npos) {
  356. port = FromString<ui16>(hostName.substr(colon + 1));
  357. host = hostName.substr(0, colon);
  358. }
  359. auto retryPolicy = CreateDefaultRequestRetryPolicy(TConfig::Get());
  360. auto error = yexception() << "can not resolve address of required version for host " << hostName;
  361. while (true) {
  362. address = new TNetworkAddress(host, port);
  363. if (ContainsAddressOfRequiredVersion(address)) {
  364. break;
  365. }
  366. retryPolicy->NotifyNewAttempt();
  367. YT_LOG_DEBUG("Failed to resolve address of required version for host %v, retrying: %v",
  368. hostName,
  369. retryPolicy->GetAttemptDescription());
  370. if (auto backoffDuration = retryPolicy->OnGenericError(error)) {
  371. NDetail::TWaitProxy::Get()->Sleep(*backoffDuration);
  372. } else {
  373. ythrow error;
  374. }
  375. }
  376. AddAddress(hostName, address);
  377. return address;
  378. }
  379. TAddressCache::TAddressPtr TAddressCache::FindAddress(const TString& hostName) const
  380. {
  381. TCacheEntry entry;
  382. {
  383. TReadGuard guard(Lock_);
  384. auto it = Cache_.find(hostName);
  385. if (it == Cache_.end()) {
  386. return nullptr;
  387. }
  388. entry = it->second;
  389. }
  390. if (TInstant::Now() > entry.ExpirationTime) {
  391. YT_LOG_DEBUG("Address resolution cache entry for host %v is expired, will retry resolution",
  392. hostName);
  393. return nullptr;
  394. }
  395. if (!ContainsAddressOfRequiredVersion(entry.Address)) {
  396. YT_LOG_DEBUG("Address of required version not found for host %v, will retry resolution",
  397. hostName);
  398. return nullptr;
  399. }
  400. return entry.Address;
  401. }
  402. void TAddressCache::AddAddress(TString hostName, TAddressPtr address)
  403. {
  404. auto entry = TCacheEntry{
  405. .Address = std::move(address),
  406. .ExpirationTime = TInstant::Now() + TConfig::Get()->AddressCacheExpirationTimeout,
  407. };
  408. {
  409. TWriteGuard guard(Lock_);
  410. Cache_.emplace(std::move(hostName), std::move(entry));
  411. }
  412. }
  413. ////////////////////////////////////////////////////////////////////////////////
  414. TConnectionPool* TConnectionPool::Get()
  415. {
  416. return Singleton<TConnectionPool>();
  417. }
  418. TConnectionPtr TConnectionPool::Connect(
  419. const TString& hostName,
  420. TDuration socketTimeout)
  421. {
  422. Refresh();
  423. if (socketTimeout == TDuration::Zero()) {
  424. socketTimeout = TConfig::Get()->SocketTimeout;
  425. }
  426. {
  427. auto guard = Guard(Lock_);
  428. auto now = TInstant::Now();
  429. auto range = Connections_.equal_range(hostName);
  430. for (auto it = range.first; it != range.second; ++it) {
  431. auto& connection = it->second;
  432. if (connection->DeadLine < now) {
  433. continue;
  434. }
  435. if (!AtomicCas(&connection->Busy, 1, 0)) {
  436. continue;
  437. }
  438. connection->DeadLine = now + socketTimeout;
  439. connection->Socket->SetSocketTimeout(socketTimeout.Seconds());
  440. return connection;
  441. }
  442. }
  443. TConnectionPtr connection(new TConnection);
  444. auto networkAddress = TAddressCache::Get()->Resolve(hostName);
  445. TSocketHolder socket(DoConnect(networkAddress));
  446. SetNonBlock(socket, false);
  447. connection->Socket = std::make_unique<TSocket>(socket.Release());
  448. connection->DeadLine = TInstant::Now() + socketTimeout;
  449. connection->Socket->SetSocketTimeout(socketTimeout.Seconds());
  450. {
  451. auto guard = Guard(Lock_);
  452. static ui32 connectionId = 0;
  453. connection->Id = ++connectionId;
  454. Connections_.insert({hostName, connection});
  455. }
  456. YT_LOG_DEBUG("New connection to %v #%v opened",
  457. hostName,
  458. connection->Id);
  459. return connection;
  460. }
  461. void TConnectionPool::Release(TConnectionPtr connection)
  462. {
  463. auto socketTimeout = TConfig::Get()->SocketTimeout;
  464. auto newDeadline = TInstant::Now() + socketTimeout;
  465. {
  466. auto guard = Guard(Lock_);
  467. connection->DeadLine = newDeadline;
  468. }
  469. connection->Socket->SetSocketTimeout(socketTimeout.Seconds());
  470. AtomicSet(connection->Busy, 0);
  471. Refresh();
  472. }
  473. void TConnectionPool::Invalidate(
  474. const TString& hostName,
  475. TConnectionPtr connection)
  476. {
  477. auto guard = Guard(Lock_);
  478. auto range = Connections_.equal_range(hostName);
  479. for (auto it = range.first; it != range.second; ++it) {
  480. if (it->second == connection) {
  481. YT_LOG_DEBUG("Closing connection #%v",
  482. connection->Id);
  483. Connections_.erase(it);
  484. return;
  485. }
  486. }
  487. }
  488. void TConnectionPool::Refresh()
  489. {
  490. auto guard = Guard(Lock_);
  491. // simple, since we don't expect too many connections
  492. using TItem = std::pair<TInstant, TConnectionMap::iterator>;
  493. std::vector<TItem> sortedConnections;
  494. for (auto it = Connections_.begin(); it != Connections_.end(); ++it) {
  495. sortedConnections.emplace_back(it->second->DeadLine, it);
  496. }
  497. std::sort(
  498. sortedConnections.begin(),
  499. sortedConnections.end(),
  500. [] (const TItem& a, const TItem& b) -> bool {
  501. return a.first < b.first;
  502. });
  503. auto removeCount = static_cast<int>(Connections_.size()) - TConfig::Get()->ConnectionPoolSize;
  504. const auto now = TInstant::Now();
  505. for (const auto& item : sortedConnections) {
  506. const auto& mapIterator = item.second;
  507. auto connection = mapIterator->second;
  508. if (AtomicGet(connection->Busy)) {
  509. continue;
  510. }
  511. if (removeCount > 0) {
  512. Connections_.erase(mapIterator);
  513. YT_LOG_DEBUG("Closing connection #%v (too many opened connections)",
  514. connection->Id);
  515. --removeCount;
  516. continue;
  517. }
  518. if (connection->DeadLine < now) {
  519. Connections_.erase(mapIterator);
  520. YT_LOG_DEBUG("Closing connection #%v (timeout)",
  521. connection->Id);
  522. }
  523. }
  524. }
  525. SOCKET TConnectionPool::DoConnect(TAddressCache::TAddressPtr address)
  526. {
  527. int lastError = 0;
  528. for (auto i = address->Begin(); i != address->End(); ++i) {
  529. struct addrinfo* info = &*i;
  530. if (TConfig::Get()->ForceIpV4 && info->ai_family != AF_INET) {
  531. continue;
  532. }
  533. if (TConfig::Get()->ForceIpV6 && info->ai_family != AF_INET6) {
  534. continue;
  535. }
  536. TSocketHolder socket(
  537. ::socket(info->ai_family, info->ai_socktype, info->ai_protocol));
  538. if (socket.Closed()) {
  539. lastError = LastSystemError();
  540. continue;
  541. }
  542. SetNonBlock(socket, true);
  543. if (TConfig::Get()->SocketPriority) {
  544. SetSocketPriority(socket, *TConfig::Get()->SocketPriority);
  545. }
  546. if (connect(socket, info->ai_addr, info->ai_addrlen) == 0)
  547. return socket.Release();
  548. int err = LastSystemError();
  549. if (err == EINPROGRESS || err == EAGAIN || err == EWOULDBLOCK) {
  550. struct pollfd p = {
  551. socket,
  552. POLLOUT,
  553. 0
  554. };
  555. const ssize_t n = PollD(&p, 1, TInstant::Now() + TConfig::Get()->ConnectTimeout);
  556. if (n < 0) {
  557. ythrow TSystemError(-(int)n) << "can not connect to " << info;
  558. }
  559. CheckedGetSockOpt(socket, SOL_SOCKET, SO_ERROR, err, "socket error");
  560. if (!err)
  561. return socket.Release();
  562. }
  563. lastError = err;
  564. continue;
  565. }
  566. ythrow TSystemError(lastError) << "can not connect to " << *address;
  567. }
  568. ////////////////////////////////////////////////////////////////////////////////
  569. class THttpResponse::THttpInputWrapped
  570. : public IInputStream
  571. {
  572. public:
  573. explicit THttpInputWrapped(TRequestContext context, IInputStream* input)
  574. : Context_(std::move(context))
  575. , HttpInput_(input)
  576. { }
  577. const THttpHeaders& Headers() const noexcept
  578. {
  579. return HttpInput_.Headers();
  580. }
  581. const TString& FirstLine() const noexcept
  582. {
  583. return HttpInput_.FirstLine();
  584. }
  585. bool IsKeepAlive() const noexcept
  586. {
  587. return HttpInput_.IsKeepAlive();
  588. }
  589. const TMaybe<THttpHeaders>& Trailers() const noexcept
  590. {
  591. return HttpInput_.Trailers();
  592. }
  593. private:
  594. size_t DoRead(void* buf, size_t len) override
  595. {
  596. try {
  597. return HttpInput_.Read(buf, len);
  598. } catch (const std::exception& ex) {
  599. auto wrapped = WrapSystemError(Context_, ex);
  600. std::rethrow_exception(wrapped);
  601. }
  602. }
  603. size_t DoSkip(size_t len) override
  604. {
  605. try {
  606. return HttpInput_.Skip(len);
  607. } catch (const std::exception& ex) {
  608. auto wrapped = WrapSystemError(Context_, ex);
  609. std::rethrow_exception(wrapped);
  610. }
  611. }
  612. private:
  613. const TRequestContext Context_;
  614. THttpInput HttpInput_;
  615. };
  616. THttpResponse::THttpResponse(
  617. TRequestContext context,
  618. IInputStream* socketStream)
  619. : HttpInput_(std::make_unique<THttpInputWrapped>(context, socketStream))
  620. , Unframe_(HttpInput_->Headers().HasHeader("X-YT-Framing"))
  621. , Context_(std::move(context))
  622. {
  623. if (auto proxyHeader = HttpInput_->Headers().FindHeader("X-YT-Proxy")) {
  624. Context_.HostName = proxyHeader->Value();
  625. }
  626. HttpCode_ = ParseHttpRetCode(HttpInput_->FirstLine());
  627. if (HttpCode_ == 200 || HttpCode_ == 202) {
  628. return;
  629. }
  630. ErrorResponse_ = TErrorResponse(HttpCode_, Context_.RequestId);
  631. auto logAndSetError = [&] (const TString& rawError) {
  632. YT_LOG_ERROR("RSP %v - HTTP %v - %v",
  633. Context_.RequestId,
  634. HttpCode_,
  635. rawError.data());
  636. ErrorResponse_->SetRawError(rawError);
  637. };
  638. switch (HttpCode_) {
  639. case 429:
  640. logAndSetError("request rate limit exceeded");
  641. break;
  642. case 500:
  643. logAndSetError(::TStringBuilder() << "internal error in proxy " << Context_.HostName);
  644. break;
  645. default: {
  646. TStringStream httpHeaders;
  647. httpHeaders << "HTTP headers (";
  648. for (const auto& header : HttpInput_->Headers()) {
  649. httpHeaders << header.Name() << ": " << header.Value() << "; ";
  650. }
  651. httpHeaders << ")";
  652. auto errorString = Sprintf("RSP %s - HTTP %d - %s",
  653. Context_.RequestId.data(),
  654. HttpCode_,
  655. httpHeaders.Str().data());
  656. YT_LOG_ERROR("%v",
  657. errorString.data());
  658. if (auto parsedResponse = ParseError(HttpInput_->Headers())) {
  659. ErrorResponse_ = parsedResponse.GetRef();
  660. } else {
  661. ErrorResponse_->SetRawError(
  662. errorString + " - X-YT-Error is missing in headers");
  663. }
  664. break;
  665. }
  666. }
  667. }
  668. THttpResponse::~THttpResponse()
  669. { }
  670. const THttpHeaders& THttpResponse::Headers() const
  671. {
  672. return HttpInput_->Headers();
  673. }
  674. void THttpResponse::CheckErrorResponse() const
  675. {
  676. if (ErrorResponse_) {
  677. throw *ErrorResponse_;
  678. }
  679. }
  680. bool THttpResponse::IsExhausted() const
  681. {
  682. return IsExhausted_;
  683. }
  684. int THttpResponse::GetHttpCode() const
  685. {
  686. return HttpCode_;
  687. }
  688. const TString& THttpResponse::GetHostName() const
  689. {
  690. return Context_.HostName;
  691. }
  692. bool THttpResponse::IsKeepAlive() const
  693. {
  694. return HttpInput_->IsKeepAlive();
  695. }
  696. TMaybe<TErrorResponse> THttpResponse::ParseError(const THttpHeaders& headers)
  697. {
  698. for (const auto& header : headers) {
  699. if (header.Name() == "X-YT-Error") {
  700. TErrorResponse errorResponse(HttpCode_, Context_.RequestId);
  701. errorResponse.ParseFromJsonError(header.Value());
  702. if (errorResponse.IsOk()) {
  703. return Nothing();
  704. }
  705. return errorResponse;
  706. }
  707. }
  708. return Nothing();
  709. }
  710. size_t THttpResponse::DoRead(void* buf, size_t len)
  711. {
  712. size_t read;
  713. if (Unframe_) {
  714. read = UnframeRead(buf, len);
  715. } else {
  716. read = HttpInput_->Read(buf, len);
  717. }
  718. if (read == 0 && len != 0) {
  719. // THttpInput MUST return defined (but may be empty)
  720. // trailers when it is exhausted.
  721. Y_ABORT_UNLESS(HttpInput_->Trailers().Defined(),
  722. "trailers MUST be defined for exhausted stream");
  723. CheckTrailers(HttpInput_->Trailers().GetRef());
  724. IsExhausted_ = true;
  725. }
  726. return read;
  727. }
  728. size_t THttpResponse::DoSkip(size_t len)
  729. {
  730. size_t skipped;
  731. if (Unframe_) {
  732. skipped = UnframeSkip(len);
  733. } else {
  734. skipped = HttpInput_->Skip(len);
  735. }
  736. if (skipped == 0 && len != 0) {
  737. // THttpInput MUST return defined (but may be empty)
  738. // trailers when it is exhausted.
  739. Y_ABORT_UNLESS(HttpInput_->Trailers().Defined(),
  740. "trailers MUST be defined for exhausted stream");
  741. CheckTrailers(HttpInput_->Trailers().GetRef());
  742. IsExhausted_ = true;
  743. }
  744. return skipped;
  745. }
  746. void THttpResponse::CheckTrailers(const THttpHeaders& trailers)
  747. {
  748. if (auto errorResponse = ParseError(trailers)) {
  749. errorResponse->SetIsFromTrailers(true);
  750. YT_LOG_ERROR("RSP %v - %v",
  751. Context_.RequestId,
  752. errorResponse.GetRef().what());
  753. ythrow errorResponse.GetRef();
  754. }
  755. }
  756. static ui32 ReadDataFrameSize(IInputStream* stream)
  757. {
  758. ui32 littleEndianSize;
  759. auto read = stream->Load(&littleEndianSize, sizeof(littleEndianSize));
  760. if (read < sizeof(littleEndianSize)) {
  761. ythrow yexception() << "Bad data frame header: " <<
  762. "expected " << sizeof(littleEndianSize) << " bytes, got " << read;
  763. }
  764. return LittleToHost(littleEndianSize);
  765. }
  766. bool THttpResponse::RefreshFrameIfNecessary()
  767. {
  768. while (RemainingFrameSize_ == 0) {
  769. ui8 frameTypeByte;
  770. auto read = HttpInput_->Read(&frameTypeByte, sizeof(frameTypeByte));
  771. if (read == 0) {
  772. return false;
  773. }
  774. auto frameType = static_cast<EFrameType>(frameTypeByte);
  775. switch (frameType) {
  776. case EFrameType::KeepAlive:
  777. break;
  778. case EFrameType::Data:
  779. RemainingFrameSize_ = ReadDataFrameSize(HttpInput_.get());
  780. break;
  781. default:
  782. ythrow yexception() << "Bad frame type " << static_cast<int>(frameTypeByte);
  783. }
  784. }
  785. return true;
  786. }
  787. size_t THttpResponse::UnframeRead(void* buf, size_t len)
  788. {
  789. if (!RefreshFrameIfNecessary()) {
  790. return 0;
  791. }
  792. auto read = HttpInput_->Read(buf, Min(len, RemainingFrameSize_));
  793. RemainingFrameSize_ -= read;
  794. return read;
  795. }
  796. size_t THttpResponse::UnframeSkip(size_t len)
  797. {
  798. if (!RefreshFrameIfNecessary()) {
  799. return 0;
  800. }
  801. auto skipped = HttpInput_->Skip(Min(len, RemainingFrameSize_));
  802. RemainingFrameSize_ -= skipped;
  803. return skipped;
  804. }
  805. ////////////////////////////////////////////////////////////////////////////////
  806. THttpRequest::THttpRequest(TString requestId, TString hostName, THttpHeader header, TDuration socketTimeout)
  807. : Context_(TRequestContext{
  808. .RequestId = std::move(requestId),
  809. .HostName = std::move(hostName),
  810. .Method = header.GetUrl(/*needProxy=*/ false)
  811. })
  812. , Header_(std::move(header))
  813. , Url_(Header_.GetUrl(true))
  814. , SocketTimeout_(socketTimeout)
  815. { }
  816. THttpRequest::~THttpRequest()
  817. {
  818. if (!Connection_) {
  819. return;
  820. }
  821. if (Input_ && Input_->IsKeepAlive() && Input_->IsExhausted()) {
  822. // We should return to the pool only connections where HTTP response was fully read.
  823. // Otherwise next reader might read our remaining data and misinterpret them (YT-6510).
  824. TConnectionPool::Get()->Release(Connection_);
  825. } else {
  826. TConnectionPool::Get()->Invalidate(Context_.HostName, Connection_);
  827. }
  828. }
  829. TString THttpRequest::GetRequestId() const
  830. {
  831. return Context_.RequestId;
  832. }
  833. IOutputStream* THttpRequest::StartRequestImpl(bool includeParameters)
  834. {
  835. YT_LOG_DEBUG("REQ %v - requesting connection to %v from connection pool",
  836. Context_.RequestId,
  837. Context_.HostName);
  838. StartTime_ = TInstant::Now();
  839. try {
  840. Connection_ = TConnectionPool::Get()->Connect(Context_.HostName, SocketTimeout_);
  841. } catch (const std::exception& ex) {
  842. auto wrapped = WrapSystemError(Context_, ex);
  843. std::rethrow_exception(wrapped);
  844. }
  845. YT_LOG_DEBUG("REQ %v - connection #%v",
  846. Context_.RequestId,
  847. Connection_->Id);
  848. auto strHeader = Header_.GetHeaderAsString(Context_.HostName, Context_.RequestId, includeParameters);
  849. LogRequest(Header_, Url_, includeParameters, Context_.RequestId, Context_.HostName);
  850. LoggedAttributes_ = GetLoggedAttributes(Header_, Url_, includeParameters, 128);
  851. auto outputFormat = Header_.GetOutputFormat();
  852. if (outputFormat && outputFormat->IsTextYson()) {
  853. LogResponse_ = true;
  854. }
  855. RequestStream_ = std::make_unique<TRequestStream>(this, *Connection_->Socket.get());
  856. RequestStream_->Write(strHeader.data(), strHeader.size());
  857. return RequestStream_.get();
  858. }
  859. IOutputStream* THttpRequest::StartRequest()
  860. {
  861. return StartRequestImpl(true);
  862. }
  863. void THttpRequest::FinishRequest()
  864. {
  865. RequestStream_->Flush();
  866. RequestStream_->Finish();
  867. }
  868. void THttpRequest::SmallRequest(TMaybe<TStringBuf> body)
  869. {
  870. if (!body && (Header_.GetMethod() == "PUT" || Header_.GetMethod() == "POST")) {
  871. const auto& parameters = Header_.GetParameters();
  872. auto parametersStr = NodeToYsonString(parameters);
  873. auto* output = StartRequestImpl(false);
  874. output->Write(parametersStr);
  875. FinishRequest();
  876. } else {
  877. auto* output = StartRequest();
  878. if (body) {
  879. output->Write(*body);
  880. }
  881. FinishRequest();
  882. }
  883. }
  884. THttpResponse* THttpRequest::GetResponseStream()
  885. {
  886. if (!Input_) {
  887. SocketInput_ = std::make_unique<TSocketInput>(*Connection_->Socket.get());
  888. if (TConfig::Get()->UseAbortableResponse) {
  889. Y_ABORT_UNLESS(!Url_.empty());
  890. Input_ = std::make_unique<TAbortableHttpResponse>(Context_, SocketInput_.get(), Url_);
  891. } else {
  892. Input_ = std::make_unique<THttpResponse>(Context_, SocketInput_.get());
  893. }
  894. Input_->CheckErrorResponse();
  895. }
  896. return Input_.get();
  897. }
  898. TString THttpRequest::GetResponse()
  899. {
  900. TString result = GetResponseStream()->ReadAll();
  901. TStringStream loggedAttributes;
  902. loggedAttributes
  903. << "Time: " << TInstant::Now() - StartTime_ << "; "
  904. << "HostName: " << GetResponseStream()->GetHostName() << "; "
  905. << LoggedAttributes_;
  906. if (LogResponse_) {
  907. constexpr auto sizeLimit = 1 << 7;
  908. YT_LOG_DEBUG("RSP %v - received response (Response: '%v'; %v)",
  909. Context_.RequestId,
  910. TruncateForLogs(result, sizeLimit),
  911. loggedAttributes.Str());
  912. } else {
  913. YT_LOG_DEBUG("RSP %v - received response of %v bytes (%v)",
  914. Context_.RequestId,
  915. result.size(),
  916. loggedAttributes.Str());
  917. }
  918. return result;
  919. }
  920. int THttpRequest::GetHttpCode() {
  921. return GetResponseStream()->GetHttpCode();
  922. }
  923. void THttpRequest::InvalidateConnection()
  924. {
  925. TConnectionPool::Get()->Invalidate(Context_.HostName, Connection_);
  926. Connection_.Reset();
  927. }
  928. ////////////////////////////////////////////////////////////////////////////////
  929. } // namespace NYT