thgraph.cpp 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "thgraph.hpp"
  14. #include "jptree.hpp"
  15. #include "commonext.hpp"
  16. #include "dasess.hpp"
  17. #include "jhtree.hpp"
  18. #include "thcodectx.hpp"
  19. #include "thbuf.hpp"
  20. #include "thormisc.hpp"
  21. #include "thbufdef.hpp"
  22. #include "thmem.hpp"
  23. #include "rtlformat.hpp"
  24. PointerArray createFuncs;
  25. void registerCreateFunc(CreateFunc func)
  26. {
  27. createFuncs.append((void *)func);
  28. }
  29. ///////////////////////////////////
  30. //////
  31. /////
  32. class CThorGraphResult : implements IThorResult, implements IRowWriter, public CInterface
  33. {
  34. CActivityBase &activity;
  35. rowcount_t rowStreamCount;
  36. IOutputMetaData *meta;
  37. Owned<IRowWriterMultiReader> rowBuffer;
  38. IThorRowInterfaces *rowIf;
  39. IEngineRowAllocator *allocator;
  40. bool stopped, readers;
  41. ThorGraphResultType resultType;
  42. void init()
  43. {
  44. stopped = readers = false;
  45. allocator = rowIf->queryRowAllocator();
  46. meta = allocator->queryOutputMeta();
  47. rowStreamCount = 0;
  48. }
  49. class CStreamWriter : implements IRowWriterMultiReader, public CSimpleInterface
  50. {
  51. CThorGraphResult &owner;
  52. CThorExpandingRowArray rows;
  53. public:
  54. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  55. CStreamWriter(CThorGraphResult &_owner, EmptyRowSemantics emptyRowSemantics) : owner(_owner), rows(owner.activity, owner.rowIf, emptyRowSemantics)
  56. {
  57. }
  58. //IRowWriterMultiReader
  59. virtual void putRow(const void *row)
  60. {
  61. rows.append(row);
  62. }
  63. virtual void flush() { }
  64. virtual IRowStream *getReader()
  65. {
  66. return rows.createRowStream(0, (rowidx_t)-1, false);
  67. }
  68. };
  69. public:
  70. IMPLEMENT_IINTERFACE;
  71. CThorGraphResult(CActivityBase &_activity, IThorRowInterfaces *_rowIf, ThorGraphResultType _resultType, unsigned spillPriority) : activity(_activity), rowIf(_rowIf), resultType(_resultType)
  72. {
  73. init();
  74. EmptyRowSemantics emptyRowSemantics;
  75. if (isGrouped())
  76. emptyRowSemantics = ers_eogonly;
  77. else if (isSparse())
  78. emptyRowSemantics = ers_allow;
  79. else
  80. emptyRowSemantics = ers_forbidden;
  81. if (SPILL_PRIORITY_DISABLE == spillPriority)
  82. rowBuffer.setown(new CStreamWriter(*this, emptyRowSemantics));
  83. else
  84. rowBuffer.setown(createOverflowableBuffer(activity, rowIf, emptyRowSemantics, true));
  85. }
  86. // IRowWriter
  87. virtual void putRow(const void *row)
  88. {
  89. assertex(!readers);
  90. ++rowStreamCount;
  91. rowBuffer->putRow(row);
  92. }
  93. virtual void flush() { }
  94. virtual offset_t getPosition() { UNIMPLEMENTED; return 0; }
  95. // IThorResult
  96. virtual IRowWriter *getWriter()
  97. {
  98. return LINK(this);
  99. }
  100. virtual void setResultStream(IRowWriterMultiReader *stream, rowcount_t count)
  101. {
  102. assertex(!readers);
  103. rowBuffer.setown(stream);
  104. rowStreamCount = count;
  105. }
  106. virtual IRowStream *getRowStream()
  107. {
  108. readers = true;
  109. return rowBuffer->getReader();
  110. }
  111. virtual IThorRowInterfaces *queryRowInterfaces() { return rowIf; }
  112. virtual CActivityBase *queryActivity() { return &activity; }
  113. virtual bool isDistributed() const { return resultType & thorgraphresult_distributed; }
  114. virtual bool isSparse() const { return resultType & thorgraphresult_sparse; }
  115. virtual bool isGrouped() const { return resultType & thorgraphresult_grouped; }
  116. virtual void serialize(MemoryBuffer &mb)
  117. {
  118. Owned<IRowStream> stream = getRowStream();
  119. bool grouped = meta->isGrouped();
  120. if (grouped)
  121. {
  122. OwnedConstThorRow prev = stream->nextRow();
  123. if (prev)
  124. {
  125. bool eog;
  126. for (;;)
  127. {
  128. eog = false;
  129. OwnedConstThorRow next = stream->nextRow();
  130. if (!next)
  131. eog = true;
  132. size32_t sz = meta->getRecordSize(prev);
  133. mb.append(sz, prev.get());
  134. mb.append(eog);
  135. if (!next)
  136. {
  137. next.setown(stream->nextRow());
  138. if (!next)
  139. break;
  140. }
  141. prev.set(next);
  142. }
  143. }
  144. }
  145. else
  146. {
  147. for (;;)
  148. {
  149. OwnedConstThorRow row = stream->nextRow();
  150. if (!row)
  151. break;
  152. size32_t sz = meta->getRecordSize(row);
  153. mb.append(sz, row.get());
  154. }
  155. }
  156. }
  157. virtual void getResult(size32_t &len, void * & data)
  158. {
  159. MemoryBuffer mb;
  160. serialize(mb);
  161. len = mb.length();
  162. data = mb.detach();
  163. }
  164. virtual void getLinkedResult(unsigned &countResult, const byte * * & result) override
  165. {
  166. assertex(rowStreamCount==((unsigned)rowStreamCount)); // catch, just in case
  167. Owned<IRowStream> stream = getRowStream();
  168. countResult = 0;
  169. OwnedConstThorRow _rowset = allocator->createRowset((unsigned)rowStreamCount);
  170. const void **rowset = (const void **)_rowset.get();
  171. while (countResult < rowStreamCount)
  172. {
  173. OwnedConstThorRow row = stream->nextRow();
  174. rowset[countResult++] = row.getClear();
  175. }
  176. result = (const byte **)_rowset.getClear();
  177. }
  178. virtual const void * getLinkedRowResult()
  179. {
  180. assertex(rowStreamCount==1); // catch, just in case
  181. Owned<IRowStream> stream = getRowStream();
  182. return stream->nextRow();
  183. }
  184. };
  185. /////
  186. IThorResult *CThorGraphResults::createResult(CActivityBase &activity, unsigned id, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
  187. {
  188. Owned<IThorResult> result = ::createResult(activity, rowIf, resultType, spillPriority);
  189. setResult(id, result);
  190. return result;
  191. }
  192. /////
  193. IThorResult *createResult(CActivityBase &activity, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
  194. {
  195. return new CThorGraphResult(activity, rowIf, resultType, spillPriority);
  196. }
  197. /////
  198. class CThorBoundLoopGraph : implements IThorBoundLoopGraph, public CInterface
  199. {
  200. CGraphBase *graph;
  201. activity_id activityId;
  202. Linked<IOutputMetaData> resultMeta;
  203. Owned<IOutputMetaData> counterMeta, loopAgainMeta;
  204. Owned<IThorRowInterfaces> resultRowIf, countRowIf, loopAgainRowIf;
  205. public:
  206. IMPLEMENT_IINTERFACE;
  207. CThorBoundLoopGraph(CGraphBase *_graph, IOutputMetaData * _resultMeta, unsigned _activityId) : graph(_graph), resultMeta(_resultMeta), activityId(_activityId)
  208. {
  209. counterMeta.setown(createFixedSizeMetaData(sizeof(thor_loop_counter_t)));
  210. loopAgainMeta.setown(createFixedSizeMetaData(sizeof(bool)));
  211. }
  212. virtual void prepareCounterResult(CActivityBase &activity, IThorGraphResults *results, unsigned loopCounter, unsigned pos)
  213. {
  214. if (!countRowIf)
  215. countRowIf.setown(activity.createRowInterfaces(counterMeta));
  216. RtlDynamicRowBuilder counterRow(countRowIf->queryRowAllocator());
  217. thor_loop_counter_t * res = (thor_loop_counter_t *)counterRow.ensureCapacity(sizeof(thor_loop_counter_t),NULL);
  218. *res = loopCounter;
  219. OwnedConstThorRow counterRowFinal = counterRow.finalizeRowClear(sizeof(thor_loop_counter_t));
  220. IThorResult *counterResult = results->createResult(activity, pos, countRowIf, thorgraphresult_nul, SPILL_PRIORITY_DISABLE);
  221. Owned<IRowWriter> counterResultWriter = counterResult->getWriter();
  222. counterResultWriter->putRow(counterRowFinal.getClear());
  223. }
  224. virtual void prepareLoopAgainResult(CActivityBase &activity, IThorGraphResults *results, unsigned pos)
  225. {
  226. if (!loopAgainRowIf)
  227. loopAgainRowIf.setown(activity.createRowInterfaces(loopAgainMeta));
  228. activity.queryGraph().createResult(activity, pos, results, loopAgainRowIf, activity.queryGraph().isLocalChild() ? thorgraphresult_nul : thorgraphresult_distributed, SPILL_PRIORITY_DISABLE);
  229. }
  230. virtual void prepareLoopResults(CActivityBase &activity, IThorGraphResults *results)
  231. {
  232. if (!resultRowIf)
  233. resultRowIf.setown(activity.createRowInterfaces(resultMeta));
  234. ThorGraphResultType resultType = activity.queryGraph().isLocalChild() ? thorgraphresult_nul : thorgraphresult_distributed;
  235. IThorResult *loopResult = results->createResult(activity, 0, resultRowIf, resultType); // loop output
  236. IThorResult *inputResult = results->createResult(activity, 1, resultRowIf, resultType); // loop input
  237. }
  238. virtual void execute(CActivityBase &activity, unsigned counter, IThorGraphResults *results, IRowWriterMultiReader *inputStream, rowcount_t rowStreamCount, size32_t parentExtractSz, const byte *parentExtract)
  239. {
  240. if (counter)
  241. graph->setLoopCounter(counter);
  242. Owned<IThorResult> inputResult = results->getResult(1);
  243. if (inputStream)
  244. inputResult->setResultStream(inputStream, rowStreamCount);
  245. graph->executeChild(parentExtractSz, parentExtract, results, NULL);
  246. }
  247. virtual void execute(CActivityBase &activity, unsigned counter, IThorGraphResults *graphLoopResults, size32_t parentExtractSz, const byte *parentExtract)
  248. {
  249. Owned<IThorGraphResults> results = graph->createThorGraphResults(1);
  250. if (counter)
  251. {
  252. prepareCounterResult(activity, results, counter, 0);
  253. graph->setLoopCounter(counter);
  254. }
  255. try
  256. {
  257. graph->executeChild(parentExtractSz, parentExtract, results, graphLoopResults);
  258. }
  259. catch (IException *e)
  260. {
  261. IThorException *te = QUERYINTERFACE(e, IThorException);
  262. if (!te)
  263. {
  264. Owned<IThorException> e2 = MakeActivityException(&activity, e, "Exception running child graphs");
  265. e->Release();
  266. te = e2.getClear();
  267. }
  268. else if (!te->queryActivityId())
  269. setExceptionActivityInfo(activity.queryContainer(), te);
  270. try { graph->abort(te); }
  271. catch (IException *abortE)
  272. {
  273. Owned<IThorException> e2 = MakeActivityException(&activity, abortE, "Exception whilst aborting graph");
  274. abortE->Release();
  275. EXCLOG(e2, NULL);
  276. }
  277. graph->queryJobChannel().fireException(te);
  278. throw te;
  279. }
  280. }
  281. virtual CGraphBase *queryGraph() { return graph; }
  282. };
  283. IThorBoundLoopGraph *createBoundLoopGraph(CGraphBase *graph, IOutputMetaData *resultMeta, unsigned activityId)
  284. {
  285. return new CThorBoundLoopGraph(graph, resultMeta, activityId);
  286. }
  287. ///////////////////////////////////
  288. bool isDiskInput(ThorActivityKind kind)
  289. {
  290. switch (kind)
  291. {
  292. case TAKcsvread:
  293. case TAKxmlread:
  294. case TAKjsonread:
  295. case TAKdiskread:
  296. case TAKdisknormalize:
  297. case TAKdiskaggregate:
  298. case TAKdiskcount:
  299. case TAKdiskgroupaggregate:
  300. case TAKindexread:
  301. case TAKindexcount:
  302. case TAKindexnormalize:
  303. case TAKindexaggregate:
  304. case TAKindexgroupaggregate:
  305. case TAKindexgroupexists:
  306. case TAKindexgroupcount:
  307. case TAKspillread:
  308. return true;
  309. default:
  310. return false;
  311. }
  312. }
  313. void CIOConnection::connect(unsigned which, CActivityBase *destActivity)
  314. {
  315. destActivity->setInput(which, activity->queryActivity(), index);
  316. }
  317. ///////////////////////////////////
  318. CGraphElementBase *createGraphElement(IPropertyTree &node, CGraphBase &owner, CGraphBase *resultsGraph)
  319. {
  320. CGraphElementBase *container = NULL;
  321. ForEachItemIn(m, createFuncs)
  322. {
  323. CreateFunc func = (CreateFunc)createFuncs.item(m);
  324. container = func(node, owner, resultsGraph);
  325. if (container) break;
  326. }
  327. if (NULL == container)
  328. {
  329. ThorActivityKind tak = (ThorActivityKind)node.getPropInt("att[@name=\"_kind\"]/@value", TAKnone);
  330. throw MakeStringException(TE_UnsupportedActivityKind, "Unsupported activity kind: %s", activityKindStr(tak));
  331. }
  332. container->setResultsGraph(resultsGraph);
  333. return container;
  334. }
  335. CGraphElementBase::CGraphElementBase(CGraphBase &_owner, IPropertyTree &_xgmml) : owner(&_owner)
  336. {
  337. xgmml.setown(createPTreeFromIPT(&_xgmml));
  338. eclText.set(xgmml->queryProp("att[@name=\"ecl\"]/@value"));
  339. id = xgmml->getPropInt("@id", 0);
  340. kind = (ThorActivityKind)xgmml->getPropInt("att[@name=\"_kind\"]/@value", TAKnone);
  341. sink = isActivitySink(kind);
  342. bool coLocal = xgmml->getPropBool("att[@name=\"coLocal\"]/@value", false);
  343. isLocalData = xgmml->getPropBool("att[@name=\"local\"]/@value", false); // local execute + local data access only
  344. isLocal = isLocalData || coLocal; // local execute
  345. isGrouped = xgmml->getPropBool("att[@name=\"grouped\"]/@value", false);
  346. resultsGraph = NULL;
  347. ownerId = xgmml->getPropInt("att[@name=\"_parentActivity\"]/@value", 0);
  348. onCreateCalled = prepared = haveCreateCtx = nullAct = false;
  349. onlyUpdateIfChanged = xgmml->getPropBool("att[@name=\"_updateIfChanged\"]/@value", false);
  350. StringBuffer helperName("fAc");
  351. xgmml->getProp("@id", helperName);
  352. helperFactory = (EclHelperFactory) queryJob().queryDllEntry().getEntry(helperName.str());
  353. if (!helperFactory)
  354. throw makeOsExceptionV(GetLastError(), "Failed to load helper factory method: %s (dll handle = %p)", helperName.str(), queryJob().queryDllEntry().getInstance());
  355. alreadyUpdated = false;
  356. whichBranch = (unsigned)-1;
  357. log = true;
  358. sentActInitData.setown(createThreadSafeBitSet());
  359. maxCores = queryXGMML().getPropInt("hint[@name=\"max_cores\"]/@value", 0);
  360. if (0 == maxCores)
  361. maxCores = queryJob().queryMaxDefaultActivityCores();
  362. baseHelper.setown(helperFactory());
  363. }
  364. CGraphElementBase::~CGraphElementBase()
  365. {
  366. activity.clear();
  367. baseHelper.clear(); // clear before dll is unloaded
  368. }
  369. CJobBase &CGraphElementBase::queryJob() const
  370. {
  371. return owner->queryJob();
  372. }
  373. CJobChannel &CGraphElementBase::queryJobChannel() const
  374. {
  375. return owner->queryJobChannel();
  376. }
  377. IGraphTempHandler *CGraphElementBase::queryTempHandler() const
  378. {
  379. if (resultsGraph)
  380. return resultsGraph->queryTempHandler();
  381. else
  382. return queryJob().queryTempHandler();
  383. }
  384. void CGraphElementBase::releaseIOs()
  385. {
  386. loopGraph.clear();
  387. if (activity)
  388. activity->releaseIOs();
  389. connectedInputs.kill();
  390. inputs.kill();
  391. outputs.kill();
  392. activity.clear();
  393. }
  394. void CGraphElementBase::addDependsOn(CGraphBase *graph, int controlId)
  395. {
  396. ForEachItemIn(i, dependsOn)
  397. {
  398. if (dependsOn.item(i).graph == graph)
  399. return;
  400. }
  401. dependsOn.append(*new CGraphDependency(graph, controlId));
  402. }
  403. StringBuffer &CGraphElementBase::getOpt(const char *prop, StringBuffer &out) const
  404. {
  405. VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
  406. if (!queryXGMML().getProp(path.toLowerCase().str(), out))
  407. queryJob().getOpt(prop, out);
  408. return out;
  409. }
  410. bool CGraphElementBase::getOptBool(const char *prop, bool defVal) const
  411. {
  412. bool def = queryJob().getOptBool(prop, defVal);
  413. VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
  414. return queryXGMML().getPropBool(path.toLowerCase().str(), def);
  415. }
  416. int CGraphElementBase::getOptInt(const char *prop, int defVal) const
  417. {
  418. int def = queryJob().getOptInt(prop, defVal);
  419. VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
  420. return queryXGMML().getPropInt(path.toLowerCase().str(), def);
  421. }
  422. __int64 CGraphElementBase::getOptInt64(const char *prop, __int64 defVal) const
  423. {
  424. __int64 def = queryJob().getOptInt64(prop, defVal);
  425. VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
  426. return queryXGMML().getPropInt64(path.toLowerCase().str(), def);
  427. }
  428. IThorGraphDependencyIterator *CGraphElementBase::getDependsIterator() const
  429. {
  430. return new ArrayIIteratorOf<const CGraphDependencyArray, CGraphDependency, IThorGraphDependencyIterator>(dependsOn);
  431. }
  432. void CGraphElementBase::reset()
  433. {
  434. alreadyUpdated = false;
  435. if (activity)
  436. activity->reset();
  437. }
  438. void CGraphElementBase::ActPrintLog(const char *format, ...)
  439. {
  440. va_list args;
  441. va_start(args, format);
  442. ::ActPrintLogArgs(this, thorlog_null, MCdebugProgress, format, args);
  443. va_end(args);
  444. }
  445. void CGraphElementBase::ActPrintLog(IException *e, const char *format, ...)
  446. {
  447. va_list args;
  448. va_start(args, format);
  449. ::ActPrintLogArgs(this, e, thorlog_all, MCexception(e), format, args);
  450. va_end(args);
  451. }
  452. void CGraphElementBase::ActPrintLog(IException *e)
  453. {
  454. ActPrintLog(e, "%s", "");
  455. }
  456. void CGraphElementBase::abort(IException *e)
  457. {
  458. CActivityBase *activity = queryActivity();
  459. if (activity)
  460. activity->abort();
  461. }
  462. void CGraphElementBase::doconnect()
  463. {
  464. ForEachItemIn(i, connectedInputs)
  465. {
  466. CIOConnection *io = connectedInputs.item(i);
  467. if (io)
  468. io->connect(i, queryActivity());
  469. }
  470. }
  471. void CGraphElementBase::clearConnections()
  472. {
  473. connectedInputs.kill();
  474. connectedOutputs.kill();
  475. if (activity)
  476. activity->clearConnections();
  477. }
  478. void CGraphElementBase::addInput(unsigned input, CGraphElementBase *inputAct, unsigned inputOutIdx)
  479. {
  480. while (inputs.ordinality()<=input) inputs.append(NULL);
  481. inputs.replace(new COwningSimpleIOConnection(LINK(inputAct), inputOutIdx), input);
  482. while (inputAct->outputs.ordinality()<=inputOutIdx) inputAct->outputs.append(NULL);
  483. inputAct->outputs.replace(new CIOConnection(this, input), inputOutIdx);
  484. }
  485. void CGraphElementBase::connectInput(unsigned input, CGraphElementBase *inputAct, unsigned inputOutIdx)
  486. {
  487. ActPrintLog("CONNECTING (id=%" ACTPF "d, idx=%d) to (id=%" ACTPF "d, idx=%d)", inputAct->queryId(), inputOutIdx, queryId(), input);
  488. while (connectedInputs.ordinality()<=input) connectedInputs.append(NULL);
  489. connectedInputs.replace(new COwningSimpleIOConnection(LINK(inputAct), inputOutIdx), input);
  490. while (inputAct->connectedOutputs.ordinality()<=inputOutIdx) inputAct->connectedOutputs.append(NULL);
  491. inputAct->connectedOutputs.replace(new CIOConnection(this, input), inputOutIdx);
  492. }
  493. void CGraphElementBase::serializeCreateContext(MemoryBuffer &mb)
  494. {
  495. if (!onCreateCalled) return;
  496. DelayedSizeMarker sizeMark(mb);
  497. queryHelper()->serializeCreateContext(mb);
  498. sizeMark.write();
  499. if (isSink())
  500. mb.append(alreadyUpdated);
  501. }
  502. void CGraphElementBase::deserializeCreateContext(MemoryBuffer &mb)
  503. {
  504. size32_t createCtxLen;
  505. mb.read(createCtxLen);
  506. createCtxMb.clear().append(createCtxLen, mb.readDirect(createCtxLen));
  507. haveCreateCtx = true;
  508. if (isSink())
  509. mb.read(alreadyUpdated);
  510. }
  511. void CGraphElementBase::serializeStartContext(MemoryBuffer &mb)
  512. {
  513. DelayedSizeMarker sizeMark(mb);
  514. queryHelper()->serializeStartContext(mb);
  515. sizeMark.write();
  516. }
  517. void CGraphElementBase::onCreate()
  518. {
  519. CriticalBlock b(crit);
  520. if (onCreateCalled)
  521. return;
  522. onCreateCalled = true;
  523. if (!nullAct)
  524. {
  525. CGraphElementBase *ownerActivity = owner->queryOwner() ? owner->queryOwner()->queryElement(ownerId) : NULL;
  526. if (ownerActivity)
  527. {
  528. ownerActivity->onCreate(); // ensure owner created, might not be if this is child query inside another child query.
  529. baseHelper->onCreate(queryCodeContext(), ownerActivity->queryHelper(), haveCreateCtx?&createCtxMb:NULL);
  530. }
  531. else
  532. baseHelper->onCreate(queryCodeContext(), NULL, haveCreateCtx?&createCtxMb:NULL);
  533. if (isLoopActivity(*this))
  534. {
  535. unsigned loopId = queryXGMML().getPropInt("att[@name=\"_loopid\"]/@value");
  536. Owned<CGraphStub> stub = owner->getChildGraph(loopId);
  537. Owned<IThorBoundLoopGraph> boundLoopGraph = createBoundLoopGraph(&stub->queryOriginalGraph(), baseHelper->queryOutputMeta(), queryId());
  538. setBoundGraph(boundLoopGraph);
  539. }
  540. }
  541. }
  542. void CGraphElementBase::onStart(size32_t parentExtractSz, const byte *parentExtract, MemoryBuffer *startCtx)
  543. {
  544. if (nullAct)
  545. return;
  546. CriticalBlock b(crit);
  547. baseHelper->onStart(parentExtract, startCtx);
  548. }
  549. bool CGraphElementBase::executeDependencies(size32_t parentExtractSz, const byte *parentExtract, int controlId, bool async)
  550. {
  551. Owned<IThorGraphDependencyIterator> deps = getDependsIterator();
  552. ForEach(*deps)
  553. {
  554. CGraphDependency &dep = deps->query();
  555. if (dep.controlId == controlId)
  556. dep.graph->execute(parentExtractSz, parentExtract, true, async);
  557. if (owner->queryJob().queryAborted() || owner->queryAborted()) return false;
  558. }
  559. return true;
  560. }
  561. bool CGraphElementBase::prepareContext(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies, bool shortCircuit, bool async, bool connectOnly)
  562. {
  563. try
  564. {
  565. bool create = true;
  566. if (connectOnly)
  567. {
  568. if (prepared)
  569. return true;
  570. ForEachItemIn(i, inputs)
  571. {
  572. if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, false, false, async, true))
  573. return false;
  574. }
  575. }
  576. else
  577. {
  578. bool _shortCircuit = shortCircuit;
  579. Owned<IThorGraphDependencyIterator> deps = getDependsIterator();
  580. bool depsDone = true;
  581. ForEach(*deps)
  582. {
  583. CGraphDependency &dep = deps->query();
  584. if (0 == dep.controlId && NotFound == owner->dependentSubGraphs.find(*dep.graph))
  585. {
  586. owner->dependentSubGraphs.append(*dep.graph);
  587. if (!dep.graph->isComplete())
  588. depsDone = false;
  589. }
  590. }
  591. if (depsDone) _shortCircuit = false;
  592. if (!depsDone && checkDependencies)
  593. {
  594. if (!executeDependencies(parentExtractSz, parentExtract, 0, async))
  595. return false;
  596. }
  597. whichBranch = (unsigned)-1;
  598. switch (getKind())
  599. {
  600. case TAKindexwrite:
  601. case TAKdiskwrite:
  602. case TAKcsvwrite:
  603. case TAKxmlwrite:
  604. case TAKjsonwrite:
  605. case TAKspillwrite:
  606. if (_shortCircuit) return true;
  607. onCreate();
  608. alreadyUpdated = checkUpdate();
  609. if (alreadyUpdated)
  610. return false;
  611. break;
  612. case TAKchildif:
  613. case TAKif:
  614. case TAKifaction:
  615. {
  616. if (_shortCircuit) return true;
  617. onCreate();
  618. onStart(parentExtractSz, parentExtract);
  619. IHThorIfArg *helper = (IHThorIfArg *)baseHelper.get();
  620. whichBranch = helper->getCondition() ? 0 : 1; // True argument precedes false...
  621. /* NB - The executeDependencies code below is only needed if actionLinkInNewGraph=true, which is no longer the default
  622. * It should be removed, once we are positive there are no issues with in-line conditional actions
  623. */
  624. if (TAKifaction == getKind())
  625. {
  626. if (!executeDependencies(parentExtractSz, parentExtract, whichBranch+1, async)) //NB whenId 1 based
  627. return false;
  628. create = false;
  629. }
  630. break;
  631. }
  632. case TAKchildcase:
  633. case TAKcase:
  634. {
  635. if (_shortCircuit) return true;
  636. onCreate();
  637. onStart(parentExtractSz, parentExtract);
  638. IHThorCaseArg *helper = (IHThorCaseArg *)baseHelper.get();
  639. whichBranch = helper->getBranch();
  640. if (whichBranch >= inputs.ordinality())
  641. whichBranch = inputs.ordinality()-1;
  642. break;
  643. }
  644. case TAKfilter:
  645. case TAKfiltergroup:
  646. case TAKfilterproject:
  647. {
  648. if (_shortCircuit) return true;
  649. onCreate();
  650. onStart(parentExtractSz, parentExtract);
  651. switch (getKind())
  652. {
  653. case TAKfilter:
  654. whichBranch = ((IHThorFilterArg *)baseHelper.get())->canMatchAny() ? 0 : 1;
  655. break;
  656. case TAKfiltergroup:
  657. whichBranch = ((IHThorFilterGroupArg *)baseHelper.get())->canMatchAny() ? 0 : 1;
  658. break;
  659. case TAKfilterproject:
  660. whichBranch = ((IHThorFilterProjectArg *)baseHelper.get())->canMatchAny() ? 0 : 1;
  661. break;
  662. }
  663. break;
  664. }
  665. case TAKsequential:
  666. case TAKparallel:
  667. {
  668. /* NB - The executeDependencies code below is only needed if actionLinkInNewGraph=true, which is no longer the default
  669. * It should be removed, once we are positive there are no issues with in-line sequential/parallel activities
  670. */
  671. for (unsigned s=1; s<=dependsOn.ordinality(); s++)
  672. executeDependencies(parentExtractSz, parentExtract, s, async);
  673. create = false;
  674. break;
  675. }
  676. case TAKwhen_dataset:
  677. case TAKwhen_action:
  678. {
  679. if (!executeDependencies(parentExtractSz, parentExtract, WhenBeforeId, async))
  680. return false;
  681. if (!executeDependencies(parentExtractSz, parentExtract, WhenParallelId, async))
  682. return false;
  683. break;
  684. }
  685. }
  686. if (checkDependencies && ((unsigned)-1 != whichBranch))
  687. {
  688. if (inputs.queryItem(whichBranch))
  689. {
  690. if (!queryInput(whichBranch)->prepareContext(parentExtractSz, parentExtract, true, false, async, connectOnly))
  691. return false;
  692. }
  693. ForEachItemIn(i, inputs)
  694. {
  695. if (i != whichBranch)
  696. {
  697. if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, false, false, async, true))
  698. return false;
  699. }
  700. }
  701. }
  702. else
  703. {
  704. ForEachItemIn(i, inputs)
  705. {
  706. if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, checkDependencies, false, async, connectOnly))
  707. return false;
  708. }
  709. }
  710. }
  711. if (create)
  712. {
  713. if (prepared) // no need to recreate
  714. return true;
  715. prepared = true;
  716. ForEachItemIn(i2, inputs)
  717. {
  718. CIOConnection *inputIO = inputs.item(i2);
  719. connectInput(i2, inputIO->activity, inputIO->index);
  720. }
  721. createActivity();
  722. }
  723. return true;
  724. }
  725. catch (IException *_e)
  726. {
  727. IThorException *e = QUERYINTERFACE(_e, IThorException);
  728. if (e)
  729. {
  730. if (!e->queryActivityId())
  731. setExceptionActivityInfo(*this, e);
  732. }
  733. else
  734. {
  735. e = MakeActivityException(this, _e);
  736. _e->Release();
  737. }
  738. throw e;
  739. }
  740. }
  741. void CGraphElementBase::preStart(size32_t parentExtractSz, const byte *parentExtract)
  742. {
  743. activity->preStart(parentExtractSz, parentExtract);
  744. }
  745. void CGraphElementBase::createActivity()
  746. {
  747. CriticalBlock b(crit);
  748. if (activity)
  749. return;
  750. activity.setown(factory());
  751. if (isSink())
  752. owner->addActiveSink(*this);
  753. }
  754. ICodeContext *CGraphElementBase::queryCodeContext()
  755. {
  756. return queryOwner().queryCodeContext();
  757. }
  758. /////
  759. // JCSMORE loop - probably need better way to check if any act in graph is global(meaning needs some synchronization between slaves in activity execution)
  760. bool isGlobalActivity(CGraphElementBase &container)
  761. {
  762. switch (container.getKind())
  763. {
  764. // always global, but only co-ordinate init/done
  765. case TAKcsvwrite:
  766. case TAKxmlwrite:
  767. case TAKjsonwrite:
  768. case TAKindexwrite:
  769. case TAKkeydiff:
  770. case TAKkeypatch:
  771. case TAKdictionaryworkunitwrite:
  772. return true;
  773. case TAKdiskwrite:
  774. {
  775. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *)container.helperFactory();
  776. unsigned flags = helper->getFlags();
  777. return (0 == (TDXtemporary & flags)); // global if not temporary
  778. }
  779. case TAKspillwrite:
  780. case TAKspill:
  781. return false;
  782. case TAKcsvread:
  783. {
  784. Owned<IHThorCsvReadArg> helper = (IHThorCsvReadArg *)container.helperFactory();
  785. // if header lines, then [may] need to co-ordinate across slaves
  786. if (container.queryOwner().queryOwner() && (!container.queryOwner().isGlobal())) // I am in a child query
  787. return false;
  788. return helper->queryCsvParameters()->queryHeaderLen() > 0;
  789. }
  790. // dependent on child acts?
  791. case TAKlooprow:
  792. case TAKloopcount:
  793. case TAKgraphloop:
  794. case TAKparallelgraphloop:
  795. case TAKloopdataset:
  796. return false;
  797. // dependent on local/grouped
  798. case TAKkeyeddistribute:
  799. case TAKhashdistribute:
  800. case TAKhashdistributemerge:
  801. case TAKworkunitwrite:
  802. case TAKdistribution:
  803. case TAKpartition:
  804. case TAKdiskaggregate:
  805. case TAKdiskcount:
  806. case TAKdiskgroupaggregate:
  807. case TAKindexaggregate:
  808. case TAKindexcount:
  809. case TAKindexgroupaggregate:
  810. case TAKindexgroupexists:
  811. case TAKindexgroupcount:
  812. case TAKremoteresult:
  813. case TAKcountproject:
  814. case TAKcreaterowlimit:
  815. case TAKskiplimit:
  816. case TAKlimit:
  817. case TAKsort:
  818. case TAKdedup:
  819. case TAKjoin:
  820. case TAKselfjoin:
  821. case TAKhashjoin:
  822. case TAKsmartjoin:
  823. case TAKkeyeddenormalize:
  824. case TAKhashdenormalize:
  825. case TAKdenormalize:
  826. case TAKlookupdenormalize: //GH->JCS why are these here, and join not?
  827. case TAKalldenormalize:
  828. case TAKsmartdenormalize:
  829. case TAKdenormalizegroup:
  830. case TAKhashdenormalizegroup:
  831. case TAKlookupdenormalizegroup:
  832. case TAKkeyeddenormalizegroup:
  833. case TAKalldenormalizegroup:
  834. case TAKsmartdenormalizegroup:
  835. case TAKaggregate:
  836. case TAKexistsaggregate:
  837. case TAKcountaggregate:
  838. case TAKhashaggregate:
  839. case TAKhashdedup:
  840. case TAKrollup:
  841. case TAKiterate:
  842. case TAKselectn:
  843. case TAKfirstn:
  844. case TAKenth:
  845. case TAKsample:
  846. case TAKgroup:
  847. case TAKchoosesets:
  848. case TAKchoosesetsenth:
  849. case TAKchoosesetslast:
  850. case TAKtopn:
  851. case TAKprocess:
  852. case TAKchildcount:
  853. case TAKwhen_dataset:
  854. case TAKwhen_action:
  855. case TAKnonempty:
  856. if (!container.queryLocalOrGrouped())
  857. return true;
  858. break;
  859. case TAKkeyedjoin:
  860. case TAKalljoin:
  861. case TAKlookupjoin:
  862. if (!container.queryLocal())
  863. return true;
  864. // always local
  865. case TAKfilter:
  866. case TAKfilterproject:
  867. case TAKfiltergroup:
  868. case TAKsplit:
  869. case TAKpipewrite:
  870. case TAKdegroup:
  871. case TAKproject:
  872. case TAKprefetchproject:
  873. case TAKprefetchcountproject:
  874. case TAKnormalize:
  875. case TAKnormalizechild:
  876. case TAKnormalizelinkedchild:
  877. case TAKpipethrough:
  878. case TAKif:
  879. case TAKchildif:
  880. case TAKchildcase:
  881. case TAKcase:
  882. case TAKparse:
  883. case TAKpiperead:
  884. case TAKxmlparse:
  885. case TAKjoinlight:
  886. case TAKselfjoinlight:
  887. case TAKdiskread:
  888. case TAKdisknormalize:
  889. case TAKchildaggregate:
  890. case TAKchildgroupaggregate:
  891. case TAKchildthroughnormalize:
  892. case TAKchildnormalize:
  893. case TAKspillread:
  894. case TAKindexread:
  895. case TAKindexnormalize:
  896. case TAKxmlread:
  897. case TAKjsonread:
  898. case TAKdiskexists:
  899. case TAKindexexists:
  900. case TAKchildexists:
  901. case TAKthroughaggregate:
  902. case TAKmerge:
  903. case TAKfunnel:
  904. case TAKregroup:
  905. case TAKcombine:
  906. case TAKrollupgroup:
  907. case TAKcombinegroup:
  908. case TAKsoap_rowdataset:
  909. case TAKhttp_rowdataset:
  910. case TAKsoap_rowaction:
  911. case TAKsoap_datasetdataset:
  912. case TAKsoap_datasetaction:
  913. case TAKlinkedrawiterator:
  914. case TAKchilditerator:
  915. case TAKstreamediterator:
  916. case TAKworkunitread:
  917. case TAKchilddataset:
  918. case TAKinlinetable:
  919. case TAKnull:
  920. case TAKemptyaction:
  921. case TAKlocalresultread:
  922. case TAKlocalresultwrite:
  923. case TAKdictionaryresultwrite:
  924. case TAKgraphloopresultread:
  925. case TAKgraphloopresultwrite:
  926. case TAKnwaygraphloopresultread:
  927. case TAKapply:
  928. case TAKsideeffect:
  929. case TAKsimpleaction:
  930. case TAKsorted:
  931. case TAKdistributed:
  932. case TAKtrace:
  933. break;
  934. case TAKnwayjoin:
  935. case TAKnwaymerge:
  936. case TAKnwaymergejoin:
  937. case TAKnwayinput:
  938. case TAKnwayselect:
  939. return false; // JCSMORE - I think and/or have to be for now
  940. // undefined
  941. case TAKdatasetresult:
  942. case TAKrowresult:
  943. case TAKremotegraph:
  944. case TAKlibrarycall:
  945. default:
  946. return true; // if in doubt
  947. }
  948. return false;
  949. }
  950. bool isLoopActivity(CGraphElementBase &container)
  951. {
  952. switch (container.getKind())
  953. {
  954. case TAKlooprow:
  955. case TAKloopcount:
  956. case TAKloopdataset:
  957. case TAKgraphloop:
  958. case TAKparallelgraphloop:
  959. return true;
  960. }
  961. return false;
  962. }
  963. static void getGlobalDeps(CGraphBase &graph, CICopyArrayOf<CGraphDependency> &deps)
  964. {
  965. Owned<IThorActivityIterator> iter = graph.getIterator();
  966. ForEach(*iter)
  967. {
  968. CGraphElementBase &elem = iter->query();
  969. Owned<IThorGraphDependencyIterator> dependIterator = elem.getDependsIterator();
  970. ForEach(*dependIterator)
  971. {
  972. CGraphDependency &dependency = dependIterator->query();
  973. if (dependency.graph->isGlobal() && NULL==dependency.graph->queryOwner())
  974. deps.append(dependency);
  975. getGlobalDeps(*dependency.graph, deps);
  976. }
  977. }
  978. }
  979. static void noteDependency(CGraphElementBase *targetActivity, CGraphElementBase *sourceActivity, CGraphBase *targetGraph, CGraphBase *sourceGraph, unsigned controlId)
  980. {
  981. targetActivity->addDependsOn(sourceGraph, controlId);
  982. // NB: record dependency in source graph, serialized to slaves, used to decided if should run dependency sinks or not
  983. Owned<IPropertyTree> dependencyFor = createPTree();
  984. dependencyFor->setPropInt("@id", sourceActivity->queryId());
  985. dependencyFor->setPropInt("@graphId", targetGraph->queryGraphId());
  986. if (controlId)
  987. dependencyFor->setPropInt("@conditionalId", controlId);
  988. sourceGraph->queryXGMML().addPropTree("Dependency", dependencyFor.getClear());
  989. }
  990. static void addDependencies(IPropertyTree *xgmml, bool failIfMissing, CGraphTableCopy &graphs)
  991. {
  992. CGraphArrayCopy dependentchildGraphs;
  993. CGraphElementArrayCopy targetActivities, sourceActivities;
  994. Owned<IPropertyTreeIterator> iter = xgmml->getElements("edge");
  995. ForEach(*iter)
  996. {
  997. IPropertyTree &edge = iter->query();
  998. graph_id sourceGid = edge.getPropInt("@source");
  999. graph_id targetGid = edge.getPropInt("@target");
  1000. Owned<CGraphBase> source = LINK(graphs.find(sourceGid));
  1001. Owned<CGraphBase> target = LINK(graphs.find(targetGid));
  1002. if (!source || !target)
  1003. {
  1004. if (failIfMissing)
  1005. throwUnexpected();
  1006. else
  1007. continue; // expected if assigning dependencies in slaves
  1008. }
  1009. CGraphElementBase *targetActivity = (CGraphElementBase *)target->queryElement(edge.getPropInt("att[@name=\"_targetActivity\"]/@value"));
  1010. CGraphElementBase *sourceActivity = (CGraphElementBase *)source->queryElement(edge.getPropInt("att[@name=\"_sourceActivity\"]/@value"));
  1011. if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value"))
  1012. {
  1013. if (TAKlocalresultwrite == sourceActivity->getKind() && (TAKlocalresultread != targetActivity->getKind()))
  1014. {
  1015. if (source->isLoopSubGraph())
  1016. source->setGlobal(true);
  1017. }
  1018. }
  1019. int controlId = 0;
  1020. if (edge.getPropBool("att[@name=\"_dependsOn\"]/@value", false))
  1021. {
  1022. if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) // JCSMORE - not sure if necess. roxie seem to do.
  1023. controlId = edge.getPropInt("att[@name=\"_when\"]/@value", 0);
  1024. CGraphBase &sourceGraph = sourceActivity->queryOwner();
  1025. unsigned sourceGraphContext = sourceGraph.queryParentActivityId();
  1026. CGraphBase *targetGraph = NULL;
  1027. unsigned targetGraphContext = -1;
  1028. for (;;)
  1029. {
  1030. targetGraph = &targetActivity->queryOwner();
  1031. targetGraphContext = targetGraph->queryParentActivityId();
  1032. if (sourceGraphContext == targetGraphContext)
  1033. break;
  1034. targetActivity = targetGraph->queryElement(targetGraphContext);
  1035. }
  1036. assertex(targetActivity && sourceActivity);
  1037. noteDependency(targetActivity, sourceActivity, target, source, controlId);
  1038. }
  1039. else if (edge.getPropBool("att[@name=\"_conditionSource\"]/@value", false))
  1040. { /* Ignore it */ }
  1041. else if (edge.getPropBool("att[@name=\"_childGraph\"]/@value", false))
  1042. {
  1043. // NB: any dependencies of the child acts. are dependencies of this act.
  1044. dependentchildGraphs.append(*source);
  1045. targetActivities.append(*targetActivity);
  1046. sourceActivities.append(*sourceActivity);
  1047. }
  1048. else
  1049. {
  1050. if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) // JCSMORE - not sure if necess. roxie seem to do.
  1051. controlId = edge.getPropInt("att[@name=\"_when\"]/@value", 0);
  1052. noteDependency(targetActivity, sourceActivity, target, source, controlId);
  1053. }
  1054. }
  1055. ForEachItemIn(c, dependentchildGraphs)
  1056. {
  1057. CGraphBase &childGraph = dependentchildGraphs.item(c);
  1058. CGraphElementBase &targetActivity = targetActivities.item(c);
  1059. CGraphElementBase &sourceActivity = sourceActivities.item(c);
  1060. if (!childGraph.isGlobal())
  1061. {
  1062. CICopyArrayOf<CGraphDependency> globalChildGraphDeps;
  1063. getGlobalDeps(childGraph, globalChildGraphDeps);
  1064. ForEachItemIn(gcd, globalChildGraphDeps)
  1065. {
  1066. CGraphDependency &globalDep = globalChildGraphDeps.item(gcd);
  1067. noteDependency(&targetActivity, &sourceActivity, globalDep.graph, &childGraph, globalDep.controlId);
  1068. }
  1069. }
  1070. }
  1071. SuperHashIteratorOf<CGraphBase> allIter(graphs);
  1072. ForEach(allIter)
  1073. {
  1074. CGraphBase &subGraph = allIter.query();
  1075. if (subGraph.queryOwner() && subGraph.queryParentActivityId())
  1076. {
  1077. CGraphElementBase *parentElement = subGraph.queryOwner()->queryElement(subGraph.queryParentActivityId());
  1078. if (isLoopActivity(*parentElement))
  1079. {
  1080. if (!parentElement->queryOwner().isLocalChild() && !subGraph.isLocalOnly())
  1081. subGraph.setGlobal(true);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. /////
  1087. CGraphBase::CGraphBase(CJobChannel &_jobChannel) : jobChannel(_jobChannel), job(_jobChannel.queryJob()), progressUpdated(false)
  1088. {
  1089. xgmml = NULL;
  1090. parent = owner = graphResultsContainer = NULL;
  1091. complete = false;
  1092. parentActivityId = 0;
  1093. connected = started = graphDone = aborted = false;
  1094. startBarrier = waitBarrier = doneBarrier = NULL;
  1095. mpTag = waitBarrierTag = startBarrierTag = doneBarrierTag = TAG_NULL;
  1096. executeReplyTag = TAG_NULL;
  1097. parentExtractSz = 0;
  1098. counter = 0; // loop/graph counter, will be set by loop/graph activity if needed
  1099. loopBodySubgraph = false;
  1100. }
  1101. CGraphBase::~CGraphBase()
  1102. {
  1103. clean();
  1104. }
  1105. CGraphBase *CGraphBase::cloneGraph()
  1106. {
  1107. Owned<CGraphBase> subGraph = queryJobChannel().createGraph();
  1108. CGraphTableCopy newGraphs;
  1109. subGraph->createFromXGMML(node, owner, parent, graphResultsContainer, newGraphs);
  1110. addDependencies(queryJob().queryXGMML(), false, newGraphs);
  1111. return subGraph.getClear();
  1112. }
  1113. void CGraphBase::init()
  1114. {
  1115. bool log = queryJob().queryForceLogging(queryGraphId(), (NULL == queryOwner()) || isGlobal());
  1116. setLogging(log);
  1117. }
  1118. void CGraphBase::clean()
  1119. {
  1120. ::Release(startBarrier);
  1121. ::Release(waitBarrier);
  1122. ::Release(doneBarrier);
  1123. localResults.clear();
  1124. graphLoopResults.clear();
  1125. childGraphsTable.releaseAll();
  1126. disconnectActivities();
  1127. containers.releaseAll();
  1128. sinks.kill();
  1129. activeSinks.kill();
  1130. }
  1131. void CGraphBase::serializeCreateContexts(MemoryBuffer &mb)
  1132. {
  1133. DelayedSizeMarker sizeMark(mb);
  1134. Owned<IThorActivityIterator> iter = getIterator();
  1135. ForEach (*iter)
  1136. {
  1137. CGraphElementBase &element = iter->query();
  1138. if (element.isOnCreated())
  1139. {
  1140. mb.append(element.queryId());
  1141. element.serializeCreateContext(mb);
  1142. }
  1143. }
  1144. mb.append((activity_id)0);
  1145. sizeMark.write();
  1146. }
  1147. void CGraphBase::deserializeCreateContexts(MemoryBuffer &mb)
  1148. {
  1149. activity_id id;
  1150. for (;;)
  1151. {
  1152. mb.read(id);
  1153. if (0 == id) break;
  1154. CGraphElementBase *element = queryElement(id);
  1155. assertex(element);
  1156. element->deserializeCreateContext(mb);
  1157. }
  1158. }
  1159. void CGraphBase::reset()
  1160. {
  1161. setCompleteEx(false);
  1162. clearProgressUpdated();
  1163. graphCancelHandler.reset();
  1164. if (0 == containers.count())
  1165. {
  1166. Owned<IThorGraphIterator> iter = getChildGraphIterator();
  1167. ForEach(*iter)
  1168. iter->query().reset();
  1169. }
  1170. else
  1171. {
  1172. Owned<IThorActivityIterator> iter = getIterator();
  1173. ForEach(*iter)
  1174. {
  1175. CGraphElementBase &element = iter->query();
  1176. element.reset();
  1177. }
  1178. dependentSubGraphs.kill();
  1179. }
  1180. if (!queryOwner())
  1181. clearNodeStats();
  1182. }
  1183. void CGraphBase::addChildGraph(CGraphStub *stub)
  1184. {
  1185. CriticalBlock b(crit);
  1186. childGraphsTable.replace(*LINK(stub));
  1187. if (sequential)
  1188. orderedChildGraphs.append(*stub);
  1189. }
  1190. IThorGraphStubIterator *CGraphBase::getChildStubIterator() const
  1191. {
  1192. CriticalBlock b(crit);
  1193. class CIter : private SuperHashIteratorOf<CGraphStub>, public CSimpleInterfaceOf<IThorGraphStubIterator>
  1194. {
  1195. typedef SuperHashIteratorOf<CGraphStub> PARENT;
  1196. public:
  1197. CIter(const CChildGraphTable &table) : PARENT(table) { }
  1198. // IIterator
  1199. virtual bool first() { return PARENT::first(); }
  1200. virtual bool next() { return PARENT::next(); }
  1201. virtual bool isValid() { return PARENT::isValid(); }
  1202. virtual CGraphStub &query() { return PARENT::query(); }
  1203. };
  1204. return new CIter(childGraphsTable);
  1205. }
  1206. IThorGraphIterator *CGraphBase::getChildGraphIterator() const
  1207. {
  1208. CriticalBlock b(crit);
  1209. class CIter : public CSimpleInterfaceOf<IThorGraphIterator>
  1210. {
  1211. Owned<IThorGraphStubIterator> iter;
  1212. public:
  1213. CIter(IThorGraphStubIterator *_iter) : iter(_iter)
  1214. {
  1215. }
  1216. // IIterator
  1217. virtual bool first() { return iter->first(); }
  1218. virtual bool next() { return iter->next(); }
  1219. virtual bool isValid() { return iter->isValid(); }
  1220. virtual CGraphBase &query()
  1221. {
  1222. CGraphStub &stub = iter->query();
  1223. return stub.queryOriginalGraph();
  1224. }
  1225. };
  1226. return new CIter(getChildStubIterator());
  1227. }
  1228. bool CGraphBase::fireException(IException *e)
  1229. {
  1230. return queryJobChannel().fireException(e);
  1231. }
  1232. bool CGraphBase::preStart(size32_t parentExtractSz, const byte *parentExtract)
  1233. {
  1234. Owned<IThorActivityIterator> iter = getConnectedIterator();
  1235. ForEach(*iter)
  1236. {
  1237. CGraphElementBase &element = iter->query();
  1238. element.preStart(parentExtractSz, parentExtract);
  1239. }
  1240. return true;
  1241. }
  1242. void CGraphBase::executeSubGraph(size32_t parentExtractSz, const byte *parentExtract)
  1243. {
  1244. CriticalBlock b(executeCrit);
  1245. if (job.queryPausing())
  1246. return;
  1247. Owned<IException> exception;
  1248. try
  1249. {
  1250. if (!queryOwner())
  1251. {
  1252. StringBuffer s;
  1253. toXML(&queryXGMML(), s, 2);
  1254. GraphPrintLog("Running graph [%s] : %s", isGlobal()?"global":"local", s.str());
  1255. }
  1256. if (localResults)
  1257. localResults->clear();
  1258. doExecute(parentExtractSz, parentExtract, false);
  1259. }
  1260. catch (IException *e)
  1261. {
  1262. GraphPrintLog(e);
  1263. exception.setown(e);
  1264. }
  1265. if (!queryOwner())
  1266. {
  1267. GraphPrintLog("Graph Done");
  1268. StringBuffer memStr;
  1269. getSystemTraceInfo(memStr, PerfMonStandard | PerfMonExtended);
  1270. GraphPrintLog("%s", memStr.str());
  1271. }
  1272. if (exception)
  1273. throw exception.getClear();
  1274. }
  1275. void CGraphBase::onCreate()
  1276. {
  1277. Owned<IThorActivityIterator> iter = getConnectedIterator();
  1278. ForEach(*iter)
  1279. {
  1280. CGraphElementBase &element = iter->query();
  1281. element.onCreate();
  1282. }
  1283. }
  1284. void CGraphBase::execute(size32_t _parentExtractSz, const byte *parentExtract, bool checkDependencies, bool async)
  1285. {
  1286. if (isComplete())
  1287. return;
  1288. if (async)
  1289. queryJobChannel().startGraph(*this, checkDependencies, _parentExtractSz, parentExtract); // may block if enough running
  1290. else
  1291. {
  1292. if (!prepare(_parentExtractSz, parentExtract, checkDependencies, false, false))
  1293. {
  1294. setComplete();
  1295. return;
  1296. }
  1297. executeSubGraph(_parentExtractSz, parentExtract);
  1298. }
  1299. }
  1300. void CGraphBase::doExecute(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies)
  1301. {
  1302. if (isComplete()) return;
  1303. if (queryAborted())
  1304. {
  1305. if (abortException)
  1306. throw abortException.getLink();
  1307. throw MakeGraphException(this, 0, "subgraph aborted");
  1308. }
  1309. GraphPrintLog("Processing graph");
  1310. Owned<IException> exception;
  1311. try
  1312. {
  1313. if (started)
  1314. reset();
  1315. else
  1316. started = true;
  1317. Owned<IThorActivityIterator> iter = getConnectedIterator();
  1318. ForEach(*iter)
  1319. {
  1320. CGraphElementBase &element = iter->query();
  1321. element.onStart(parentExtractSz, parentExtract);
  1322. element.initActivity();
  1323. }
  1324. initialized = true;
  1325. if (!preStart(parentExtractSz, parentExtract)) return;
  1326. start();
  1327. if (!wait(aborted?MEDIUMTIMEOUT:INFINITE)) // can't wait indefinitely, query may have aborted and stall, but prudent to wait a short time for underlying graphs to unwind.
  1328. GraphPrintLogEx(this, thorlog_null, MCuserWarning, "Graph wait cancelled, aborted=%s", aborted?"true":"false");
  1329. else
  1330. graphDone = true;
  1331. }
  1332. catch (IException *e)
  1333. {
  1334. GraphPrintLog(e);
  1335. exception.setown(e);
  1336. }
  1337. try
  1338. {
  1339. if (!exception && abortException)
  1340. exception.setown(abortException.getClear());
  1341. if (exception)
  1342. {
  1343. if (NULL == owner || isGlobal())
  1344. waitBarrier->cancel(exception);
  1345. if (!queryOwner())
  1346. {
  1347. StringBuffer str;
  1348. Owned<IThorException> e = MakeGraphException(this, exception->errorCode(), "%s", exception->errorMessage(str).str());
  1349. e->setAction(tea_abort);
  1350. fireException(e);
  1351. }
  1352. }
  1353. }
  1354. catch (IException *e)
  1355. {
  1356. GraphPrintLog(e, "during abort()");
  1357. e->Release();
  1358. }
  1359. try
  1360. {
  1361. done();
  1362. if (doneBarrier)
  1363. doneBarrier->wait(false);
  1364. }
  1365. catch (IException *e)
  1366. {
  1367. GraphPrintLog(e);
  1368. if (!exception.get())
  1369. exception.setown(e);
  1370. else
  1371. e->Release();
  1372. }
  1373. end();
  1374. if (exception)
  1375. throw exception.getClear();
  1376. if (!queryAborted())
  1377. setComplete();
  1378. }
  1379. bool CGraphBase::prepare(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies, bool shortCircuit, bool async)
  1380. {
  1381. if (isComplete()) return false;
  1382. bool needToExecute = false;
  1383. ForEachItemIn(s, sinks)
  1384. {
  1385. CGraphElementBase &sink = sinks.item(s);
  1386. if (sink.prepareContext(parentExtractSz, parentExtract, checkDependencies, shortCircuit, async, false))
  1387. needToExecute = true;
  1388. }
  1389. onCreate();
  1390. return needToExecute;
  1391. }
  1392. void CGraphBase::done()
  1393. {
  1394. if (aborted) return; // activity done methods only called on success
  1395. Owned<IThorActivityIterator> iter = getConnectedIterator();
  1396. ForEach (*iter)
  1397. {
  1398. CGraphElementBase &element = iter->query();
  1399. element.queryActivity()->done();
  1400. }
  1401. }
  1402. unsigned CGraphBase::queryJobChannelNumber() const
  1403. {
  1404. return queryJobChannel().queryChannel();
  1405. }
  1406. IMPServer &CGraphBase::queryMPServer() const
  1407. {
  1408. return jobChannel.queryMPServer();
  1409. }
  1410. bool CGraphBase::syncInitData()
  1411. {
  1412. CGraphElementBase *parentElement = queryOwner() ? queryOwner()->queryElement(queryParentActivityId()) : NULL;
  1413. if (parentElement && isLoopActivity(*parentElement) && loopBodySubgraph)
  1414. return parentElement->queryLoopGraph()->queryGraph()->isGlobal();
  1415. else
  1416. return !isLocalChild();
  1417. }
  1418. void CGraphBase::end()
  1419. {
  1420. // always called, any final action clear up
  1421. Owned<IThorActivityIterator> iter = getIterator();
  1422. ForEach(*iter)
  1423. {
  1424. CGraphElementBase &element = iter->query();
  1425. try
  1426. {
  1427. if (element.queryActivity())
  1428. element.queryActivity()->kill();
  1429. }
  1430. catch (IException *e)
  1431. {
  1432. Owned<IException> e2 = MakeActivityException(element.queryActivity(), e, "Error calling kill()");
  1433. GraphPrintLog(e2);
  1434. e->Release();
  1435. }
  1436. }
  1437. }
  1438. class CGraphTraverseIteratorBase : implements IThorActivityIterator, public CInterface
  1439. {
  1440. protected:
  1441. CGraphBase &graph;
  1442. Linked<CGraphElementBase> cur;
  1443. CIArrayOf<CGraphElementBase> others;
  1444. CGraphElementArrayCopy covered;
  1445. CGraphElementBase *popNext()
  1446. {
  1447. if (!others.ordinality())
  1448. {
  1449. cur.clear();
  1450. return NULL;
  1451. }
  1452. cur.setown(&others.popGet());
  1453. return cur;
  1454. }
  1455. void setNext(bool branchOnConditional)
  1456. {
  1457. if (branchOnConditional && ((unsigned)-1) != cur->whichBranch)
  1458. {
  1459. CIOConnection *io = cur->connectedInputs.queryItem(cur->whichBranch);
  1460. if (io)
  1461. cur.set(io->activity);
  1462. else
  1463. cur.clear();
  1464. }
  1465. else
  1466. {
  1467. CIOConnectionArray &inputs = cur->connectedInputs;
  1468. cur.clear();
  1469. unsigned n = inputs.ordinality();
  1470. bool first = true;
  1471. for (unsigned i=0; i<n; i++)
  1472. {
  1473. CIOConnection *io = inputs.queryItem(i);
  1474. if (io)
  1475. {
  1476. if (first)
  1477. {
  1478. first = false;
  1479. cur.set(io->activity);
  1480. }
  1481. else
  1482. others.append(*LINK(io->activity));
  1483. }
  1484. }
  1485. }
  1486. if (!cur)
  1487. {
  1488. if (!popNext())
  1489. return;
  1490. }
  1491. // check haven't been here before
  1492. for (;;)
  1493. {
  1494. if (cur->getOutputs() < 2)
  1495. break;
  1496. else if (NotFound == covered.find(*cur))
  1497. {
  1498. if (!cur->alreadyUpdated)
  1499. {
  1500. covered.append(*cur);
  1501. break;
  1502. }
  1503. }
  1504. if (!popNext())
  1505. return;
  1506. }
  1507. }
  1508. public:
  1509. IMPLEMENT_IINTERFACE;
  1510. CGraphTraverseIteratorBase(CGraphBase &_graph) : graph(_graph)
  1511. {
  1512. }
  1513. virtual bool first()
  1514. {
  1515. covered.kill();
  1516. others.kill();
  1517. cur.clear();
  1518. Owned<IThorActivityIterator> sinkIter = graph.getSinkIterator();
  1519. if (!sinkIter->first())
  1520. return false;
  1521. for (;;)
  1522. {
  1523. cur.set(& sinkIter->query());
  1524. if (!cur->alreadyUpdated)
  1525. break;
  1526. if (!sinkIter->next())
  1527. return false;
  1528. }
  1529. while (sinkIter->next())
  1530. others.append(sinkIter->get());
  1531. return true;
  1532. }
  1533. virtual bool isValid() { return NULL != cur.get(); }
  1534. virtual CGraphElementBase & query() { return *cur; }
  1535. CGraphElementBase & get() { return *LINK(cur); }
  1536. };
  1537. class CGraphTraverseConnectedIterator : public CGraphTraverseIteratorBase
  1538. {
  1539. bool branchOnConditional;
  1540. public:
  1541. CGraphTraverseConnectedIterator(CGraphBase &graph, bool _branchOnConditional) : CGraphTraverseIteratorBase(graph), branchOnConditional(_branchOnConditional) { }
  1542. virtual bool next()
  1543. {
  1544. setNext(branchOnConditional);
  1545. return NULL!=cur.get();
  1546. }
  1547. };
  1548. IThorActivityIterator *CGraphBase::getConnectedIterator(bool branchOnConditional)
  1549. {
  1550. return new CGraphTraverseConnectedIterator(*this, branchOnConditional);
  1551. }
  1552. bool CGraphBase::wait(unsigned timeout)
  1553. {
  1554. CTimeMon tm(timeout);
  1555. unsigned remaining = timeout;
  1556. class CWaitException
  1557. {
  1558. CGraphBase *graph;
  1559. Owned<IException> exception;
  1560. public:
  1561. CWaitException(CGraphBase *_graph) : graph(_graph) { }
  1562. IException *get() { return exception; }
  1563. void set(IException *e)
  1564. {
  1565. if (!exception)
  1566. exception.setown(e);
  1567. else
  1568. e->Release();
  1569. }
  1570. void throwException()
  1571. {
  1572. if (exception)
  1573. throw exception.getClear();
  1574. throw MakeGraphException(graph, 0, "Timed out waiting for graph to end");
  1575. }
  1576. } waitException(this);
  1577. Owned<IThorActivityIterator> iter = getConnectedIterator();
  1578. ForEach (*iter)
  1579. {
  1580. CGraphElementBase &element = iter->query();
  1581. CActivityBase *activity = element.queryActivity();
  1582. if (INFINITE != timeout && tm.timedout(&remaining))
  1583. waitException.throwException();
  1584. try
  1585. {
  1586. if (!activity->wait(remaining))
  1587. waitException.throwException();
  1588. }
  1589. catch (IException *e)
  1590. {
  1591. waitException.set(e); // will discard if already set
  1592. if (timeout == INFINITE)
  1593. {
  1594. unsigned e = tm.elapsed();
  1595. if (e >= MEDIUMTIMEOUT)
  1596. waitException.throwException();
  1597. timeout = MEDIUMTIMEOUT-e;
  1598. tm.reset(timeout);
  1599. }
  1600. }
  1601. }
  1602. if (waitException.get())
  1603. waitException.throwException();
  1604. // synchronize all slaves to end of graphs
  1605. if (NULL == owner || isGlobal())
  1606. {
  1607. if (INFINITE != timeout && tm.timedout(&remaining))
  1608. waitException.throwException();
  1609. if (!waitBarrier->wait(true, remaining))
  1610. return false;
  1611. }
  1612. return true;
  1613. }
  1614. void CGraphBase::abort(IException *e)
  1615. {
  1616. if (aborted)
  1617. return;
  1618. {
  1619. CriticalBlock cb(crit);
  1620. abortException.set(e);
  1621. aborted = true;
  1622. graphCancelHandler.cancel(0);
  1623. if (0 == containers.count())
  1624. {
  1625. Owned<IThorGraphStubIterator> iter = getChildStubIterator();
  1626. ForEach(*iter)
  1627. {
  1628. CGraphStub &graph = iter->query();
  1629. graph.abort(e);
  1630. }
  1631. }
  1632. }
  1633. if (started && !graphDone)
  1634. {
  1635. Owned<IThorActivityIterator> iter = getConnectedIterator();
  1636. ForEach (*iter)
  1637. {
  1638. iter->query().abort(e); // JCSMORE - could do in parallel, they can take some time to timeout
  1639. }
  1640. if (startBarrier)
  1641. startBarrier->cancel(e);
  1642. if (waitBarrier)
  1643. waitBarrier->cancel(e);
  1644. if (doneBarrier)
  1645. doneBarrier->cancel(e);
  1646. }
  1647. }
  1648. void CGraphBase::GraphPrintLog(const char *format, ...)
  1649. {
  1650. va_list args;
  1651. va_start(args, format);
  1652. ::GraphPrintLogArgs(this, thorlog_null, MCdebugProgress, format, args);
  1653. va_end(args);
  1654. }
  1655. void CGraphBase::GraphPrintLog(IException *e, const char *format, ...)
  1656. {
  1657. va_list args;
  1658. va_start(args, format);
  1659. ::GraphPrintLogArgs(this, e, thorlog_null, MCdebugProgress, format, args);
  1660. va_end(args);
  1661. }
  1662. void CGraphBase::GraphPrintLog(IException *e)
  1663. {
  1664. GraphPrintLog(e, "%s", "");
  1665. }
  1666. void CGraphBase::setLogging(bool tf)
  1667. {
  1668. Owned<IThorActivityIterator> iter = getIterator();
  1669. ForEach(*iter)
  1670. iter->query().setLogging(tf);
  1671. }
  1672. void CGraphBase::createFromXGMML(IPropertyTree *_node, CGraphBase *_owner, CGraphBase *_parent, CGraphBase *resultsGraph, CGraphTableCopy &newGraphs)
  1673. {
  1674. class CChildParallelFactory : public CGraphStub
  1675. {
  1676. Linked<CGraphBase> originalChildGraph;
  1677. CriticalSection crit;
  1678. CIArrayOf<CGraphBase> stack;
  1679. CIArrayOf<CGraphBase> active;
  1680. bool originalAvailable = true;
  1681. CGraphBase *getGraph()
  1682. {
  1683. Owned<CGraphBase> childGraph;
  1684. {
  1685. CriticalBlock b(crit);
  1686. if (originalAvailable)
  1687. {
  1688. originalAvailable = false;
  1689. active.append(*originalChildGraph.getLink());
  1690. return originalChildGraph.getLink();
  1691. }
  1692. if (stack.length())
  1693. childGraph.setown(&stack.popGet());
  1694. }
  1695. if (!childGraph)
  1696. childGraph.setown(originalChildGraph->cloneGraph());
  1697. if (originalChildGraph->queryAborted())
  1698. throw MakeGraphException(originalChildGraph, 0, "Job aborted");
  1699. {
  1700. CriticalBlock b(crit);
  1701. active.append(*childGraph.getLink());
  1702. }
  1703. return childGraph.getClear();
  1704. }
  1705. void pushGraph(CGraphBase *childGraph)
  1706. {
  1707. CriticalBlock b(crit);
  1708. verifyex(active.zap(*childGraph));
  1709. if (childGraph == originalChildGraph)
  1710. originalAvailable = true;
  1711. else
  1712. stack.append(*LINK(childGraph));
  1713. }
  1714. public:
  1715. CChildParallelFactory(CGraphBase *_originalChildGraph) : originalChildGraph(_originalChildGraph)
  1716. {
  1717. graphId = originalChildGraph->queryGraphId();
  1718. }
  1719. virtual CGraphBase &queryOriginalGraph() override { return *originalChildGraph; }
  1720. virtual void abort(IException *e) override
  1721. {
  1722. for (;;)
  1723. {
  1724. Owned<CGraphBase> activeChildGraph;
  1725. {
  1726. CriticalBlock b(crit);
  1727. activeChildGraph.setown(&active.popGet());
  1728. if (!activeChildGraph)
  1729. break;
  1730. }
  1731. activeChildGraph->abort(e);
  1732. }
  1733. }
  1734. virtual bool serializeStats(MemoryBuffer &mb) override
  1735. {
  1736. // JCSMORE - need to merge other instances
  1737. return originalChildGraph->serializeStats(mb);
  1738. }
  1739. virtual IEclGraphResults * evaluate(unsigned parentExtractSz, const byte * parentExtract) override
  1740. {
  1741. Owned<CGraphBase> childGraph = getGraph();
  1742. Owned<IEclGraphResults> results = childGraph->evaluate(parentExtractSz, parentExtract);
  1743. pushGraph(childGraph);
  1744. return results.getClear();
  1745. }
  1746. };
  1747. owner = _owner;
  1748. parent = _parent?_parent:owner;
  1749. node.setown(createPTreeFromIPT(_node));
  1750. xgmml = node->queryPropTree("att/graph");
  1751. sink = xgmml->getPropBool("att[@name=\"rootGraph\"]/@value", false);
  1752. sequential = xgmml->getPropBool("@sequential");
  1753. graphId = node->getPropInt("@id");
  1754. global = false;
  1755. localOnly = -1; // unset
  1756. parentActivityId = node->getPropInt("att[@name=\"_parentActivity\"]/@value", 0);
  1757. graphResultsContainer = resultsGraph;
  1758. CGraphBase *graphContainer = this;
  1759. if (resultsGraph)
  1760. graphContainer = resultsGraph; // JCSMORE is this right?
  1761. graphCodeContext.setContext(this, graphContainer, (ICodeContextExt *)&jobChannel.queryCodeContext());
  1762. unsigned numResults = xgmml->getPropInt("att[@name=\"_numResults\"]/@value", 0);
  1763. if (numResults)
  1764. {
  1765. localResults.setown(createThorGraphResults(numResults));
  1766. resultsGraph = this;
  1767. // JCSMORE - it might more sense if this temp handler was owned by parent act., which may finish(get stopped) earlier than the owning graph
  1768. tmpHandler.setown(queryJob().createTempHandler(false));
  1769. }
  1770. localChild = false;
  1771. if (owner && parentActivityId)
  1772. {
  1773. CGraphElementBase *parentElement = owner->queryElement(parentActivityId);
  1774. if (isLoopActivity(*parentElement))
  1775. {
  1776. localChild = parentElement->queryOwner().isLocalChild();
  1777. unsigned loopId = parentElement->queryXGMML().getPropInt("att[@name=\"_loopid\"]/@value");
  1778. if ((graphId == loopId) || (owner->queryGraphId() == loopId))
  1779. loopBodySubgraph = true;
  1780. else
  1781. localChild = true;
  1782. }
  1783. else
  1784. localChild = true;
  1785. }
  1786. Owned<IPropertyTreeIterator> nodes = xgmml->getElements("node");
  1787. ForEach(*nodes)
  1788. {
  1789. IPropertyTree &e = nodes->query();
  1790. ThorActivityKind kind = (ThorActivityKind) e.getPropInt("att[@name=\"_kind\"]/@value");
  1791. if (TAKsubgraph == kind)
  1792. {
  1793. Owned<CGraphBase> subGraph = queryJobChannel().createGraph();
  1794. subGraph->createFromXGMML(&e, this, parent, resultsGraph, newGraphs);
  1795. activity_id subGraphParentActivityId = e.getPropInt("att[@name=\"_parentActivity\"]/@value", 0);
  1796. if (subGraphParentActivityId) // JCS - not sure if ever false
  1797. {
  1798. Owned<CGraphStub> stub = new CChildParallelFactory(subGraph);
  1799. addChildGraph(stub);
  1800. }
  1801. else
  1802. addChildGraph(subGraph);
  1803. if (!global)
  1804. global = subGraph->isGlobal();
  1805. newGraphs.replace(*subGraph);
  1806. }
  1807. else
  1808. {
  1809. if (localChild && !e.getPropBool("att[@name=\"coLocal\"]/@value", false))
  1810. {
  1811. IPropertyTree *att = createPTree("att");
  1812. att->setProp("@name", "coLocal");
  1813. att->setPropBool("@value", true);
  1814. e.addPropTree("att", att);
  1815. }
  1816. CGraphElementBase *act = createGraphElement(e, *this, resultsGraph);
  1817. addActivity(act);
  1818. if (!global)
  1819. global = isGlobalActivity(*act);
  1820. }
  1821. }
  1822. Owned<IPropertyTreeIterator> edges = xgmml->getElements("edge");
  1823. ForEach(*edges)
  1824. {
  1825. IPropertyTree &edge = edges->query();
  1826. unsigned sourceOutput = edge.getPropInt("att[@name=\"_sourceIndex\"]/@value", 0);
  1827. unsigned targetInput = edge.getPropInt("att[@name=\"_targetIndex\"]/@value", 0);
  1828. CGraphElementBase *source = queryElement(edge.getPropInt("@source"));
  1829. CGraphElementBase *target = queryElement(edge.getPropInt("@target"));
  1830. target->addInput(targetInput, source, sourceOutput);
  1831. }
  1832. Owned<IThorActivityIterator> iter = getIterator();
  1833. ForEach(*iter)
  1834. {
  1835. CGraphElementBase &element = iter->query();
  1836. if (0 == element.getOutputs())
  1837. {
  1838. /* JCSMORE - Making some outputs conditional, will require:
  1839. * a) Pass through information as to which dependent graph causes this graph (and this sink) to execute)
  1840. * b) Allow the subgraph to re-executed by other dependent subgraphs and avoid re-executing completed sinks
  1841. * c) Keep common points (splitters) around (preferably in memory), re-execution of graph will need them
  1842. */
  1843. sinks.append(*LINK(&element));
  1844. }
  1845. }
  1846. init();
  1847. }
  1848. void CGraphBase::executeChildGraphs(size32_t parentExtractSz, const byte *parentExtract)
  1849. {
  1850. if (sequential)
  1851. {
  1852. // JCSMORE - would need to re-think how this is done if these sibling child queries could be executed in parallel
  1853. ForEachItemIn(o, orderedChildGraphs)
  1854. {
  1855. CGraphBase &graph = orderedChildGraphs.item(o).queryOriginalGraph();
  1856. if (graph.isSink())
  1857. graph.execute(parentExtractSz, parentExtract, true, false);
  1858. }
  1859. }
  1860. else
  1861. {
  1862. Owned<IThorGraphIterator> iter = getChildGraphIterator();
  1863. ForEach(*iter)
  1864. {
  1865. CGraphBase &graph = iter->query();
  1866. if (graph.isSink())
  1867. graph.execute(parentExtractSz, parentExtract, true, false);
  1868. }
  1869. }
  1870. }
  1871. void CGraphBase::doExecuteChild(size32_t parentExtractSz, const byte *parentExtract)
  1872. {
  1873. reset();
  1874. if (0 == containers.count())
  1875. executeChildGraphs(parentExtractSz, parentExtract);
  1876. else
  1877. execute(parentExtractSz, parentExtract, false, false);
  1878. queryTempHandler()->clearTemps();
  1879. }
  1880. void CGraphBase::executeChild(size32_t & retSize, void * &ret, size32_t parentExtractSz, const byte *parentExtract)
  1881. {
  1882. reset();
  1883. doExecute(parentExtractSz, parentExtract, false);
  1884. UNIMPLEMENTED;
  1885. /*
  1886. ForEachItemIn(idx1, elements)
  1887. {
  1888. EclGraphElement & cur = elements.item(idx1);
  1889. if (cur.isResult)
  1890. {
  1891. cur.extractResult(retSize, ret);
  1892. return;
  1893. }
  1894. }
  1895. */
  1896. throwUnexpected();
  1897. }
  1898. void CGraphBase::setResults(IThorGraphResults *results) // used by master only
  1899. {
  1900. localResults.set(results);
  1901. }
  1902. void CGraphBase::executeChild(size32_t parentExtractSz, const byte *parentExtract, IThorGraphResults *results, IThorGraphResults *_graphLoopResults)
  1903. {
  1904. localResults.set(results);
  1905. graphLoopResults.set(_graphLoopResults);
  1906. doExecuteChild(parentExtractSz, parentExtract);
  1907. graphLoopResults.clear();
  1908. localResults.clear();
  1909. }
  1910. StringBuffer &getGlobals(CGraphBase &graph, StringBuffer &str)
  1911. {
  1912. bool first = true;
  1913. Owned<IThorActivityIterator> iter = graph.getIterator();
  1914. ForEach(*iter)
  1915. {
  1916. CGraphElementBase &e = iter->query();
  1917. if (isGlobalActivity(e))
  1918. {
  1919. if (first)
  1920. str.append("Graph(").append(graph.queryGraphId()).append("): [");
  1921. else
  1922. str.append(", ");
  1923. first = false;
  1924. ThorActivityKind kind = e.getKind();
  1925. str.append(activityKindStr(kind));
  1926. str.append("(").append(e.queryId()).append(")");
  1927. }
  1928. }
  1929. if (!first)
  1930. str.append("]");
  1931. Owned<IThorGraphIterator> childIter = graph.getChildGraphIterator();
  1932. ForEach(*childIter)
  1933. {
  1934. CGraphBase &childGraph = childIter->query();
  1935. getGlobals(childGraph, str);
  1936. }
  1937. return str;
  1938. }
  1939. void CGraphBase::executeChild(size32_t parentExtractSz, const byte *parentExtract)
  1940. {
  1941. assertex(localResults);
  1942. localResults->clear();
  1943. if (isGlobal()) // any slave
  1944. {
  1945. StringBuffer str("Global acts = ");
  1946. getGlobals(*this, str);
  1947. throw MakeGraphException(this, 0, "Global child graph? : %s", str.str());
  1948. }
  1949. doExecuteChild(parentExtractSz, parentExtract);
  1950. }
  1951. IThorResult *CGraphBase::getResult(unsigned id, bool distributed)
  1952. {
  1953. return localResults->getResult(id, distributed);
  1954. }
  1955. IThorResult *CGraphBase::getGraphLoopResult(unsigned id, bool distributed)
  1956. {
  1957. return graphLoopResults->getResult(id, distributed);
  1958. }
  1959. IThorResult *CGraphBase::createResult(CActivityBase &activity, unsigned id, IThorGraphResults *results, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
  1960. {
  1961. return results->createResult(activity, id, rowIf, resultType, spillPriority);
  1962. }
  1963. IThorResult *CGraphBase::createResult(CActivityBase &activity, unsigned id, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
  1964. {
  1965. return localResults->createResult(activity, id, rowIf, resultType, spillPriority);
  1966. }
  1967. IThorResult *CGraphBase::createGraphLoopResult(CActivityBase &activity, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
  1968. {
  1969. return graphLoopResults->createResult(activity, rowIf, resultType, spillPriority);
  1970. }
  1971. // IEclGraphResults
  1972. void CGraphBase::getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id)
  1973. {
  1974. Owned<IThorResult> result = getResult(id, true); // will get collated distributed result
  1975. result->getLinkedResult(count, ret);
  1976. }
  1977. void CGraphBase::getLinkedResult(unsigned & count, const byte * * & ret, unsigned id)
  1978. {
  1979. Owned<IThorResult> result = getResult(id, true); // will get collated distributed result
  1980. result->getLinkedResult(count, ret);
  1981. }
  1982. const void * CGraphBase::getLinkedRowResult(unsigned id)
  1983. {
  1984. Owned<IThorResult> result = getResult(id, true); // will get collated distributed result
  1985. return result->getLinkedRowResult();
  1986. }
  1987. // IThorChildGraph impl.
  1988. IEclGraphResults *CGraphBase::evaluate(unsigned _parentExtractSz, const byte *parentExtract)
  1989. {
  1990. CriticalBlock block(evaluateCrit);
  1991. localResults.setown(createThorGraphResults(xgmml->getPropInt("att[@name=\"_numResults\"]/@value", 0)));
  1992. parentExtractSz = _parentExtractSz;
  1993. executeChild(parentExtractSz, parentExtract);
  1994. return localResults.getClear();
  1995. }
  1996. static bool isLocalOnly(const CGraphElementBase &activity);
  1997. static bool isLocalOnly(const CGraphBase &graph) // checks all dependencies, if something needs to be global, whole body is forced to be execution sync.
  1998. {
  1999. if (0 == graph.activityCount())
  2000. {
  2001. Owned<IThorGraphIterator> iter = graph.getChildGraphIterator();
  2002. ForEach(*iter)
  2003. {
  2004. CGraphBase &childGraph = iter->query();
  2005. if (childGraph.isSink())
  2006. {
  2007. if (!isLocalOnly(childGraph))
  2008. return false;
  2009. }
  2010. }
  2011. }
  2012. else
  2013. {
  2014. if (graph.isGlobal())
  2015. return false;
  2016. Owned<IThorActivityIterator> sinkIter = graph.getAllSinkIterator();
  2017. ForEach(*sinkIter)
  2018. {
  2019. CGraphElementBase &sink = sinkIter->query();
  2020. if (!isLocalOnly(sink))
  2021. return false;
  2022. }
  2023. }
  2024. return true;
  2025. }
  2026. static bool isLocalOnly(const CGraphElementBase &activity)
  2027. {
  2028. Owned<IThorGraphDependencyIterator> deps = activity.getDependsIterator();
  2029. ForEach(*deps)
  2030. {
  2031. if (!isLocalOnly(*(deps->query().graph)))
  2032. return false;
  2033. }
  2034. StringBuffer match("edge[@target=\"");
  2035. match.append(activity.queryId()).append("\"]");
  2036. Owned<IPropertyTreeIterator> inputs = activity.queryOwner().queryXGMML().getElements(match.str());
  2037. ForEach(*inputs)
  2038. {
  2039. CGraphElementBase *sourceAct = activity.queryOwner().queryElement(inputs->query().getPropInt("@source"));
  2040. if (!isLocalOnly(*sourceAct))
  2041. return false;
  2042. }
  2043. return true;
  2044. }
  2045. bool CGraphBase::isLocalOnly() const // checks all dependencies, if something needs to be global, whole body is forced to be execution sync.
  2046. {
  2047. if (-1 == localOnly)
  2048. localOnly = (int)::isLocalOnly(*this);
  2049. return 1==localOnly;
  2050. }
  2051. IThorGraphResults *CGraphBase::createThorGraphResults(unsigned num)
  2052. {
  2053. return new CThorGraphResults(num);
  2054. }
  2055. ////
  2056. void CGraphTempHandler::registerFile(const char *name, graph_id graphId, unsigned usageCount, bool temp, WUFileKind fileKind, StringArray *clusters)
  2057. {
  2058. assertex(temp);
  2059. LOG(MCdebugProgress, thorJob, "registerTmpFile name=%s, usageCount=%d", name, usageCount);
  2060. CriticalBlock b(crit);
  2061. if (tmpFiles.find(name))
  2062. throw MakeThorException(TE_FileAlreadyUsedAsTempFile, "File already used as temp file (%s)", name);
  2063. tmpFiles.replace(* new CFileUsageEntry(name, graphId, fileKind, usageCount));
  2064. }
  2065. void CGraphTempHandler::deregisterFile(const char *name, bool kept)
  2066. {
  2067. LOG(MCdebugProgress, thorJob, "deregisterTmpFile name=%s", name);
  2068. CriticalBlock b(crit);
  2069. CFileUsageEntry *fileUsage = tmpFiles.find(name);
  2070. if (!fileUsage)
  2071. {
  2072. if (errorOnMissing)
  2073. throw MakeThorException(TE_FileNotFound, "File not found (%s) deregistering tmp file", name);
  2074. return;
  2075. }
  2076. if (0 == fileUsage->queryUsage()) // marked 'not to be deleted' until workunit complete.
  2077. return;
  2078. else if (1 == fileUsage->queryUsage())
  2079. {
  2080. tmpFiles.remove(name);
  2081. try
  2082. {
  2083. if (!removeTemp(name))
  2084. LOG(MCwarning, unknownJob, "Failed to delete tmp file : %s (not found)", name);
  2085. }
  2086. catch (IException *e) { StringBuffer s("Failed to delete tmp file : "); FLLOG(MCwarning, thorJob, e, s.append(name).str()); }
  2087. }
  2088. else
  2089. fileUsage->decUsage();
  2090. }
  2091. void CGraphTempHandler::clearTemps()
  2092. {
  2093. CriticalBlock b(crit);
  2094. Owned<IFileUsageIterator> iter = getIterator();
  2095. ForEach(*iter)
  2096. {
  2097. CFileUsageEntry &entry = iter->query();
  2098. const char *tmpname = entry.queryName();
  2099. try
  2100. {
  2101. if (!removeTemp(tmpname))
  2102. LOG(MCwarning, thorJob, "Failed to delete tmp file : %s (not found)", tmpname);
  2103. }
  2104. catch (IException *e) { StringBuffer s("Failed to delete tmp file : "); FLLOG(MCwarning, thorJob, e, s.append(tmpname).str()); }
  2105. }
  2106. iter.clear();
  2107. tmpFiles.kill();
  2108. }
  2109. /////
  2110. class CGraphExecutor;
  2111. class CGraphExecutorGraphInfo : public CInterface
  2112. {
  2113. public:
  2114. CGraphExecutorGraphInfo(CGraphExecutor &_executor, CGraphBase *_subGraph, IGraphCallback &_callback, const byte *parentExtract, size32_t parentExtractSz) : executor(_executor), subGraph(_subGraph), callback(_callback)
  2115. {
  2116. parentExtractMb.append(parentExtractSz, parentExtract);
  2117. }
  2118. CGraphExecutor &executor;
  2119. IGraphCallback &callback;
  2120. Linked<CGraphBase> subGraph;
  2121. MemoryBuffer parentExtractMb;
  2122. };
  2123. class CGraphExecutor : implements IGraphExecutor, public CInterface
  2124. {
  2125. CJobChannel &jobChannel;
  2126. CJobBase &job;
  2127. CIArrayOf<CGraphExecutorGraphInfo> stack, running, toRun;
  2128. UnsignedArray seen;
  2129. bool stopped;
  2130. unsigned limit;
  2131. unsigned waitOnRunning;
  2132. CriticalSection crit;
  2133. Semaphore runningSem;
  2134. Owned<IThreadPool> graphPool;
  2135. class CGraphExecutorFactory : implements IThreadFactory, public CInterface
  2136. {
  2137. CGraphExecutor &executor;
  2138. public:
  2139. IMPLEMENT_IINTERFACE;
  2140. CGraphExecutorFactory(CGraphExecutor &_executor) : executor(_executor) { }
  2141. // IThreadFactory
  2142. virtual IPooledThread *createNew()
  2143. {
  2144. class CGraphExecutorThread : implements IPooledThread, public CInterface
  2145. {
  2146. Owned<CGraphExecutorGraphInfo> graphInfo;
  2147. public:
  2148. IMPLEMENT_IINTERFACE;
  2149. CGraphExecutorThread()
  2150. {
  2151. }
  2152. virtual void init(void *startInfo) override
  2153. {
  2154. graphInfo.setown((CGraphExecutorGraphInfo *)startInfo);
  2155. }
  2156. virtual void threadmain() override
  2157. {
  2158. for (;;)
  2159. {
  2160. Linked<CGraphBase> graph = graphInfo->subGraph;
  2161. Owned<IException> e;
  2162. try
  2163. {
  2164. PROGLOG("CGraphExecutor: Running graph, graphId=%" GIDPF "d", graph->queryGraphId());
  2165. graphInfo->callback.runSubgraph(*graph, graphInfo->parentExtractMb.length(), (const byte *)graphInfo->parentExtractMb.toByteArray());
  2166. }
  2167. catch (IException *_e)
  2168. {
  2169. e.setown(_e);
  2170. }
  2171. Owned<CGraphExecutorGraphInfo> nextGraphInfo;
  2172. try
  2173. {
  2174. nextGraphInfo.setown(graphInfo->executor.graphDone(*graphInfo, e));
  2175. }
  2176. catch (IException *e)
  2177. {
  2178. GraphPrintLog(graph, e, "graphDone");
  2179. e->Release();
  2180. }
  2181. if (e)
  2182. throw e.getClear();
  2183. if (!nextGraphInfo)
  2184. return;
  2185. graphInfo.setown(nextGraphInfo.getClear());
  2186. }
  2187. }
  2188. virtual bool canReuse() const override { return true; }
  2189. virtual bool stop() override { return true; }
  2190. };
  2191. return new CGraphExecutorThread();
  2192. }
  2193. } *factory;
  2194. CGraphExecutorGraphInfo *findRunning(graph_id gid)
  2195. {
  2196. ForEachItemIn(r, running)
  2197. {
  2198. CGraphExecutorGraphInfo *graphInfo = &running.item(r);
  2199. if (gid == graphInfo->subGraph->queryGraphId())
  2200. return graphInfo;
  2201. }
  2202. return NULL;
  2203. }
  2204. public:
  2205. IMPLEMENT_IINTERFACE;
  2206. CGraphExecutor(CJobChannel &_jobChannel) : jobChannel(_jobChannel), job(_jobChannel.queryJob())
  2207. {
  2208. limit = (unsigned)job.getWorkUnitValueInt("concurrentSubGraphs", globals->getPropInt("@concurrentSubGraphs", 1));
  2209. PROGLOG("CGraphExecutor: limit = %d", limit);
  2210. waitOnRunning = 0;
  2211. stopped = false;
  2212. factory = new CGraphExecutorFactory(*this);
  2213. graphPool.setown(createThreadPool("CGraphExecutor pool", factory, &jobChannel, limit));
  2214. }
  2215. ~CGraphExecutor()
  2216. {
  2217. stopped = true;
  2218. graphPool->joinAll();
  2219. factory->Release();
  2220. }
  2221. CGraphExecutorGraphInfo *graphDone(CGraphExecutorGraphInfo &doneGraphInfo, IException *e)
  2222. {
  2223. CriticalBlock b(crit);
  2224. running.zap(doneGraphInfo);
  2225. if (waitOnRunning)
  2226. {
  2227. runningSem.signal(waitOnRunning);
  2228. waitOnRunning = 0;
  2229. }
  2230. if (e || job.queryAborted())
  2231. {
  2232. stopped = true;
  2233. stack.kill();
  2234. return NULL;
  2235. }
  2236. if (job.queryPausing())
  2237. stack.kill();
  2238. else if (stack.ordinality())
  2239. {
  2240. CICopyArrayOf<CGraphExecutorGraphInfo> toMove;
  2241. ForEachItemIn(s, stack)
  2242. {
  2243. bool dependenciesDone = true;
  2244. CGraphExecutorGraphInfo &graphInfo = stack.item(s);
  2245. ForEachItemIn (d, graphInfo.subGraph->dependentSubGraphs)
  2246. {
  2247. CGraphBase &subGraph = graphInfo.subGraph->dependentSubGraphs.item(d);
  2248. if (!subGraph.isComplete())
  2249. {
  2250. dependenciesDone = false;
  2251. break;
  2252. }
  2253. }
  2254. if (dependenciesDone)
  2255. {
  2256. graphInfo.subGraph->dependentSubGraphs.kill();
  2257. graphInfo.subGraph->prepare(graphInfo.parentExtractMb.length(), (const byte *)graphInfo.parentExtractMb.toByteArray(), true, true, true); // now existing deps done, maybe more to prepare
  2258. ForEachItemIn (d, graphInfo.subGraph->dependentSubGraphs)
  2259. {
  2260. CGraphBase &subGraph = graphInfo.subGraph->dependentSubGraphs.item(d);
  2261. if (!subGraph.isComplete())
  2262. {
  2263. dependenciesDone = false;
  2264. break;
  2265. }
  2266. }
  2267. if (dependenciesDone)
  2268. {
  2269. graphInfo.subGraph->dependentSubGraphs.kill(); // none to track anymore
  2270. toMove.append(graphInfo);
  2271. }
  2272. }
  2273. }
  2274. ForEachItemIn(m, toMove)
  2275. {
  2276. Linked<CGraphExecutorGraphInfo> graphInfo = &toMove.item(m);
  2277. stack.zap(*graphInfo);
  2278. toRun.add(*graphInfo.getClear(), 0);
  2279. }
  2280. }
  2281. job.markWuDirty();
  2282. PROGLOG("CGraphExecutor running=%d, waitingToRun=%d, dependentsWaiting=%d", running.ordinality(), toRun.ordinality(), stack.ordinality());
  2283. while (toRun.ordinality())
  2284. {
  2285. if (job.queryPausing())
  2286. return NULL;
  2287. Linked<CGraphExecutorGraphInfo> nextGraphInfo = &toRun.item(0);
  2288. toRun.remove(0);
  2289. if (!nextGraphInfo->subGraph->isComplete() && (NULL == findRunning(nextGraphInfo->subGraph->queryGraphId())))
  2290. {
  2291. running.append(*nextGraphInfo.getLink());
  2292. return nextGraphInfo.getClear();
  2293. }
  2294. }
  2295. return NULL;
  2296. }
  2297. // IGraphExecutor
  2298. virtual void add(CGraphBase *subGraph, IGraphCallback &callback, bool checkDependencies, size32_t parentExtractSz, const byte *parentExtract)
  2299. {
  2300. bool alreadyRunning;
  2301. {
  2302. CriticalBlock b(crit);
  2303. if (job.queryPausing())
  2304. return;
  2305. if (subGraph->isComplete())
  2306. return;
  2307. alreadyRunning = NULL != findRunning(subGraph->queryGraphId());
  2308. if (alreadyRunning)
  2309. ++waitOnRunning;
  2310. }
  2311. if (alreadyRunning)
  2312. {
  2313. for (;;)
  2314. {
  2315. PROGLOG("Waiting on subgraph %" GIDPF "d", subGraph->queryGraphId());
  2316. if (runningSem.wait(MEDIUMTIMEOUT) || job.queryAborted() || job.queryPausing())
  2317. break;
  2318. }
  2319. return;
  2320. }
  2321. else
  2322. {
  2323. CriticalBlock b(crit);
  2324. if (seen.contains(subGraph->queryGraphId()))
  2325. return; // already queued;
  2326. seen.append(subGraph->queryGraphId());
  2327. }
  2328. if (!subGraph->prepare(parentExtractSz, parentExtract, checkDependencies, true, true))
  2329. {
  2330. subGraph->setComplete();
  2331. return;
  2332. }
  2333. if (subGraph->dependentSubGraphs.ordinality())
  2334. {
  2335. bool dependenciesDone = true;
  2336. ForEachItemIn (d, subGraph->dependentSubGraphs)
  2337. {
  2338. CGraphBase &graph = subGraph->dependentSubGraphs.item(d);
  2339. if (!graph.isComplete())
  2340. {
  2341. dependenciesDone = false;
  2342. break;
  2343. }
  2344. }
  2345. if (dependenciesDone)
  2346. subGraph->dependentSubGraphs.kill(); // none to track anymore
  2347. }
  2348. Owned<CGraphExecutorGraphInfo> graphInfo = new CGraphExecutorGraphInfo(*this, subGraph, callback, parentExtract, parentExtractSz);
  2349. CriticalBlock b(crit);
  2350. if (0 == subGraph->dependentSubGraphs.ordinality())
  2351. {
  2352. if (running.ordinality()<limit)
  2353. {
  2354. running.append(*LINK(graphInfo));
  2355. PROGLOG("Add: Launching graph thread for graphId=%" GIDPF "d", subGraph->queryGraphId());
  2356. graphPool->start(graphInfo.getClear());
  2357. }
  2358. else
  2359. stack.add(*graphInfo.getClear(), 0); // push to front, no dependency, free to run next.
  2360. }
  2361. else
  2362. stack.append(*graphInfo.getClear()); // as dependencies finish, may move up the list
  2363. }
  2364. virtual IThreadPool &queryGraphPool() { return *graphPool; }
  2365. virtual void wait()
  2366. {
  2367. PROGLOG("CGraphExecutor exiting, waiting on graph pool");
  2368. graphPool->joinAll();
  2369. PROGLOG("CGraphExecutor graphPool finished");
  2370. }
  2371. };
  2372. ////
  2373. // IContextLogger
  2374. class CThorContextLogger : implements IContextLogger, public CSimpleInterface
  2375. {
  2376. CJobBase &job;
  2377. unsigned traceLevel;
  2378. StringAttr globalIdHeader;
  2379. StringAttr callerIdHeader;
  2380. StringAttr globalId;
  2381. StringBuffer localId;
  2382. public:
  2383. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2384. CThorContextLogger(CJobBase &_job) : job(_job)
  2385. {
  2386. traceLevel = 1;
  2387. if (globals->hasProp("@httpGlobalIdHeader"))
  2388. setHttpIdHeaders(globals->queryProp("@httpGlobalIdHeader"), globals->queryProp("@httpCallerIdHeader"));
  2389. }
  2390. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  2391. {
  2392. StringBuffer ss;
  2393. ss.valist_appendf(format, args);
  2394. LOG(MCdebugProgress, thorJob, "%s", ss.str());
  2395. }
  2396. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  2397. {
  2398. StringBuffer ss;
  2399. ss.append("ERROR");
  2400. if (E)
  2401. ss.append(": ").append(E->errorCode());
  2402. if (file)
  2403. ss.appendf(": %s(%d) ", file, line);
  2404. if (E)
  2405. E->errorMessage(ss.append(": "));
  2406. if (format)
  2407. ss.append(": ").valist_appendf(format, args);
  2408. LOG(MCoperatorProgress, thorJob, "%s", ss.str());
  2409. }
  2410. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  2411. {
  2412. }
  2413. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  2414. {
  2415. }
  2416. virtual unsigned queryTraceLevel() const
  2417. {
  2418. return traceLevel;
  2419. }
  2420. virtual void setGlobalId(const char *id, SocketEndpoint &ep, unsigned pid)
  2421. {
  2422. globalId.set(id);
  2423. appendLocalId(localId.clear(), ep, pid);
  2424. }
  2425. virtual const char *queryGlobalId() const
  2426. {
  2427. return globalId.get();
  2428. }
  2429. virtual const char *queryLocalId() const
  2430. {
  2431. return localId.str();
  2432. }
  2433. virtual void setHttpIdHeaders(const char *global, const char *caller)
  2434. {
  2435. if (global && *global)
  2436. globalIdHeader.set(global);
  2437. if (caller && *caller)
  2438. callerIdHeader.set(caller);
  2439. }
  2440. virtual const char *queryGlobalIdHttpHeader() const
  2441. {
  2442. return globalIdHeader.str();
  2443. }
  2444. virtual const char *queryCallerIdHttpHeader() const
  2445. {
  2446. return callerIdHeader.str();
  2447. }
  2448. };
  2449. ////
  2450. CJobBase::CJobBase(ILoadedDllEntry *_querySo, const char *_graphName) : querySo(_querySo), graphName(_graphName)
  2451. {
  2452. maxDiskUsage = diskUsage = 0;
  2453. dirty = true;
  2454. aborted = false;
  2455. globalMemoryMB = globals->getPropInt("@globalMemorySize"); // in MB
  2456. channelsPerSlave = globals->getPropInt("@channelsPerSlave", 1);
  2457. numChannels = channelsPerSlave;
  2458. pluginMap = new SafePluginMap(&pluginCtx, true);
  2459. // JCSMORE - Will pass down at job creation time...
  2460. jobGroup.set(&::queryClusterGroup());
  2461. slaveGroup.setown(jobGroup->remove(0));
  2462. nodeGroup.set(&queryNodeGroup());
  2463. myNodeRank = nodeGroup->rank(::queryMyNode());
  2464. unsigned channelsPerSlave = globals->getPropInt("@channelsPerSlave", 1);
  2465. jobChannelSlaveNumbers.allocateN(channelsPerSlave, true); // filled when channels are added.
  2466. jobSlaveChannelNum.allocateN(querySlaves()); // filled when channels are added.
  2467. for (unsigned s=0; s<querySlaves(); s++)
  2468. jobSlaveChannelNum[s] = NotFound;
  2469. StringBuffer wuXML;
  2470. if (!getEmbeddedWorkUnitXML(querySo, wuXML))
  2471. throw MakeStringException(0, "Failed to locate workunit info in query : %s", querySo->queryName());
  2472. Owned<ILocalWorkUnit> localWU = createLocalWorkUnit(wuXML);
  2473. Owned<IConstWUGraph> graph = localWU->getGraph(graphName);
  2474. graphXGMML.setown(graph->getXGMMLTree(false));
  2475. if (!graphXGMML)
  2476. throwUnexpected();
  2477. }
  2478. void CJobBase::init()
  2479. {
  2480. StringBuffer tmp;
  2481. tmp.append(wuid);
  2482. tmp.append(graphName);
  2483. key.set(tmp.str());
  2484. SCMStringBuffer tokenUser, password;
  2485. extractToken(token.str(), wuid.str(), tokenUser, password);
  2486. userDesc = createUserDescriptor();
  2487. userDesc->set(user.str(), password.str());
  2488. forceLogGraphIdMin = (graph_id)getWorkUnitValueInt("forceLogGraphIdMin", 0);
  2489. forceLogGraphIdMax = (graph_id)getWorkUnitValueInt("forceLogGraphIdMax", 0);
  2490. logctx.setown(new CThorContextLogger(*this));
  2491. // global setting default on, can be overridden by #option
  2492. timeActivities = 0 != getWorkUnitValueInt("timeActivities", globals->getPropBool("@timeActivities", true));
  2493. maxActivityCores = (unsigned)getWorkUnitValueInt("maxActivityCores", 0); // NB: 0 means system decides
  2494. if (0 == maxActivityCores)
  2495. maxActivityCores = getAffinityCpus();
  2496. pausing = false;
  2497. resumed = false;
  2498. crcChecking = 0 != getWorkUnitValueInt("THOR_ROWCRC", globals->getPropBool("@THOR_ROWCRC", false));
  2499. usePackedAllocator = 0 != getWorkUnitValueInt("THOR_PACKEDALLOCATOR", globals->getPropBool("@THOR_PACKEDALLOCATOR", true));
  2500. memorySpillAtPercentage = (unsigned)getWorkUnitValueInt("memorySpillAt", globals->getPropInt("@memorySpillAt", 80));
  2501. sharedMemoryLimitPercentage = (unsigned)getWorkUnitValueInt("globalMemoryLimitPC", globals->getPropInt("@sharedMemoryLimit", 90));
  2502. sharedMemoryMB = globalMemoryMB*sharedMemoryLimitPercentage/100;
  2503. PROGLOG("Global memory size = %d MB, shared memory = %d%%, memory spill at = %d%%", globalMemoryMB, sharedMemoryLimitPercentage, memorySpillAtPercentage);
  2504. StringBuffer tracing("maxActivityCores = ");
  2505. if (maxActivityCores)
  2506. tracing.append(maxActivityCores);
  2507. else
  2508. tracing.append("[unbound]");
  2509. PROGLOG("%s", tracing.str());
  2510. }
  2511. void CJobBase::beforeDispose()
  2512. {
  2513. endJob();
  2514. ForEachItemIn(c, jobChannels)
  2515. jobChannels.item(c).clean();
  2516. }
  2517. CJobBase::~CJobBase()
  2518. {
  2519. jobChannels.kill(); // avoiding circular references. Kill before other CJobBase components are destroyed that channels reference.
  2520. ::Release(userDesc);
  2521. ::Release(pluginMap);
  2522. StringBuffer memStatsStr;
  2523. roxiemem::memstats(memStatsStr);
  2524. PROGLOG("Roxiemem stats: %s", memStatsStr.str());
  2525. memsize_t heapUsage = getMapInfo("heap");
  2526. if (heapUsage) // if 0, assumed to be unavailable
  2527. {
  2528. memsize_t rmtotal = roxiemem::getTotalMemoryLimit();
  2529. PROGLOG("Heap usage (excluding Roxiemem) : %" I64F "d bytes", (unsigned __int64)(heapUsage-rmtotal));
  2530. }
  2531. }
  2532. CJobChannel &CJobBase::queryJobChannel(unsigned c) const
  2533. {
  2534. return jobChannels.item(c);
  2535. }
  2536. CActivityBase &CJobBase::queryChannelActivity(unsigned c, graph_id gid, activity_id id) const
  2537. {
  2538. CJobChannel &channel = queryJobChannel(c);
  2539. Owned<CGraphBase> graph = channel.getGraph(gid);
  2540. dbgassertex(graph);
  2541. CGraphElementBase *container = graph->queryElement(id);
  2542. dbgassertex(container);
  2543. return *container->queryActivity();
  2544. }
  2545. void CJobBase::startJob()
  2546. {
  2547. LOG(MCdebugProgress, thorJob, "New Graph started : %s", graphName.get());
  2548. ClearTempDirs();
  2549. perfmonhook.setown(createThorMemStatsPerfMonHook(*this, getOptInt(THOROPT_MAX_KERNLOG, 3)));
  2550. setPerformanceMonitorHook(perfmonhook);
  2551. PrintMemoryStatusLog();
  2552. logDiskSpace();
  2553. unsigned keyNodeCacheMB = (unsigned)getWorkUnitValueInt("keyNodeCacheMB", DEFAULT_KEYNODECACHEMB * queryJobChannels());
  2554. unsigned keyLeafCacheMB = (unsigned)getWorkUnitValueInt("keyLeafCacheMB", DEFAULT_KEYLEAFCACHEMB * queryJobChannels());
  2555. unsigned keyBlobCacheMB = (unsigned)getWorkUnitValueInt("keyBlobCacheMB", DEFAULT_KEYBLOBCACHEMB * queryJobChannels());
  2556. setNodeCacheMem(keyNodeCacheMB * 0x100000);
  2557. setLeafCacheMem(keyLeafCacheMB * 0x100000);
  2558. setBlobCacheMem(keyBlobCacheMB * 0x100000);
  2559. PROGLOG("Key node caching setting: node=%u MB, leaf=%u MB, blob=%u MB", keyNodeCacheMB, keyLeafCacheMB, keyBlobCacheMB);
  2560. unsigned keyFileCacheLimit = (unsigned)getWorkUnitValueInt("keyFileCacheLimit", 0);
  2561. if (!keyFileCacheLimit)
  2562. keyFileCacheLimit = (querySlaves()+1)*2;
  2563. setKeyIndexCacheSize(keyFileCacheLimit);
  2564. PROGLOG("Key file cache size set to: %d", keyFileCacheLimit);
  2565. if (getOptBool("dumpStacks")) // mainly as an example of printAllStacks() usage
  2566. {
  2567. StringBuffer output;
  2568. if (getAllStacks(output))
  2569. PrintLogDirect(output);
  2570. else
  2571. WARNLOG("Failed to capture process stacks: %s", output.str());
  2572. }
  2573. }
  2574. void CJobBase::endJob()
  2575. {
  2576. setPerformanceMonitorHook(nullptr);
  2577. LOG(MCdebugProgress, thorJob, "Job ended : %s", graphName.get());
  2578. clearKeyStoreCache(true);
  2579. PrintMemoryStatusLog();
  2580. }
  2581. bool CJobBase::queryForceLogging(graph_id graphId, bool def) const
  2582. {
  2583. // JCSMORE, could add comma separated range, e.g. 1-5,10-12
  2584. if ((graphId >= forceLogGraphIdMin) && (graphId <= forceLogGraphIdMax))
  2585. return true;
  2586. return def;
  2587. }
  2588. void CJobBase::addSubGraph(IPropertyTree &xgmml)
  2589. {
  2590. CriticalBlock b(crit);
  2591. for (unsigned c=0; c<queryJobChannels(); c++)
  2592. {
  2593. CJobChannel &jobChannel = queryJobChannel(c);
  2594. Owned<CGraphBase> subGraph = jobChannel.createGraph();
  2595. subGraph->createFromXGMML(&xgmml, NULL, NULL, NULL, jobChannel.queryAllGraphs());
  2596. jobChannel.addSubGraph(*subGraph.getClear());
  2597. }
  2598. }
  2599. void CJobBase::addDependencies(IPropertyTree *xgmml, bool failIfMissing)
  2600. {
  2601. for (unsigned c=0; c<queryJobChannels(); c++)
  2602. {
  2603. CJobChannel &jobChannel = queryJobChannel(c);
  2604. jobChannel.addDependencies(xgmml, failIfMissing);
  2605. }
  2606. }
  2607. bool CJobBase::queryUseCheckpoints() const
  2608. {
  2609. return globals->getPropBool("@checkPointRecovery") || 0 != getWorkUnitValueInt("checkPointRecovery", 0);
  2610. }
  2611. void CJobBase::abort(IException *e)
  2612. {
  2613. aborted = true;
  2614. for (unsigned c=0; c<queryJobChannels(); c++)
  2615. {
  2616. CJobChannel &jobChannel = queryJobChannel(c);
  2617. jobChannel.abort(e);
  2618. }
  2619. }
  2620. void CJobBase::increase(offset_t usage, const char *key)
  2621. {
  2622. diskUsage += usage;
  2623. if (diskUsage > maxDiskUsage) maxDiskUsage = diskUsage;
  2624. }
  2625. void CJobBase::decrease(offset_t usage, const char *key)
  2626. {
  2627. diskUsage -= usage;
  2628. }
  2629. // these getX methods for property in workunit settings, then global setting, defaulting to provided 'dft' if not present
  2630. StringBuffer &CJobBase::getOpt(const char *opt, StringBuffer &out)
  2631. {
  2632. if (!opt || !*opt)
  2633. return out; // probably error
  2634. VStringBuffer gOpt("Debug/@%s", opt);
  2635. getWorkUnitValue(opt, out);
  2636. if (0 == out.length())
  2637. globals->getProp(gOpt, out);
  2638. return out;
  2639. }
  2640. bool CJobBase::getOptBool(const char *opt, bool dft)
  2641. {
  2642. if (!opt || !*opt)
  2643. return dft; // probably error
  2644. VStringBuffer gOpt("Debug/@%s", opt);
  2645. return getWorkUnitValueBool(opt, globals->getPropBool(gOpt, dft));
  2646. }
  2647. int CJobBase::getOptInt(const char *opt, int dft)
  2648. {
  2649. if (!opt || !*opt)
  2650. return dft; // probably error
  2651. VStringBuffer gOpt("Debug/@%s", opt);
  2652. return (int)getWorkUnitValueInt(opt, globals->getPropInt(gOpt, dft));
  2653. }
  2654. __int64 CJobBase::getOptInt64(const char *opt, __int64 dft)
  2655. {
  2656. if (!opt || !*opt)
  2657. return dft; // probably error
  2658. VStringBuffer gOpt("Debug/@%s", opt);
  2659. return getWorkUnitValueInt(opt, globals->getPropInt64(gOpt, dft));
  2660. }
  2661. IThorAllocator *CJobBase::getThorAllocator(unsigned channel)
  2662. {
  2663. return sharedAllocator.getLink();
  2664. }
  2665. /// CJobChannel
  2666. CJobChannel::CJobChannel(CJobBase &_job, IMPServer *_mpServer, unsigned _channel)
  2667. : job(_job), mpServer(_mpServer), channel(_channel)
  2668. {
  2669. aborted = false;
  2670. thorAllocator.setown(job.getThorAllocator(channel));
  2671. jobComm.setown(mpServer->createCommunicator(&job.queryJobGroup()));
  2672. myrank = job.queryJobGroup().rank(queryMyNode());
  2673. graphExecutor.setown(new CGraphExecutor(*this));
  2674. }
  2675. CJobChannel::~CJobChannel()
  2676. {
  2677. queryRowManager()->reportMemoryUsage(false);
  2678. PROGLOG("CJobBase resetting memory manager");
  2679. thorAllocator.clear();
  2680. wait();
  2681. clean();
  2682. codeCtx.clear();
  2683. }
  2684. INode *CJobChannel::queryMyNode()
  2685. {
  2686. return mpServer->queryMyNode();
  2687. }
  2688. void CJobChannel::wait()
  2689. {
  2690. if (graphExecutor)
  2691. graphExecutor->wait();
  2692. }
  2693. ICodeContext &CJobChannel::queryCodeContext() const
  2694. {
  2695. return *codeCtx;
  2696. }
  2697. ICodeContext &CJobChannel::querySharedMemCodeContext() const
  2698. {
  2699. return *sharedMemCodeCtx;
  2700. }
  2701. mptag_t CJobChannel::deserializeMPTag(MemoryBuffer &mb)
  2702. {
  2703. mptag_t tag;
  2704. deserializeMPtag(mb, tag);
  2705. if (TAG_NULL != tag)
  2706. {
  2707. PROGLOG("deserializeMPTag: tag = %d", (int)tag);
  2708. jobComm->flush(tag);
  2709. }
  2710. return tag;
  2711. }
  2712. IEngineRowAllocator *CJobChannel::getRowAllocator(IOutputMetaData * meta, activity_id activityId, roxiemem::RoxieHeapFlags flags) const
  2713. {
  2714. return thorAllocator->getRowAllocator(meta, activityId, flags);
  2715. }
  2716. roxiemem::IRowManager *CJobChannel::queryRowManager() const
  2717. {
  2718. return thorAllocator->queryRowManager();
  2719. }
  2720. void CJobChannel::addDependencies(IPropertyTree *xgmml, bool failIfMissing)
  2721. {
  2722. ::addDependencies(xgmml, failIfMissing, allGraphs);
  2723. }
  2724. IThorGraphIterator *CJobChannel::getSubGraphs()
  2725. {
  2726. CriticalBlock b(crit);
  2727. return new CGraphTableIterator(subGraphs);
  2728. }
  2729. void CJobChannel::clean()
  2730. {
  2731. if (graphExecutor)
  2732. {
  2733. graphExecutor->queryGraphPool().stopAll();
  2734. graphExecutor.clear();
  2735. }
  2736. subGraphs.kill();
  2737. }
  2738. void CJobChannel::startGraph(CGraphBase &graph, bool checkDependencies, size32_t parentExtractSize, const byte *parentExtract)
  2739. {
  2740. graphExecutor->add(&graph, *this, checkDependencies, parentExtractSize, parentExtract);
  2741. }
  2742. IThorResult *CJobChannel::getOwnedResult(graph_id gid, activity_id ownerId, unsigned resultId)
  2743. {
  2744. Owned<CGraphBase> graph = getGraph(gid);
  2745. if (!graph)
  2746. {
  2747. Owned<IThorException> e = MakeThorException(0, "getOwnedResult: graph not found");
  2748. e->setGraphInfo(queryJob().queryGraphName(), gid);
  2749. throw e.getClear();
  2750. }
  2751. Owned<IThorResult> result;
  2752. if (ownerId)
  2753. {
  2754. CGraphElementBase *container = graph->queryElement(ownerId);
  2755. assertex(container);
  2756. CActivityBase *activity = container->queryActivity();
  2757. IThorGraphResults *results = activity->queryResults();
  2758. if (!results)
  2759. throw MakeGraphException(graph, 0, "GraphGetResult: no results created (requesting: %d)", resultId);
  2760. result.setown(activity->queryResults()->getResult(resultId));
  2761. }
  2762. else
  2763. result.setown(graph->getResult(resultId));
  2764. if (!result)
  2765. throw MakeGraphException(graph, 0, "GraphGetResult: result not found: %d", resultId);
  2766. return result.getClear();
  2767. }
  2768. void CJobChannel::abort(IException *e)
  2769. {
  2770. aborted = true;
  2771. Owned<IThorGraphIterator> iter = getSubGraphs();
  2772. ForEach (*iter)
  2773. {
  2774. CGraphBase &graph = iter->query();
  2775. graph.abort(e);
  2776. }
  2777. }
  2778. // IGraphCallback
  2779. void CJobChannel::runSubgraph(CGraphBase &graph, size32_t parentExtractSz, const byte *parentExtract)
  2780. {
  2781. graph.executeSubGraph(parentExtractSz, parentExtract);
  2782. }
  2783. static IThorResource *iThorResource = NULL;
  2784. void setIThorResource(IThorResource &r)
  2785. {
  2786. iThorResource = &r;
  2787. }
  2788. IThorResource &queryThor()
  2789. {
  2790. return *iThorResource;
  2791. }
  2792. //
  2793. //
  2794. //
  2795. //
  2796. CActivityBase::CActivityBase(CGraphElementBase *_container) : container(*_container), timeActivities(_container->queryJob().queryTimeActivities())
  2797. {
  2798. mpTag = TAG_NULL;
  2799. abortSoon = receiving = cancelledReceive = initialized = reInit = false;
  2800. baseHelper.set(container.queryHelper());
  2801. parentExtractSz = 0;
  2802. parentExtract = NULL;
  2803. }
  2804. CActivityBase::~CActivityBase()
  2805. {
  2806. }
  2807. void CActivityBase::abort()
  2808. {
  2809. if (!abortSoon) ActPrintLog("Abort condition set");
  2810. abortSoon = true;
  2811. }
  2812. void CActivityBase::kill()
  2813. {
  2814. ownedResults.clear();
  2815. }
  2816. bool CActivityBase::appendRowXml(StringBuffer & target, IOutputMetaData & meta, const void * row) const
  2817. {
  2818. if (!meta.hasXML())
  2819. {
  2820. target.append("<xml-unavailable/>");
  2821. return false;
  2822. }
  2823. try
  2824. {
  2825. CommonXmlWriter xmlWrite(XWFnoindent);
  2826. meta.toXML((byte *) row, xmlWrite);
  2827. target.append(xmlWrite.str());
  2828. return true;
  2829. }
  2830. catch (IException * e)
  2831. {
  2832. e->Release();
  2833. target.append("<invalid-row/>");
  2834. return false;
  2835. }
  2836. }
  2837. void CActivityBase::logRow(const char * prefix, IOutputMetaData & meta, const void * row)
  2838. {
  2839. bool blindLogging = false; // MORE: should check a workunit/global option
  2840. if (meta.hasXML() && !blindLogging)
  2841. {
  2842. StringBuffer xml;
  2843. appendRowXml(xml, meta, row);
  2844. ActPrintLog("%s: %s", prefix, xml.str());
  2845. }
  2846. }
  2847. void CActivityBase::ActPrintLog(const char *format, ...)
  2848. {
  2849. va_list args;
  2850. va_start(args, format);
  2851. ::ActPrintLogArgs(&queryContainer(), thorlog_null, MCdebugProgress, format, args);
  2852. va_end(args);
  2853. }
  2854. void CActivityBase::ActPrintLog(IException *e, const char *format, ...)
  2855. {
  2856. va_list args;
  2857. va_start(args, format);
  2858. ::ActPrintLogArgs(&queryContainer(), e, thorlog_all, MCexception(e), format, args);
  2859. va_end(args);
  2860. }
  2861. void CActivityBase::ActPrintLog(IException *e)
  2862. {
  2863. ActPrintLog(e, "%s", "");
  2864. }
  2865. IThorRowInterfaces * CActivityBase::createRowInterfaces(IOutputMetaData * meta, byte seq)
  2866. {
  2867. activity_id id = createCompoundActSeqId(queryId(), seq);
  2868. return createThorRowInterfaces(queryRowManager(), meta, id, queryHeapFlags(), queryCodeContext());
  2869. }
  2870. IThorRowInterfaces * CActivityBase::createRowInterfaces(IOutputMetaData * meta, roxiemem::RoxieHeapFlags heapFlags, byte seq)
  2871. {
  2872. activity_id id = createCompoundActSeqId(queryId(), seq);
  2873. return createThorRowInterfaces(queryRowManager(), meta, id, heapFlags, queryCodeContext());
  2874. }
  2875. bool CActivityBase::fireException(IException *e)
  2876. {
  2877. Owned<IThorException> _te;
  2878. IThorException *te = QUERYINTERFACE(e, IThorException);
  2879. if (te)
  2880. {
  2881. if (!te->queryActivityId())
  2882. setExceptionActivityInfo(container, te);
  2883. }
  2884. else
  2885. {
  2886. te = MakeActivityException(this, e);
  2887. te->setAudience(e->errorAudience());
  2888. _te.setown(te);
  2889. }
  2890. return container.queryOwner().fireException(te);
  2891. }
  2892. void CActivityBase::processAndThrowOwnedException(IException * _e)
  2893. {
  2894. IThorException *e = QUERYINTERFACE(_e, IThorException);
  2895. if (e)
  2896. {
  2897. if (!e->queryActivityId())
  2898. setExceptionActivityInfo(container, e);
  2899. }
  2900. else
  2901. {
  2902. e = MakeActivityException(this, _e);
  2903. _e->Release();
  2904. }
  2905. throw e;
  2906. }
  2907. IEngineRowAllocator * CActivityBase::queryRowAllocator()
  2908. {
  2909. if (CABallocatorlock.lock()) {
  2910. if (!rowAllocator)
  2911. {
  2912. roxiemem::RoxieHeapFlags heapFlags = queryHeapFlags();
  2913. rowAllocator.setown(getRowAllocator(queryRowMetaData(), heapFlags));
  2914. }
  2915. CABallocatorlock.unlock();
  2916. }
  2917. return rowAllocator;
  2918. }
  2919. IOutputRowSerializer * CActivityBase::queryRowSerializer()
  2920. {
  2921. if (CABserializerlock.lock()) {
  2922. if (!rowSerializer)
  2923. rowSerializer.setown(queryRowMetaData()->createDiskSerializer(queryCodeContext(),queryId()));
  2924. CABserializerlock.unlock();
  2925. }
  2926. return rowSerializer;
  2927. }
  2928. IOutputRowDeserializer * CActivityBase::queryRowDeserializer()
  2929. {
  2930. if (CABdeserializerlock.lock()) {
  2931. if (!rowDeserializer)
  2932. rowDeserializer.setown(queryRowMetaData()->createDiskDeserializer(queryCodeContext(),queryId()));
  2933. CABdeserializerlock.unlock();
  2934. }
  2935. return rowDeserializer;
  2936. }
  2937. IThorRowInterfaces *CActivityBase::getRowInterfaces()
  2938. {
  2939. // create an independent instance, to avoid circular link dependency problems
  2940. return createThorRowInterfaces(queryRowManager(), queryRowMetaData(), container.queryId(), queryHeapFlags(), queryCodeContext());
  2941. }
  2942. IEngineRowAllocator *CActivityBase::getRowAllocator(IOutputMetaData * meta, roxiemem::RoxieHeapFlags flags, byte seq) const
  2943. {
  2944. activity_id actId = createCompoundActSeqId(queryId(), seq);
  2945. return queryJobChannel().getRowAllocator(meta, actId, flags);
  2946. }
  2947. bool CActivityBase::receiveMsg(ICommunicator &comm, CMessageBuffer &mb, const rank_t rank, const mptag_t mpTag, rank_t *sender, unsigned timeout)
  2948. {
  2949. BooleanOnOff onOff(receiving);
  2950. CTimeMon t(timeout);
  2951. unsigned remaining = timeout;
  2952. // check 'cancelledReceive' every 10 secs
  2953. while (!cancelledReceive && ((MP_WAIT_FOREVER==timeout) || !t.timedout(&remaining)))
  2954. {
  2955. if (comm.recv(mb, rank, mpTag, sender, remaining>10000?10000:remaining))
  2956. return true;
  2957. }
  2958. return false;
  2959. }
  2960. bool CActivityBase::receiveMsg(CMessageBuffer &mb, const rank_t rank, const mptag_t mpTag, rank_t *sender, unsigned timeout)
  2961. {
  2962. return receiveMsg(queryJobChannel().queryJobComm(), mb, rank, mpTag, sender, timeout);
  2963. }
  2964. void CActivityBase::cancelReceiveMsg(ICommunicator &comm, const rank_t rank, const mptag_t mpTag)
  2965. {
  2966. cancelledReceive = true;
  2967. if (receiving)
  2968. comm.cancel(rank, mpTag);
  2969. }
  2970. void CActivityBase::cancelReceiveMsg(const rank_t rank, const mptag_t mpTag)
  2971. {
  2972. cancelReceiveMsg(queryJobChannel().queryJobComm(), rank, mpTag);
  2973. }