operation.cpp 102 KB

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