operation.cpp 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143
  1. #include "operation.h"
  2. #include "abortable_registry.h"
  3. #include "client.h"
  4. #include "operation_helpers.h"
  5. #include "operation_tracker.h"
  6. #include "prepare_operation.h"
  7. #include "skiff.h"
  8. #include "structured_table_formats.h"
  9. #include "yt_poller.h"
  10. #include <yt/cpp/mapreduce/common/helpers.h>
  11. #include <yt/cpp/mapreduce/common/retry_lib.h>
  12. #include <yt/cpp/mapreduce/common/wait_proxy.h>
  13. #include <yt/cpp/mapreduce/interface/config.h>
  14. #include <yt/cpp/mapreduce/interface/errors.h>
  15. #include <yt/cpp/mapreduce/interface/fluent.h>
  16. #include <yt/cpp/mapreduce/interface/format.h>
  17. #include <yt/cpp/mapreduce/interface/job_statistics.h>
  18. #include <yt/cpp/mapreduce/interface/protobuf_format.h>
  19. #include <yt/cpp/mapreduce/interface/logging/yt_log.h>
  20. #include <yt/cpp/mapreduce/http/requests.h>
  21. #include <yt/cpp/mapreduce/http/retry_request.h>
  22. #include <yt/cpp/mapreduce/io/job_reader.h>
  23. #include <yt/cpp/mapreduce/io/job_writer.h>
  24. #include <yt/cpp/mapreduce/io/yamr_table_reader.h>
  25. #include <yt/cpp/mapreduce/io/yamr_table_writer.h>
  26. #include <yt/cpp/mapreduce/io/node_table_reader.h>
  27. #include <yt/cpp/mapreduce/io/node_table_writer.h>
  28. #include <yt/cpp/mapreduce/io/proto_table_reader.h>
  29. #include <yt/cpp/mapreduce/io/proto_table_writer.h>
  30. #include <yt/cpp/mapreduce/io/proto_helpers.h>
  31. #include <yt/cpp/mapreduce/io/skiff_table_reader.h>
  32. #include <yt/cpp/mapreduce/http_client/raw_requests.h>
  33. #include <library/cpp/yson/node/serialize.h>
  34. #include <util/generic/hash_set.h>
  35. #include <util/string/builder.h>
  36. #include <util/string/cast.h>
  37. #include <util/system/thread.h>
  38. #include <util/system/env.h>
  39. #include <util/system/fs.h>
  40. namespace NYT {
  41. namespace NDetail {
  42. using ::ToString;
  43. ////////////////////////////////////////////////////////////////////////////////
  44. static const ui64 DefaultExrtaTmpfsSize = 1024LL * 1024LL;
  45. ////////////////////////////////////////////////////////////////////////////////
  46. namespace {
  47. ////////////////////////////////////////////////////////////////////////////////
  48. struct TMapReduceOperationIo
  49. {
  50. TVector<TRichYPath> Inputs;
  51. TVector<TRichYPath> MapOutputs;
  52. TVector<TRichYPath> Outputs;
  53. TMaybe<TFormat> MapperInputFormat;
  54. TMaybe<TFormat> MapperOutputFormat;
  55. TMaybe<TFormat> ReduceCombinerInputFormat;
  56. TMaybe<TFormat> ReduceCombinerOutputFormat;
  57. TFormat ReducerInputFormat = TFormat::YsonBinary();
  58. TFormat ReducerOutputFormat = TFormat::YsonBinary();
  59. TVector<TSmallJobFile> MapperJobFiles;
  60. TVector<TSmallJobFile> ReduceCombinerJobFiles;
  61. TVector<TSmallJobFile> ReducerJobFiles;
  62. };
  63. template <typename T>
  64. void VerifyHasElements(const TVector<T>& paths, TStringBuf name)
  65. {
  66. if (paths.empty()) {
  67. ythrow TApiUsageError() << "no " << name << " table is specified";
  68. }
  69. }
  70. ////////////////////////////////////////////////////////////////////////////////
  71. TVector<TSmallJobFile> CreateFormatConfig(
  72. TMaybe<TSmallJobFile> inputConfig,
  73. const TMaybe<TSmallJobFile>& outputConfig)
  74. {
  75. TVector<TSmallJobFile> result;
  76. if (inputConfig) {
  77. result.push_back(std::move(*inputConfig));
  78. }
  79. if (outputConfig) {
  80. result.push_back(std::move(*outputConfig));
  81. }
  82. return result;
  83. }
  84. template <typename T>
  85. ENodeReaderFormat NodeReaderFormatFromHintAndGlobalConfig(const TUserJobFormatHintsBase<T>& formatHints)
  86. {
  87. auto result = TConfig::Get()->NodeReaderFormat;
  88. if (formatHints.InputFormatHints_ && formatHints.InputFormatHints_->SkipNullValuesForTNode_) {
  89. Y_ENSURE_EX(
  90. result != ENodeReaderFormat::Skiff,
  91. TApiUsageError() << "skiff format doesn't support SkipNullValuesForTNode format hint");
  92. result = ENodeReaderFormat::Yson;
  93. }
  94. return result;
  95. }
  96. template <class TSpec>
  97. const TVector<TStructuredTablePath>& GetStructuredInputs(const TSpec& spec)
  98. {
  99. if constexpr (std::is_same_v<TSpec, TVanillaTask>) {
  100. static const TVector<TStructuredTablePath> empty;
  101. return empty;
  102. } else {
  103. return spec.GetStructuredInputs();
  104. }
  105. }
  106. template <class TSpec>
  107. const TVector<TStructuredTablePath>& GetStructuredOutputs(const TSpec& spec)
  108. {
  109. return spec.GetStructuredOutputs();
  110. }
  111. template <class TSpec>
  112. const TMaybe<TFormatHints>& GetInputFormatHints(const TSpec& spec)
  113. {
  114. if constexpr (std::is_same_v<TSpec, TVanillaTask>) {
  115. static const TMaybe<TFormatHints> empty = Nothing();
  116. return empty;
  117. } else {
  118. return spec.InputFormatHints_;
  119. }
  120. }
  121. template <class TSpec>
  122. const TMaybe<TFormatHints>& GetOutputFormatHints(const TSpec& spec)
  123. {
  124. return spec.OutputFormatHints_;
  125. }
  126. template <class TSpec>
  127. ENodeReaderFormat GetNodeReaderFormat(const TSpec& spec, bool allowSkiff)
  128. {
  129. if constexpr (std::is_same<TSpec, TVanillaTask>::value) {
  130. return ENodeReaderFormat::Yson;
  131. } else {
  132. return allowSkiff
  133. ? NodeReaderFormatFromHintAndGlobalConfig(spec)
  134. : ENodeReaderFormat::Yson;
  135. }
  136. }
  137. static void SortColumnsToNames(const TSortColumns& sortColumns, THashSet<TString>* result)
  138. {
  139. auto names = sortColumns.GetNames();
  140. result->insert(names.begin(), names.end());
  141. }
  142. static THashSet<TString> SortColumnsToNames(const TSortColumns& sortColumns)
  143. {
  144. THashSet<TString> columnNames;
  145. SortColumnsToNames(sortColumns, &columnNames);
  146. return columnNames;
  147. }
  148. THashSet<TString> GetColumnsUsedInOperation(const TJoinReduceOperationSpec& spec)
  149. {
  150. return SortColumnsToNames(spec.JoinBy_);
  151. }
  152. THashSet<TString> GetColumnsUsedInOperation(const TReduceOperationSpec& spec) {
  153. auto result = SortColumnsToNames(spec.SortBy_);
  154. SortColumnsToNames(spec.ReduceBy_, &result);
  155. if (spec.JoinBy_) {
  156. SortColumnsToNames(*spec.JoinBy_, &result);
  157. }
  158. return result;
  159. }
  160. THashSet<TString> GetColumnsUsedInOperation(const TMapReduceOperationSpec& spec)
  161. {
  162. auto result = SortColumnsToNames(spec.SortBy_);
  163. SortColumnsToNames(spec.ReduceBy_, &result);
  164. return result;
  165. }
  166. THashSet<TString> GetColumnsUsedInOperation(const TMapOperationSpec&)
  167. {
  168. return THashSet<TString>();
  169. }
  170. THashSet<TString> GetColumnsUsedInOperation(const TVanillaTask&)
  171. {
  172. return THashSet<TString>();
  173. }
  174. TStructuredJobTableList ApplyProtobufColumnFilters(
  175. const TStructuredJobTableList& tableList,
  176. const TOperationPreparer& preparer,
  177. const THashSet<TString>& columnsUsedInOperations,
  178. const TOperationOptions& options)
  179. {
  180. bool hasInputQuery = options.Spec_.Defined() && options.Spec_->IsMap() && options.Spec_->HasKey("input_query");
  181. if (hasInputQuery) {
  182. return tableList;
  183. }
  184. auto isDynamic = NRawClient::BatchTransform(
  185. preparer.GetClient()->GetRawClient(),
  186. tableList,
  187. [&] (IRawBatchRequestPtr batch, const auto& table) {
  188. return batch->Get(preparer.GetTransactionId(), table.RichYPath->Path_ + "/@dynamic", TGetOptions());
  189. });
  190. auto newTableList = tableList;
  191. for (size_t tableIndex = 0; tableIndex < tableList.size(); ++tableIndex) {
  192. if (isDynamic[tableIndex].AsBool()) {
  193. continue;
  194. }
  195. auto& table = newTableList[tableIndex];
  196. Y_ABORT_UNLESS(table.RichYPath);
  197. if (table.RichYPath->Columns_) {
  198. continue;
  199. }
  200. if (!std::holds_alternative<TProtobufTableStructure>(table.Description)) {
  201. continue;
  202. }
  203. const auto& descriptor = std::get<TProtobufTableStructure>(table.Description).Descriptor;
  204. if (!descriptor) {
  205. continue;
  206. }
  207. auto fromDescriptor = NDetail::InferColumnFilter(*descriptor);
  208. if (!fromDescriptor) {
  209. continue;
  210. }
  211. THashSet<TString> columns(fromDescriptor->begin(), fromDescriptor->end());
  212. columns.insert(columnsUsedInOperations.begin(), columnsUsedInOperations.end());
  213. table.RichYPath->Columns(TVector<TString>(columns.begin(), columns.end()));
  214. }
  215. return newTableList;
  216. }
  217. template <class TSpec>
  218. TSimpleOperationIo CreateSimpleOperationIo(
  219. const IStructuredJob& structuredJob,
  220. const TOperationPreparer& preparer,
  221. const TSpec& spec,
  222. const TOperationOptions& options,
  223. bool allowSkiff)
  224. {
  225. if (!std::holds_alternative<TVoidStructuredRowStream>(structuredJob.GetInputRowStreamDescription())) {
  226. VerifyHasElements(GetStructuredInputs(spec), "input");
  227. }
  228. TUserJobFormatHints hints;
  229. hints.InputFormatHints_ = GetInputFormatHints(spec);
  230. hints.OutputFormatHints_ = GetOutputFormatHints(spec);
  231. ENodeReaderFormat nodeReaderFormat = GetNodeReaderFormat(spec, allowSkiff);
  232. return CreateSimpleOperationIoHelper(
  233. structuredJob,
  234. preparer,
  235. options,
  236. CanonizeStructuredTableList(preparer.GetClient()->GetRawClient(), GetStructuredInputs(spec)),
  237. CanonizeStructuredTableList(preparer.GetClient()->GetRawClient(), GetStructuredOutputs(spec)),
  238. hints,
  239. nodeReaderFormat,
  240. GetColumnsUsedInOperation(spec));
  241. }
  242. template <class T>
  243. TSimpleOperationIo CreateSimpleOperationIo(
  244. const IJob& job,
  245. const TOperationPreparer& preparer,
  246. const TSimpleRawOperationIoSpec<T>& spec)
  247. {
  248. auto getFormatOrDefault = [&] (const TMaybe<TFormat>& maybeFormat, const char* formatName) {
  249. if (maybeFormat) {
  250. return *maybeFormat;
  251. } else if (spec.Format_) {
  252. return *spec.Format_;
  253. } else {
  254. ythrow TApiUsageError() << "Neither " << formatName << "format nor default format is specified for raw operation";
  255. }
  256. };
  257. auto inputs = NRawClient::CanonizeYPaths(preparer.GetClient()->GetRawClient(), spec.GetInputs());
  258. auto outputs = NRawClient::CanonizeYPaths(preparer.GetClient()->GetRawClient(), spec.GetOutputs());
  259. VerifyHasElements(inputs, "input");
  260. VerifyHasElements(outputs, "output");
  261. TUserJobFormatHints hints;
  262. auto outputSchemas = PrepareOperation(
  263. job,
  264. TOperationPreparationContext(
  265. inputs,
  266. outputs,
  267. preparer.GetClient()->GetRawClient(),
  268. preparer.GetClientRetryPolicy(),
  269. preparer.GetTransactionId()),
  270. &inputs,
  271. &outputs,
  272. hints);
  273. Y_ABORT_UNLESS(outputs.size() == outputSchemas.size());
  274. for (int i = 0; i < static_cast<int>(outputs.size()); ++i) {
  275. if (!outputs[i].Schema_ && !outputSchemas[i].Columns().empty()) {
  276. outputs[i].Schema_ = outputSchemas[i];
  277. }
  278. }
  279. return TSimpleOperationIo {
  280. inputs,
  281. outputs,
  282. getFormatOrDefault(spec.InputFormat_, "input"),
  283. getFormatOrDefault(spec.OutputFormat_, "output"),
  284. TVector<TSmallJobFile>{},
  285. };
  286. }
  287. ////////////////////////////////////////////////////////////////////////////////
  288. TString GetJobStderrWithRetriesAndIgnoreErrors(
  289. const IRequestRetryPolicyPtr& retryPolicy,
  290. const IRawClientPtr& rawClient,
  291. const TOperationId& operationId,
  292. const TJobId& jobId,
  293. const size_t stderrTailSize,
  294. const TGetJobStderrOptions& options = {})
  295. {
  296. TString jobStderr;
  297. try {
  298. jobStderr = RequestWithRetry<TString>(
  299. retryPolicy,
  300. [&rawClient, &operationId, &jobId, &options] (TMutationId /*mutationId*/) {
  301. return rawClient->GetJobStderr(operationId, jobId, options)->ReadAll();
  302. });
  303. } catch (const TErrorResponse& e) {
  304. YT_LOG_ERROR("Cannot get job stderr (OperationId: %v, JobId: %v, Error: %v)",
  305. operationId,
  306. jobId,
  307. e.what());
  308. }
  309. if (jobStderr.size() > stderrTailSize) {
  310. jobStderr = jobStderr.substr(jobStderr.size() - stderrTailSize, stderrTailSize);
  311. }
  312. return jobStderr;
  313. }
  314. TVector<TFailedJobInfo> GetFailedJobInfo(
  315. const IClientRetryPolicyPtr& clientRetryPolicy,
  316. const IRawClientPtr& rawClient,
  317. const TOperationId& operationId,
  318. const TGetFailedJobInfoOptions& options)
  319. {
  320. const auto listJobsResult = RequestWithRetry<TListJobsResult>(
  321. clientRetryPolicy->CreatePolicyForGenericRequest(),
  322. [&rawClient, &operationId, &options] (TMutationId /*mutationId*/) {
  323. return rawClient->ListJobs(
  324. operationId,
  325. TListJobsOptions()
  326. .State(EJobState::Failed)
  327. .Limit(options.MaxJobCount_));
  328. });
  329. const auto stderrTailSize = options.StderrTailSize_;
  330. TVector<TFailedJobInfo> result;
  331. for (const auto& job : listJobsResult.Jobs) {
  332. auto& info = result.emplace_back();
  333. Y_ENSURE(job.Id);
  334. info.JobId = *job.Id;
  335. info.Error = job.Error.GetOrElse(TYtError(TString("unknown error")));
  336. if (job.StderrSize.GetOrElse(0) != 0) {
  337. // There are cases when due to bad luck we cannot read stderr even if
  338. // list_jobs reports that stderr_size > 0.
  339. //
  340. // Such errors don't have special error code
  341. // so we ignore all errors and try our luck on other jobs.
  342. info.Stderr = GetJobStderrWithRetriesAndIgnoreErrors(
  343. clientRetryPolicy->CreatePolicyForGenericRequest(),
  344. rawClient,
  345. operationId,
  346. *job.Id,
  347. stderrTailSize);
  348. }
  349. }
  350. return result;
  351. }
  352. struct TGetJobsStderrOptions
  353. {
  354. using TSelf = TGetJobsStderrOptions;
  355. // How many jobs to download. Which jobs will be chosen is undefined.
  356. FLUENT_FIELD_DEFAULT(ui64, MaxJobCount, 10);
  357. // How much of stderr should be downloaded.
  358. FLUENT_FIELD_DEFAULT(ui64, StderrTailSize, 64 * 1024);
  359. };
  360. static TVector<TString> GetJobsStderr(
  361. const IClientRetryPolicyPtr& clientRetryPolicy,
  362. const IRawClientPtr& rawClient,
  363. const TOperationId& operationId,
  364. const TGetJobsStderrOptions& options = {})
  365. {
  366. const auto listJobsResult = RequestWithRetry<TListJobsResult>(
  367. clientRetryPolicy->CreatePolicyForGenericRequest(),
  368. [&rawClient, &operationId, &options] (TMutationId /*mutationId*/) {
  369. return rawClient->ListJobs(
  370. operationId,
  371. TListJobsOptions()
  372. .Limit(options.MaxJobCount_)
  373. .WithStderr(true));
  374. });
  375. const auto stderrTailSize = options.StderrTailSize_;
  376. TVector<TString> result;
  377. for (const auto& job : listJobsResult.Jobs) {
  378. result.push_back(
  379. // There are cases when due to bad luck we cannot read stderr even if
  380. // list_jobs reports that stderr_size > 0.
  381. //
  382. // Such errors don't have special error code
  383. // so we ignore all errors and try our luck on other jobs.
  384. GetJobStderrWithRetriesAndIgnoreErrors(
  385. clientRetryPolicy->CreatePolicyForGenericRequest(),
  386. rawClient,
  387. operationId,
  388. *job.Id,
  389. stderrTailSize)
  390. );
  391. }
  392. return result;
  393. }
  394. int CountIntermediateTables(const TStructuredJobTableList& tables)
  395. {
  396. int result = 0;
  397. for (const auto& table : tables) {
  398. if (table.RichYPath) {
  399. break;
  400. }
  401. ++result;
  402. }
  403. return result;
  404. }
  405. ////////////////////////////////////////////////////////////////////////////////
  406. } // namespace
  407. ////////////////////////////////////////////////////////////////////////////////
  408. TSimpleOperationIo CreateSimpleOperationIoHelper(
  409. const IStructuredJob& structuredJob,
  410. const TOperationPreparer& preparer,
  411. const TOperationOptions& options,
  412. TStructuredJobTableList structuredInputs,
  413. TStructuredJobTableList structuredOutputs,
  414. TUserJobFormatHints hints,
  415. ENodeReaderFormat nodeReaderFormat,
  416. const THashSet<TString>& columnsUsedInOperations)
  417. {
  418. auto intermediateInputTableCount = CountIntermediateTables(structuredInputs);
  419. auto intermediateOutputTableCount = CountIntermediateTables(structuredOutputs);
  420. auto jobSchemaInferenceResult = PrepareOperation(
  421. structuredJob,
  422. TOperationPreparationContext(
  423. structuredInputs,
  424. structuredOutputs,
  425. preparer.GetClient()->GetRawClient(),
  426. preparer.GetClientRetryPolicy(),
  427. preparer.GetTransactionId()),
  428. &structuredInputs,
  429. &structuredOutputs,
  430. hints);
  431. TVector<TSmallJobFile> formatConfigList;
  432. TFormatBuilder formatBuilder(
  433. preparer.GetClient()->GetRawClient(),
  434. preparer.GetClientRetryPolicy(),
  435. preparer.GetContext(),
  436. preparer.GetTransactionId(),
  437. options);
  438. auto [inputFormat, inputFormatConfig] = formatBuilder.CreateFormat(
  439. structuredJob,
  440. EIODirection::Input,
  441. structuredInputs,
  442. hints.InputFormatHints_,
  443. nodeReaderFormat,
  444. /* allowFormatFromTableAttribute = */ true);
  445. auto [outputFormat, outputFormatConfig] = formatBuilder.CreateFormat(
  446. structuredJob,
  447. EIODirection::Output,
  448. structuredOutputs,
  449. hints.OutputFormatHints_,
  450. ENodeReaderFormat::Yson,
  451. /* allowFormatFromTableAttribute = */ false);
  452. const bool inferOutputSchema = options.InferOutputSchema_.GetOrElse(preparer.GetContext().Config->InferTableSchema);
  453. auto outputPaths = GetPathList(
  454. TStructuredJobTableList(structuredOutputs.begin() + intermediateOutputTableCount, structuredOutputs.end()),
  455. TVector<TTableSchema>(jobSchemaInferenceResult.begin() + intermediateOutputTableCount, jobSchemaInferenceResult.end()),
  456. inferOutputSchema);
  457. auto inputPaths = GetPathList(
  458. ApplyProtobufColumnFilters(
  459. TStructuredJobTableList(structuredInputs.begin() + intermediateInputTableCount, structuredInputs.end()),
  460. preparer,
  461. columnsUsedInOperations,
  462. options),
  463. /*schemaInferenceResult*/ Nothing(),
  464. /*inferSchema*/ false);
  465. return TSimpleOperationIo {
  466. inputPaths,
  467. outputPaths,
  468. inputFormat,
  469. outputFormat,
  470. CreateFormatConfig(inputFormatConfig, outputFormatConfig)
  471. };
  472. }
  473. EOperationBriefState CheckOperation(
  474. const IRawClientPtr& rawClient,
  475. const IClientRetryPolicyPtr& clientRetryPolicy,
  476. const TOperationId& operationId)
  477. {
  478. auto attributes = RequestWithRetry<TOperationAttributes>(
  479. clientRetryPolicy->CreatePolicyForGenericRequest(),
  480. [&rawClient, &operationId] (TMutationId /*mutationId*/) {
  481. return rawClient->GetOperation(
  482. operationId,
  483. TGetOperationOptions().AttributeFilter(TOperationAttributeFilter()
  484. .Add(EOperationAttribute::State)
  485. .Add(EOperationAttribute::Result)));
  486. });
  487. Y_ABORT_UNLESS(attributes.BriefState,
  488. "get_operation for operation %s has not returned \"state\" field",
  489. GetGuidAsString(operationId).data());
  490. if (*attributes.BriefState == EOperationBriefState::Completed) {
  491. return EOperationBriefState::Completed;
  492. } else if (*attributes.BriefState == EOperationBriefState::Aborted || *attributes.BriefState == EOperationBriefState::Failed) {
  493. YT_LOG_ERROR("Operation %v %v (%v)",
  494. operationId,
  495. ToString(*attributes.BriefState),
  496. ToString(TOperationExecutionTimeTracker::Get()->Finish(operationId)));
  497. auto failedJobInfoList = GetFailedJobInfo(
  498. clientRetryPolicy,
  499. rawClient,
  500. operationId,
  501. TGetFailedJobInfoOptions());
  502. Y_ABORT_UNLESS(attributes.Result && attributes.Result->Error);
  503. ythrow TOperationFailedError(
  504. *attributes.BriefState == EOperationBriefState::Aborted
  505. ? TOperationFailedError::Aborted
  506. : TOperationFailedError::Failed,
  507. operationId,
  508. *attributes.Result->Error,
  509. failedJobInfoList);
  510. }
  511. return EOperationBriefState::InProgress;
  512. }
  513. void WaitForOperation(
  514. const IClientRetryPolicyPtr& clientRetryPolicy,
  515. const IRawClientPtr& rawClient,
  516. const TClientContext& context,
  517. const TOperationId& operationId)
  518. {
  519. const TDuration checkOperationStateInterval =
  520. UseLocalModeOptimization(rawClient, context, clientRetryPolicy)
  521. ? Min(TDuration::MilliSeconds(100), context.Config->OperationTrackerPollPeriod)
  522. : context.Config->OperationTrackerPollPeriod;
  523. while (true) {
  524. auto status = CheckOperation(rawClient, clientRetryPolicy, operationId);
  525. if (status == EOperationBriefState::Completed) {
  526. YT_LOG_INFO("Operation %v completed (%v)",
  527. operationId,
  528. TOperationExecutionTimeTracker::Get()->Finish(operationId));
  529. break;
  530. }
  531. TWaitProxy::Get()->Sleep(checkOperationStateInterval);
  532. }
  533. }
  534. ////////////////////////////////////////////////////////////////////////////////
  535. namespace {
  536. TNode BuildAutoMergeSpec(const TAutoMergeSpec& options)
  537. {
  538. TNode result;
  539. if (options.Mode_) {
  540. result["mode"] = ToString(*options.Mode_);
  541. }
  542. if (options.MaxIntermediateChunkCount_) {
  543. result["max_intermediate_chunk_count"] = *options.MaxIntermediateChunkCount_;
  544. }
  545. if (options.ChunkCountPerMergeJob_) {
  546. result["chunk_count_per_merge_job"] = *options.ChunkCountPerMergeJob_;
  547. }
  548. if (options.ChunkSizeThreshold_) {
  549. result["chunk_size_threshold"] = *options.ChunkSizeThreshold_;
  550. }
  551. return result;
  552. }
  553. [[maybe_unused]] TNode BuildJobProfilerSpec(const TJobProfilerSpec& profilerSpec)
  554. {
  555. TNode result;
  556. if (profilerSpec.ProfilingBinary_) {
  557. result["binary"] = ToString(*profilerSpec.ProfilingBinary_);
  558. }
  559. if (profilerSpec.ProfilerType_) {
  560. result["type"] = ToString(*profilerSpec.ProfilerType_);
  561. }
  562. if (profilerSpec.ProfilingProbability_) {
  563. result["profiling_probability"] = *profilerSpec.ProfilingProbability_;
  564. }
  565. if (profilerSpec.SamplingFrequency_) {
  566. result["sampling_frequency"] = *profilerSpec.SamplingFrequency_;
  567. }
  568. return result;
  569. }
  570. // Returns undefined node if resources doesn't contain any meaningful field
  571. TNode BuildSchedulerResourcesSpec(const TSchedulerResources& resources)
  572. {
  573. TNode result;
  574. if (resources.UserSlots().Defined()) {
  575. result["user_slots"] = *resources.UserSlots();
  576. }
  577. if (resources.Cpu().Defined()) {
  578. result["cpu"] = *resources.Cpu();
  579. }
  580. if (resources.Memory().Defined()) {
  581. result["memory"] = *resources.Memory();
  582. }
  583. return result;
  584. }
  585. void BuildUserJobFluently(
  586. const TJobPreparer& preparer,
  587. const TMaybe<TFormat>& inputFormat,
  588. const TMaybe<TFormat>& outputFormat,
  589. TFluentMap fluent)
  590. {
  591. const auto& userJobSpec = preparer.GetSpec();
  592. TMaybe<i64> memoryLimit = userJobSpec.MemoryLimit_;
  593. TMaybe<double> cpuLimit = userJobSpec.CpuLimit_;
  594. TMaybe<ui16> portCount = userJobSpec.PortCount_;
  595. // Use 1MB extra tmpfs size by default, it helps to detect job sandbox as tmp directory
  596. // for standard python libraries. See YTADMINREQ-14505 for more details.
  597. auto tmpfsSize = preparer.GetSpec().ExtraTmpfsSize_.GetOrElse(DefaultExrtaTmpfsSize);
  598. if (preparer.ShouldMountSandbox()) {
  599. tmpfsSize += preparer.GetTotalFileSize();
  600. if (tmpfsSize == 0) {
  601. // This can be a case for example when it is local mode and we don't upload binary.
  602. // NOTE: YT doesn't like zero tmpfs size.
  603. tmpfsSize = RoundUpFileSize(1);
  604. }
  605. memoryLimit = memoryLimit.GetOrElse(512ll << 20) + tmpfsSize;
  606. }
  607. fluent
  608. .Item("file_paths").List(preparer.GetFiles())
  609. .DoIf(!preparer.GetLayers().empty(), [&] (TFluentMap fluentMap) {
  610. fluentMap.Item("layer_paths").List(preparer.GetLayers());
  611. })
  612. .DoIf(userJobSpec.DockerImage_.Defined(), [&] (TFluentMap fluentMap) {
  613. fluentMap.Item("docker_image").Value(*userJobSpec.DockerImage_);
  614. })
  615. .Item("command").Value(preparer.GetCommand())
  616. .Item("class_name").Value(preparer.GetClassName())
  617. .DoIf(!userJobSpec.Environment_.empty(), [&] (TFluentMap fluentMap) {
  618. TNode environment;
  619. for (const auto& item : userJobSpec.Environment_) {
  620. environment[item.first] = item.second;
  621. }
  622. fluentMap.Item("environment").Value(environment);
  623. })
  624. .DoIf(userJobSpec.DiskSpaceLimit_.Defined(), [&] (TFluentMap fluentMap) {
  625. fluentMap.Item("disk_space_limit").Value(*userJobSpec.DiskSpaceLimit_);
  626. })
  627. .DoIf(inputFormat.Defined(), [&] (TFluentMap fluentMap) {
  628. fluentMap.Item("input_format").Value(inputFormat->Config);
  629. })
  630. .DoIf(outputFormat.Defined(), [&] (TFluentMap fluentMap) {
  631. fluentMap.Item("output_format").Value(outputFormat->Config);
  632. })
  633. .DoIf(memoryLimit.Defined(), [&] (TFluentMap fluentMap) {
  634. fluentMap.Item("memory_limit").Value(*memoryLimit);
  635. })
  636. .DoIf(userJobSpec.MemoryReserveFactor_.Defined(), [&] (TFluentMap fluentMap) {
  637. fluentMap.Item("memory_reserve_factor").Value(*userJobSpec.MemoryReserveFactor_);
  638. })
  639. .DoIf(cpuLimit.Defined(), [&] (TFluentMap fluentMap) {
  640. fluentMap.Item("cpu_limit").Value(*cpuLimit);
  641. })
  642. .DoIf(portCount.Defined(), [&] (TFluentMap fluentMap) {
  643. fluentMap.Item("port_count").Value(*portCount);
  644. })
  645. .DoIf(userJobSpec.JobTimeLimit_.Defined(), [&] (TFluentMap fluentMap) {
  646. fluentMap.Item("job_time_limit").Value(userJobSpec.JobTimeLimit_->MilliSeconds());
  647. })
  648. .DoIf(userJobSpec.DiskRequest_.Defined(), [&] (TFluentMap fluentMap) {
  649. const auto& diskRequest = *userJobSpec.DiskRequest_;
  650. TNode diskRequestNode = TNode::CreateMap();
  651. if (diskRequest.DiskSpace_.Defined()) {
  652. diskRequestNode["disk_space"] = *diskRequest.DiskSpace_;
  653. }
  654. if (diskRequest.InodeCount_.Defined()) {
  655. diskRequestNode["inode_count"] = *diskRequest.InodeCount_;
  656. }
  657. if (diskRequest.Account_.Defined()) {
  658. diskRequestNode["account"] = *diskRequest.Account_;
  659. }
  660. if (diskRequest.MediumName_.Defined()) {
  661. diskRequestNode["medium_name"] = *diskRequest.MediumName_;
  662. }
  663. fluentMap.Item("disk_request").Value(diskRequestNode);
  664. })
  665. .DoIf(userJobSpec.NetworkProject_.Defined(), [&] (TFluentMap fluentMap) {
  666. fluentMap.Item("network_project").Value(*userJobSpec.NetworkProject_);
  667. })
  668. .DoIf(preparer.ShouldMountSandbox(), [&] (TFluentMap fluentMap) {
  669. fluentMap.Item("tmpfs_path").Value(".");
  670. fluentMap.Item("tmpfs_size").Value(tmpfsSize);
  671. fluentMap.Item("copy_files").Value(true);
  672. })
  673. .Item("profilers")
  674. .BeginList()
  675. .DoFor(userJobSpec.JobProfilers_, [&] (TFluentList list, const auto& jobProfiler) {
  676. list.Item().Value(BuildJobProfilerSpec(jobProfiler));
  677. })
  678. .EndList()
  679. .Item("redirect_stdout_to_stderr").Value(preparer.ShouldRedirectStdoutToStderr());
  680. }
  681. struct TNirvanaContext
  682. {
  683. TNode BlockUrl;
  684. TNode Annotations;
  685. };
  686. // Try to detect if we are inside nirvana operation and reat nirvana job context.
  687. // Items of TNirvanaContext might be Undefined, if we are not inside nirvana context (or if nirvana context is unexpected)
  688. TNirvanaContext GetNirvanaContext()
  689. {
  690. static const auto filePath = TString("/slot/sandbox/j/job_context.json");
  691. auto nvYtOperationId = GetEnv("NV_YT_OPERATION_ID");
  692. if (nvYtOperationId.empty()) {
  693. return {};
  694. }
  695. if (!NFs::Exists(filePath)) {
  696. return {};
  697. }
  698. NJson::TJsonValue json;
  699. try {
  700. auto inf = TIFStream(filePath);
  701. json = NJson::ReadJsonTree(&inf, /*throwOnError*/ true);
  702. } catch (const std::exception& ex) {
  703. YT_LOG_ERROR("Failed to load nirvana job context: %v", ex.what());
  704. return {};
  705. }
  706. TNirvanaContext result;
  707. const auto* url = json.GetValueByPath("meta.blockURL");
  708. if (url && url->IsString()) {
  709. result.BlockUrl = url->GetString();
  710. result.BlockUrl.Attributes()["_type_tag"] = "url";
  711. }
  712. const auto* annotations = json.GetValueByPath("meta.annotations");
  713. if (annotations && annotations->IsMap()) {
  714. result.Annotations = NodeFromJsonValue(*annotations);
  715. }
  716. return result;
  717. }
  718. template <typename T>
  719. void BuildCommonOperationPart(
  720. const TConfigPtr& config,
  721. const TOperationSpecBase<T>& baseSpec,
  722. const TOperationOptions& options,
  723. TNode* specNode)
  724. {
  725. const TProcessState* properties = TProcessState::Get();
  726. auto& startedBySpec = (*specNode)["started_by"];
  727. startedBySpec["hostname"] = properties->FqdnHostName,
  728. startedBySpec["pid"] = properties->Pid;
  729. startedBySpec["user"] = properties->UserName;
  730. startedBySpec["wrapper_version"] = properties->ClientVersion;
  731. startedBySpec["binary"] = properties->BinaryPath;
  732. startedBySpec["binary_name"] = properties->BinaryName;
  733. auto nirvanaContext = GetNirvanaContext();
  734. if (!nirvanaContext.BlockUrl.IsUndefined()) {
  735. startedBySpec["nirvana_block_url"] = nirvanaContext.BlockUrl;
  736. }
  737. if (!nirvanaContext.Annotations.IsUndefined()) {
  738. MergeNodes((*specNode)["annotations"], nirvanaContext.Annotations);
  739. }
  740. TString pool;
  741. if (baseSpec.Pool_) {
  742. pool = *baseSpec.Pool_;
  743. } else {
  744. pool = config->Pool;
  745. }
  746. if (!pool.empty()) {
  747. (*specNode)["pool"] = pool;
  748. }
  749. if (baseSpec.Weight_.Defined()) {
  750. (*specNode)["weight"] = *baseSpec.Weight_;
  751. }
  752. if (baseSpec.TimeLimit_.Defined()) {
  753. (*specNode)["time_limit"] = baseSpec.TimeLimit_->MilliSeconds();
  754. }
  755. if (baseSpec.PoolTrees().Defined()) {
  756. TNode poolTreesSpec = TNode::CreateList();
  757. for (const auto& tree : *baseSpec.PoolTrees()) {
  758. poolTreesSpec.Add(tree);
  759. }
  760. (*specNode)["pool_trees"] = std::move(poolTreesSpec);
  761. }
  762. if (baseSpec.ResourceLimits().Defined()) {
  763. auto resourceLimitsSpec = BuildSchedulerResourcesSpec(*baseSpec.ResourceLimits());
  764. if (!resourceLimitsSpec.IsUndefined()) {
  765. (*specNode)["resource_limits"] = std::move(resourceLimitsSpec);
  766. }
  767. }
  768. if (options.SecureVault_.Defined()) {
  769. Y_ENSURE(options.SecureVault_->IsMap(),
  770. "SecureVault must be a map node, got " << options.SecureVault_->GetType());
  771. (*specNode)["secure_vault"] = *options.SecureVault_;
  772. }
  773. if (baseSpec.Title_.Defined()) {
  774. (*specNode)["title"] = *baseSpec.Title_;
  775. }
  776. if (baseSpec.MaxFailedJobCount_.Defined()) {
  777. (*specNode)["max_failed_job_count"] = *baseSpec.MaxFailedJobCount_;
  778. }
  779. }
  780. template <typename TSpec>
  781. void BuildCommonUserOperationPart(const TSpec& baseSpec, TNode* spec)
  782. {
  783. if (baseSpec.FailOnJobRestart_.Defined()) {
  784. (*spec)["fail_on_job_restart"] = *baseSpec.FailOnJobRestart_;
  785. }
  786. if (baseSpec.StderrTablePath_.Defined()) {
  787. (*spec)["stderr_table_path"] = *baseSpec.StderrTablePath_;
  788. }
  789. if (baseSpec.CoreTablePath_.Defined()) {
  790. (*spec)["core_table_path"] = *baseSpec.CoreTablePath_;
  791. }
  792. if (baseSpec.WaitingJobTimeout_.Defined()) {
  793. (*spec)["waiting_job_timeout"] = baseSpec.WaitingJobTimeout_->MilliSeconds();
  794. }
  795. }
  796. template <typename TSpec>
  797. void BuildJobCountOperationPart(const TSpec& spec, TNode* nodeSpec)
  798. {
  799. if (spec.JobCount_.Defined()) {
  800. (*nodeSpec)["job_count"] = *spec.JobCount_;
  801. }
  802. if (spec.DataSizePerJob_.Defined()) {
  803. (*nodeSpec)["data_size_per_job"] = *spec.DataSizePerJob_;
  804. }
  805. }
  806. template <typename TSpec>
  807. void BuildPartitionCountOperationPart(const TSpec& spec, TNode* nodeSpec)
  808. {
  809. if (spec.PartitionCount_.Defined()) {
  810. (*nodeSpec)["partition_count"] = *spec.PartitionCount_;
  811. }
  812. if (spec.PartitionDataSize_.Defined()) {
  813. (*nodeSpec)["partition_data_size"] = *spec.PartitionDataSize_;
  814. }
  815. }
  816. template <typename TSpec>
  817. void BuildDataSizePerSortJobPart(const TSpec& spec, TNode* nodeSpec)
  818. {
  819. if (spec.DataSizePerSortJob_.Defined()) {
  820. (*nodeSpec)["data_size_per_sort_job"] = *spec.DataSizePerSortJob_;
  821. }
  822. }
  823. template <typename TSpec>
  824. void BuildPartitionJobCountOperationPart(const TSpec& spec, TNode* nodeSpec)
  825. {
  826. if (spec.PartitionJobCount_.Defined()) {
  827. (*nodeSpec)["partition_job_count"] = *spec.PartitionJobCount_;
  828. }
  829. if (spec.DataSizePerPartitionJob_.Defined()) {
  830. (*nodeSpec)["data_size_per_partition_job"] = *spec.DataSizePerPartitionJob_;
  831. }
  832. }
  833. template <typename TSpec>
  834. void BuildMapJobCountOperationPart(const TSpec& spec, TNode* nodeSpec)
  835. {
  836. if (spec.MapJobCount_.Defined()) {
  837. (*nodeSpec)["map_job_count"] = *spec.MapJobCount_;
  838. }
  839. if (spec.DataSizePerMapJob_.Defined()) {
  840. (*nodeSpec)["data_size_per_map_job"] = *spec.DataSizePerMapJob_;
  841. }
  842. }
  843. template <typename TSpec>
  844. void BuildIntermediateDataPart(const TSpec& spec, TNode* nodeSpec)
  845. {
  846. if (spec.IntermediateDataAccount_.Defined()) {
  847. (*nodeSpec)["intermediate_data_account"] = *spec.IntermediateDataAccount_;
  848. }
  849. if (spec.IntermediateDataReplicationFactor_.Defined()) {
  850. (*nodeSpec)["intermediate_data_replication_factor"] = *spec.IntermediateDataReplicationFactor_;
  851. }
  852. }
  853. ////////////////////////////////////////////////////////////////////////////////
  854. TNode MergeSpec(TNode dst, TNode spec, const TOperationOptions& options)
  855. {
  856. MergeNodes(dst, spec);
  857. if (options.Spec_) {
  858. MergeNodes(dst, *options.Spec_);
  859. }
  860. return dst;
  861. }
  862. template <typename TSpec>
  863. void CreateDebugOutputTables(const TSpec& spec, const TOperationPreparer& preparer)
  864. {
  865. if (spec.StderrTablePath_.Defined()) {
  866. RequestWithRetry<void>(
  867. preparer.GetClientRetryPolicy()->CreatePolicyForGenericRequest(),
  868. [&spec, &preparer] (TMutationId& mutationId) {
  869. preparer.GetClient()->GetRawClient()->Create(
  870. mutationId,
  871. TTransactionId(),
  872. *spec.StderrTablePath_,
  873. NT_TABLE,
  874. TCreateOptions()
  875. .IgnoreExisting(true)
  876. .Recursive(true));
  877. });
  878. }
  879. if (spec.CoreTablePath_.Defined()) {
  880. RequestWithRetry<void>(
  881. preparer.GetClientRetryPolicy()->CreatePolicyForGenericRequest(),
  882. [&spec, &preparer] (TMutationId& mutationId) {
  883. preparer.GetClient()->GetRawClient()->Create(
  884. mutationId,
  885. TTransactionId(),
  886. *spec.CoreTablePath_,
  887. NT_TABLE,
  888. TCreateOptions()
  889. .IgnoreExisting(true)
  890. .Recursive(true));
  891. });
  892. }
  893. }
  894. void CreateOutputTable(
  895. const TOperationPreparer& preparer,
  896. const TRichYPath& path)
  897. {
  898. Y_ENSURE(path.Path_, "Output table is not set");
  899. if (!path.Create_.Defined()) {
  900. // If `create` attribute is defined
  901. RequestWithRetry<void>(
  902. preparer.GetClientRetryPolicy()->CreatePolicyForGenericRequest(),
  903. [&preparer, &path] (TMutationId& mutationId) {
  904. preparer.GetClient()->GetRawClient()->Create(
  905. mutationId,
  906. preparer.GetTransactionId(),
  907. path.Path_,
  908. NT_TABLE,
  909. TCreateOptions()
  910. .IgnoreExisting(true)
  911. .Recursive(true));
  912. });
  913. }
  914. }
  915. void CreateOutputTables(
  916. const TOperationPreparer& preparer,
  917. const TVector<TRichYPath>& paths)
  918. {
  919. for (auto& path : paths) {
  920. CreateOutputTable(preparer, path);
  921. }
  922. }
  923. void CheckInputTablesExist(
  924. const TOperationPreparer& preparer,
  925. const TVector<TRichYPath>& paths)
  926. {
  927. Y_ENSURE(!paths.empty(), "Input tables are not set");
  928. for (auto& path : paths) {
  929. auto curTransactionId = path.TransactionId_.GetOrElse(preparer.GetTransactionId());
  930. auto exists = RequestWithRetry<bool>(
  931. preparer.GetClientRetryPolicy()->CreatePolicyForGenericRequest(),
  932. [&preparer, &curTransactionId, &path] (TMutationId /*mutationId*/) {
  933. return preparer.GetClient()->GetRawClient()->Exists(
  934. curTransactionId,
  935. path.Path_);
  936. });
  937. Y_ENSURE_EX(
  938. path.Cluster_.Defined() || exists,
  939. TApiUsageError() << "Input table '" << path.Path_ << "' doesn't exist");
  940. }
  941. }
  942. void LogJob(const TOperationId& opId, const IJob* job, const char* type)
  943. {
  944. if (job) {
  945. YT_LOG_INFO("Operation %v; %v = %v",
  946. opId,
  947. type,
  948. TJobFactory::Get()->GetJobName(job));
  949. }
  950. }
  951. void LogYPaths(const TOperationId& opId, const TVector<TRichYPath>& paths, const char* type)
  952. {
  953. for (size_t i = 0; i < paths.size(); ++i) {
  954. YT_LOG_INFO("Operation %v; %v[%v] = %v",
  955. opId,
  956. type,
  957. i,
  958. paths[i].Path_);
  959. }
  960. }
  961. void LogYPath(const TOperationId& opId, const TRichYPath& path, const char* type)
  962. {
  963. YT_LOG_INFO("Operation %v; %v = %v",
  964. opId,
  965. type,
  966. path.Path_);
  967. }
  968. TString AddModeToTitleIfDebug(const TString& title) {
  969. #ifndef NDEBUG
  970. return title + " (debug build)";
  971. #else
  972. return title;
  973. #endif
  974. }
  975. } // namespace
  976. ////////////////////////////////////////////////////////////////////////////////
  977. template <typename T>
  978. void DoExecuteMap(
  979. const TOperationPtr& operation,
  980. const TOperationPreparerPtr& preparer,
  981. const TSimpleOperationIo& operationIo,
  982. TMapOperationSpecBase<T> spec,
  983. const IJobPtr& mapper,
  984. const TOperationOptions& options)
  985. {
  986. if (options.CreateDebugOutputTables_) {
  987. CreateDebugOutputTables(spec, *preparer);
  988. }
  989. if (options.CreateOutputTables_) {
  990. CheckInputTablesExist(*preparer, operationIo.Inputs);
  991. CreateOutputTables(*preparer, operationIo.Outputs);
  992. }
  993. TJobPreparer map(
  994. *preparer,
  995. spec.MapperSpec_,
  996. *mapper,
  997. operationIo.Outputs.size(),
  998. operationIo.JobFiles,
  999. options);
  1000. spec.Title_ = spec.Title_.GetOrElse(AddModeToTitleIfDebug(map.GetClassName()));
  1001. TNode specNode = BuildYsonNodeFluently()
  1002. .BeginMap()
  1003. .Item("mapper").DoMap([&] (TFluentMap fluent) {
  1004. BuildUserJobFluently(
  1005. map,
  1006. operationIo.InputFormat,
  1007. operationIo.OutputFormat,
  1008. fluent);
  1009. })
  1010. .DoIf(spec.AutoMerge_.Defined(), [&] (TFluentMap fluent) {
  1011. auto autoMergeSpec = BuildAutoMergeSpec(*spec.AutoMerge_);
  1012. if (!autoMergeSpec.IsUndefined()) {
  1013. fluent.Item("auto_merge").Value(std::move(autoMergeSpec));
  1014. }
  1015. })
  1016. .Item("input_table_paths").List(operationIo.Inputs)
  1017. .Item("output_table_paths").List(operationIo.Outputs)
  1018. .DoIf(spec.Ordered_.Defined(), [&] (TFluentMap fluent) {
  1019. fluent.Item("ordered").Value(spec.Ordered_.GetRef());
  1020. })
  1021. .EndMap();
  1022. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1023. specNode["job_io"]["control_attributes"]["enable_row_index"] = TNode(true);
  1024. specNode["job_io"]["control_attributes"]["enable_range_index"] = TNode(true);
  1025. if (!preparer->GetContext().Config->TableWriter.Empty()) {
  1026. specNode["job_io"]["table_writer"] = preparer->GetContext().Config->TableWriter;
  1027. }
  1028. BuildCommonUserOperationPart(spec, &specNode);
  1029. BuildJobCountOperationPart(spec, &specNode);
  1030. auto startOperation = [
  1031. operation=operation.Get(),
  1032. spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options),
  1033. preparer,
  1034. operationIo,
  1035. mapper
  1036. ] () {
  1037. auto operationId = preparer->StartOperation(operation, EOperationType::Map, spec);
  1038. LogJob(operationId, mapper.Get(), "mapper");
  1039. LogYPaths(operationId, operationIo.Inputs, "input");
  1040. LogYPaths(operationId, operationIo.Outputs, "output");
  1041. return operationId;
  1042. };
  1043. operation->SetDelayedStartFunction(std::move(startOperation));
  1044. }
  1045. void ExecuteMap(
  1046. const TOperationPtr& operation,
  1047. const TOperationPreparerPtr& preparer,
  1048. const TMapOperationSpec& spec,
  1049. const ::TIntrusivePtr<IStructuredJob>& mapper,
  1050. const TOperationOptions& options)
  1051. {
  1052. YT_LOG_DEBUG("Starting map operation (PreparationId: %v)",
  1053. preparer->GetPreparationId());
  1054. auto operationIo = CreateSimpleOperationIo(*mapper, *preparer, spec, options, /* allowSkiff = */ true);
  1055. DoExecuteMap(
  1056. operation,
  1057. preparer,
  1058. operationIo,
  1059. spec,
  1060. mapper,
  1061. options);
  1062. }
  1063. void ExecuteRawMap(
  1064. const TOperationPtr& operation,
  1065. const TOperationPreparerPtr& preparer,
  1066. const TRawMapOperationSpec& spec,
  1067. const ::TIntrusivePtr<IRawJob>& mapper,
  1068. const TOperationOptions& options)
  1069. {
  1070. YT_LOG_DEBUG("Starting raw map operation (PreparationId: %v)",
  1071. preparer->GetPreparationId());
  1072. auto operationIo = CreateSimpleOperationIo(*mapper, *preparer, spec);
  1073. DoExecuteMap(
  1074. operation,
  1075. preparer,
  1076. operationIo,
  1077. spec,
  1078. mapper,
  1079. options);
  1080. }
  1081. ////////////////////////////////////////////////////////////////////////////////
  1082. template <typename T>
  1083. void DoExecuteReduce(
  1084. const TOperationPtr& operation,
  1085. const TOperationPreparerPtr& preparer,
  1086. const TSimpleOperationIo& operationIo,
  1087. TReduceOperationSpecBase<T> spec,
  1088. const IJobPtr& reducer,
  1089. const TOperationOptions& options)
  1090. {
  1091. if (options.CreateDebugOutputTables_) {
  1092. CreateDebugOutputTables(spec, *preparer);
  1093. }
  1094. if (options.CreateOutputTables_) {
  1095. CheckInputTablesExist(*preparer, operationIo.Inputs);
  1096. CreateOutputTables(*preparer, operationIo.Outputs);
  1097. }
  1098. TJobPreparer reduce(
  1099. *preparer,
  1100. spec.ReducerSpec_,
  1101. *reducer,
  1102. operationIo.Outputs.size(),
  1103. operationIo.JobFiles,
  1104. options);
  1105. spec.Title_ = spec.Title_.GetOrElse(AddModeToTitleIfDebug(reduce.GetClassName()));
  1106. TNode specNode = BuildYsonNodeFluently()
  1107. .BeginMap()
  1108. .Item("reducer").DoMap([&] (TFluentMap fluent) {
  1109. BuildUserJobFluently(
  1110. reduce,
  1111. operationIo.InputFormat,
  1112. operationIo.OutputFormat,
  1113. fluent);
  1114. })
  1115. .DoIf(!spec.SortBy_.Parts_.empty(), [&] (TFluentMap fluent) {
  1116. fluent.Item("sort_by").Value(spec.SortBy_);
  1117. })
  1118. .Item("reduce_by").Value(spec.ReduceBy_)
  1119. .DoIf(spec.JoinBy_.Defined(), [&] (TFluentMap fluent) {
  1120. fluent.Item("join_by").Value(spec.JoinBy_.GetRef());
  1121. })
  1122. .DoIf(spec.EnableKeyGuarantee_.Defined(), [&] (TFluentMap fluent) {
  1123. fluent.Item("enable_key_guarantee").Value(spec.EnableKeyGuarantee_.GetRef());
  1124. })
  1125. .Item("input_table_paths").List(operationIo.Inputs)
  1126. .Item("output_table_paths").List(operationIo.Outputs)
  1127. .Item("job_io").BeginMap()
  1128. .Item("control_attributes").BeginMap()
  1129. .Item("enable_key_switch").Value(true)
  1130. .Item("enable_row_index").Value(true)
  1131. .Item("enable_range_index").Value(true)
  1132. .EndMap()
  1133. .DoIf(!preparer->GetContext().Config->TableWriter.Empty(), [&] (TFluentMap fluent) {
  1134. fluent.Item("table_writer").Value(preparer->GetContext().Config->TableWriter);
  1135. })
  1136. .EndMap()
  1137. .DoIf(spec.AutoMerge_.Defined(), [&] (TFluentMap fluent) {
  1138. fluent.Item("auto_merge").Value(BuildAutoMergeSpec(*spec.AutoMerge_));
  1139. })
  1140. .EndMap();
  1141. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1142. BuildCommonUserOperationPart(spec, &specNode);
  1143. BuildJobCountOperationPart(spec, &specNode);
  1144. auto startOperation = [
  1145. operation=operation.Get(),
  1146. spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options),
  1147. preparer,
  1148. operationIo,
  1149. reducer
  1150. ] () {
  1151. auto operationId = preparer->StartOperation(operation, EOperationType::Reduce, spec);
  1152. LogJob(operationId, reducer.Get(), "reducer");
  1153. LogYPaths(operationId, operationIo.Inputs, "input");
  1154. LogYPaths(operationId, operationIo.Outputs, "output");
  1155. return operationId;
  1156. };
  1157. operation->SetDelayedStartFunction(std::move(startOperation));
  1158. }
  1159. void ExecuteReduce(
  1160. const TOperationPtr& operation,
  1161. const TOperationPreparerPtr& preparer,
  1162. const TReduceOperationSpec& spec,
  1163. const ::TIntrusivePtr<IStructuredJob>& reducer,
  1164. const TOperationOptions& options)
  1165. {
  1166. YT_LOG_DEBUG("Starting reduce operation (PreparationId: %v)",
  1167. preparer->GetPreparationId());
  1168. auto operationIo = CreateSimpleOperationIo(*reducer, *preparer, spec, options, /* allowSkiff = */ false);
  1169. DoExecuteReduce(
  1170. operation,
  1171. preparer,
  1172. operationIo,
  1173. spec,
  1174. reducer,
  1175. options);
  1176. }
  1177. void ExecuteRawReduce(
  1178. const TOperationPtr& operation,
  1179. const TOperationPreparerPtr& preparer,
  1180. const TRawReduceOperationSpec& spec,
  1181. const ::TIntrusivePtr<IRawJob>& reducer,
  1182. const TOperationOptions& options)
  1183. {
  1184. YT_LOG_DEBUG("Starting raw reduce operation (PreparationId: %v)",
  1185. preparer->GetPreparationId());
  1186. auto operationIo = CreateSimpleOperationIo(*reducer, *preparer, spec);
  1187. DoExecuteReduce(
  1188. operation,
  1189. preparer,
  1190. operationIo,
  1191. spec,
  1192. reducer,
  1193. options);
  1194. }
  1195. ////////////////////////////////////////////////////////////////////////////////
  1196. template <typename T>
  1197. void DoExecuteJoinReduce(
  1198. const TOperationPtr& operation,
  1199. const TOperationPreparerPtr& preparer,
  1200. const TSimpleOperationIo& operationIo,
  1201. TJoinReduceOperationSpecBase<T> spec,
  1202. const IJobPtr& reducer,
  1203. const TOperationOptions& options)
  1204. {
  1205. if (options.CreateDebugOutputTables_) {
  1206. CreateDebugOutputTables(spec, *preparer);
  1207. }
  1208. if (options.CreateOutputTables_) {
  1209. CheckInputTablesExist(*preparer, operationIo.Inputs);
  1210. CreateOutputTables(*preparer, operationIo.Outputs);
  1211. }
  1212. TJobPreparer reduce(
  1213. *preparer,
  1214. spec.ReducerSpec_,
  1215. *reducer,
  1216. operationIo.Outputs.size(),
  1217. operationIo.JobFiles,
  1218. options);
  1219. spec.Title_ = spec.Title_.GetOrElse(AddModeToTitleIfDebug(reduce.GetClassName()));
  1220. TNode specNode = BuildYsonNodeFluently()
  1221. .BeginMap()
  1222. .Item("reducer").DoMap([&] (TFluentMap fluent) {
  1223. BuildUserJobFluently(
  1224. reduce,
  1225. operationIo.InputFormat,
  1226. operationIo.OutputFormat,
  1227. fluent);
  1228. })
  1229. .Item("join_by").Value(spec.JoinBy_)
  1230. .Item("input_table_paths").List(operationIo.Inputs)
  1231. .Item("output_table_paths").List(operationIo.Outputs)
  1232. .Item("job_io").BeginMap()
  1233. .Item("control_attributes").BeginMap()
  1234. .Item("enable_key_switch").Value(true)
  1235. .Item("enable_row_index").Value(true)
  1236. .Item("enable_range_index").Value(true)
  1237. .EndMap()
  1238. .DoIf(!preparer->GetContext().Config->TableWriter.Empty(), [&] (TFluentMap fluent) {
  1239. fluent.Item("table_writer").Value(preparer->GetContext().Config->TableWriter);
  1240. })
  1241. .EndMap()
  1242. .EndMap();
  1243. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1244. BuildCommonUserOperationPart(spec, &specNode);
  1245. BuildJobCountOperationPart(spec, &specNode);
  1246. auto startOperation = [
  1247. operation=operation.Get(),
  1248. spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options),
  1249. preparer,
  1250. reducer,
  1251. operationIo
  1252. ] () {
  1253. auto operationId = preparer->StartOperation(operation, EOperationType::JoinReduce, spec);
  1254. LogJob(operationId, reducer.Get(), "reducer");
  1255. LogYPaths(operationId, operationIo.Inputs, "input");
  1256. LogYPaths(operationId, operationIo.Outputs, "output");
  1257. return operationId;
  1258. };
  1259. operation->SetDelayedStartFunction(std::move(startOperation));
  1260. }
  1261. void ExecuteJoinReduce(
  1262. const TOperationPtr& operation,
  1263. const TOperationPreparerPtr& preparer,
  1264. const TJoinReduceOperationSpec& spec,
  1265. const ::TIntrusivePtr<IStructuredJob>& reducer,
  1266. const TOperationOptions& options)
  1267. {
  1268. YT_LOG_DEBUG("Starting join reduce operation (PreparationId: %v)",
  1269. preparer->GetPreparationId());
  1270. auto operationIo = CreateSimpleOperationIo(*reducer, *preparer, spec, options, /* allowSkiff = */ false);
  1271. return DoExecuteJoinReduce(
  1272. operation,
  1273. preparer,
  1274. operationIo,
  1275. spec,
  1276. reducer,
  1277. options);
  1278. }
  1279. void ExecuteRawJoinReduce(
  1280. const TOperationPtr& operation,
  1281. const TOperationPreparerPtr& preparer,
  1282. const TRawJoinReduceOperationSpec& spec,
  1283. const ::TIntrusivePtr<IRawJob>& reducer,
  1284. const TOperationOptions& options)
  1285. {
  1286. YT_LOG_DEBUG("Starting raw join reduce operation (PreparationId: %v)",
  1287. preparer->GetPreparationId());
  1288. auto operationIo = CreateSimpleOperationIo(*reducer, *preparer, spec);
  1289. return DoExecuteJoinReduce(
  1290. operation,
  1291. preparer,
  1292. operationIo,
  1293. spec,
  1294. reducer,
  1295. options);
  1296. }
  1297. ////////////////////////////////////////////////////////////////////////////////
  1298. template <typename T>
  1299. void DoExecuteMapReduce(
  1300. const TOperationPtr& operation,
  1301. const TOperationPreparerPtr& preparer,
  1302. const TMapReduceOperationIo& operationIo,
  1303. TMapReduceOperationSpecBase<T> spec,
  1304. const IJobPtr& mapper,
  1305. const IJobPtr& reduceCombiner,
  1306. const IJobPtr& reducer,
  1307. const TOperationOptions& options)
  1308. {
  1309. TVector<TRichYPath> allOutputs;
  1310. allOutputs.insert(allOutputs.end(), operationIo.MapOutputs.begin(), operationIo.MapOutputs.end());
  1311. allOutputs.insert(allOutputs.end(), operationIo.Outputs.begin(), operationIo.Outputs.end());
  1312. if (options.CreateDebugOutputTables_) {
  1313. CreateDebugOutputTables(spec, *preparer);
  1314. }
  1315. if (options.CreateOutputTables_) {
  1316. CheckInputTablesExist(*preparer, operationIo.Inputs);
  1317. CreateOutputTables(*preparer, allOutputs);
  1318. }
  1319. TSortColumns sortBy = spec.SortBy_;
  1320. TSortColumns reduceBy = spec.ReduceBy_;
  1321. if (sortBy.Parts_.empty()) {
  1322. sortBy = reduceBy;
  1323. }
  1324. const bool hasMapper = mapper != nullptr;
  1325. const bool hasCombiner = reduceCombiner != nullptr;
  1326. TVector<TRichYPath> files;
  1327. TJobPreparer reduce(
  1328. *preparer,
  1329. spec.ReducerSpec_,
  1330. *reducer,
  1331. operationIo.Outputs.size(),
  1332. operationIo.ReducerJobFiles,
  1333. options);
  1334. TString title;
  1335. TNode specNode = BuildYsonNodeFluently()
  1336. .BeginMap()
  1337. .DoIf(hasMapper, [&] (TFluentMap fluent) {
  1338. TJobPreparer map(
  1339. *preparer,
  1340. spec.MapperSpec_,
  1341. *mapper,
  1342. 1 + operationIo.MapOutputs.size(),
  1343. operationIo.MapperJobFiles,
  1344. options);
  1345. fluent.Item("mapper").DoMap([&] (TFluentMap fluent) {
  1346. BuildUserJobFluently(
  1347. std::cref(map),
  1348. *operationIo.MapperInputFormat,
  1349. *operationIo.MapperOutputFormat,
  1350. fluent);
  1351. });
  1352. title = "mapper:" + map.GetClassName() + " ";
  1353. })
  1354. .DoIf(hasCombiner, [&] (TFluentMap fluent) {
  1355. TJobPreparer combine(
  1356. *preparer,
  1357. spec.ReduceCombinerSpec_,
  1358. *reduceCombiner,
  1359. size_t(1),
  1360. operationIo.ReduceCombinerJobFiles,
  1361. options);
  1362. fluent.Item("reduce_combiner").DoMap([&] (TFluentMap fluent) {
  1363. BuildUserJobFluently(
  1364. combine,
  1365. *operationIo.ReduceCombinerInputFormat,
  1366. *operationIo.ReduceCombinerOutputFormat,
  1367. fluent);
  1368. });
  1369. title += "combiner:" + combine.GetClassName() + " ";
  1370. })
  1371. .Item("reducer").DoMap([&] (TFluentMap fluent) {
  1372. BuildUserJobFluently(
  1373. reduce,
  1374. operationIo.ReducerInputFormat,
  1375. operationIo.ReducerOutputFormat,
  1376. fluent);
  1377. })
  1378. .Item("sort_by").Value(sortBy)
  1379. .Item("reduce_by").Value(reduceBy)
  1380. .Item("input_table_paths").List(operationIo.Inputs)
  1381. .Item("output_table_paths").List(allOutputs)
  1382. .Item("mapper_output_table_count").Value(operationIo.MapOutputs.size())
  1383. .DoIf(spec.ForceReduceCombiners_.Defined(), [&] (TFluentMap fluent) {
  1384. fluent.Item("force_reduce_combiners").Value(*spec.ForceReduceCombiners_);
  1385. })
  1386. .Item("map_job_io").BeginMap()
  1387. .Item("control_attributes").BeginMap()
  1388. .Item("enable_row_index").Value(true)
  1389. .Item("enable_range_index").Value(true)
  1390. .EndMap()
  1391. .DoIf(!preparer->GetContext().Config->TableWriter.Empty(), [&] (TFluentMap fluent) {
  1392. fluent.Item("table_writer").Value(preparer->GetContext().Config->TableWriter);
  1393. })
  1394. .EndMap()
  1395. .Item("sort_job_io").BeginMap()
  1396. .Item("control_attributes").BeginMap()
  1397. .Item("enable_key_switch").Value(true)
  1398. .EndMap()
  1399. .DoIf(!preparer->GetContext().Config->TableWriter.Empty(), [&] (TFluentMap fluent) {
  1400. fluent.Item("table_writer").Value(preparer->GetContext().Config->TableWriter);
  1401. })
  1402. .EndMap()
  1403. .Item("reduce_job_io").BeginMap()
  1404. .Item("control_attributes").BeginMap()
  1405. .Item("enable_key_switch").Value(true)
  1406. .EndMap()
  1407. .DoIf(!preparer->GetContext().Config->TableWriter.Empty(), [&] (TFluentMap fluent) {
  1408. fluent.Item("table_writer").Value(preparer->GetContext().Config->TableWriter);
  1409. })
  1410. .EndMap()
  1411. .Do([&] (TFluentMap) {
  1412. spec.Title_ = spec.Title_.GetOrElse(AddModeToTitleIfDebug(title + "reducer:" + reduce.GetClassName()));
  1413. })
  1414. .EndMap();
  1415. if (spec.Ordered_) {
  1416. specNode["ordered"] = *spec.Ordered_;
  1417. }
  1418. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1419. BuildCommonUserOperationPart(spec, &specNode);
  1420. BuildMapJobCountOperationPart(spec, &specNode);
  1421. BuildPartitionCountOperationPart(spec, &specNode);
  1422. BuildIntermediateDataPart(spec, &specNode);
  1423. BuildDataSizePerSortJobPart(spec, &specNode);
  1424. auto startOperation = [
  1425. operation=operation.Get(),
  1426. spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options),
  1427. preparer,
  1428. mapper,
  1429. reduceCombiner,
  1430. reducer,
  1431. inputs=operationIo.Inputs,
  1432. allOutputs
  1433. ] () {
  1434. auto operationId = preparer->StartOperation(operation, EOperationType::MapReduce, spec);
  1435. LogJob(operationId, mapper.Get(), "mapper");
  1436. LogJob(operationId, reduceCombiner.Get(), "reduce_combiner");
  1437. LogJob(operationId, reducer.Get(), "reducer");
  1438. LogYPaths(operationId, inputs, "input");
  1439. LogYPaths(operationId, allOutputs, "output");
  1440. return operationId;
  1441. };
  1442. operation->SetDelayedStartFunction(std::move(startOperation));
  1443. }
  1444. void ExecuteMapReduce(
  1445. const TOperationPtr& operation,
  1446. const TOperationPreparerPtr& preparer,
  1447. const TMapReduceOperationSpec& spec_,
  1448. const ::TIntrusivePtr<IStructuredJob>& mapper,
  1449. const ::TIntrusivePtr<IStructuredJob>& reduceCombiner,
  1450. const ::TIntrusivePtr<IStructuredJob>& reducer,
  1451. const TOperationOptions& options)
  1452. {
  1453. YT_LOG_DEBUG("Starting map-reduce operation (PreparationId: %v)",
  1454. preparer->GetPreparationId());
  1455. TMapReduceOperationSpec spec = spec_;
  1456. TMapReduceOperationIo operationIo;
  1457. auto structuredInputs = CanonizeStructuredTableList(preparer->GetClient()->GetRawClient(), spec.GetStructuredInputs());
  1458. auto structuredMapOutputs = CanonizeStructuredTableList(preparer->GetClient()->GetRawClient(), spec.GetStructuredMapOutputs());
  1459. auto structuredOutputs = CanonizeStructuredTableList(preparer->GetClient()->GetRawClient(), spec.GetStructuredOutputs());
  1460. const bool inferOutputSchema = options.InferOutputSchema_.GetOrElse(preparer->GetContext().Config->InferTableSchema);
  1461. TVector<TTableSchema> currentInferenceResult;
  1462. auto fixSpec = [&] (const TFormat& format) {
  1463. if (format.IsYamredDsv()) {
  1464. spec.SortBy_.Parts_.clear();
  1465. spec.ReduceBy_.Parts_.clear();
  1466. const TYamredDsvAttributes attributes = format.GetYamredDsvAttributes();
  1467. for (auto& column : attributes.KeyColumnNames) {
  1468. spec.SortBy_.Parts_.push_back(column);
  1469. spec.ReduceBy_.Parts_.push_back(column);
  1470. }
  1471. for (const auto& column : attributes.SubkeyColumnNames) {
  1472. spec.SortBy_.Parts_.push_back(column);
  1473. }
  1474. }
  1475. };
  1476. VerifyHasElements(structuredInputs, "inputs");
  1477. TFormatBuilder formatBuilder(
  1478. preparer->GetClient()->GetRawClient(),
  1479. preparer->GetClientRetryPolicy(),
  1480. preparer->GetContext(),
  1481. preparer->GetTransactionId(),
  1482. options);
  1483. if (mapper) {
  1484. auto mapperOutputDescription =
  1485. spec.GetIntermediateMapOutputDescription()
  1486. .GetOrElse(TUnspecifiedTableStructure());
  1487. TStructuredJobTableList mapperOutput = {
  1488. TStructuredJobTable::Intermediate(mapperOutputDescription),
  1489. };
  1490. for (const auto& table : structuredMapOutputs) {
  1491. mapperOutput.push_back(TStructuredJobTable{table.Description, table.RichYPath});
  1492. }
  1493. auto hints = spec.MapperFormatHints_;
  1494. auto mapperInferenceResult = PrepareOperation<TStructuredJobTableList>(
  1495. *mapper,
  1496. TOperationPreparationContext(
  1497. structuredInputs,
  1498. mapperOutput,
  1499. preparer->GetClient()->GetRawClient(),
  1500. preparer->GetClientRetryPolicy(),
  1501. preparer->GetTransactionId()),
  1502. &structuredInputs,
  1503. /* outputs */ nullptr,
  1504. hints);
  1505. auto nodeReaderFormat = NodeReaderFormatFromHintAndGlobalConfig(spec.MapperFormatHints_);
  1506. auto [inputFormat, inputFormatConfig] = formatBuilder.CreateFormat(
  1507. *mapper,
  1508. EIODirection::Input,
  1509. structuredInputs,
  1510. hints.InputFormatHints_,
  1511. nodeReaderFormat,
  1512. /* allowFormatFromTableAttribute */ true);
  1513. auto [outputFormat, outputFormatConfig] = formatBuilder.CreateFormat(
  1514. *mapper,
  1515. EIODirection::Output,
  1516. mapperOutput,
  1517. hints.OutputFormatHints_,
  1518. ENodeReaderFormat::Yson,
  1519. /* allowFormatFromTableAttribute */ false);
  1520. operationIo.MapperJobFiles = CreateFormatConfig(inputFormatConfig, outputFormatConfig);
  1521. operationIo.MapperInputFormat = inputFormat;
  1522. operationIo.MapperOutputFormat = outputFormat;
  1523. Y_ABORT_UNLESS(mapperInferenceResult.size() >= 1);
  1524. currentInferenceResult = TVector<TTableSchema>{mapperInferenceResult[0]};
  1525. // The first output as it corresponds to the intermediate data.
  1526. TVector<TTableSchema> additionalOutputsInferenceResult(mapperInferenceResult.begin() + 1, mapperInferenceResult.end());
  1527. operationIo.MapOutputs = GetPathList(
  1528. structuredMapOutputs,
  1529. additionalOutputsInferenceResult,
  1530. inferOutputSchema);
  1531. }
  1532. if (reduceCombiner) {
  1533. const bool isFirstStep = !mapper;
  1534. TStructuredJobTableList inputs;
  1535. if (isFirstStep) {
  1536. inputs = structuredInputs;
  1537. } else {
  1538. auto reduceCombinerIntermediateInput =
  1539. spec.GetIntermediateReduceCombinerInputDescription()
  1540. .GetOrElse(TUnspecifiedTableStructure());
  1541. inputs = {
  1542. TStructuredJobTable::Intermediate(reduceCombinerIntermediateInput),
  1543. };
  1544. }
  1545. auto reduceCombinerOutputDescription = spec.GetIntermediateReduceCombinerOutputDescription()
  1546. .GetOrElse(TUnspecifiedTableStructure());
  1547. TStructuredJobTableList outputs = {
  1548. TStructuredJobTable::Intermediate(reduceCombinerOutputDescription),
  1549. };
  1550. auto hints = spec.ReduceCombinerFormatHints_;
  1551. if (isFirstStep) {
  1552. currentInferenceResult = PrepareOperation<TStructuredJobTableList>(
  1553. *reduceCombiner,
  1554. TOperationPreparationContext(
  1555. inputs,
  1556. outputs,
  1557. preparer->GetClient()->GetRawClient(),
  1558. preparer->GetClientRetryPolicy(),
  1559. preparer->GetTransactionId()),
  1560. &inputs,
  1561. /* outputs */ nullptr,
  1562. hints);
  1563. } else {
  1564. currentInferenceResult = PrepareOperation<TStructuredJobTableList>(
  1565. *reduceCombiner,
  1566. TSpeculativeOperationPreparationContext(
  1567. currentInferenceResult,
  1568. inputs,
  1569. outputs),
  1570. /* inputs */ nullptr,
  1571. /* outputs */ nullptr,
  1572. hints);
  1573. }
  1574. auto [inputFormat, inputFormatConfig] = formatBuilder.CreateFormat(
  1575. *reduceCombiner,
  1576. EIODirection::Input,
  1577. inputs,
  1578. hints.InputFormatHints_,
  1579. ENodeReaderFormat::Yson,
  1580. /* allowFormatFromTableAttribute = */ isFirstStep);
  1581. auto [outputFormat, outputFormatConfig] = formatBuilder.CreateFormat(
  1582. *reduceCombiner,
  1583. EIODirection::Output,
  1584. outputs,
  1585. hints.OutputFormatHints_,
  1586. ENodeReaderFormat::Yson,
  1587. /* allowFormatFromTableAttribute = */ false);
  1588. operationIo.ReduceCombinerJobFiles = CreateFormatConfig(inputFormatConfig, outputFormatConfig);
  1589. operationIo.ReduceCombinerInputFormat = inputFormat;
  1590. operationIo.ReduceCombinerOutputFormat = outputFormat;
  1591. if (isFirstStep) {
  1592. fixSpec(*operationIo.ReduceCombinerInputFormat);
  1593. }
  1594. }
  1595. const bool isFirstStep = (!mapper && !reduceCombiner);
  1596. TStructuredJobTableList reducerInputs;
  1597. if (isFirstStep) {
  1598. reducerInputs = structuredInputs;
  1599. } else {
  1600. auto reducerInputDescription =
  1601. spec.GetIntermediateReducerInputDescription()
  1602. .GetOrElse(TUnspecifiedTableStructure());
  1603. reducerInputs = {
  1604. TStructuredJobTable::Intermediate(reducerInputDescription),
  1605. };
  1606. }
  1607. auto hints = spec.ReducerFormatHints_;
  1608. TVector<TTableSchema> reducerInferenceResult;
  1609. if (isFirstStep) {
  1610. reducerInferenceResult = PrepareOperation(
  1611. *reducer,
  1612. TOperationPreparationContext(
  1613. structuredInputs,
  1614. structuredOutputs,
  1615. preparer->GetClient()->GetRawClient(),
  1616. preparer->GetClientRetryPolicy(),
  1617. preparer->GetTransactionId()),
  1618. &structuredInputs,
  1619. &structuredOutputs,
  1620. hints);
  1621. } else {
  1622. reducerInferenceResult = PrepareOperation<TStructuredJobTableList>(
  1623. *reducer,
  1624. TSpeculativeOperationPreparationContext(
  1625. currentInferenceResult,
  1626. reducerInputs,
  1627. structuredOutputs),
  1628. /* inputs */ nullptr,
  1629. &structuredOutputs,
  1630. hints);
  1631. }
  1632. auto [inputFormat, inputFormatConfig] = formatBuilder.CreateFormat(
  1633. *reducer,
  1634. EIODirection::Input,
  1635. reducerInputs,
  1636. hints.InputFormatHints_,
  1637. ENodeReaderFormat::Yson,
  1638. /* allowFormatFromTableAttribute = */ isFirstStep);
  1639. auto [outputFormat, outputFormatConfig] = formatBuilder.CreateFormat(
  1640. *reducer,
  1641. EIODirection::Output,
  1642. ToStructuredJobTableList(spec.GetStructuredOutputs()),
  1643. hints.OutputFormatHints_,
  1644. ENodeReaderFormat::Yson,
  1645. /* allowFormatFromTableAttribute = */ false);
  1646. operationIo.ReducerJobFiles = CreateFormatConfig(inputFormatConfig, outputFormatConfig);
  1647. operationIo.ReducerInputFormat = inputFormat;
  1648. operationIo.ReducerOutputFormat = outputFormat;
  1649. if (isFirstStep) {
  1650. fixSpec(operationIo.ReducerInputFormat);
  1651. }
  1652. operationIo.Inputs = GetPathList(
  1653. ApplyProtobufColumnFilters(
  1654. structuredInputs,
  1655. *preparer,
  1656. GetColumnsUsedInOperation(spec),
  1657. options),
  1658. /* jobSchemaInferenceResult */ Nothing(),
  1659. /* inferSchema */ false);
  1660. operationIo.Outputs = GetPathList(
  1661. structuredOutputs,
  1662. reducerInferenceResult,
  1663. inferOutputSchema);
  1664. VerifyHasElements(operationIo.Outputs, "outputs");
  1665. return DoExecuteMapReduce(
  1666. operation,
  1667. preparer,
  1668. operationIo,
  1669. spec,
  1670. mapper,
  1671. reduceCombiner,
  1672. reducer,
  1673. options);
  1674. }
  1675. void ExecuteRawMapReduce(
  1676. const TOperationPtr& operation,
  1677. const TOperationPreparerPtr& preparer,
  1678. const TRawMapReduceOperationSpec& spec,
  1679. const ::TIntrusivePtr<IRawJob>& mapper,
  1680. const ::TIntrusivePtr<IRawJob>& reduceCombiner,
  1681. const ::TIntrusivePtr<IRawJob>& reducer,
  1682. const TOperationOptions& options)
  1683. {
  1684. YT_LOG_DEBUG("Starting raw map-reduce operation (PreparationId: %v)",
  1685. preparer->GetPreparationId());
  1686. TMapReduceOperationIo operationIo;
  1687. operationIo.Inputs = NRawClient::CanonizeYPaths(preparer->GetClient()->GetRawClient(), spec.GetInputs());
  1688. operationIo.MapOutputs = NRawClient::CanonizeYPaths(preparer->GetClient()->GetRawClient(), spec.GetMapOutputs());
  1689. operationIo.Outputs = NRawClient::CanonizeYPaths(preparer->GetClient()->GetRawClient(), spec.GetOutputs());
  1690. VerifyHasElements(operationIo.Inputs, "inputs");
  1691. VerifyHasElements(operationIo.Outputs, "outputs");
  1692. auto getFormatOrDefault = [&] (const TMaybe<TFormat>& maybeFormat, const TMaybe<TFormat> stageDefaultFormat, const char* formatName) {
  1693. if (maybeFormat) {
  1694. return *maybeFormat;
  1695. } else if (stageDefaultFormat) {
  1696. return *stageDefaultFormat;
  1697. } else {
  1698. ythrow TApiUsageError() << "Cannot derive " << formatName;
  1699. }
  1700. };
  1701. if (mapper) {
  1702. operationIo.MapperInputFormat = getFormatOrDefault(spec.MapperInputFormat_, spec.MapperFormat_, "mapper input format");
  1703. operationIo.MapperOutputFormat = getFormatOrDefault(spec.MapperOutputFormat_, spec.MapperFormat_, "mapper output format");
  1704. }
  1705. if (reduceCombiner) {
  1706. operationIo.ReduceCombinerInputFormat = getFormatOrDefault(spec.ReduceCombinerInputFormat_, spec.ReduceCombinerFormat_, "reduce combiner input format");
  1707. operationIo.ReduceCombinerOutputFormat = getFormatOrDefault(spec.ReduceCombinerOutputFormat_, spec.ReduceCombinerFormat_, "reduce combiner output format");
  1708. }
  1709. operationIo.ReducerInputFormat = getFormatOrDefault(spec.ReducerInputFormat_, spec.ReducerFormat_, "reducer input format");
  1710. operationIo.ReducerOutputFormat = getFormatOrDefault(spec.ReducerOutputFormat_, spec.ReducerFormat_, "reducer output format");
  1711. return DoExecuteMapReduce(
  1712. operation,
  1713. preparer,
  1714. operationIo,
  1715. spec,
  1716. mapper,
  1717. reduceCombiner,
  1718. reducer,
  1719. options);
  1720. }
  1721. void ExecuteSort(
  1722. const TOperationPtr& operation,
  1723. const TOperationPreparerPtr& preparer,
  1724. const TSortOperationSpec& spec,
  1725. const TOperationOptions& options)
  1726. {
  1727. YT_LOG_DEBUG("Starting sort operation (PreparationId: %v)",
  1728. preparer->GetPreparationId());
  1729. auto inputs = NRawClient::CanonizeYPaths(preparer->GetClient()->GetRawClient(), spec.Inputs_);
  1730. auto output = NRawClient::CanonizeYPath(preparer->GetClient()->GetRawClient(), spec.Output_);
  1731. if (options.CreateOutputTables_) {
  1732. CheckInputTablesExist(*preparer, inputs);
  1733. CreateOutputTable(*preparer, output);
  1734. }
  1735. TNode specNode = BuildYsonNodeFluently()
  1736. .BeginMap()
  1737. .Item("input_table_paths").List(inputs)
  1738. .Item("output_table_path").Value(output)
  1739. .Item("sort_by").Value(spec.SortBy_)
  1740. .DoIf(spec.SchemaInferenceMode_.Defined(), [&] (TFluentMap fluent) {
  1741. fluent.Item("schema_inference_mode").Value(ToString(*spec.SchemaInferenceMode_));
  1742. })
  1743. .EndMap();
  1744. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1745. BuildPartitionCountOperationPart(spec, &specNode);
  1746. BuildPartitionJobCountOperationPart(spec, &specNode);
  1747. BuildIntermediateDataPart(spec, &specNode);
  1748. auto startOperation = [
  1749. operation=operation.Get(),
  1750. spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options),
  1751. preparer,
  1752. inputs,
  1753. output
  1754. ] () {
  1755. auto operationId = preparer->StartOperation(operation, EOperationType::Sort, spec);
  1756. LogYPaths(operationId, inputs, "input");
  1757. LogYPath(operationId, output, "output");
  1758. return operationId;
  1759. };
  1760. operation->SetDelayedStartFunction(std::move(startOperation));
  1761. }
  1762. void ExecuteMerge(
  1763. const TOperationPtr& operation,
  1764. const TOperationPreparerPtr& preparer,
  1765. const TMergeOperationSpec& spec,
  1766. const TOperationOptions& options)
  1767. {
  1768. YT_LOG_DEBUG("Starting merge operation (PreparationId: %v)",
  1769. preparer->GetPreparationId());
  1770. auto inputs = NRawClient::CanonizeYPaths(preparer->GetClient()->GetRawClient(), spec.Inputs_);
  1771. auto output = NRawClient::CanonizeYPath(preparer->GetClient()->GetRawClient(), spec.Output_);
  1772. if (options.CreateOutputTables_) {
  1773. CheckInputTablesExist(*preparer, inputs);
  1774. CreateOutputTable(*preparer, output);
  1775. }
  1776. TNode specNode = BuildYsonNodeFluently()
  1777. .BeginMap()
  1778. .Item("input_table_paths").List(inputs)
  1779. .Item("output_table_path").Value(output)
  1780. .Item("mode").Value(ToString(spec.Mode_))
  1781. .Item("combine_chunks").Value(spec.CombineChunks_)
  1782. .Item("force_transform").Value(spec.ForceTransform_)
  1783. .Item("merge_by").Value(spec.MergeBy_)
  1784. .DoIf(spec.SchemaInferenceMode_.Defined(), [&] (TFluentMap fluent) {
  1785. fluent.Item("schema_inference_mode").Value(ToString(*spec.SchemaInferenceMode_));
  1786. })
  1787. .EndMap();
  1788. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1789. BuildJobCountOperationPart(spec, &specNode);
  1790. auto startOperation = [
  1791. operation=operation.Get(),
  1792. spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options),
  1793. preparer,
  1794. inputs,
  1795. output
  1796. ] () {
  1797. auto operationId = preparer->StartOperation(operation, EOperationType::Merge, spec);
  1798. LogYPaths(operationId, inputs, "input");
  1799. LogYPath(operationId, output, "output");
  1800. return operationId;
  1801. };
  1802. operation->SetDelayedStartFunction(std::move(startOperation));
  1803. }
  1804. void ExecuteErase(
  1805. const TOperationPtr& operation,
  1806. const TOperationPreparerPtr& preparer,
  1807. const TEraseOperationSpec& spec,
  1808. const TOperationOptions& options)
  1809. {
  1810. YT_LOG_DEBUG("Starting erase operation (PreparationId: %v)",
  1811. preparer->GetPreparationId());
  1812. auto tablePath = NRawClient::CanonizeYPath(preparer->GetClient()->GetRawClient(), spec.TablePath_);
  1813. TNode specNode = BuildYsonNodeFluently()
  1814. .BeginMap()
  1815. .Item("table_path").Value(tablePath)
  1816. .Item("combine_chunks").Value(spec.CombineChunks_)
  1817. .DoIf(spec.SchemaInferenceMode_.Defined(), [&] (TFluentMap fluent) {
  1818. fluent.Item("schema_inference_mode").Value(ToString(*spec.SchemaInferenceMode_));
  1819. })
  1820. .EndMap();
  1821. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1822. auto startOperation = [
  1823. operation=operation.Get(),
  1824. spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options),
  1825. preparer,
  1826. tablePath
  1827. ] () {
  1828. auto operationId = preparer->StartOperation(operation, EOperationType::Erase, spec);
  1829. LogYPath(operationId, tablePath, "table_path");
  1830. return operationId;
  1831. };
  1832. operation->SetDelayedStartFunction(std::move(startOperation));
  1833. }
  1834. void ExecuteRemoteCopy(
  1835. const TOperationPtr& operation,
  1836. const TOperationPreparerPtr& preparer,
  1837. const TRemoteCopyOperationSpec& spec,
  1838. const TOperationOptions& options)
  1839. {
  1840. YT_LOG_DEBUG("Starting remote copy operation (PreparationId: %v)",
  1841. preparer->GetPreparationId());
  1842. auto inputs = NRawClient::CanonizeYPaths(preparer->GetClient()->GetRawClient(), spec.Inputs_);
  1843. auto output = NRawClient::CanonizeYPath(preparer->GetClient()->GetRawClient(), spec.Output_);
  1844. if (options.CreateOutputTables_) {
  1845. CreateOutputTable(*preparer, output);
  1846. }
  1847. Y_ENSURE_EX(!spec.ClusterName_.empty(), TApiUsageError() << "ClusterName parameter is required");
  1848. TNode specNode = BuildYsonNodeFluently()
  1849. .BeginMap()
  1850. .Item("cluster_name").Value(spec.ClusterName_)
  1851. .Item("input_table_paths").List(inputs)
  1852. .Item("output_table_path").Value(output)
  1853. .DoIf(spec.NetworkName_.Defined(), [&] (TFluentMap fluent) {
  1854. fluent.Item("network_name").Value(*spec.NetworkName_);
  1855. })
  1856. .DoIf(spec.SchemaInferenceMode_.Defined(), [&] (TFluentMap fluent) {
  1857. fluent.Item("schema_inference_mode").Value(ToString(*spec.SchemaInferenceMode_));
  1858. })
  1859. .Item("copy_attributes").Value(spec.CopyAttributes_)
  1860. .DoIf(!spec.AttributeKeys_.empty(), [&] (TFluentMap fluent) {
  1861. Y_ENSURE_EX(spec.CopyAttributes_, TApiUsageError() <<
  1862. "Specifying nonempty AttributeKeys in RemoteCopy "
  1863. "doesn't make sense without CopyAttributes == true");
  1864. fluent.Item("attribute_keys").List(spec.AttributeKeys_);
  1865. })
  1866. .EndMap();
  1867. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1868. auto startOperation = [
  1869. operation=operation.Get(),
  1870. spec=MergeSpec(specNode, preparer->GetContext().Config->Spec, options),
  1871. preparer,
  1872. inputs,
  1873. output
  1874. ] () {
  1875. auto operationId = preparer->StartOperation(operation, EOperationType::RemoteCopy, spec);
  1876. LogYPaths(operationId, inputs, "input");
  1877. LogYPath(operationId, output, "output");
  1878. return operationId;
  1879. };
  1880. operation->SetDelayedStartFunction(std::move(startOperation));
  1881. }
  1882. void ExecuteVanilla(
  1883. const TOperationPtr& operation,
  1884. const TOperationPreparerPtr& preparer,
  1885. const TVanillaOperationSpec& spec,
  1886. const TOperationOptions& options)
  1887. {
  1888. YT_LOG_DEBUG("Starting vanilla operation (PreparationId: %v)",
  1889. preparer->GetPreparationId());
  1890. auto addTask = [&](TFluentMap fluent, const TVanillaTask& task) {
  1891. Y_ABORT_UNLESS(task.Job_.Get());
  1892. if (std::holds_alternative<TVoidStructuredRowStream>(task.Job_->GetOutputRowStreamDescription())) {
  1893. Y_ENSURE_EX(task.Outputs_.empty(),
  1894. TApiUsageError() << "Vanilla task with void IVanillaJob doesn't expect output tables");
  1895. TJobPreparer jobPreparer(
  1896. *preparer,
  1897. task.Spec_,
  1898. *task.Job_,
  1899. /* outputTableCount */ 0,
  1900. /* smallFileList */ {},
  1901. options);
  1902. fluent
  1903. .Item(task.Name_).BeginMap()
  1904. .Item("job_count").Value(task.JobCount_)
  1905. .DoIf(task.NetworkProject_.Defined(), [&](TFluentMap fluent) {
  1906. fluent.Item("network_project").Value(*task.NetworkProject_);
  1907. })
  1908. .Do([&] (TFluentMap fluent) {
  1909. BuildUserJobFluently(
  1910. std::cref(jobPreparer),
  1911. /* inputFormat */ Nothing(),
  1912. /* outputFormat */ Nothing(),
  1913. fluent);
  1914. })
  1915. .EndMap();
  1916. } else {
  1917. auto operationIo = CreateSimpleOperationIo(
  1918. *task.Job_,
  1919. *preparer,
  1920. task,
  1921. options,
  1922. false);
  1923. Y_ENSURE_EX(operationIo.Outputs.size() > 0,
  1924. TApiUsageError() << "Vanilla task with IVanillaJob that has table writer expects output tables");
  1925. if (options.CreateOutputTables_) {
  1926. CreateOutputTables(*preparer, operationIo.Outputs);
  1927. }
  1928. TJobPreparer jobPreparer(
  1929. *preparer,
  1930. task.Spec_,
  1931. *task.Job_,
  1932. operationIo.Outputs.size(),
  1933. operationIo.JobFiles,
  1934. options);
  1935. fluent
  1936. .Item(task.Name_).BeginMap()
  1937. .Item("job_count").Value(task.JobCount_)
  1938. .DoIf(task.NetworkProject_.Defined(), [&](TFluentMap fluent) {
  1939. fluent.Item("network_project").Value(*task.NetworkProject_);
  1940. })
  1941. .Do([&] (TFluentMap fluent) {
  1942. BuildUserJobFluently(
  1943. std::cref(jobPreparer),
  1944. /* inputFormat */ Nothing(),
  1945. operationIo.OutputFormat,
  1946. fluent);
  1947. })
  1948. .Item("output_table_paths").List(operationIo.Outputs)
  1949. .Item("job_io").BeginMap()
  1950. .DoIf(!preparer->GetContext().Config->TableWriter.Empty(), [&](TFluentMap fluent) {
  1951. fluent.Item("table_writer").Value(preparer->GetContext().Config->TableWriter);
  1952. })
  1953. .Item("control_attributes").BeginMap()
  1954. .Item("enable_row_index").Value(TNode(true))
  1955. .Item("enable_range_index").Value(TNode(true))
  1956. .EndMap()
  1957. .EndMap()
  1958. .EndMap();
  1959. }
  1960. };
  1961. if (options.CreateDebugOutputTables_) {
  1962. CreateDebugOutputTables(spec, *preparer);
  1963. }
  1964. TNode specNode = BuildYsonNodeFluently()
  1965. .BeginMap()
  1966. .Item("tasks").DoMapFor(spec.Tasks_, addTask)
  1967. .EndMap();
  1968. BuildCommonOperationPart(preparer->GetContext().Config, spec, options, &specNode);
  1969. BuildCommonUserOperationPart(spec, &specNode);
  1970. auto startOperation = [operation=operation.Get(), spec=MergeSpec(std::move(specNode), preparer->GetContext().Config->Spec, options), preparer] () {
  1971. auto operationId = preparer->StartOperation(operation, EOperationType::Vanilla, spec);
  1972. return operationId;
  1973. };
  1974. operation->SetDelayedStartFunction(std::move(startOperation));
  1975. }
  1976. ////////////////////////////////////////////////////////////////////////////////
  1977. class TOperation::TOperationImpl
  1978. : public TThrRefBase
  1979. {
  1980. public:
  1981. TOperationImpl(
  1982. IRawClientPtr rawClient,
  1983. IClientRetryPolicyPtr clientRetryPolicy,
  1984. TClientContext context,
  1985. const TMaybe<TOperationId>& operationId = {})
  1986. : RawClient_(std::move(rawClient))
  1987. , Context_(std::move(context))
  1988. , ClientRetryPolicy_(clientRetryPolicy)
  1989. , Id_(operationId)
  1990. , PreparedPromise_(::NThreading::NewPromise<void>())
  1991. , StartedPromise_(::NThreading::NewPromise<void>())
  1992. {
  1993. if (Id_) {
  1994. PreparedPromise_.SetValue();
  1995. StartedPromise_.SetValue();
  1996. } else {
  1997. PreparedPromise_.GetFuture().Subscribe([this_=::TIntrusivePtr(this)] (const ::NThreading::TFuture<void>& preparedResult) {
  1998. try {
  1999. preparedResult.GetValue();
  2000. } catch (...) {
  2001. this_->StartedPromise_.SetException(std::current_exception());
  2002. return;
  2003. }
  2004. });
  2005. }
  2006. }
  2007. const TOperationId& GetId() const;
  2008. TString GetWebInterfaceUrl() const;
  2009. void OnPrepared();
  2010. void SetDelayedStartFunction(std::function<TOperationId()> start);
  2011. void Start();
  2012. bool IsStarted() const;
  2013. void OnPreparationException(std::exception_ptr e);
  2014. TString GetStatus();
  2015. void OnStatusUpdated(const TString& newStatus);
  2016. ::NThreading::TFuture<void> GetPreparedFuture();
  2017. ::NThreading::TFuture<void> GetStartedFuture();
  2018. ::NThreading::TFuture<void> Watch(TClientPtr client);
  2019. EOperationBriefState GetBriefState();
  2020. TMaybe<TYtError> GetError();
  2021. TJobStatistics GetJobStatistics();
  2022. TMaybe<TOperationBriefProgress> GetBriefProgress();
  2023. void AbortOperation();
  2024. void CompleteOperation();
  2025. void SuspendOperation(const TSuspendOperationOptions& options);
  2026. void ResumeOperation(const TResumeOperationOptions& options);
  2027. TOperationAttributes GetAttributes(const TGetOperationOptions& options);
  2028. void UpdateParameters(const TUpdateOperationParametersOptions& options);
  2029. TJobAttributes GetJob(const TJobId& jobId, const TGetJobOptions& options);
  2030. TListJobsResult ListJobs(const TListJobsOptions& options);
  2031. void AsyncFinishOperation(TOperationAttributes operationAttributes);
  2032. void FinishWithException(std::exception_ptr exception);
  2033. void UpdateBriefProgress(TMaybe<TOperationBriefProgress> briefProgress);
  2034. void AnalyzeUnrecognizedSpec(TNode unrecognizedSpec);
  2035. const TClientContext& GetContext() const;
  2036. private:
  2037. void OnStarted(const TOperationId& operationId);
  2038. void UpdateAttributesAndCall(bool needJobStatistics, std::function<void(const TOperationAttributes&)> func);
  2039. void SyncFinishOperationImpl(const TOperationAttributes&);
  2040. static void* SyncFinishOperationProc(void* );
  2041. void ValidateOperationStarted() const;
  2042. private:
  2043. const IRawClientPtr RawClient_;
  2044. const TClientContext Context_;
  2045. IClientRetryPolicyPtr ClientRetryPolicy_;
  2046. TMaybe<TOperationId> Id_;
  2047. TMutex Lock_;
  2048. ::NThreading::TPromise<void> PreparedPromise_;
  2049. ::NThreading::TPromise<void> StartedPromise_;
  2050. TMaybe<::NThreading::TPromise<void>> CompletePromise_;
  2051. std::function<TOperationId()> DelayedStartFunction_;
  2052. TString Status_;
  2053. TOperationAttributes Attributes_;
  2054. };
  2055. ////////////////////////////////////////////////////////////////////////////////
  2056. class TOperationPollerItem
  2057. : public IYtPollerItem
  2058. {
  2059. public:
  2060. TOperationPollerItem(::TIntrusivePtr<TOperation::TOperationImpl> operationImpl)
  2061. : OperationImpl_(std::move(operationImpl))
  2062. { }
  2063. void PrepareRequest(IRawBatchRequest* batchRequest) override
  2064. {
  2065. auto filter = TOperationAttributeFilter()
  2066. .Add(EOperationAttribute::State)
  2067. .Add(EOperationAttribute::BriefProgress)
  2068. .Add(EOperationAttribute::Result);
  2069. if (!UnrecognizedSpecAnalyzed_) {
  2070. filter.Add(EOperationAttribute::UnrecognizedSpec);
  2071. }
  2072. OperationState_ = batchRequest->GetOperation(
  2073. OperationImpl_->GetId(),
  2074. TGetOperationOptions().AttributeFilter(filter));
  2075. }
  2076. EStatus OnRequestExecuted() override
  2077. {
  2078. try {
  2079. const auto& attributes = OperationState_.GetValue();
  2080. if (!UnrecognizedSpecAnalyzed_ && !attributes.UnrecognizedSpec.Empty()) {
  2081. OperationImpl_->AnalyzeUnrecognizedSpec(*attributes.UnrecognizedSpec);
  2082. UnrecognizedSpecAnalyzed_ = true;
  2083. }
  2084. Y_ABORT_UNLESS(attributes.BriefState,
  2085. "get_operation for operation %s has not returned \"state\" field",
  2086. GetGuidAsString(OperationImpl_->GetId()).data());
  2087. if (*attributes.BriefState != EOperationBriefState::InProgress) {
  2088. OperationImpl_->AsyncFinishOperation(attributes);
  2089. return PollBreak;
  2090. } else {
  2091. OperationImpl_->UpdateBriefProgress(attributes.BriefProgress);
  2092. }
  2093. } catch (const TErrorResponse& e) {
  2094. if (!IsRetriable(e)) {
  2095. OperationImpl_->FinishWithException(std::current_exception());
  2096. return PollBreak;
  2097. }
  2098. } catch (const std::exception& e) {
  2099. OperationImpl_->FinishWithException(std::current_exception());
  2100. return PollBreak;
  2101. }
  2102. return PollContinue;
  2103. }
  2104. void OnItemDiscarded() override {
  2105. OperationImpl_->FinishWithException(std::make_exception_ptr(yexception() << "Operation cancelled"));
  2106. }
  2107. private:
  2108. ::TIntrusivePtr<TOperation::TOperationImpl> OperationImpl_;
  2109. ::NThreading::TFuture<TOperationAttributes> OperationState_;
  2110. bool UnrecognizedSpecAnalyzed_ = false;
  2111. };
  2112. ////////////////////////////////////////////////////////////////////////////////
  2113. const TOperationId& TOperation::TOperationImpl::GetId() const
  2114. {
  2115. ValidateOperationStarted();
  2116. return *Id_;
  2117. }
  2118. TString TOperation::TOperationImpl::GetWebInterfaceUrl() const
  2119. {
  2120. ValidateOperationStarted();
  2121. return GetOperationWebInterfaceUrl(Context_.ServerName, *Id_);
  2122. }
  2123. void TOperation::TOperationImpl::OnPrepared()
  2124. {
  2125. Y_ABORT_IF(PreparedPromise_.HasException());
  2126. Y_ABORT_IF(PreparedPromise_.HasValue());
  2127. PreparedPromise_.SetValue();
  2128. }
  2129. void TOperation::TOperationImpl::SetDelayedStartFunction(std::function<TOperationId()> start)
  2130. {
  2131. DelayedStartFunction_ = std::move(start);
  2132. }
  2133. void TOperation::TOperationImpl::Start()
  2134. {
  2135. {
  2136. auto guard = Guard(Lock_);
  2137. if (Id_) {
  2138. ythrow TApiUsageError() << "Start() should not be called on running operations";
  2139. }
  2140. }
  2141. GetPreparedFuture().GetValueSync();
  2142. std::function<TOperationId()> startStuff;
  2143. {
  2144. auto guard = Guard(Lock_);
  2145. startStuff.swap(DelayedStartFunction_);
  2146. }
  2147. if (!startStuff) {
  2148. ythrow TApiUsageError() << "Seems that Start() was called multiple times. If not, contact yt@";
  2149. }
  2150. TOperationId operationId;
  2151. try {
  2152. operationId = startStuff();
  2153. } catch (...) {
  2154. auto exception = std::current_exception();
  2155. StartedPromise_.SetException(exception);
  2156. std::rethrow_exception(exception);
  2157. }
  2158. OnStarted(operationId);
  2159. }
  2160. bool TOperation::TOperationImpl::IsStarted() const {
  2161. auto guard = Guard(Lock_);
  2162. return bool(Id_);
  2163. }
  2164. void TOperation::TOperationImpl::OnPreparationException(std::exception_ptr e)
  2165. {
  2166. Y_ABORT_IF(PreparedPromise_.HasValue());
  2167. Y_ABORT_IF(PreparedPromise_.HasException());
  2168. PreparedPromise_.SetException(e);
  2169. }
  2170. TString TOperation::TOperationImpl::GetStatus()
  2171. {
  2172. {
  2173. auto guard = Guard(Lock_);
  2174. if (!Id_) {
  2175. return Status_;
  2176. }
  2177. }
  2178. TMaybe<TString> state;
  2179. UpdateAttributesAndCall(false, [&] (const TOperationAttributes& attributes) {
  2180. state = attributes.State;
  2181. });
  2182. return "On YT cluster: " + state.GetOrElse("undefined state");
  2183. }
  2184. void TOperation::TOperationImpl::OnStatusUpdated(const TString& newStatus)
  2185. {
  2186. auto guard = Guard(Lock_);
  2187. Status_ = newStatus;
  2188. }
  2189. ::NThreading::TFuture<void> TOperation::TOperationImpl::GetPreparedFuture()
  2190. {
  2191. return PreparedPromise_.GetFuture();
  2192. }
  2193. ::NThreading::TFuture<void> TOperation::TOperationImpl::GetStartedFuture()
  2194. {
  2195. return StartedPromise_.GetFuture();
  2196. }
  2197. ::NThreading::TFuture<void> TOperation::TOperationImpl::Watch(TClientPtr client)
  2198. {
  2199. {
  2200. auto guard = Guard(Lock_);
  2201. if (CompletePromise_) {
  2202. return *CompletePromise_;
  2203. }
  2204. CompletePromise_ = ::NThreading::NewPromise<void>();
  2205. }
  2206. GetStartedFuture().Subscribe([
  2207. this_=::TIntrusivePtr(this),
  2208. client=std::move(client)
  2209. ] (const ::NThreading::TFuture<void>& startedResult) {
  2210. try {
  2211. startedResult.GetValue();
  2212. } catch (...) {
  2213. this_->CompletePromise_->SetException(std::current_exception());
  2214. return;
  2215. }
  2216. client->GetYtPoller().Watch(::MakeIntrusive<TOperationPollerItem>(this_));
  2217. auto operationId = this_->GetId();
  2218. auto registry = TAbortableRegistry::Get();
  2219. registry->Add(
  2220. operationId,
  2221. ::MakeIntrusive<TOperationAbortable>(this_->RawClient_, this_->ClientRetryPolicy_, operationId));
  2222. // We have to own an IntrusivePtr to registry to prevent use-after-free
  2223. auto removeOperation = [registry, operationId] (const ::NThreading::TFuture<void>&) {
  2224. registry->Remove(operationId);
  2225. };
  2226. this_->CompletePromise_->GetFuture().Subscribe(removeOperation);
  2227. });
  2228. return *CompletePromise_;
  2229. }
  2230. EOperationBriefState TOperation::TOperationImpl::GetBriefState()
  2231. {
  2232. ValidateOperationStarted();
  2233. EOperationBriefState result = EOperationBriefState::InProgress;
  2234. UpdateAttributesAndCall(false, [&] (const TOperationAttributes& attributes) {
  2235. Y_ABORT_UNLESS(attributes.BriefState,
  2236. "get_operation for operation %s has not returned \"state\" field",
  2237. GetGuidAsString(*Id_).data());
  2238. result = *attributes.BriefState;
  2239. });
  2240. return result;
  2241. }
  2242. TMaybe<TYtError> TOperation::TOperationImpl::GetError()
  2243. {
  2244. ValidateOperationStarted();
  2245. TMaybe<TYtError> result;
  2246. UpdateAttributesAndCall(false, [&] (const TOperationAttributes& attributes) {
  2247. Y_ABORT_UNLESS(attributes.Result);
  2248. result = attributes.Result->Error;
  2249. });
  2250. return result;
  2251. }
  2252. TJobStatistics TOperation::TOperationImpl::GetJobStatistics()
  2253. {
  2254. ValidateOperationStarted();
  2255. TJobStatistics result;
  2256. UpdateAttributesAndCall(true, [&] (const TOperationAttributes& attributes) {
  2257. if (attributes.Progress) {
  2258. result = attributes.Progress->JobStatistics;
  2259. }
  2260. });
  2261. return result;
  2262. }
  2263. TMaybe<TOperationBriefProgress> TOperation::TOperationImpl::GetBriefProgress()
  2264. {
  2265. ValidateOperationStarted();
  2266. {
  2267. auto g = Guard(Lock_);
  2268. if (CompletePromise_.Defined()) {
  2269. // Poller do this job for us
  2270. return Attributes_.BriefProgress;
  2271. }
  2272. }
  2273. TMaybe<TOperationBriefProgress> result;
  2274. UpdateAttributesAndCall(false, [&] (const TOperationAttributes& attributes) {
  2275. result = attributes.BriefProgress;
  2276. });
  2277. return result;
  2278. }
  2279. void TOperation::TOperationImpl::UpdateBriefProgress(TMaybe<TOperationBriefProgress> briefProgress)
  2280. {
  2281. auto g = Guard(Lock_);
  2282. Attributes_.BriefProgress = std::move(briefProgress);
  2283. }
  2284. void TOperation::TOperationImpl::AnalyzeUnrecognizedSpec(TNode unrecognizedSpec)
  2285. {
  2286. static const TVector<TVector<TString>> knownUnrecognizedSpecFieldPaths = {
  2287. {"mapper", "class_name"},
  2288. {"reducer", "class_name"},
  2289. {"reduce_combiner", "class_name"},
  2290. };
  2291. auto removeByPath = [] (TNode& node, auto pathBegin, auto pathEnd, auto& removeByPath) {
  2292. if (pathBegin == pathEnd) {
  2293. return;
  2294. }
  2295. if (!node.IsMap()) {
  2296. return;
  2297. }
  2298. auto* child = node.AsMap().FindPtr(*pathBegin);
  2299. if (!child) {
  2300. return;
  2301. }
  2302. removeByPath(*child, std::next(pathBegin), pathEnd, removeByPath);
  2303. if (std::next(pathBegin) == pathEnd || (child->IsMap() && child->Empty())) {
  2304. node.AsMap().erase(*pathBegin);
  2305. }
  2306. };
  2307. Y_ABORT_UNLESS(unrecognizedSpec.IsMap());
  2308. for (const auto& knownFieldPath : knownUnrecognizedSpecFieldPaths) {
  2309. Y_ABORT_UNLESS(!knownFieldPath.empty());
  2310. removeByPath(unrecognizedSpec, knownFieldPath.cbegin(), knownFieldPath.cend(), removeByPath);
  2311. }
  2312. if (!unrecognizedSpec.Empty()) {
  2313. YT_LOG_INFO(
  2314. "WARNING! Unrecognized spec for operation %s is not empty "
  2315. "(fields added by the YT API library are excluded): %s",
  2316. GetGuidAsString(*Id_).data(),
  2317. NodeToYsonString(unrecognizedSpec).data());
  2318. }
  2319. }
  2320. void TOperation::TOperationImpl::OnStarted(const TOperationId& operationId)
  2321. {
  2322. auto guard = Guard(Lock_);
  2323. Y_ABORT_UNLESS(!Id_,
  2324. "OnStarted() called with operationId = %s for operation with id %s",
  2325. GetGuidAsString(operationId).data(),
  2326. GetGuidAsString(*Id_).data());
  2327. Id_ = operationId;
  2328. Y_ABORT_UNLESS(!StartedPromise_.HasValue() && !StartedPromise_.HasException());
  2329. StartedPromise_.SetValue();
  2330. }
  2331. void TOperation::TOperationImpl::UpdateAttributesAndCall(
  2332. bool needJobStatistics,
  2333. std::function<void(const TOperationAttributes&)> func)
  2334. {
  2335. {
  2336. auto g = Guard(Lock_);
  2337. if (Attributes_.BriefState
  2338. && *Attributes_.BriefState != EOperationBriefState::InProgress
  2339. && (!needJobStatistics || Attributes_.Progress))
  2340. {
  2341. func(Attributes_);
  2342. return;
  2343. }
  2344. }
  2345. auto attributes = RequestWithRetry<TOperationAttributes>(
  2346. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2347. [this] (TMutationId /*mutationId*/) {
  2348. return RawClient_->GetOperation(
  2349. *Id_,
  2350. TGetOperationOptions().AttributeFilter(TOperationAttributeFilter()
  2351. .Add(EOperationAttribute::Result)
  2352. .Add(EOperationAttribute::Progress)
  2353. .Add(EOperationAttribute::State)
  2354. .Add(EOperationAttribute::BriefProgress)));
  2355. });
  2356. func(attributes);
  2357. Y_ENSURE(attributes.BriefState);
  2358. if (*attributes.BriefState != EOperationBriefState::InProgress) {
  2359. auto g = Guard(Lock_);
  2360. Attributes_ = std::move(attributes);
  2361. }
  2362. }
  2363. void TOperation::TOperationImpl::FinishWithException(std::exception_ptr e)
  2364. {
  2365. CompletePromise_->SetException(std::move(e));
  2366. }
  2367. void TOperation::TOperationImpl::AbortOperation()
  2368. {
  2369. ValidateOperationStarted();
  2370. RequestWithRetry<void>(
  2371. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2372. [this] (TMutationId& mutationId) {
  2373. RawClient_->AbortOperation(mutationId, *Id_);
  2374. });
  2375. }
  2376. void TOperation::TOperationImpl::CompleteOperation()
  2377. {
  2378. ValidateOperationStarted();
  2379. RequestWithRetry<void>(
  2380. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2381. [this] (TMutationId& mutationId) {
  2382. RawClient_->CompleteOperation(mutationId, *Id_);
  2383. });
  2384. }
  2385. void TOperation::TOperationImpl::SuspendOperation(const TSuspendOperationOptions& options)
  2386. {
  2387. ValidateOperationStarted();
  2388. RequestWithRetry<void>(
  2389. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2390. [this, &options] (TMutationId& mutationId) {
  2391. RawClient_->SuspendOperation(mutationId, *Id_, options);
  2392. });
  2393. }
  2394. void TOperation::TOperationImpl::ResumeOperation(const TResumeOperationOptions& options)
  2395. {
  2396. ValidateOperationStarted();
  2397. RequestWithRetry<void>(
  2398. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2399. [this, &options] (TMutationId& mutationId) {
  2400. RawClient_->ResumeOperation(mutationId, *Id_, options);
  2401. });
  2402. }
  2403. TOperationAttributes TOperation::TOperationImpl::GetAttributes(const TGetOperationOptions& options)
  2404. {
  2405. ValidateOperationStarted();
  2406. return RequestWithRetry<TOperationAttributes>(
  2407. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2408. [this, &options] (TMutationId /*mutationId*/) {
  2409. return RawClient_->GetOperation(*Id_, options);
  2410. });
  2411. }
  2412. void TOperation::TOperationImpl::UpdateParameters(const TUpdateOperationParametersOptions& options)
  2413. {
  2414. ValidateOperationStarted();
  2415. RequestWithRetry<void>(
  2416. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2417. [this, &options] (TMutationId /*mutationId*/) {
  2418. RawClient_->UpdateOperationParameters(*Id_, options);
  2419. });
  2420. }
  2421. TJobAttributes TOperation::TOperationImpl::GetJob(const TJobId& jobId, const TGetJobOptions& options)
  2422. {
  2423. ValidateOperationStarted();
  2424. auto result = RequestWithRetry<NYson::TYsonString>(
  2425. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2426. [this, &jobId, &options] (TMutationId /*mutationId*/) {
  2427. return RawClient_->GetJob(*Id_, jobId, options);
  2428. });
  2429. return NRawClient::ParseJobAttributes(NodeFromYsonString(result.AsStringBuf()));
  2430. }
  2431. TListJobsResult TOperation::TOperationImpl::ListJobs(const TListJobsOptions& options)
  2432. {
  2433. ValidateOperationStarted();
  2434. return RequestWithRetry<TListJobsResult>(
  2435. ClientRetryPolicy_->CreatePolicyForGenericRequest(),
  2436. [this, &options] (TMutationId /*mutationId*/) {
  2437. return RawClient_->ListJobs(*Id_, options);
  2438. });
  2439. }
  2440. struct TAsyncFinishOperationsArgs
  2441. {
  2442. ::TIntrusivePtr<TOperation::TOperationImpl> OperationImpl;
  2443. TOperationAttributes OperationAttributes;
  2444. };
  2445. void TOperation::TOperationImpl::AsyncFinishOperation(TOperationAttributes operationAttributes)
  2446. {
  2447. auto args = new TAsyncFinishOperationsArgs;
  2448. args->OperationImpl = this;
  2449. args->OperationAttributes = std::move(operationAttributes);
  2450. TThread thread(TThread::TParams(&TOperation::TOperationImpl::SyncFinishOperationProc, args).SetName("finish operation"));
  2451. thread.Start();
  2452. thread.Detach();
  2453. }
  2454. void* TOperation::TOperationImpl::SyncFinishOperationProc(void* pArgs)
  2455. {
  2456. std::unique_ptr<TAsyncFinishOperationsArgs> args(static_cast<TAsyncFinishOperationsArgs*>(pArgs));
  2457. args->OperationImpl->SyncFinishOperationImpl(args->OperationAttributes);
  2458. return nullptr;
  2459. }
  2460. void TOperation::TOperationImpl::SyncFinishOperationImpl(const TOperationAttributes& attributes)
  2461. {
  2462. {
  2463. auto guard = Guard(Lock_);
  2464. Y_ABORT_UNLESS(Id_);
  2465. }
  2466. Y_ABORT_UNLESS(attributes.BriefState,
  2467. "get_operation for operation %s has not returned \"state\" field",
  2468. GetGuidAsString(*Id_).data());
  2469. Y_ABORT_UNLESS(*attributes.BriefState != EOperationBriefState::InProgress);
  2470. {
  2471. try {
  2472. // `attributes' that came from poller don't have JobStatistics
  2473. // so we call `GetJobStatistics' in order to get it from server
  2474. // and cache inside object.
  2475. GetJobStatistics();
  2476. } catch (const TErrorResponse& ) {
  2477. // But if for any reason we failed to get attributes
  2478. // we complete operation using what we have.
  2479. auto g = Guard(Lock_);
  2480. Attributes_ = attributes;
  2481. }
  2482. }
  2483. if (*attributes.BriefState == EOperationBriefState::Completed) {
  2484. CompletePromise_->SetValue();
  2485. } else if (*attributes.BriefState == EOperationBriefState::Aborted || *attributes.BriefState == EOperationBriefState::Failed) {
  2486. Y_ABORT_UNLESS(attributes.Result && attributes.Result->Error);
  2487. const auto& error = *attributes.Result->Error;
  2488. YT_LOG_ERROR("Operation %v is `%v' with error: %v",
  2489. *Id_,
  2490. ToString(*attributes.BriefState),
  2491. error.FullDescription());
  2492. TString additionalExceptionText;
  2493. TVector<TFailedJobInfo> failedJobStderrInfo;
  2494. if (*attributes.BriefState == EOperationBriefState::Failed) {
  2495. try {
  2496. failedJobStderrInfo = NYT::NDetail::GetFailedJobInfo(ClientRetryPolicy_, RawClient_, *Id_, TGetFailedJobInfoOptions());
  2497. } catch (const std::exception& e) {
  2498. additionalExceptionText = "Cannot get job stderrs: ";
  2499. additionalExceptionText += e.what();
  2500. }
  2501. }
  2502. CompletePromise_->SetException(
  2503. std::make_exception_ptr(
  2504. TOperationFailedError(
  2505. *attributes.BriefState == EOperationBriefState::Failed
  2506. ? TOperationFailedError::Failed
  2507. : TOperationFailedError::Aborted,
  2508. *Id_,
  2509. error,
  2510. failedJobStderrInfo) << additionalExceptionText));
  2511. }
  2512. }
  2513. void TOperation::TOperationImpl::ValidateOperationStarted() const
  2514. {
  2515. auto guard = Guard(Lock_);
  2516. if (!Id_) {
  2517. ythrow TApiUsageError() << "Operation is not started";
  2518. }
  2519. }
  2520. const TClientContext& TOperation::TOperationImpl::GetContext() const
  2521. {
  2522. return Context_;
  2523. }
  2524. ////////////////////////////////////////////////////////////////////////////////
  2525. TOperation::TOperation(TClientPtr client)
  2526. : Client_(std::move(client))
  2527. , Impl_(::MakeIntrusive<TOperationImpl>(
  2528. Client_->GetRawClient(),
  2529. Client_->GetRetryPolicy(),
  2530. Client_->GetContext()))
  2531. {
  2532. }
  2533. TOperation::TOperation(TOperationId id, TClientPtr client)
  2534. : Client_(std::move(client))
  2535. , Impl_(::MakeIntrusive<TOperationImpl>(
  2536. Client_->GetRawClient(),
  2537. Client_->GetRetryPolicy(),
  2538. Client_->GetContext(), id))
  2539. {
  2540. }
  2541. const TOperationId& TOperation::GetId() const
  2542. {
  2543. return Impl_->GetId();
  2544. }
  2545. TString TOperation::GetWebInterfaceUrl() const
  2546. {
  2547. return Impl_->GetWebInterfaceUrl();
  2548. }
  2549. void TOperation::OnPrepared()
  2550. {
  2551. Impl_->OnPrepared();
  2552. }
  2553. void TOperation::SetDelayedStartFunction(std::function<TOperationId()> start)
  2554. {
  2555. Impl_->SetDelayedStartFunction(std::move(start));
  2556. }
  2557. void TOperation::Start()
  2558. {
  2559. Impl_->Start();
  2560. }
  2561. bool TOperation::IsStarted() const
  2562. {
  2563. return Impl_->IsStarted();
  2564. }
  2565. void TOperation::OnPreparationException(std::exception_ptr e)
  2566. {
  2567. Impl_->OnPreparationException(std::move(e));
  2568. }
  2569. TString TOperation::GetStatus() const
  2570. {
  2571. return Impl_->GetStatus();
  2572. }
  2573. void TOperation::OnStatusUpdated(const TString& newStatus)
  2574. {
  2575. Impl_->OnStatusUpdated(newStatus);
  2576. }
  2577. ::NThreading::TFuture<void> TOperation::GetPreparedFuture()
  2578. {
  2579. return Impl_->GetPreparedFuture();
  2580. }
  2581. ::NThreading::TFuture<void> TOperation::GetStartedFuture()
  2582. {
  2583. return Impl_->GetStartedFuture();
  2584. }
  2585. ::NThreading::TFuture<void> TOperation::Watch()
  2586. {
  2587. return Impl_->Watch(Client_);
  2588. }
  2589. TVector<TFailedJobInfo> TOperation::GetFailedJobInfo(const TGetFailedJobInfoOptions& options)
  2590. {
  2591. return NYT::NDetail::GetFailedJobInfo(Client_->GetRetryPolicy(), Client_->GetRawClient(), GetId(), options);
  2592. }
  2593. EOperationBriefState TOperation::GetBriefState()
  2594. {
  2595. return Impl_->GetBriefState();
  2596. }
  2597. TMaybe<TYtError> TOperation::GetError()
  2598. {
  2599. return Impl_->GetError();
  2600. }
  2601. TJobStatistics TOperation::GetJobStatistics()
  2602. {
  2603. return Impl_->GetJobStatistics();
  2604. }
  2605. TMaybe<TOperationBriefProgress> TOperation::GetBriefProgress()
  2606. {
  2607. return Impl_->GetBriefProgress();
  2608. }
  2609. void TOperation::AbortOperation()
  2610. {
  2611. Impl_->AbortOperation();
  2612. }
  2613. void TOperation::CompleteOperation()
  2614. {
  2615. Impl_->CompleteOperation();
  2616. }
  2617. void TOperation::SuspendOperation(const TSuspendOperationOptions& options)
  2618. {
  2619. Impl_->SuspendOperation(options);
  2620. }
  2621. void TOperation::ResumeOperation(const TResumeOperationOptions& options)
  2622. {
  2623. Impl_->ResumeOperation(options);
  2624. }
  2625. TOperationAttributes TOperation::GetAttributes(const TGetOperationOptions& options)
  2626. {
  2627. return Impl_->GetAttributes(options);
  2628. }
  2629. void TOperation::UpdateParameters(const TUpdateOperationParametersOptions& options)
  2630. {
  2631. Impl_->UpdateParameters(options);
  2632. }
  2633. TJobAttributes TOperation::GetJob(const TJobId& jobId, const TGetJobOptions& options)
  2634. {
  2635. return Impl_->GetJob(jobId, options);
  2636. }
  2637. TListJobsResult TOperation::ListJobs(const TListJobsOptions& options)
  2638. {
  2639. return Impl_->ListJobs(options);
  2640. }
  2641. ////////////////////////////////////////////////////////////////////////////////
  2642. struct TAsyncPrepareAndStartOperationArgs
  2643. {
  2644. std::function<void()> PrepareAndStart;
  2645. };
  2646. void* SyncPrepareAndStartOperation(void* pArgs)
  2647. {
  2648. std::unique_ptr<TAsyncPrepareAndStartOperationArgs> args(static_cast<TAsyncPrepareAndStartOperationArgs*>(pArgs));
  2649. args->PrepareAndStart();
  2650. return nullptr;
  2651. }
  2652. ::TIntrusivePtr<TOperation> ProcessOperation(
  2653. NYT::NDetail::TClientPtr client,
  2654. std::function<void()> prepare,
  2655. ::TIntrusivePtr<TOperation> operation,
  2656. const TOperationOptions& options)
  2657. {
  2658. auto prepareAndStart = [prepare = std::move(prepare), operation, mode = options.StartOperationMode_] () {
  2659. try {
  2660. prepare();
  2661. operation->OnPrepared();
  2662. } catch (const std::exception& ex) {
  2663. YT_LOG_INFO("Operation preparation failed: %v", ex.what());
  2664. operation->OnPreparationException(std::current_exception());
  2665. }
  2666. if (mode >= TOperationOptions::EStartOperationMode::AsyncStart) {
  2667. try {
  2668. operation->Start();
  2669. } catch (...) { }
  2670. }
  2671. };
  2672. if (options.StartOperationMode_ >= TOperationOptions::EStartOperationMode::SyncStart) {
  2673. prepareAndStart();
  2674. WaitIfRequired(operation, client, options);
  2675. } else {
  2676. auto args = new TAsyncPrepareAndStartOperationArgs;
  2677. args->PrepareAndStart = std::move(prepareAndStart);
  2678. TThread thread(TThread::TParams(SyncPrepareAndStartOperation, args).SetName("prepare and start operation"));
  2679. thread.Start();
  2680. thread.Detach();
  2681. }
  2682. return operation;
  2683. }
  2684. void WaitIfRequired(const TOperationPtr& operation, const TClientPtr& client, const TOperationOptions& options)
  2685. {
  2686. auto retryPolicy = client->GetRetryPolicy();
  2687. auto context = client->GetContext();
  2688. if (options.StartOperationMode_ >= TOperationOptions::EStartOperationMode::SyncStart) {
  2689. operation->GetStartedFuture().GetValueSync();
  2690. }
  2691. if (options.StartOperationMode_ == TOperationOptions::EStartOperationMode::SyncWait) {
  2692. auto finishedFuture = operation->Watch();
  2693. TWaitProxy::Get()->WaitFuture(finishedFuture);
  2694. finishedFuture.GetValue();
  2695. if (context.Config->WriteStderrSuccessfulJobs) {
  2696. auto stderrs = GetJobsStderr(retryPolicy, client->GetRawClient(), operation->GetId());
  2697. for (const auto& jobStderr : stderrs) {
  2698. if (!jobStderr.empty()) {
  2699. Cerr << jobStderr << '\n';
  2700. }
  2701. }
  2702. }
  2703. }
  2704. }
  2705. ////////////////////////////////////////////////////////////////////////////////
  2706. void ResetUseClientProtobuf(const char* methodName)
  2707. {
  2708. Cerr << "WARNING! OPTION `TConfig::UseClientProtobuf' IS RESET TO `true'; "
  2709. << "IT CAN DETERIORATE YOUR CODE PERFORMANCE!!! DON'T USE DEPRECATED METHOD `"
  2710. << "TOperationIOSpec::" << methodName << "' TO AVOID THIS RESET" << Endl;
  2711. // Give users some time to contemplate about usage of deprecated functions.
  2712. Cerr << "Sleeping for 5 seconds..." << Endl;
  2713. Sleep(TDuration::Seconds(5));
  2714. TConfig::Get()->UseClientProtobuf = true;
  2715. }
  2716. } // namespace NDetail
  2717. ////////////////////////////////////////////////////////////////////////////////
  2718. ::TIntrusivePtr<INodeReaderImpl> CreateJobNodeReader(TRawTableReaderPtr rawTableReader)
  2719. {
  2720. if (auto schema = NDetail::GetJobInputSkiffSchema()) {
  2721. return new NDetail::TSkiffTableReader(rawTableReader, schema);
  2722. } else {
  2723. return new TNodeTableReader(rawTableReader);
  2724. }
  2725. }
  2726. ::TIntrusivePtr<IYaMRReaderImpl> CreateJobYaMRReader(TRawTableReaderPtr rawTableReader)
  2727. {
  2728. return new TYaMRTableReader(rawTableReader);
  2729. }
  2730. ::TIntrusivePtr<IProtoReaderImpl> CreateJobProtoReader(TRawTableReaderPtr rawTableReader)
  2731. {
  2732. if (TConfig::Get()->UseClientProtobuf) {
  2733. return new TProtoTableReader(
  2734. rawTableReader,
  2735. GetJobInputDescriptors());
  2736. } else {
  2737. return new TLenvalProtoTableReader(
  2738. rawTableReader,
  2739. GetJobInputDescriptors());
  2740. }
  2741. }
  2742. ::TIntrusivePtr<INodeWriterImpl> CreateJobNodeWriter(THolder<IProxyOutput> rawJobWriter)
  2743. {
  2744. return new TNodeTableWriter(std::move(rawJobWriter));
  2745. }
  2746. ::TIntrusivePtr<IYaMRWriterImpl> CreateJobYaMRWriter(THolder<IProxyOutput> rawJobWriter)
  2747. {
  2748. return new TYaMRTableWriter(std::move(rawJobWriter));
  2749. }
  2750. ::TIntrusivePtr<IProtoWriterImpl> CreateJobProtoWriter(THolder<IProxyOutput> rawJobWriter)
  2751. {
  2752. if (TConfig::Get()->UseClientProtobuf) {
  2753. return new TProtoTableWriter(
  2754. std::move(rawJobWriter),
  2755. GetJobOutputDescriptors());
  2756. } else {
  2757. return new TLenvalProtoTableWriter(
  2758. std::move(rawJobWriter),
  2759. GetJobOutputDescriptors());
  2760. }
  2761. }
  2762. ////////////////////////////////////////////////////////////////////////////////
  2763. } // namespace NYT