thgraph.cpp 99 KB

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