thgraph.cpp 97 KB

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