raw_requests.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. #include "raw_requests.h"
  2. #include "raw_batch_request.h"
  3. #include "rpc_parameters_serialization.h"
  4. #include <yt/cpp/mapreduce/common/helpers.h>
  5. #include <yt/cpp/mapreduce/common/retry_lib.h>
  6. #include <yt/cpp/mapreduce/common/wait_proxy.h>
  7. #include <yt/cpp/mapreduce/http/fwd.h>
  8. #include <yt/cpp/mapreduce/http/context.h>
  9. #include <yt/cpp/mapreduce/http/helpers.h>
  10. #include <yt/cpp/mapreduce/http/http_client.h>
  11. #include <yt/cpp/mapreduce/http/retry_request.h>
  12. #include <yt/cpp/mapreduce/interface/config.h>
  13. #include <yt/cpp/mapreduce/interface/client.h>
  14. #include <yt/cpp/mapreduce/interface/operation.h>
  15. #include <yt/cpp/mapreduce/interface/serialize.h>
  16. #include <yt/cpp/mapreduce/interface/tvm.h>
  17. #include <yt/cpp/mapreduce/interface/logging/yt_log.h>
  18. #include <library/cpp/yson/node/node_io.h>
  19. #include <util/generic/guid.h>
  20. #include <util/generic/scope.h>
  21. namespace NYT::NDetail::NRawClient {
  22. ////////////////////////////////////////////////////////////////////////////////
  23. void ExecuteBatch(
  24. IRequestRetryPolicyPtr retryPolicy,
  25. const TClientContext& context,
  26. TRawBatchRequest& batchRequest,
  27. const TExecuteBatchOptions& options)
  28. {
  29. if (batchRequest.IsExecuted()) {
  30. ythrow yexception() << "Cannot execute batch request since it is already executed";
  31. }
  32. Y_DEFER {
  33. batchRequest.MarkExecuted();
  34. };
  35. const auto concurrency = options.Concurrency_.GetOrElse(50);
  36. const auto batchPartMaxSize = options.BatchPartMaxSize_.GetOrElse(concurrency * 5);
  37. if (!retryPolicy) {
  38. retryPolicy = CreateDefaultRequestRetryPolicy(context.Config);
  39. }
  40. while (batchRequest.BatchSize()) {
  41. TRawBatchRequest retryBatch(context.Config);
  42. while (batchRequest.BatchSize()) {
  43. auto parameters = TNode::CreateMap();
  44. TInstant nextTry;
  45. batchRequest.FillParameterList(batchPartMaxSize, &parameters["requests"], &nextTry);
  46. if (nextTry) {
  47. SleepUntil(nextTry);
  48. }
  49. parameters["concurrency"] = concurrency;
  50. auto body = NodeToYsonString(parameters);
  51. THttpHeader header("POST", "execute_batch");
  52. header.AddMutationId();
  53. NDetail::TResponseInfo result;
  54. try {
  55. result = RetryRequestWithPolicy(retryPolicy, context, header, body);
  56. } catch (const std::exception& e) {
  57. batchRequest.SetErrorResult(std::current_exception());
  58. retryBatch.SetErrorResult(std::current_exception());
  59. throw;
  60. }
  61. batchRequest.ParseResponse(std::move(result), retryPolicy.Get(), &retryBatch);
  62. }
  63. batchRequest = std::move(retryBatch);
  64. }
  65. }
  66. TNode Get(
  67. const IRequestRetryPolicyPtr& retryPolicy,
  68. const TClientContext& context,
  69. const TTransactionId& transactionId,
  70. const TYPath& path,
  71. const TGetOptions& options)
  72. {
  73. THttpHeader header("GET", "get");
  74. header.MergeParameters(SerializeParamsForGet(transactionId, context.Config->Prefix, path, options));
  75. return NodeFromYsonString(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  76. }
  77. TNode TryGet(
  78. const IRequestRetryPolicyPtr& retryPolicy,
  79. const TClientContext& context,
  80. const TTransactionId& transactionId,
  81. const TYPath& path,
  82. const TGetOptions& options)
  83. {
  84. try {
  85. return Get(retryPolicy, context, transactionId, path, options);
  86. } catch (const TErrorResponse& error) {
  87. if (!error.IsResolveError()) {
  88. throw;
  89. }
  90. return TNode();
  91. }
  92. }
  93. void Set(
  94. const IRequestRetryPolicyPtr& retryPolicy,
  95. const TClientContext& context,
  96. const TTransactionId& transactionId,
  97. const TYPath& path,
  98. const TNode& value,
  99. const TSetOptions& options)
  100. {
  101. THttpHeader header("PUT", "set");
  102. header.AddMutationId();
  103. header.MergeParameters(SerializeParamsForSet(transactionId, context.Config->Prefix, path, options));
  104. auto body = NodeToYsonString(value);
  105. RetryRequestWithPolicy(retryPolicy, context, header, body);
  106. }
  107. void MultisetAttributes(
  108. const IRequestRetryPolicyPtr& retryPolicy,
  109. const TClientContext& context,
  110. const TTransactionId& transactionId,
  111. const TYPath& path,
  112. const TNode::TMapType& value,
  113. const TMultisetAttributesOptions& options)
  114. {
  115. THttpHeader header("PUT", "api/v4/multiset_attributes", false);
  116. header.AddMutationId();
  117. header.MergeParameters(SerializeParamsForMultisetAttributes(transactionId, context.Config->Prefix, path, options));
  118. auto body = NodeToYsonString(value);
  119. RetryRequestWithPolicy(retryPolicy, context, header, body);
  120. }
  121. bool Exists(
  122. const IRequestRetryPolicyPtr& retryPolicy,
  123. const TClientContext& context,
  124. const TTransactionId& transactionId,
  125. const TYPath& path,
  126. const TExistsOptions& options)
  127. {
  128. THttpHeader header("GET", "exists");
  129. header.MergeParameters(SerializeParamsForExists(transactionId, context.Config->Prefix, path, options));
  130. return ParseBoolFromResponse(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  131. }
  132. TNodeId Create(
  133. const IRequestRetryPolicyPtr& retryPolicy,
  134. const TClientContext& context,
  135. const TTransactionId& transactionId,
  136. const TYPath& path,
  137. const ENodeType& type,
  138. const TCreateOptions& options)
  139. {
  140. THttpHeader header("POST", "create");
  141. header.AddMutationId();
  142. header.MergeParameters(SerializeParamsForCreate(transactionId, context.Config->Prefix, path, type, options));
  143. return ParseGuidFromResponse(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  144. }
  145. TNodeId CopyWithoutRetries(
  146. const TClientContext& context,
  147. const TTransactionId& transactionId,
  148. const TYPath& sourcePath,
  149. const TYPath& destinationPath,
  150. const TCopyOptions& options)
  151. {
  152. THttpHeader header("POST", "copy");
  153. header.AddMutationId();
  154. header.MergeParameters(SerializeParamsForCopy(transactionId, context.Config->Prefix, sourcePath, destinationPath, options));
  155. return ParseGuidFromResponse(RequestWithoutRetry(context, header).Response);
  156. }
  157. TNodeId CopyInsideMasterCell(
  158. const IRequestRetryPolicyPtr& retryPolicy,
  159. const TClientContext& context,
  160. const TTransactionId& transactionId,
  161. const TYPath& sourcePath,
  162. const TYPath& destinationPath,
  163. const TCopyOptions& options)
  164. {
  165. THttpHeader header("POST", "copy");
  166. header.AddMutationId();
  167. auto params = SerializeParamsForCopy(transactionId, context.Config->Prefix, sourcePath, destinationPath, options);
  168. // Make cross cell copying disable.
  169. params["enable_cross_cell_copying"] = false;
  170. header.MergeParameters(params);
  171. return ParseGuidFromResponse(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  172. }
  173. TNodeId MoveWithoutRetries(
  174. const TClientContext& context,
  175. const TTransactionId& transactionId,
  176. const TYPath& sourcePath,
  177. const TYPath& destinationPath,
  178. const TMoveOptions& options)
  179. {
  180. THttpHeader header("POST", "move");
  181. header.AddMutationId();
  182. header.MergeParameters(SerializeParamsForMove(transactionId, context.Config->Prefix, sourcePath, destinationPath, options));
  183. return ParseGuidFromResponse(RequestWithoutRetry( context, header).Response);
  184. }
  185. TNodeId MoveInsideMasterCell(
  186. const IRequestRetryPolicyPtr& retryPolicy,
  187. const TClientContext& context,
  188. const TTransactionId& transactionId,
  189. const TYPath& sourcePath,
  190. const TYPath& destinationPath,
  191. const TMoveOptions& options)
  192. {
  193. THttpHeader header("POST", "move");
  194. header.AddMutationId();
  195. auto params = SerializeParamsForMove(transactionId, context.Config->Prefix, sourcePath, destinationPath, options);
  196. // Make cross cell copying disable.
  197. params["enable_cross_cell_copying"] = false;
  198. header.MergeParameters(params);
  199. return ParseGuidFromResponse(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  200. }
  201. void Remove(
  202. const IRequestRetryPolicyPtr& retryPolicy,
  203. const TClientContext& context,
  204. const TTransactionId& transactionId,
  205. const TYPath& path,
  206. const TRemoveOptions& options)
  207. {
  208. THttpHeader header("POST", "remove");
  209. header.AddMutationId();
  210. header.MergeParameters(SerializeParamsForRemove(transactionId, context.Config->Prefix, path, options));
  211. RetryRequestWithPolicy(retryPolicy, context, header);
  212. }
  213. TNode::TListType List(
  214. const IRequestRetryPolicyPtr& retryPolicy,
  215. const TClientContext& context,
  216. const TTransactionId& transactionId,
  217. const TYPath& path,
  218. const TListOptions& options)
  219. {
  220. THttpHeader header("GET", "list");
  221. TYPath updatedPath = AddPathPrefix(path, context.Config->Prefix);
  222. // Translate "//" to "/"
  223. // Translate "//some/constom/prefix/from/config/" to "//some/constom/prefix/from/config"
  224. if (path.empty() && updatedPath.EndsWith('/')) {
  225. updatedPath.pop_back();
  226. }
  227. header.MergeParameters(SerializeParamsForList(transactionId, context.Config->Prefix, updatedPath, options));
  228. auto result = RetryRequestWithPolicy(retryPolicy, context, header);
  229. return NodeFromYsonString(result.Response).AsList();
  230. }
  231. TNodeId Link(
  232. const IRequestRetryPolicyPtr& retryPolicy,
  233. const TClientContext& context,
  234. const TTransactionId& transactionId,
  235. const TYPath& targetPath,
  236. const TYPath& linkPath,
  237. const TLinkOptions& options)
  238. {
  239. THttpHeader header("POST", "link");
  240. header.AddMutationId();
  241. header.MergeParameters(SerializeParamsForLink(transactionId, context.Config->Prefix, targetPath, linkPath, options));
  242. return ParseGuidFromResponse(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  243. }
  244. TLockId Lock(
  245. const IRequestRetryPolicyPtr& retryPolicy,
  246. const TClientContext& context,
  247. const TTransactionId& transactionId,
  248. const TYPath& path,
  249. ELockMode mode,
  250. const TLockOptions& options)
  251. {
  252. THttpHeader header("POST", "lock");
  253. header.AddMutationId();
  254. header.MergeParameters(SerializeParamsForLock(transactionId, context.Config->Prefix, path, mode, options));
  255. return ParseGuidFromResponse(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  256. }
  257. void Unlock(
  258. IRequestRetryPolicyPtr retryPolicy,
  259. const TClientContext& context,
  260. const TTransactionId& transactionId,
  261. const TYPath& path,
  262. const TUnlockOptions& options)
  263. {
  264. THttpHeader header("POST", "unlock");
  265. header.AddMutationId();
  266. header.MergeParameters(SerializeParamsForUnlock(transactionId, context.Config->Prefix, path, options));
  267. RetryRequestWithPolicy(retryPolicy, context, header);
  268. }
  269. void Concatenate(
  270. const TClientContext& context,
  271. const TTransactionId& transactionId,
  272. const TVector<TRichYPath>& sourcePaths,
  273. const TRichYPath& destinationPath,
  274. const TConcatenateOptions& options)
  275. {
  276. THttpHeader header("POST", "concatenate");
  277. header.AddMutationId();
  278. header.MergeParameters(SerializeParamsForConcatenate(transactionId, context.Config->Prefix, sourcePaths, destinationPath, options));
  279. RequestWithoutRetry(context, header);
  280. }
  281. void PingTx(
  282. const IRequestRetryPolicyPtr& retryPolicy,
  283. const TClientContext& context,
  284. const TTransactionId& transactionId)
  285. {
  286. THttpHeader header("POST", "ping_tx");
  287. header.MergeParameters(SerializeParamsForPingTx(transactionId));
  288. TRequestConfig requestConfig;
  289. requestConfig.HttpConfig = NHttpClient::THttpConfig{
  290. .SocketTimeout = context.Config->PingTimeout
  291. };
  292. RetryRequestWithPolicy(retryPolicy, context, header, {}, requestConfig);
  293. }
  294. TOperationAttributes ParseOperationAttributes(const TNode& node)
  295. {
  296. const auto& mapNode = node.AsMap();
  297. TOperationAttributes result;
  298. if (auto idNode = mapNode.FindPtr("id")) {
  299. result.Id = GetGuid(idNode->AsString());
  300. }
  301. if (auto typeNode = mapNode.FindPtr("type")) {
  302. result.Type = FromString<EOperationType>(typeNode->AsString());
  303. } else if (auto operationTypeNode = mapNode.FindPtr("operation_type")) {
  304. // COMPAT(levysotsky): "operation_type" is a deprecated synonym for "type".
  305. // This branch should be removed when all clusters are updated.
  306. result.Type = FromString<EOperationType>(operationTypeNode->AsString());
  307. }
  308. if (auto stateNode = mapNode.FindPtr("state")) {
  309. result.State = stateNode->AsString();
  310. // We don't use FromString here, because OS_IN_PROGRESS unites many states: "initializing", "running", etc.
  311. if (*result.State == "completed") {
  312. result.BriefState = EOperationBriefState::Completed;
  313. } else if (*result.State == "aborted") {
  314. result.BriefState = EOperationBriefState::Aborted;
  315. } else if (*result.State == "failed") {
  316. result.BriefState = EOperationBriefState::Failed;
  317. } else {
  318. result.BriefState = EOperationBriefState::InProgress;
  319. }
  320. }
  321. if (auto authenticatedUserNode = mapNode.FindPtr("authenticated_user")) {
  322. result.AuthenticatedUser = authenticatedUserNode->AsString();
  323. }
  324. if (auto startTimeNode = mapNode.FindPtr("start_time")) {
  325. result.StartTime = TInstant::ParseIso8601(startTimeNode->AsString());
  326. }
  327. if (auto finishTimeNode = mapNode.FindPtr("finish_time")) {
  328. result.FinishTime = TInstant::ParseIso8601(finishTimeNode->AsString());
  329. }
  330. auto briefProgressNode = mapNode.FindPtr("brief_progress");
  331. if (briefProgressNode && briefProgressNode->HasKey("jobs")) {
  332. result.BriefProgress.ConstructInPlace();
  333. static auto load = [] (const TNode& item) {
  334. // Backward compatibility with old YT versions
  335. return item.IsInt64() ? item.AsInt64() : item["total"].AsInt64();
  336. };
  337. const auto& jobs = (*briefProgressNode)["jobs"];
  338. result.BriefProgress->Aborted = load(jobs["aborted"]);
  339. result.BriefProgress->Completed = load(jobs["completed"]);
  340. result.BriefProgress->Running = jobs["running"].AsInt64();
  341. result.BriefProgress->Total = jobs["total"].AsInt64();
  342. result.BriefProgress->Failed = jobs["failed"].AsInt64();
  343. result.BriefProgress->Lost = jobs["lost"].AsInt64();
  344. result.BriefProgress->Pending = jobs["pending"].AsInt64();
  345. }
  346. if (auto briefSpecNode = mapNode.FindPtr("brief_spec")) {
  347. result.BriefSpec = *briefSpecNode;
  348. }
  349. if (auto specNode = mapNode.FindPtr("spec")) {
  350. result.Spec = *specNode;
  351. }
  352. if (auto fullSpecNode = mapNode.FindPtr("full_spec")) {
  353. result.FullSpec = *fullSpecNode;
  354. }
  355. if (auto unrecognizedSpecNode = mapNode.FindPtr("unrecognized_spec")) {
  356. result.UnrecognizedSpec = *unrecognizedSpecNode;
  357. }
  358. if (auto suspendedNode = mapNode.FindPtr("suspended")) {
  359. result.Suspended = suspendedNode->AsBool();
  360. }
  361. if (auto resultNode = mapNode.FindPtr("result")) {
  362. result.Result.ConstructInPlace();
  363. auto error = TYtError((*resultNode)["error"]);
  364. if (error.GetCode() != 0) {
  365. result.Result->Error = std::move(error);
  366. }
  367. }
  368. if (auto progressNode = mapNode.FindPtr("progress")) {
  369. const auto& progressMap = progressNode->AsMap();
  370. TMaybe<TInstant> buildTime;
  371. if (auto buildTimeNode = progressMap.FindPtr("build_time")) {
  372. buildTime = TInstant::ParseIso8601(buildTimeNode->AsString());
  373. }
  374. TJobStatistics jobStatistics;
  375. if (auto jobStatisticsNode = progressMap.FindPtr("job_statistics")) {
  376. jobStatistics = TJobStatistics(*jobStatisticsNode);
  377. }
  378. TJobCounters jobCounters;
  379. if (auto jobCountersNode = progressMap.FindPtr("total_job_counter")) {
  380. jobCounters = TJobCounters(*jobCountersNode);
  381. }
  382. result.Progress = TOperationProgress{
  383. .JobStatistics = std::move(jobStatistics),
  384. .JobCounters = std::move(jobCounters),
  385. .BuildTime = buildTime,
  386. };
  387. }
  388. if (auto eventsNode = mapNode.FindPtr("events")) {
  389. result.Events.ConstructInPlace().reserve(eventsNode->Size());
  390. for (const auto& eventNode : eventsNode->AsList()) {
  391. result.Events->push_back(TOperationEvent{
  392. eventNode["state"].AsString(),
  393. TInstant::ParseIso8601(eventNode["time"].AsString()),
  394. });
  395. }
  396. }
  397. if (auto alertsNode = mapNode.FindPtr("alerts")) {
  398. result.Alerts.ConstructInPlace();
  399. for (const auto& [alertType, alertError] : alertsNode->AsMap()) {
  400. result.Alerts->emplace(alertType, TYtError(alertError));
  401. }
  402. }
  403. return result;
  404. }
  405. TOperationAttributes GetOperation(
  406. const IRequestRetryPolicyPtr& retryPolicy,
  407. const TClientContext& context,
  408. const TOperationId& operationId,
  409. const TGetOperationOptions& options)
  410. {
  411. THttpHeader header("GET", "get_operation");
  412. header.MergeParameters(SerializeParamsForGetOperation(operationId, options));
  413. auto result = RetryRequestWithPolicy(retryPolicy, context, header);
  414. return ParseOperationAttributes(NodeFromYsonString(result.Response));
  415. }
  416. TOperationAttributes GetOperation(
  417. const IRequestRetryPolicyPtr& retryPolicy,
  418. const TClientContext& context,
  419. const TString& alias,
  420. const TGetOperationOptions& options)
  421. {
  422. THttpHeader header("GET", "get_operation");
  423. header.MergeParameters(SerializeParamsForGetOperation(alias, options));
  424. auto result = RetryRequestWithPolicy(retryPolicy, context, header);
  425. return ParseOperationAttributes(NodeFromYsonString(result.Response));
  426. }
  427. void AbortOperation(
  428. const IRequestRetryPolicyPtr& retryPolicy,
  429. const TClientContext& context,
  430. const TOperationId& operationId)
  431. {
  432. THttpHeader header("POST", "abort_op");
  433. header.AddMutationId();
  434. header.MergeParameters(SerializeParamsForAbortOperation(operationId));
  435. RetryRequestWithPolicy(retryPolicy, context, header);
  436. }
  437. void CompleteOperation(
  438. const IRequestRetryPolicyPtr& retryPolicy,
  439. const TClientContext& context,
  440. const TOperationId& operationId)
  441. {
  442. THttpHeader header("POST", "complete_op");
  443. header.AddMutationId();
  444. header.MergeParameters(SerializeParamsForCompleteOperation(operationId));
  445. RetryRequestWithPolicy(retryPolicy, context, header);
  446. }
  447. void SuspendOperation(
  448. const IRequestRetryPolicyPtr& retryPolicy,
  449. const TClientContext& context,
  450. const TOperationId& operationId,
  451. const TSuspendOperationOptions& options)
  452. {
  453. THttpHeader header("POST", "suspend_op");
  454. header.AddMutationId();
  455. header.MergeParameters(SerializeParamsForSuspendOperation(operationId, options));
  456. RetryRequestWithPolicy(retryPolicy, context, header);
  457. }
  458. void ResumeOperation(
  459. const IRequestRetryPolicyPtr& retryPolicy,
  460. const TClientContext& context,
  461. const TOperationId& operationId,
  462. const TResumeOperationOptions& options)
  463. {
  464. THttpHeader header("POST", "resume_op");
  465. header.AddMutationId();
  466. header.MergeParameters(SerializeParamsForResumeOperation(operationId, options));
  467. RetryRequestWithPolicy(retryPolicy, context, header);
  468. }
  469. template <typename TKey>
  470. static THashMap<TKey, i64> GetCounts(const TNode& countsNode)
  471. {
  472. THashMap<TKey, i64> counts;
  473. for (const auto& entry : countsNode.AsMap()) {
  474. counts.emplace(FromString<TKey>(entry.first), entry.second.AsInt64());
  475. }
  476. return counts;
  477. }
  478. TListOperationsResult ListOperations(
  479. const IRequestRetryPolicyPtr& retryPolicy,
  480. const TClientContext& context,
  481. const TListOperationsOptions& options)
  482. {
  483. THttpHeader header("GET", "list_operations");
  484. header.MergeParameters(SerializeParamsForListOperations(options));
  485. auto responseInfo = RetryRequestWithPolicy(retryPolicy, context, header);
  486. auto resultNode = NodeFromYsonString(responseInfo.Response);
  487. TListOperationsResult result;
  488. for (const auto& operationNode : resultNode["operations"].AsList()) {
  489. result.Operations.push_back(ParseOperationAttributes(operationNode));
  490. }
  491. if (resultNode.HasKey("pool_counts")) {
  492. result.PoolCounts = GetCounts<TString>(resultNode["pool_counts"]);
  493. }
  494. if (resultNode.HasKey("user_counts")) {
  495. result.UserCounts = GetCounts<TString>(resultNode["user_counts"]);
  496. }
  497. if (resultNode.HasKey("type_counts")) {
  498. result.TypeCounts = GetCounts<EOperationType>(resultNode["type_counts"]);
  499. }
  500. if (resultNode.HasKey("state_counts")) {
  501. result.StateCounts = GetCounts<TString>(resultNode["state_counts"]);
  502. }
  503. if (resultNode.HasKey("failed_jobs_count")) {
  504. result.WithFailedJobsCount = resultNode["failed_jobs_count"].AsInt64();
  505. }
  506. result.Incomplete = resultNode["incomplete"].AsBool();
  507. return result;
  508. }
  509. void UpdateOperationParameters(
  510. const IRequestRetryPolicyPtr& retryPolicy,
  511. const TClientContext& context,
  512. const TOperationId& operationId,
  513. const TUpdateOperationParametersOptions& options)
  514. {
  515. THttpHeader header("POST", "update_op_parameters");
  516. header.MergeParameters(SerializeParamsForUpdateOperationParameters(operationId, options));
  517. RetryRequestWithPolicy(retryPolicy, context, header);
  518. }
  519. TJobAttributes ParseJobAttributes(const TNode& node)
  520. {
  521. const auto& mapNode = node.AsMap();
  522. TJobAttributes result;
  523. // Currently "get_job" returns "job_id" field and "list_jobs" returns "id" field.
  524. auto idNode = mapNode.FindPtr("id");
  525. if (!idNode) {
  526. idNode = mapNode.FindPtr("job_id");
  527. }
  528. if (idNode) {
  529. result.Id = GetGuid(idNode->AsString());
  530. }
  531. if (auto typeNode = mapNode.FindPtr("type")) {
  532. result.Type = FromString<EJobType>(typeNode->AsString());
  533. }
  534. if (auto stateNode = mapNode.FindPtr("state")) {
  535. result.State = FromString<EJobState>(stateNode->AsString());
  536. }
  537. if (auto addressNode = mapNode.FindPtr("address")) {
  538. result.Address = addressNode->AsString();
  539. }
  540. if (auto taskNameNode = mapNode.FindPtr("task_name")) {
  541. result.TaskName = taskNameNode->AsString();
  542. }
  543. if (auto startTimeNode = mapNode.FindPtr("start_time")) {
  544. result.StartTime = TInstant::ParseIso8601(startTimeNode->AsString());
  545. }
  546. if (auto finishTimeNode = mapNode.FindPtr("finish_time")) {
  547. result.FinishTime = TInstant::ParseIso8601(finishTimeNode->AsString());
  548. }
  549. if (auto progressNode = mapNode.FindPtr("progress")) {
  550. result.Progress = progressNode->AsDouble();
  551. }
  552. if (auto stderrSizeNode = mapNode.FindPtr("stderr_size")) {
  553. result.StderrSize = stderrSizeNode->AsUint64();
  554. }
  555. if (auto errorNode = mapNode.FindPtr("error")) {
  556. result.Error.ConstructInPlace(*errorNode);
  557. }
  558. if (auto briefStatisticsNode = mapNode.FindPtr("brief_statistics")) {
  559. result.BriefStatistics = *briefStatisticsNode;
  560. }
  561. if (auto inputPathsNode = mapNode.FindPtr("input_paths")) {
  562. const auto& inputPathNodesList = inputPathsNode->AsList();
  563. result.InputPaths.ConstructInPlace();
  564. result.InputPaths->reserve(inputPathNodesList.size());
  565. for (const auto& inputPathNode : inputPathNodesList) {
  566. TRichYPath path;
  567. Deserialize(path, inputPathNode);
  568. result.InputPaths->push_back(std::move(path));
  569. }
  570. }
  571. if (auto coreInfosNode = mapNode.FindPtr("core_infos")) {
  572. const auto& coreInfoNodesList = coreInfosNode->AsList();
  573. result.CoreInfos.ConstructInPlace();
  574. result.CoreInfos->reserve(coreInfoNodesList.size());
  575. for (const auto& coreInfoNode : coreInfoNodesList) {
  576. TCoreInfo coreInfo;
  577. coreInfo.ProcessId = coreInfoNode["process_id"].AsInt64();
  578. coreInfo.ExecutableName = coreInfoNode["executable_name"].AsString();
  579. if (coreInfoNode.HasKey("size")) {
  580. coreInfo.Size = coreInfoNode["size"].AsUint64();
  581. }
  582. if (coreInfoNode.HasKey("error")) {
  583. coreInfo.Error.ConstructInPlace(coreInfoNode["error"]);
  584. }
  585. result.CoreInfos->push_back(std::move(coreInfo));
  586. }
  587. }
  588. return result;
  589. }
  590. TJobAttributes GetJob(
  591. const IRequestRetryPolicyPtr& retryPolicy,
  592. const TClientContext& context,
  593. const TOperationId& operationId,
  594. const TJobId& jobId,
  595. const TGetJobOptions& options)
  596. {
  597. THttpHeader header("GET", "get_job");
  598. header.MergeParameters(SerializeParamsForGetJob(operationId, jobId, options));
  599. auto responseInfo = RetryRequestWithPolicy(retryPolicy, context, header);
  600. auto resultNode = NodeFromYsonString(responseInfo.Response);
  601. return ParseJobAttributes(resultNode);
  602. }
  603. TListJobsResult ListJobs(
  604. const IRequestRetryPolicyPtr& retryPolicy,
  605. const TClientContext& context,
  606. const TOperationId& operationId,
  607. const TListJobsOptions& options)
  608. {
  609. THttpHeader header("GET", "list_jobs");
  610. header.MergeParameters(SerializeParamsForListJobs(operationId, options));
  611. auto responseInfo = RetryRequestWithPolicy(retryPolicy, context, header);
  612. auto resultNode = NodeFromYsonString(responseInfo.Response);
  613. TListJobsResult result;
  614. const auto& jobNodesList = resultNode["jobs"].AsList();
  615. result.Jobs.reserve(jobNodesList.size());
  616. for (const auto& jobNode : jobNodesList) {
  617. result.Jobs.push_back(ParseJobAttributes(jobNode));
  618. }
  619. if (resultNode.HasKey("cypress_job_count") && !resultNode["cypress_job_count"].IsNull()) {
  620. result.CypressJobCount = resultNode["cypress_job_count"].AsInt64();
  621. }
  622. if (resultNode.HasKey("controller_agent_job_count") && !resultNode["controller_agent_job_count"].IsNull()) {
  623. result.ControllerAgentJobCount = resultNode["scheduler_job_count"].AsInt64();
  624. }
  625. if (resultNode.HasKey("archive_job_count") && !resultNode["archive_job_count"].IsNull()) {
  626. result.ArchiveJobCount = resultNode["archive_job_count"].AsInt64();
  627. }
  628. return result;
  629. }
  630. class TResponseReader
  631. : public IFileReader
  632. {
  633. public:
  634. TResponseReader(const TClientContext& context, THttpHeader header)
  635. {
  636. if (context.ServiceTicketAuth) {
  637. header.SetServiceTicket(context.ServiceTicketAuth->Ptr->IssueServiceTicket());
  638. } else {
  639. header.SetToken(context.Token);
  640. }
  641. if (context.ImpersonationUser) {
  642. header.SetImpersonationUser(*context.ImpersonationUser);
  643. }
  644. auto hostName = GetProxyForHeavyRequest(context);
  645. auto requestId = CreateGuidAsString();
  646. UpdateHeaderForProxyIfNeed(hostName, context, header);
  647. Response_ = context.HttpClient->Request(GetFullUrl(hostName, context, header), requestId, header);
  648. ResponseStream_ = Response_->GetResponseStream();
  649. }
  650. private:
  651. size_t DoRead(void* buf, size_t len) override
  652. {
  653. return ResponseStream_->Read(buf, len);
  654. }
  655. size_t DoSkip(size_t len) override
  656. {
  657. return ResponseStream_->Skip(len);
  658. }
  659. private:
  660. THttpRequest Request_;
  661. NHttpClient::IHttpResponsePtr Response_;
  662. IInputStream* ResponseStream_;
  663. };
  664. IFileReaderPtr GetJobInput(
  665. const TClientContext& context,
  666. const TJobId& jobId,
  667. const TGetJobInputOptions& /* options */)
  668. {
  669. THttpHeader header("GET", "get_job_input");
  670. header.AddParameter("job_id", GetGuidAsString(jobId));
  671. return new TResponseReader(context, std::move(header));
  672. }
  673. IFileReaderPtr GetJobFailContext(
  674. const TClientContext& context,
  675. const TOperationId& operationId,
  676. const TJobId& jobId,
  677. const TGetJobFailContextOptions& /* options */)
  678. {
  679. THttpHeader header("GET", "get_job_fail_context");
  680. header.AddOperationId(operationId);
  681. header.AddParameter("job_id", GetGuidAsString(jobId));
  682. return new TResponseReader(context, std::move(header));
  683. }
  684. TString GetJobStderrWithRetries(
  685. const IRequestRetryPolicyPtr& retryPolicy,
  686. const TClientContext& context,
  687. const TOperationId& operationId,
  688. const TJobId& jobId,
  689. const TGetJobStderrOptions& /* options */)
  690. {
  691. THttpHeader header("GET", "get_job_stderr");
  692. header.AddOperationId(operationId);
  693. header.AddParameter("job_id", GetGuidAsString(jobId));
  694. TRequestConfig config;
  695. config.IsHeavy = true;
  696. auto responseInfo = RetryRequestWithPolicy(retryPolicy, context, header, {}, config);
  697. return responseInfo.Response;
  698. }
  699. IFileReaderPtr GetJobStderr(
  700. const TClientContext& context,
  701. const TOperationId& operationId,
  702. const TJobId& jobId,
  703. const TGetJobStderrOptions& /* options */)
  704. {
  705. THttpHeader header("GET", "get_job_stderr");
  706. header.AddOperationId(operationId);
  707. header.AddParameter("job_id", GetGuidAsString(jobId));
  708. return new TResponseReader(context, std::move(header));
  709. }
  710. TMaybe<TYPath> GetFileFromCache(
  711. const IRequestRetryPolicyPtr& retryPolicy,
  712. const TClientContext& context,
  713. const TTransactionId& transactionId,
  714. const TString& md5Signature,
  715. const TYPath& cachePath,
  716. const TGetFileFromCacheOptions& options)
  717. {
  718. THttpHeader header("GET", "get_file_from_cache");
  719. header.MergeParameters(SerializeParamsForGetFileFromCache(transactionId, md5Signature, cachePath, options));
  720. auto responseInfo = RetryRequestWithPolicy(retryPolicy, context, header);
  721. auto path = NodeFromYsonString(responseInfo.Response).AsString();
  722. return path.empty() ? Nothing() : TMaybe<TYPath>(path);
  723. }
  724. TYPath PutFileToCache(
  725. const IRequestRetryPolicyPtr& retryPolicy,
  726. const TClientContext& context,
  727. const TTransactionId& transactionId,
  728. const TYPath& filePath,
  729. const TString& md5Signature,
  730. const TYPath& cachePath,
  731. const TPutFileToCacheOptions& options)
  732. {
  733. THttpHeader header("POST", "put_file_to_cache");
  734. header.MergeParameters(SerializeParamsForPutFileToCache(transactionId, context.Config->Prefix, filePath, md5Signature, cachePath, options));
  735. auto result = RetryRequestWithPolicy(retryPolicy, context, header);
  736. return NodeFromYsonString(result.Response).AsString();
  737. }
  738. TNode::TListType SkyShareTable(
  739. const IRequestRetryPolicyPtr& retryPolicy,
  740. const TClientContext& context,
  741. const std::vector<TYPath>& tablePaths,
  742. const TSkyShareTableOptions& options)
  743. {
  744. THttpHeader header("POST", "api/v1/share", /*IsApi*/ false);
  745. auto proxyName = context.ServerName.substr(0, context.ServerName.find('.'));
  746. auto host = context.Config->SkynetApiHost;
  747. if (host == "") {
  748. host = "skynet." + proxyName + ".yt.yandex.net";
  749. }
  750. header.MergeParameters(SerializeParamsForSkyShareTable(proxyName, context.Config->Prefix, tablePaths, options));
  751. TClientContext skyApiHost({ .ServerName = host, .HttpClient = NHttpClient::CreateDefaultHttpClient() });
  752. TResponseInfo response = {};
  753. // As documented at https://wiki.yandex-team.ru/yt/userdoc/blob_tables/#shag3.sozdajomrazdachu
  754. // first request returns HTTP status code 202 (Accepted). And we need retrying until we have 200 (OK).
  755. while (response.HttpCode != 200) {
  756. response = RetryRequestWithPolicy(retryPolicy, skyApiHost, header, "");
  757. TWaitProxy::Get()->Sleep(TDuration::Seconds(5));
  758. }
  759. if (options.KeyColumns_) {
  760. return NodeFromJsonString(response.Response)["torrents"].AsList();
  761. } else {
  762. TNode torrent;
  763. torrent["key"] = TNode::CreateList();
  764. torrent["rbtorrent"] = response.Response;
  765. return TNode::TListType{ torrent };
  766. }
  767. }
  768. TCheckPermissionResponse ParseCheckPermissionResponse(const TNode& node)
  769. {
  770. auto parseSingleResult = [] (const TNode::TMapType& node) {
  771. TCheckPermissionResult result;
  772. result.Action = ::FromString<ESecurityAction>(node.at("action").AsString());
  773. if (auto objectId = node.FindPtr("object_id")) {
  774. result.ObjectId = GetGuid(objectId->AsString());
  775. }
  776. if (auto objectName = node.FindPtr("object_name")) {
  777. result.ObjectName = objectName->AsString();
  778. }
  779. if (auto subjectId = node.FindPtr("subject_id")) {
  780. result.SubjectId = GetGuid(subjectId->AsString());
  781. }
  782. if (auto subjectName = node.FindPtr("subject_name")) {
  783. result.SubjectName = subjectName->AsString();
  784. }
  785. return result;
  786. };
  787. const auto& mapNode = node.AsMap();
  788. TCheckPermissionResponse result;
  789. static_cast<TCheckPermissionResult&>(result) = parseSingleResult(mapNode);
  790. if (auto columns = mapNode.FindPtr("columns")) {
  791. result.Columns.reserve(columns->AsList().size());
  792. for (const auto& columnNode : columns->AsList()) {
  793. result.Columns.push_back(parseSingleResult(columnNode.AsMap()));
  794. }
  795. }
  796. return result;
  797. }
  798. TCheckPermissionResponse CheckPermission(
  799. const IRequestRetryPolicyPtr& retryPolicy,
  800. const TClientContext& context,
  801. const TString& user,
  802. EPermission permission,
  803. const TYPath& path,
  804. const TCheckPermissionOptions& options)
  805. {
  806. THttpHeader header("GET", "check_permission");
  807. header.MergeParameters(SerializeParamsForCheckPermission(user, permission, context.Config->Prefix, path, options));
  808. auto response = RetryRequestWithPolicy(retryPolicy, context, header);
  809. return ParseCheckPermissionResponse(NodeFromYsonString(response.Response));
  810. }
  811. TVector<TTabletInfo> GetTabletInfos(
  812. const IRequestRetryPolicyPtr& retryPolicy,
  813. const TClientContext& context,
  814. const TYPath& path,
  815. const TVector<int>& tabletIndexes,
  816. const TGetTabletInfosOptions& options)
  817. {
  818. THttpHeader header("POST", "api/v4/get_tablet_infos", false);
  819. header.MergeParameters(SerializeParamsForGetTabletInfos(context.Config->Prefix, path, tabletIndexes, options));
  820. auto response = RetryRequestWithPolicy(retryPolicy, context, header);
  821. TVector<TTabletInfo> result;
  822. Deserialize(result, *NodeFromYsonString(response.Response).AsMap().FindPtr("tablets"));
  823. return result;
  824. }
  825. TVector<TTableColumnarStatistics> GetTableColumnarStatistics(
  826. const IRequestRetryPolicyPtr& retryPolicy,
  827. const TClientContext& context,
  828. const TTransactionId& transactionId,
  829. const TVector<TRichYPath>& paths,
  830. const TGetTableColumnarStatisticsOptions& options)
  831. {
  832. THttpHeader header("GET", "get_table_columnar_statistics");
  833. header.MergeParameters(SerializeParamsForGetTableColumnarStatistics(transactionId, paths, options));
  834. TRequestConfig config;
  835. config.IsHeavy = true;
  836. auto requestResult = RetryRequestWithPolicy(retryPolicy, context, header, {}, config);
  837. auto response = NodeFromYsonString(requestResult.Response);
  838. TVector<TTableColumnarStatistics> result;
  839. Deserialize(result, response);
  840. return result;
  841. }
  842. TMultiTablePartitions GetTablePartitions(
  843. const IRequestRetryPolicyPtr& retryPolicy,
  844. const TClientContext& context,
  845. const TTransactionId& transactionId,
  846. const TVector<TRichYPath>& paths,
  847. const TGetTablePartitionsOptions& options)
  848. {
  849. THttpHeader header("GET", "partition_tables");
  850. header.MergeParameters(SerializeParamsForGetTablePartitions(transactionId, paths, options));
  851. TRequestConfig config;
  852. config.IsHeavy = true;
  853. auto requestResult = RetryRequestWithPolicy(retryPolicy, context, header, {}, config);
  854. auto response = NodeFromYsonString(requestResult.Response);
  855. TMultiTablePartitions result;
  856. Deserialize(result, response);
  857. return result;
  858. }
  859. TRichYPath CanonizeYPath(
  860. const IRequestRetryPolicyPtr& retryPolicy,
  861. const TClientContext& context,
  862. const TRichYPath& path)
  863. {
  864. return CanonizeYPaths(retryPolicy, context, {path}).front();
  865. }
  866. TVector<TRichYPath> CanonizeYPaths(
  867. const IRequestRetryPolicyPtr& retryPolicy,
  868. const TClientContext& context,
  869. const TVector<TRichYPath>& paths)
  870. {
  871. TRawBatchRequest batch(context.Config);
  872. TVector<NThreading::TFuture<TRichYPath>> futures;
  873. futures.reserve(paths.size());
  874. for (int i = 0; i < static_cast<int>(paths.size()); ++i) {
  875. futures.push_back(batch.CanonizeYPath(paths[i]));
  876. }
  877. ExecuteBatch(retryPolicy, context, batch, TExecuteBatchOptions{});
  878. TVector<TRichYPath> result;
  879. result.reserve(futures.size());
  880. for (auto& future : futures) {
  881. result.push_back(future.ExtractValueSync());
  882. }
  883. return result;
  884. }
  885. void AlterTable(
  886. const IRequestRetryPolicyPtr& retryPolicy,
  887. const TClientContext& context,
  888. const TTransactionId& transactionId,
  889. const TYPath& path,
  890. const TAlterTableOptions& options)
  891. {
  892. THttpHeader header("POST", "alter_table");
  893. header.AddMutationId();
  894. header.MergeParameters(SerializeParamsForAlterTable(transactionId, context.Config->Prefix, path, options));
  895. RetryRequestWithPolicy(retryPolicy, context, header);
  896. }
  897. void AlterTableReplica(
  898. const IRequestRetryPolicyPtr& retryPolicy,
  899. const TClientContext& context,
  900. const TReplicaId& replicaId,
  901. const TAlterTableReplicaOptions& options)
  902. {
  903. THttpHeader header("POST", "alter_table_replica");
  904. header.AddMutationId();
  905. header.MergeParameters(NRawClient::SerializeParamsForAlterTableReplica(replicaId, options));
  906. RetryRequestWithPolicy(retryPolicy, context, header);
  907. }
  908. void DeleteRows(
  909. const IRequestRetryPolicyPtr& retryPolicy,
  910. const TClientContext& context,
  911. const TYPath& path,
  912. const TNode::TListType& keys,
  913. const TDeleteRowsOptions& options)
  914. {
  915. THttpHeader header("PUT", "delete_rows");
  916. header.SetInputFormat(TFormat::YsonBinary());
  917. header.MergeParameters(NRawClient::SerializeParametersForDeleteRows(context.Config->Prefix, path, options));
  918. auto body = NodeListToYsonString(keys);
  919. TRequestConfig requestConfig;
  920. requestConfig.IsHeavy = true;
  921. RetryRequestWithPolicy(retryPolicy, context, header, body, requestConfig);
  922. }
  923. void FreezeTable(
  924. const IRequestRetryPolicyPtr& retryPolicy,
  925. const TClientContext& context,
  926. const TYPath& path,
  927. const TFreezeTableOptions& options)
  928. {
  929. THttpHeader header("POST", "freeze_table");
  930. header.MergeParameters(SerializeParamsForFreezeTable(context.Config->Prefix, path, options));
  931. RetryRequestWithPolicy(retryPolicy, context, header);
  932. }
  933. void UnfreezeTable(
  934. const IRequestRetryPolicyPtr& retryPolicy,
  935. const TClientContext& context,
  936. const TYPath& path,
  937. const TUnfreezeTableOptions& options)
  938. {
  939. THttpHeader header("POST", "unfreeze_table");
  940. header.MergeParameters(SerializeParamsForUnfreezeTable(context.Config->Prefix, path, options));
  941. RetryRequestWithPolicy(retryPolicy, context, header);
  942. }
  943. void AbortTransaction(
  944. const IRequestRetryPolicyPtr& retryPolicy,
  945. const TClientContext& context,
  946. const TTransactionId& transactionId)
  947. {
  948. THttpHeader header("POST", "abort_tx");
  949. header.AddMutationId();
  950. header.MergeParameters(NRawClient::SerializeParamsForAbortTransaction(transactionId));
  951. RetryRequestWithPolicy(retryPolicy, context, header);
  952. }
  953. void CommitTransaction(
  954. const IRequestRetryPolicyPtr& retryPolicy,
  955. const TClientContext& context,
  956. const TTransactionId& transactionId)
  957. {
  958. THttpHeader header("POST", "commit_tx");
  959. header.AddMutationId();
  960. header.MergeParameters(NRawClient::SerializeParamsForCommitTransaction(transactionId));
  961. RetryRequestWithPolicy(retryPolicy, context, header);
  962. }
  963. TTransactionId StartTransaction(
  964. const IRequestRetryPolicyPtr& retryPolicy,
  965. const TClientContext& context,
  966. const TTransactionId& parentTransactionId,
  967. const TStartTransactionOptions& options)
  968. {
  969. THttpHeader header("POST", "start_tx");
  970. header.AddMutationId();
  971. header.MergeParameters(NRawClient::SerializeParamsForStartTransaction(parentTransactionId, context.Config->TxTimeout, options));
  972. return ParseGuidFromResponse(RetryRequestWithPolicy(retryPolicy, context, header).Response);
  973. }
  974. ////////////////////////////////////////////////////////////////////////////////
  975. } // namespace NYT::NDetail::NRawClient