ccdcontext.cpp 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2013 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 "platform.h"
  14. #include "jlib.hpp"
  15. #include "wujobq.hpp"
  16. #include "nbcd.hpp"
  17. #include "rtlread_imp.hpp"
  18. #include "thorplugin.hpp"
  19. #include "thorxmlread.hpp"
  20. #include "roxiemem.hpp"
  21. #include "eventqueue.hpp"
  22. #include "ccd.hpp"
  23. #include "ccdcontext.hpp"
  24. #include "ccddebug.hpp"
  25. #include "ccddali.hpp"
  26. #include "ccdquery.hpp"
  27. #include "ccdqueue.ipp"
  28. #include "ccdsnmp.hpp"
  29. #include "ccdstate.hpp"
  30. #include "roxiehelper.hpp"
  31. using roxiemem::IRowManager;
  32. //=======================================================================================================================
  33. #define DEBUGEE_TIMEOUT 10000
  34. class CSlaveDebugContext : public CBaseDebugContext
  35. {
  36. /*
  37. Some thoughts on slave debugging
  38. 1. Something like a ping can be used to get data from slave when needed
  39. 2. Should disable IBYTI processing (always use primary) - DONE
  40. and server-side caching - DONE
  41. 3. Roxie server can know what slave transactions are pending by intercepting the sends - no need for slave to call back just to indicate start of slave subgraph
  42. 4. There is a problem when a slave hits a breakpoint in that the breakpoint cound have been deleted by the time it gets a chance to tell the Roxie server - can't
  43. happen in local case because of the critical block at the head of checkBreakpoint but the local copy of BPs out on slave CAN get out of date. Should we care?
  44. Should there be a "Sorry, your breakpoints are out of date, here's the new set" response?
  45. Actually what we do is recheck the BP on the server, and ensure that breakpoint indexes are persistant. DONE
  46. 5. We need to serialize over our graph info if changed since last time.
  47. 6. I think we need to change implementation of debugGraph to support children. Then we have a place to put a proxy for a remote one.
  48. - id's should probably be structured so we can use a hash table at each level
  49. */
  50. const RoxiePacketHeader &header;
  51. memsize_t parentActivity;
  52. unsigned channel;
  53. int debugSequence;
  54. CriticalSection crit;
  55. const IRoxieContextLogger &logctx; // hides base class definition with more derived class pointer
  56. public:
  57. CSlaveDebugContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx, RoxiePacketHeader &_header)
  58. : CBaseDebugContext(_logctx), header(_header), logctx(_logctx)
  59. {
  60. channel = header.channel;
  61. debugSequence = 0;
  62. parentActivity = 0;
  63. }
  64. void init(const IRoxieQueryPacket *_packet)
  65. {
  66. unsigned traceLength = _packet->getTraceLength();
  67. assertex(traceLength);
  68. const byte *traceInfo = _packet->queryTraceInfo();
  69. assertex((*traceInfo & LOGGING_DEBUGGERACTIVE) != 0);
  70. unsigned debugLen = *(unsigned short *) (traceInfo + 1);
  71. MemoryBuffer b;
  72. b.setBuffer(debugLen, (char *) (traceInfo + 1 + sizeof(unsigned short)), false);
  73. deserialize(b);
  74. __uint64 tmp; // can't serialize memsize_t
  75. b.read(tmp); // note - this is written by the RemoteAdaptor not by the serialize....
  76. parentActivity = (memsize_t)tmp;
  77. }
  78. virtual unsigned queryChannel() const
  79. {
  80. return channel;
  81. }
  82. virtual BreakpointActionMode checkBreakpoint(DebugState state, IActivityDebugContext *probe, const void *extra)
  83. {
  84. return CBaseDebugContext::checkBreakpoint(state, probe, extra);
  85. }
  86. virtual void waitForDebugger(DebugState state, IActivityDebugContext *probe)
  87. {
  88. StringBuffer debugIdString;
  89. CriticalBlock b(crit); // Make sure send sequentially - don't know if this is strictly needed...
  90. debugSequence++;
  91. debugIdString.appendf(".debug.%x", debugSequence);
  92. IPendingCallback *callback = ROQ->notePendingCallback(header, debugIdString.str()); // note that we register before the send to avoid a race.
  93. try
  94. {
  95. RoxiePacketHeader newHeader(header, ROXIE_DEBUGCALLBACK);
  96. loop // retry indefinately, as more than likely Roxie server is waiting for user input ...
  97. {
  98. Owned<IMessagePacker> output = ROQ->createOutputStream(newHeader, true, logctx);
  99. // These are deserialized in onDebugCallback..
  100. MemoryBuffer debugInfo;
  101. debugInfo.append(debugSequence);
  102. debugInfo.append((char) state);
  103. if (state==DebugStateGraphFinished)
  104. {
  105. debugInfo.append(globalCounts.count());
  106. HashIterator edges(globalCounts);
  107. ForEach(edges)
  108. {
  109. IGlobalEdgeRecord *edge = globalCounts.mapToValue(&edges.query());
  110. debugInfo.append((const char *) edges.query().getKey());
  111. debugInfo.append(edge->queryCount());
  112. }
  113. }
  114. debugInfo.append(currentBreakpointUID);
  115. debugInfo.append((__uint64)parentActivity); // can't serialize memsize_t
  116. debugInfo.append(channel);
  117. assertex (currentGraph); // otherwise what am I remote debugging?
  118. currentGraph->serializeProxyGraphs(debugInfo);
  119. debugInfo.append(probe ? probe->queryEdgeId() : "");
  120. char *buf = (char *) output->getBuffer(debugInfo.length(), true);
  121. memcpy(buf, debugInfo.toByteArray(), debugInfo.length());
  122. output->putBuffer(buf, debugInfo.length(), true);
  123. output->flush(true);
  124. output.clear();
  125. if (callback->wait(5000))
  126. break;
  127. }
  128. if (traceLevel > 6)
  129. { StringBuffer s; DBGLOG("Processing information from Roxie server in response to %s", newHeader.toString(s).str()); }
  130. MemoryBuffer &serverData = callback->queryData();
  131. deserialize(serverData);
  132. }
  133. catch (...)
  134. {
  135. ROQ->removePendingCallback(callback);
  136. throw;
  137. }
  138. ROQ->removePendingCallback(callback);
  139. }
  140. virtual IRoxieQueryPacket *onDebugCallback(const RoxiePacketHeader &header, size32_t len, char *data)
  141. {
  142. // MORE - Implies a server -> slave child -> slave grandchild type situation - need to pass call on to Roxie server (rather as I do for file callback)
  143. UNIMPLEMENTED;
  144. }
  145. virtual bool onDebuggerTimeout()
  146. {
  147. throwUnexpected();
  148. }
  149. virtual void debugCounts(IXmlWriter *output, unsigned sinceSequence, bool reset)
  150. {
  151. // This gives info for the global view - accumulated counts for all instances, plus the graph as fetched from the workunit
  152. HashIterator edges(globalCounts);
  153. ForEach(edges)
  154. {
  155. IGlobalEdgeRecord *edge = globalCounts.mapToValue(&edges.query());
  156. if (edge->queryLastSequence() && (!sinceSequence || edge->queryLastSequence() > sinceSequence))
  157. {
  158. output->outputBeginNested("edge", true);
  159. output->outputCString((const char *) edges.query().getKey(), "@edgeId");
  160. output->outputUInt(edge->queryCount(), "@count");
  161. output->outputEndNested("edge");
  162. }
  163. if (reset)
  164. edge->reset();
  165. }
  166. }
  167. };
  168. //=======================================================================================================================
  169. #define DEFAULT_PERSIST_COPIES (-1)
  170. #define PERSIST_LOCK_TIMEOUT 10000
  171. #define PERSIST_LOCK_SLEEP 5000
  172. class CRoxieWorkflowMachine : public WorkflowMachine
  173. {
  174. class PersistVersion : public CInterface
  175. {
  176. public:
  177. PersistVersion(char const * _logicalName, unsigned _eclCRC, unsigned __int64 _allCRC, bool _isFile) : logicalName(_logicalName), eclCRC(_eclCRC), allCRC(_allCRC), isFile(_isFile) {}
  178. StringAttr logicalName;
  179. unsigned eclCRC;
  180. unsigned __int64 allCRC;
  181. bool isFile;
  182. };
  183. public:
  184. CRoxieWorkflowMachine(IPropertyTree *_workflowInfo, IConstWorkUnit *_wu, bool _doOnce, const IRoxieContextLogger &_logctx)
  185. : WorkflowMachine(_logctx)
  186. {
  187. workunit = _wu;
  188. workflowInfo = _workflowInfo;
  189. doOnce = _doOnce;
  190. }
  191. void returnPersistVersion(char const * logicalName, unsigned eclCRC, unsigned __int64 allCRC, bool isFile)
  192. {
  193. persist.setown(new PersistVersion(logicalName, eclCRC, allCRC, isFile));
  194. }
  195. protected:
  196. virtual void begin()
  197. {
  198. // MORE - should pre-do more of this work
  199. unsigned count = 0;
  200. Owned<IConstWorkflowItemIterator> iter = createWorkflowItemIterator(workflowInfo);
  201. for(iter->first(); iter->isValid(); iter->next())
  202. count++;
  203. workflow.setown(createWorkflowItemArray(count));
  204. for(iter->first(); iter->isValid(); iter->next())
  205. {
  206. IConstWorkflowItem *item = iter->query();
  207. bool isOnce = (item->queryMode() == WFModeOnce);
  208. workflow->addClone(item);
  209. if (isOnce != doOnce)
  210. workflow->queryWfid(item->queryWfid()).setState(WFStateDone);
  211. }
  212. }
  213. virtual void end()
  214. {
  215. workflow.clear();
  216. }
  217. virtual void schedulingStart() { throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Scheduling not supported in roxie"); }
  218. virtual bool schedulingPull() { throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Scheduling not supported in roxie"); }
  219. virtual bool schedulingPullStop() { throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Scheduling not supported in roxie"); }
  220. virtual void reportContingencyFailure(char const * type, IException * e) {}
  221. virtual void checkForAbort(unsigned wfid, IException * handling) {}
  222. virtual void doExecutePersistItem(IRuntimeWorkflowItem & item)
  223. {
  224. if (!workunit)
  225. {
  226. throw MakeStringException(0, "PERSIST not supported when running predeployed queries");
  227. }
  228. unsigned wfid = item.queryWfid();
  229. // Old persist model requires dependencies to be executed BEFORE checking if the persist is up to date
  230. // Defaults to old model, in case executing a WU that is created by earlier eclcc
  231. if (!workunit->getDebugValueBool("expandPersistInputDependencies", false))
  232. doExecuteItemDependencies(item, wfid);
  233. SCMStringBuffer name;
  234. const char *logicalName = item.getPersistName(name).str();
  235. int maxPersistCopies = item.queryPersistCopies();
  236. if (maxPersistCopies < 0)
  237. maxPersistCopies = DEFAULT_PERSIST_COPIES;
  238. Owned<IRemoteConnection> persistLock;
  239. persistLock.setown(startPersist(logicalName));
  240. doExecuteItemDependency(item, item.queryPersistWfid(), wfid, true); // generated code should end up calling back to returnPersistVersion, which sets persist
  241. if (!persist)
  242. {
  243. StringBuffer errmsg;
  244. errmsg.append("Internal error in generated code: for wfid ").append(wfid).append(", persist CRC wfid ").append(item.queryPersistWfid()).append(" did not call returnPersistVersion");
  245. throw MakeStringExceptionDirect(0, errmsg.str());
  246. }
  247. Owned<PersistVersion> thisPersist = persist.getClear();
  248. if (strcmp(logicalName, thisPersist->logicalName.get()) != 0)
  249. {
  250. StringBuffer errmsg;
  251. errmsg.append("Failed workflow/persist consistency check: wfid ").append(wfid).append(", WU persist name ").append(logicalName).append(", runtime persist name ").append(thisPersist->logicalName.get());
  252. throw MakeStringExceptionDirect(0, errmsg.str());
  253. }
  254. if (workunit->getDebugValueInt("freezepersists", 0) != 0)
  255. {
  256. checkPersistMatches(logicalName, thisPersist->eclCRC);
  257. }
  258. else if(!isPersistUptoDate(persistLock, logicalName, thisPersist->eclCRC, thisPersist->allCRC, thisPersist->isFile))
  259. {
  260. // New persist model allows dependencies to be executed AFTER checking if the persist is up to date
  261. if (workunit->getDebugValueBool("expandPersistInputDependencies", false))
  262. doExecuteItemDependencies(item, wfid);
  263. if (maxPersistCopies > 0)
  264. deleteLRUPersists(logicalName, (unsigned) maxPersistCopies-1);
  265. doExecuteItem(item, wfid);
  266. updatePersist(persistLock, logicalName, thisPersist->eclCRC, thisPersist->allCRC);
  267. }
  268. logctx.CTXLOG("Finished persists - add to read lock list");
  269. persistReadLocks.append(*persistLock);
  270. }
  271. private:
  272. bool isResult(const char *name, unsigned sequence)
  273. {
  274. Owned<IConstWUResult> r = getWorkUnitResult(workunit, name, sequence);
  275. return r != NULL && r->getResultStatus() != ResultStatusUndefined;
  276. }
  277. unsigned getResultHash(const char * name, unsigned sequence)
  278. {
  279. Owned<IConstWUResult> r = getWorkUnitResult(workunit, name, sequence);
  280. if (!r)
  281. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Failed to retrieve hash value %s from workunit", name);
  282. return r->getResultHash();
  283. }
  284. unsigned __int64 getResultInt(const char * name, unsigned sequence)
  285. {
  286. Owned<IConstWUResult> r = getWorkUnitResult(workunit, name, sequence);
  287. if (!r)
  288. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Failed to retrieve persist value %s from workunit", name);
  289. return r->getResultInt();
  290. }
  291. void setResultInt(const char * name, unsigned sequence, unsigned __int64 value)
  292. {
  293. WorkunitUpdate w(&workunit->lock());
  294. w->setResultInt(name, sequence, value);
  295. }
  296. inline bool fileExists(const char *lfn)
  297. {
  298. Owned<IDistributedFile> f = queryDistributedFileDirectory().lookup(lfn, NULL); // MORE - need a userdescriptor from workunit
  299. if (f)
  300. return true;
  301. return false;
  302. }
  303. inline IUserDescriptor *queryUserDescriptor()
  304. {
  305. return workunit->queryUserDescriptor();
  306. }
  307. bool checkPersistUptoDate(const char * logicalName, unsigned eclCRC, unsigned __int64 allCRC, bool isFile, StringBuffer &errText)
  308. {
  309. StringBuffer lfn, crcName, eclName;
  310. expandLogicalFilename(lfn, logicalName, workunit, false);
  311. crcName.append(lfn).append("$crc");
  312. eclName.append(lfn).append("$eclcrc");
  313. if (!isResult(lfn, ResultSequencePersist))
  314. errText.appendf("Building PERSIST('%s'): It hasn't been calculated before", logicalName);
  315. else if (!isResult(crcName, ResultSequencePersist))
  316. errText.appendf("Rebuilding PERSIST('%s'): Saved CRC isn't present", logicalName);
  317. else if (isFile && !fileExists(lfn))
  318. errText.appendf("Rebuilding PERSIST('%s'): Persistent file does not exist", logicalName);
  319. else
  320. {
  321. unsigned savedEclCRC = (unsigned) getResultInt(eclName, ResultSequencePersist);
  322. unsigned __int64 savedCRC = (unsigned __int64)getResultInt(crcName, ResultSequencePersist);
  323. if (savedEclCRC != eclCRC)
  324. errText.appendf("Rebuilding PERSIST('%s'): ECL has changed", logicalName);
  325. else if (savedCRC != allCRC)
  326. errText.appendf("Rebuilding PERSIST('%s'): Input files have changed", logicalName);
  327. else
  328. return true;
  329. }
  330. return false;
  331. }
  332. bool changePersistLockMode(IRemoteConnection *persistLock, unsigned mode, const char * name, bool repeat)
  333. {
  334. logctx.CTXLOG("Waiting to change persist lock to %s for %s", (mode == RTM_LOCK_WRITE) ? "write" : "read", name); // MORE - pass a logctx around?
  335. //When converting a read lock to a write lock so the persist can be rebuilt hold onto the lock as short as
  336. //possible. Otherwise lots of workunits each trying to convert read locks to write locks will mean
  337. //that the read lock is never released by all the workunits at the same time, so no workunit can progress.
  338. unsigned timeout = repeat ? PERSIST_LOCK_TIMEOUT : 0;
  339. loop
  340. {
  341. try
  342. {
  343. persistLock->changeMode(mode, timeout);
  344. logctx.CTXLOG("Changed persist lock");
  345. return true;
  346. }
  347. catch(ISDSException *E)
  348. {
  349. if (SDSExcpt_LockTimeout != E->errorCode())
  350. throw E;
  351. E->Release();
  352. }
  353. if (!repeat)
  354. {
  355. logctx.CTXLOG("Failed to convert persist lock");
  356. return false;
  357. }
  358. //This is only executed when converting write->read. There is significant doubt whether the changeMode()
  359. //can ever fail - and whether the execution can ever get here.
  360. logctx.CTXLOG("Waiting to convert persist lock"); // MORE - give a chance to abort
  361. }
  362. }
  363. IRemoteConnection *getPersistReadLock(const char * logicalName)
  364. {
  365. StringBuffer lfn;
  366. expandLogicalFilename(lfn, logicalName, workunit, false);
  367. if (!lfn.length())
  368. throw MakeStringException(0, "Invalid persist name used : '%s'", logicalName);
  369. const char * name = lfn;
  370. StringBuffer xpath;
  371. xpath.append("/PersistRunLocks/");
  372. if (isdigit(*name))
  373. xpath.append("_");
  374. for (const char * cur = name;*cur;cur++)
  375. xpath.append(isalnum(*cur) ? *cur : '_');
  376. logctx.CTXLOG("Waiting for persist read lock for %s", name);
  377. Owned<IRemoteConnection> persistLock;
  378. loop
  379. {
  380. try
  381. {
  382. unsigned mode = RTM_CREATE_QUERY | RTM_LOCK_READ;
  383. if (queryDaliServerVersion().compare("1.4") >= 0)
  384. mode |= RTM_DELETE_ON_DISCONNECT;
  385. persistLock.setown(querySDS().connect(xpath.str(), myProcessSession(), mode, PERSIST_LOCK_TIMEOUT));
  386. }
  387. catch(ISDSException *E)
  388. {
  389. if (SDSExcpt_LockTimeout != E->errorCode())
  390. throw E;
  391. E->Release();
  392. }
  393. if (persistLock)
  394. break;
  395. logctx.CTXLOG("Waiting for persist read lock"); // MORE - give a chance to abort
  396. }
  397. logctx.CTXLOG("Obtained persist read lock");
  398. return persistLock.getClear();
  399. }
  400. void setBlockedOnPersist(const char * logicalName)
  401. {
  402. StringBuffer s;
  403. s.append("Waiting for persist ").append(logicalName);
  404. WorkunitUpdate w(&workunit->lock());
  405. w->setState(WUStateBlocked);
  406. w->setStateEx(s.str());
  407. }
  408. bool isPersistUptoDate(Owned<IRemoteConnection> &persistLock, const char * logicalName, unsigned eclCRC, unsigned __int64 allCRC, bool isFile)
  409. {
  410. //Loop trying to get a write lock - if it fails, then release the read lock, otherwise
  411. //you can get a deadlock with several things waiting to read, and none being able to write.
  412. bool rebuildAllPersists = false; // Useful for debugging purposes
  413. loop
  414. {
  415. StringBuffer dummy;
  416. if (checkPersistUptoDate(logicalName, eclCRC, allCRC, isFile, dummy) && !rebuildAllPersists)
  417. {
  418. logctx.CTXLOG("PERSIST('%s') is up to date", logicalName);
  419. return true;
  420. }
  421. //Get a write lock
  422. setBlockedOnPersist(logicalName);
  423. if (changePersistLockMode(persistLock, RTM_LOCK_WRITE, logicalName, false))
  424. break;
  425. //failed to get a write lock, so release our read lock
  426. persistLock.clear();
  427. MilliSleep(PERSIST_LOCK_SLEEP + (getRandom()%PERSIST_LOCK_SLEEP));
  428. persistLock.setown(getPersistReadLock(logicalName));
  429. }
  430. WorkunitUpdate w(&workunit->lock());
  431. w->setState(WUStateRunning);
  432. //Check again whether up to date, someone else might have updated it!
  433. StringBuffer errText;
  434. if (checkPersistUptoDate(logicalName, eclCRC, allCRC, isFile, errText) && !rebuildAllPersists)
  435. {
  436. logctx.CTXLOG("PERSIST('%s') is up to date (after being calculated by another job)", logicalName);
  437. changePersistLockMode(persistLock, RTM_LOCK_READ, logicalName, true);
  438. return true;
  439. }
  440. if (errText.length())
  441. logctx.CTXLOG("%s", errText.str());
  442. return false;
  443. }
  444. void updatePersist(IRemoteConnection *persistLock, const char * logicalName, unsigned eclCRC, unsigned __int64 allCRC)
  445. {
  446. StringBuffer lfn, crcName, eclName;
  447. expandLogicalFilename(lfn, logicalName, workunit, false);
  448. crcName.append(lfn).append("$crc");
  449. eclName.append(lfn).append("$eclcrc");
  450. setResultInt(crcName, ResultSequencePersist, allCRC);
  451. setResultInt(eclName, ResultSequencePersist, eclCRC);
  452. logctx.CTXLOG("Convert persist write lock to read lock");
  453. changePersistLockMode(persistLock, RTM_LOCK_READ, logicalName, true);
  454. }
  455. IRemoteConnection *startPersist(const char * logicalName)
  456. {
  457. setBlockedOnPersist(logicalName);
  458. IRemoteConnection *persistLock = getPersistReadLock(logicalName);
  459. WorkunitUpdate w(&workunit->lock());
  460. w->setState(WUStateRunning);
  461. return persistLock;
  462. }
  463. void checkPersistMatches(const char * logicalName, unsigned eclCRC)
  464. {
  465. StringBuffer lfn, eclName;
  466. expandLogicalFilename(lfn, logicalName, workunit, true);
  467. eclName.append(lfn).append("$eclcrc");
  468. if (!isResult(lfn, ResultSequencePersist))
  469. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Frozen PERSIST('%s') hasn't been calculated ", logicalName);
  470. if (isResult(eclName, ResultSequencePersist) && (getResultInt(eclName, ResultSequencePersist) != eclCRC))
  471. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Frozen PERSIST('%s') ECL has changed", logicalName);
  472. StringBuffer msg;
  473. msg.append("Frozen PERSIST('").append(logicalName).append("') is up to date");
  474. logctx.CTXLOG("%s", msg.str());
  475. }
  476. static int comparePersistAccess(IInterface **_a, IInterface **_b)
  477. {
  478. IPropertyTree *a = *(IPropertyTree **)_a;
  479. IPropertyTree *b = *(IPropertyTree **)_b;
  480. const char *accessedA = a->queryProp("@accessed");
  481. const char *accessedB = b->queryProp("@accessed");
  482. if (accessedA && accessedB)
  483. return strcmp(accessedB, accessedA);
  484. else if (accessedB)
  485. return -1;
  486. else if (accessedA)
  487. return 1;
  488. else
  489. return 0;
  490. }
  491. void deleteLRUPersists(const char * logicalName, unsigned keep)
  492. {
  493. StringBuffer lfn;
  494. expandLogicalFilename(lfn, logicalName, workunit, false);
  495. logicalName = lfn.str();
  496. const char *tail = strrchr(logicalName, '_'); // Locate the trailing double-underbar
  497. assertex(tail);
  498. StringBuffer head(tail-logicalName+1, logicalName);
  499. head.append("p*"); // Multi-mode persist names end with __pNNNNNNN
  500. restart: // If things change beneath us as we are deleting, repeat the process
  501. IArrayOf<IPropertyTree> persists;
  502. Owned<IDFAttributesIterator> iter = queryDistributedFileDirectory().getDFAttributesIterator(head,queryUserDescriptor(),false,false,NULL);
  503. ForEach(*iter)
  504. {
  505. IPropertyTree &pt = iter->query();
  506. const char *name = pt.queryProp("@name");
  507. if (stricmp(name, logicalName) == 0) // Don't include the one we are intending to recreate in the LRU list (keep value does not include it)
  508. continue;
  509. if (pt.getPropBool("@persistent", false))
  510. {
  511. // Paranoia - check as far as we can that it really is another instance of this persist
  512. tail = strrchr(name, '_'); // Locate the trailing double-underbar
  513. assertex(tail);
  514. tail++;
  515. bool crcSuffix = (*tail++=='p');
  516. while (crcSuffix && *tail)
  517. {
  518. if (!isdigit(*tail))
  519. crcSuffix = false;
  520. tail++;
  521. }
  522. if (crcSuffix)
  523. persists.append(*LINK(&pt));
  524. }
  525. }
  526. if (persists.ordinality() > keep)
  527. {
  528. persists.sort(comparePersistAccess);
  529. while (persists.ordinality() > keep)
  530. {
  531. Owned<IPropertyTree> oldest = &persists.popGet();
  532. const char *oldAccessTime = oldest->queryProp("@accessed");
  533. VStringBuffer goer("~%s", oldest->queryProp("@name")); // Make sure we don't keep adding the scope
  534. Owned<IRemoteConnection> persistLock = getPersistReadLock(goer);
  535. while (!changePersistLockMode(persistLock, RTM_LOCK_WRITE, goer, false))
  536. {
  537. persistLock.clear();
  538. MilliSleep(PERSIST_LOCK_SLEEP + (getRandom()%PERSIST_LOCK_SLEEP));
  539. persistLock.setown(getPersistReadLock(goer));
  540. }
  541. Owned<IDistributedFile> f = queryDistributedFileDirectory().lookup(goer, queryUserDescriptor(), true);
  542. if (!f)
  543. goto restart; // Persist has been deleted since last checked - repeat the whole process
  544. const char *newAccessTime = f->queryAttributes().queryProp("@accessed");
  545. if (oldAccessTime && newAccessTime && !streq(oldAccessTime, newAccessTime))
  546. goto restart; // Persist has been accessed since last checked - repeat the whole process
  547. else if (newAccessTime && !oldAccessTime)
  548. goto restart; // Persist has been accessed since last checked - repeat the whole process
  549. DBGLOG("Deleting LRU persist %s (last accessed at %s)", goer.str(), oldAccessTime);
  550. f->detach();
  551. }
  552. }
  553. }
  554. IConstWorkUnit *workunit;
  555. IPropertyTree *workflowInfo;
  556. Owned<PersistVersion> persist;
  557. Array persistReadLocks;
  558. bool doOnce;
  559. };
  560. CRoxieWorkflowMachine *createRoxieWorkflowMachine(IPropertyTree *_workflowInfo, IConstWorkUnit *_wu, bool _doOnce, const IRoxieContextLogger &_logctx)
  561. {
  562. return new CRoxieWorkflowMachine(_workflowInfo, _wu, _doOnce, _logctx);
  563. }
  564. //=======================================================================================================================
  565. typedef byte *row_t;
  566. typedef row_t * rowset_t;
  567. class DeserializedDataReader : public CInterface, implements IWorkUnitRowReader
  568. {
  569. const rowset_t data;
  570. size32_t count;
  571. unsigned idx;
  572. public:
  573. IMPLEMENT_IINTERFACE;
  574. DeserializedDataReader(size32_t _count, rowset_t _data)
  575. : data(_data), count(_count)
  576. {
  577. idx = 0;
  578. }
  579. virtual const void * nextInGroup()
  580. {
  581. if (idx < count)
  582. {
  583. const void *row = data[idx];
  584. if (row)
  585. LinkRoxieRow(row);
  586. idx++;
  587. return row;
  588. }
  589. return NULL;
  590. }
  591. virtual void getResultRowset(size32_t & tcount, byte * * & tgt)
  592. {
  593. tcount = count;
  594. if (data)
  595. rtlLinkRowset(data);
  596. tgt = data;
  597. }
  598. };
  599. class CDeserializedResultStore : public CInterface, implements IDeserializedResultStore
  600. {
  601. PointerArrayOf<row_t> stored;
  602. UnsignedArray counts;
  603. PointerIArrayOf<IOutputMetaData> metas;
  604. mutable SpinLock lock;
  605. public:
  606. IMPLEMENT_IINTERFACE;
  607. ~CDeserializedResultStore()
  608. {
  609. ForEachItemIn(idx, stored)
  610. {
  611. rowset_t rows = stored.item(idx);
  612. if (rows)
  613. {
  614. rtlReleaseRowset(counts.item(idx), (byte**) rows);
  615. }
  616. }
  617. }
  618. virtual int addResult(size32_t count, rowset_t data, IOutputMetaData *meta)
  619. {
  620. SpinBlock b(lock);
  621. stored.append(data);
  622. counts.append(count);
  623. metas.append(meta);
  624. return stored.ordinality()-1;
  625. }
  626. virtual void queryResult(int id, size32_t &count, rowset_t &data) const
  627. {
  628. count = counts.item(id);
  629. data = stored.item(id);
  630. }
  631. virtual IWorkUnitRowReader *createDeserializedReader(int id) const
  632. {
  633. return new DeserializedDataReader(counts.item(id), stored.item(id));
  634. }
  635. virtual void serialize(unsigned & tlen, void * & tgt, int id, ICodeContext *codectx) const
  636. {
  637. IOutputMetaData *meta = metas.item(id);
  638. rowset_t data = stored.item(id);
  639. size32_t count = counts.item(id);
  640. MemoryBuffer result;
  641. Owned<IOutputRowSerializer> rowSerializer = meta->createDiskSerializer(codectx, 0); // NOTE - we don't have a meaningful activity id. Only used for error reporting.
  642. bool grouped = meta->isGrouped();
  643. for (size32_t idx = 0; idx<count; idx++)
  644. {
  645. const byte *row = data[idx];
  646. if (grouped && idx)
  647. result.append(row == NULL);
  648. if (row)
  649. {
  650. CThorDemoRowSerializer serializerTarget(result);
  651. rowSerializer->serialize(serializerTarget, row);
  652. }
  653. }
  654. tlen = result.length();
  655. tgt= result.detach();
  656. }
  657. };
  658. extern IDeserializedResultStore *createDeserializedResultStore()
  659. {
  660. return new CDeserializedResultStore;
  661. }
  662. class WorkUnitRowReaderBase : public CInterface, implements IWorkUnitRowReader
  663. {
  664. protected:
  665. Linked<IEngineRowAllocator> rowAllocator;
  666. bool isGrouped;
  667. public:
  668. IMPLEMENT_IINTERFACE;
  669. WorkUnitRowReaderBase(IEngineRowAllocator *_rowAllocator, bool _isGrouped)
  670. : rowAllocator(_rowAllocator), isGrouped(_isGrouped)
  671. {
  672. }
  673. virtual void getResultRowset(size32_t & tcount, byte * * & tgt)
  674. {
  675. bool atEOG = true;
  676. RtlLinkedDatasetBuilder builder(rowAllocator);
  677. loop
  678. {
  679. const void *ret = nextInGroup();
  680. if (!ret)
  681. {
  682. if (atEOG || !isGrouped)
  683. break;
  684. atEOG = true;
  685. }
  686. else
  687. atEOG = false;
  688. builder.appendOwn(ret);
  689. }
  690. tcount = builder.getcount();
  691. tgt = builder.linkrows();
  692. }
  693. };
  694. class RawDataReader : public WorkUnitRowReaderBase
  695. {
  696. protected:
  697. const IRoxieContextLogger &logctx;
  698. byte *bufferBase;
  699. MemoryBuffer blockBuffer;
  700. Owned<ISerialStream> bufferStream;
  701. CThorStreamDeserializerSource rowSource;
  702. bool eof;
  703. bool eogPending;
  704. Owned<IOutputRowDeserializer> rowDeserializer;
  705. virtual bool nextBlock(unsigned & tlen, void * & tgt, void * & base) = 0;
  706. bool reload()
  707. {
  708. free(bufferBase);
  709. size32_t lenData;
  710. bufferBase = NULL;
  711. void *tempData, *base;
  712. eof = !nextBlock(lenData, tempData, base);
  713. bufferBase = (byte *) base;
  714. blockBuffer.setBuffer(lenData, tempData, false);
  715. return !eof;
  716. }
  717. public:
  718. RawDataReader(ICodeContext *codeContext, IEngineRowAllocator *_rowAllocator, bool _isGrouped, const IRoxieContextLogger &_logctx)
  719. : WorkUnitRowReaderBase(_rowAllocator, _isGrouped), logctx(_logctx)
  720. {
  721. eof = false;
  722. eogPending = false;
  723. bufferBase = NULL;
  724. rowDeserializer.setown(rowAllocator->createDiskDeserializer(codeContext));
  725. bufferStream.setown(createMemoryBufferSerialStream(blockBuffer));
  726. rowSource.setStream(bufferStream);
  727. }
  728. ~RawDataReader()
  729. {
  730. if (bufferBase)
  731. free(bufferBase);
  732. }
  733. virtual const void *nextInGroup()
  734. {
  735. if (eof)
  736. return NULL;
  737. if (rowSource.eos() && !reload())
  738. return NULL;
  739. if (eogPending)
  740. {
  741. eogPending = false;
  742. return NULL;
  743. }
  744. #if 0
  745. // MORE - think a bit about what happens on incomplete rows - I think deserializer will throw an exception?
  746. unsigned thisSize = meta.getRecordSize(data+cursor);
  747. if (thisSize > lenData-cursor)
  748. {
  749. CTXLOG("invalid stored dataset - incomplete row at end");
  750. throw MakeStringException(ROXIE_DATA_ERROR, "invalid stored dataset - incomplete row at end");
  751. }
  752. #endif
  753. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  754. size32_t size = rowDeserializer->deserialize(rowBuilder, rowSource);
  755. if (isGrouped)
  756. rowSource.read(sizeof(bool), &eogPending);
  757. atomic_inc(&rowsIn);
  758. return rowBuilder.finalizeRowClear(size);
  759. }
  760. };
  761. class InlineRawDataReader : public RawDataReader
  762. {
  763. Linked<IPropertyTree> xml;
  764. public:
  765. InlineRawDataReader(ICodeContext *codeContext, IEngineRowAllocator *_rowAllocator, bool _isGrouped, const IRoxieContextLogger &_logctx, IPropertyTree *_xml)
  766. : RawDataReader(codeContext, _rowAllocator, _isGrouped, _logctx), xml(_xml)
  767. {
  768. }
  769. virtual bool nextBlock(unsigned & tlen, void * & tgt, void * & base)
  770. {
  771. base = tgt = NULL;
  772. if (xml)
  773. {
  774. MemoryBuffer result;
  775. xml->getPropBin(NULL, result);
  776. tlen = result.length();
  777. base = tgt = result.detach();
  778. xml.clear();
  779. return tlen != 0;
  780. }
  781. else
  782. {
  783. tlen = 0;
  784. return false;
  785. }
  786. }
  787. };
  788. class StreamedRawDataReader : public RawDataReader
  789. {
  790. SafeSocket &client;
  791. StringAttr id;
  792. offset_t offset;
  793. public:
  794. StreamedRawDataReader(ICodeContext *codeContext, IEngineRowAllocator *_rowAllocator, bool _isGrouped, const IRoxieContextLogger &_logctx, SafeSocket &_client, const char *_id)
  795. : RawDataReader(codeContext, _rowAllocator, _isGrouped, _logctx), client(_client), id(_id)
  796. {
  797. offset = 0;
  798. }
  799. virtual bool nextBlock(unsigned & tlen, void * & tgt, void * & base)
  800. {
  801. try
  802. {
  803. #ifdef FAKE_EXCEPTIONS
  804. if (offset > 0x10000)
  805. throw MakeStringException(ROXIE_INTERNAL_ERROR, "TEST EXCEPTION");
  806. #endif
  807. // Go request from the socket
  808. MemoryBuffer request;
  809. request.reserve(sizeof(size32_t));
  810. request.append('D');
  811. offset_t loffset = offset;
  812. _WINREV(loffset);
  813. request.append(sizeof(loffset), &loffset);
  814. request.append(strlen(id)+1, id);
  815. size32_t len = request.length() - sizeof(size32_t);
  816. len |= 0x80000000;
  817. _WINREV(len);
  818. *(size32_t *) request.toByteArray() = len;
  819. client.write(request.toByteArray(), request.length());
  820. // Note: I am the only thread reading (we only support a single input dataset in roxiepipe mode)
  821. MemoryBuffer reply;
  822. client.readBlock(reply, readTimeout);
  823. tlen = reply.length();
  824. // MORE - not very robust!
  825. // skip past block header
  826. if (tlen > 0)
  827. {
  828. tgt = base = reply.detach();
  829. tgt = ((char *)base) + 9;
  830. tgt = strchr((char *)tgt, '\0') + 1;
  831. tlen -= ((char *)tgt - (char *)base);
  832. offset += tlen;
  833. }
  834. else
  835. tgt = base = NULL;
  836. return tlen != 0;
  837. }
  838. catch (IException *E)
  839. {
  840. StringBuffer text;
  841. E->errorMessage(text);
  842. int errCode = E->errorCode();
  843. E->Release();
  844. IException *ee = MakeStringException(MSGAUD_internal, errCode, "%s", text.str());
  845. logctx.logOperatorException(ee, __FILE__, __LINE__, "Exception caught in RawDataReader::nextBlock");
  846. throw ee;
  847. }
  848. catch (...)
  849. {
  850. logctx.logOperatorException(NULL, __FILE__, __LINE__, "Unknown exception caught in RawDataReader::nextBlock");
  851. throw;
  852. }
  853. }
  854. };
  855. class WuResultDataReader : public RawDataReader
  856. {
  857. Owned<IConstWUResult> result;
  858. IXmlToRowTransformer *rowTransformer;
  859. public:
  860. WuResultDataReader(ICodeContext *codeContext, IEngineRowAllocator *_rowAllocator, bool _isGrouped, const IRoxieContextLogger &_logctx, IConstWUResult *_result, IXmlToRowTransformer *_rowTransformer)
  861. : RawDataReader(codeContext, _rowAllocator, _isGrouped, _logctx), result(_result), rowTransformer(_rowTransformer)
  862. {
  863. }
  864. virtual bool nextBlock(unsigned & tlen, void * & tgt, void * & base)
  865. {
  866. tgt = NULL;
  867. base = NULL;
  868. if (result)
  869. {
  870. Variable2IDataVal r(&tlen, &tgt);
  871. Owned<IXmlToRawTransformer> rawXmlTransformer = createXmlRawTransformer(rowTransformer);
  872. result->getResultRaw(r, rawXmlTransformer, NULL);
  873. base = tgt;
  874. result.clear();
  875. return tlen != 0;
  876. }
  877. else
  878. {
  879. tlen = 0;
  880. return false;
  881. }
  882. }
  883. };
  884. class InlineXmlDataReader : public WorkUnitRowReaderBase
  885. {
  886. Linked<IPropertyTree> xml;
  887. Owned <XmlColumnProvider> columns;
  888. Owned<IPropertyTreeIterator> rows;
  889. IXmlToRowTransformer &rowTransformer;
  890. public:
  891. IMPLEMENT_IINTERFACE;
  892. InlineXmlDataReader(IXmlToRowTransformer &_rowTransformer, IPropertyTree *_xml, IEngineRowAllocator *_rowAllocator, bool _isGrouped)
  893. : WorkUnitRowReaderBase(_rowAllocator, _isGrouped), xml(_xml), rowTransformer(_rowTransformer)
  894. {
  895. columns.setown(new XmlDatasetColumnProvider);
  896. rows.setown(xml->getElements("Row")); // NOTE - the 'hack for Gordon' as found in thorxmlread is not implemented here. Does it need to be ?
  897. rows->first();
  898. }
  899. virtual const void *nextInGroup()
  900. {
  901. if (rows->isValid())
  902. {
  903. columns->setRow(&rows->query());
  904. rows->next();
  905. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  906. NullDiskCallback callback;
  907. size_t outSize = rowTransformer.transform(rowBuilder, columns, &callback);
  908. return rowBuilder.finalizeRowClear(outSize);
  909. }
  910. return NULL;
  911. }
  912. };
  913. //---------------------------------------------------------------------------------------
  914. class CSlaveContext : public CInterface, implements IRoxieSlaveContext, implements ICodeContext, implements roxiemem::ITimeLimiter, implements IRowAllocatorMetaActIdCacheCallback
  915. {
  916. protected:
  917. mutable Owned<IRowAllocatorMetaActIdCache> allocatorMetaCache;
  918. Owned<IRowManager> rowManager; // NOTE: the order of destruction here is significant. For leak check to work destroy this BEFORE allAllocators, but after most other things
  919. Owned <IDebuggableContext> debugContext;
  920. const IQueryFactory *factory;
  921. Owned<IProbeManager> probeManager; // must be destroyed after childGraphs
  922. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  923. Owned<IActivityGraph> graph;
  924. unsigned priority;
  925. StringBuffer authToken;
  926. Owned<IPropertyTree> probeQuery;
  927. RoxiePacketHeader *header;
  928. unsigned lastWuAbortCheck;
  929. unsigned startTime;
  930. unsigned timeLimit;
  931. unsigned totSlavesReplyLen;
  932. unsigned ctxParallelJoinPreload;
  933. unsigned ctxFullKeyedJoinPreload;
  934. unsigned ctxKeyedJoinPreload;
  935. unsigned ctxConcatPreload;
  936. unsigned ctxFetchPreload;
  937. unsigned ctxPrefetchProjectPreload;
  938. bool traceActivityTimes;
  939. bool checkingHeap;
  940. bool timeActivities;
  941. Owned<IConstWorkUnit> workUnit;
  942. Owned<IRoxieDaliHelper> daliHelperLink;
  943. Owned<IDistributedFileTransaction> superfileTransaction;
  944. CriticalSection statsCrit;
  945. const ContextLogger &logctx;
  946. protected:
  947. CriticalSection resultsCrit;
  948. PointerIArrayOf<FlushingStringBuffer> resultMap;
  949. bool exceptionLogged;
  950. bool aborted;
  951. CriticalSection abortLock; // NOTE: we don't bother to get lock when just reading to see whether to abort
  952. Owned<IException> exception;
  953. static void _toXML(IPropertyTree *tree, StringBuffer &xgmml, unsigned indent)
  954. {
  955. if (tree->getPropInt("att[@name='_roxieStarted']/@value", 1) == 0)
  956. return;
  957. if (0 && tree->getPropInt("att[@name='_kind']/@value", 0) == 496)
  958. {
  959. Owned<IPropertyTreeIterator> sub = tree->getElements(".//att[@name='_roxieStarted']");
  960. bool foundOne = false;
  961. ForEach(*sub)
  962. {
  963. if (sub->query().getPropInt("@value", 1)==0)
  964. {
  965. foundOne = true;
  966. break;
  967. }
  968. }
  969. if (!foundOne)
  970. return;
  971. }
  972. const char *name = tree->queryName();
  973. xgmml.pad(indent).append('<').append(name);
  974. Owned<IAttributeIterator> it = tree->getAttributes(true);
  975. if (it->first())
  976. {
  977. do
  978. {
  979. const char *key = it->queryName();
  980. xgmml.append(' ').append(key+1).append("=\"");
  981. encodeXML(it->queryValue(), xgmml, ENCODE_NEWLINES);
  982. xgmml.append("\"");
  983. }
  984. while (it->next());
  985. }
  986. Owned<IPropertyTreeIterator> sub = tree->getElements("*", iptiter_sort);
  987. if (!sub->first())
  988. {
  989. xgmml.append("/>\n");
  990. }
  991. else
  992. {
  993. xgmml.append(">\n");
  994. for(; sub->isValid(); sub->next())
  995. _toXML(&sub->query(), xgmml, indent+1);
  996. xgmml.pad(indent).append("</").append(name).append(">\n");
  997. }
  998. }
  999. public:
  1000. IMPLEMENT_IINTERFACE;
  1001. CSlaveContext(const IQueryFactory *_factory, const ContextLogger &_logctx, unsigned _timeLimit, memsize_t _memoryLimit, IRoxieQueryPacket *_packet, bool _traceActivityTimes, bool _debuggerActive, bool _checkingHeap, bool _timeActivities=defaultTimeActivities)
  1002. : factory(_factory), logctx(_logctx)
  1003. {
  1004. if (_packet)
  1005. header = &_packet->queryHeader();
  1006. else
  1007. header = NULL;
  1008. timeLimit = _timeLimit;
  1009. startTime = lastWuAbortCheck = msTick();
  1010. ctxParallelJoinPreload = 0;
  1011. ctxFullKeyedJoinPreload = 0;
  1012. ctxKeyedJoinPreload = 0;
  1013. ctxConcatPreload = 0;
  1014. ctxFetchPreload = 0;
  1015. ctxPrefetchProjectPreload = 0;
  1016. traceActivityTimes = _traceActivityTimes;
  1017. persists = NULL;
  1018. temporaries = NULL;
  1019. deserializedResultStore = NULL;
  1020. rereadResults = NULL;
  1021. xmlStoredDatasetReadFlags = ptr_none;
  1022. if (_debuggerActive)
  1023. {
  1024. assertex(header);
  1025. CSlaveDebugContext *slaveDebugContext = new CSlaveDebugContext(this, logctx, *header);
  1026. slaveDebugContext->init(_packet);
  1027. debugContext.setown(slaveDebugContext);
  1028. probeManager.setown(createDebugManager(debugContext, "slaveDebugger"));
  1029. }
  1030. checkingHeap = _checkingHeap;
  1031. timeActivities = _timeActivities;
  1032. aborted = false;
  1033. exceptionLogged = false;
  1034. priority = 0;
  1035. totSlavesReplyLen = 0;
  1036. allocatorMetaCache.setown(createRowAllocatorCache(this));
  1037. rowManager.setown(roxiemem::createRowManager(_memoryLimit, this, logctx, allocatorMetaCache, false));
  1038. //MORE: If checking heap required then should have
  1039. //rowManager.setown(createCheckingHeap(rowManager)) or something similar.
  1040. }
  1041. ~CSlaveContext()
  1042. {
  1043. ::Release(rereadResults);
  1044. ::Release(persists);
  1045. ::Release(temporaries);
  1046. ::Release(deserializedResultStore);
  1047. }
  1048. // interface IRoxieServerContext
  1049. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  1050. {
  1051. logctx.noteStatistic(statCode, value, count);
  1052. }
  1053. virtual void CTXLOG(const char *format, ...) const
  1054. {
  1055. va_list args;
  1056. va_start(args, format);
  1057. logctx.CTXLOGva(format, args);
  1058. va_end(args);
  1059. }
  1060. virtual void CTXLOGva(const char *format, va_list args) const
  1061. {
  1062. logctx.CTXLOGva(format, args);
  1063. }
  1064. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  1065. {
  1066. logctx.CTXLOGa(category, prefix, text);
  1067. }
  1068. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  1069. {
  1070. va_list args;
  1071. va_start(args, format);
  1072. logctx.logOperatorExceptionVA(E, file, line, format, args);
  1073. va_end(args);
  1074. }
  1075. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  1076. {
  1077. logctx.logOperatorExceptionVA(E, file, line, format, args);
  1078. }
  1079. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  1080. {
  1081. va_list args;
  1082. va_start(args, format);
  1083. logctx.CTXLOGaeva(E, file, line, prefix, format, args);
  1084. va_end(args);
  1085. }
  1086. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  1087. {
  1088. logctx.CTXLOGaeva(E, file, line, prefix, format, args);
  1089. }
  1090. virtual void CTXLOGl(LogItem *log) const
  1091. {
  1092. if (log->isStatistics())
  1093. {
  1094. logctx.noteStatistic(log->getStatCode(), log->getStatValue(), (unsigned)log->getStatCount());
  1095. log->Release();
  1096. }
  1097. else
  1098. logctx.CTXLOGl(log);
  1099. }
  1100. virtual unsigned logString(const char *text) const
  1101. {
  1102. if (text && *text)
  1103. {
  1104. CTXLOG("USER: %s", text);
  1105. return strlen(text);
  1106. }
  1107. else
  1108. return 0;
  1109. }
  1110. virtual const IContextLogger &queryContextLogger() const
  1111. {
  1112. return logctx;
  1113. }
  1114. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1115. {
  1116. return logctx.getLogPrefix(ret);
  1117. }
  1118. virtual bool isIntercepted() const
  1119. {
  1120. return logctx.isIntercepted();
  1121. }
  1122. virtual bool isBlind() const
  1123. {
  1124. return logctx.isBlind();
  1125. }
  1126. virtual unsigned queryTraceLevel() const
  1127. {
  1128. return logctx.queryTraceLevel();
  1129. }
  1130. virtual void noteProcessed(const IRoxieContextLogger &activityContext, const IRoxieServerActivity *activity, unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  1131. {
  1132. if (traceActivityTimes)
  1133. {
  1134. StringBuffer text, prefix;
  1135. text.appendf("%s outputIdx %d processed %d total %d us local %d us",
  1136. getActivityText(activity->getKind()), _idx, _processed, (unsigned) (cycle_to_nanosec(_totalCycles)/1000), (unsigned)(cycle_to_nanosec(_localCycles)/1000));
  1137. activityContext.getLogPrefix(prefix);
  1138. CTXLOGa(LOG_TIMING, prefix.str(), text.str());
  1139. }
  1140. if (graphProgress)
  1141. {
  1142. IPropertyTree& nodeProgress = graphProgress->updateNode(activity->querySubgraphId(), activity->queryId());
  1143. nodeProgress.setPropInt64("@totalTime", (unsigned) (cycle_to_nanosec(_totalCycles)/1000));
  1144. nodeProgress.setPropInt64("@localTime", (unsigned) (cycle_to_nanosec(_localCycles)/1000));
  1145. if (_processed)
  1146. {
  1147. StringBuffer edgeId;
  1148. edgeId.append(activity->queryId()).append('_').append(_idx);
  1149. IPropertyTree& edgeProgress = graphProgress->updateEdge(activity->querySubgraphId(), edgeId.str());
  1150. edgeProgress.setPropInt64("@count", _processed);
  1151. }
  1152. }
  1153. }
  1154. virtual bool queryTraceActivityTimes() const
  1155. {
  1156. return traceActivityTimes;
  1157. }
  1158. virtual bool queryCheckingHeap() const
  1159. {
  1160. return checkingHeap;
  1161. }
  1162. virtual bool queryTimeActivities() const
  1163. {
  1164. return timeActivities;
  1165. }
  1166. virtual void checkAbort()
  1167. {
  1168. // MORE - really should try to apply limits at slave end too
  1169. #ifdef __linux__
  1170. if (linuxYield)
  1171. sched_yield();
  1172. #endif
  1173. #ifdef _DEBUG
  1174. if (shuttingDown)
  1175. throw MakeStringException(ROXIE_FORCE_SHUTDOWN, "Roxie is shutting down");
  1176. #endif
  1177. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  1178. {
  1179. CriticalBlock b(abortLock);
  1180. if (!exception)
  1181. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  1182. throw exception.getLink();
  1183. }
  1184. if (graph)
  1185. graph->checkAbort();
  1186. if (timeLimit && (msTick() - startTime > timeLimit))
  1187. {
  1188. unsigned oldLimit = timeLimit;
  1189. //timeLimit = 0; // to prevent exceptions in cleanup - this means only one arm gets stopped!
  1190. CriticalBlock b(abortLock);
  1191. IException *E = MakeStringException(ROXIE_TIMEOUT, "Query %s exceeded time limit (%d ms) - terminated", factory->queryQueryName(), oldLimit);
  1192. if (!exceptionLogged)
  1193. {
  1194. logOperatorException(E, NULL, 0, NULL);
  1195. exceptionLogged = true;
  1196. }
  1197. throw E;
  1198. }
  1199. if (workUnit && (msTick() - lastWuAbortCheck > 5000))
  1200. {
  1201. CriticalBlock b(abortLock);
  1202. if (workUnit->aborting())
  1203. {
  1204. if (!exception)
  1205. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  1206. throw exception.getLink();
  1207. }
  1208. lastWuAbortCheck = msTick();
  1209. }
  1210. }
  1211. virtual unsigned checkInterval() const
  1212. {
  1213. unsigned interval = MAX_ABORT_CHECK_INTERVAL;
  1214. if (timeLimit)
  1215. {
  1216. interval = timeLimit / 10;
  1217. if (interval < MIN_ABORT_CHECK_INTERVAL)
  1218. interval = MIN_ABORT_CHECK_INTERVAL;
  1219. if (interval > MAX_ABORT_CHECK_INTERVAL)
  1220. interval = MAX_ABORT_CHECK_INTERVAL;
  1221. }
  1222. return interval;
  1223. }
  1224. virtual void notifyAbort(IException *E)
  1225. {
  1226. CriticalBlock b(abortLock);
  1227. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  1228. {
  1229. aborted = true;
  1230. exception.set(E);
  1231. setWUState(WUStateAborting);
  1232. }
  1233. }
  1234. virtual void setWUState(WUState state)
  1235. {
  1236. if (workUnit)
  1237. {
  1238. WorkunitUpdate w(&workUnit->lock());
  1239. w->setState(state);
  1240. }
  1241. }
  1242. virtual bool checkWuAborted()
  1243. {
  1244. return workUnit && workUnit->aborting();
  1245. }
  1246. virtual unsigned parallelJoinPreload()
  1247. {
  1248. return ctxParallelJoinPreload;
  1249. }
  1250. virtual unsigned concatPreload()
  1251. {
  1252. return ctxConcatPreload;
  1253. }
  1254. virtual unsigned fetchPreload()
  1255. {
  1256. return ctxFetchPreload;
  1257. }
  1258. virtual unsigned fullKeyedJoinPreload()
  1259. {
  1260. return ctxFullKeyedJoinPreload;
  1261. }
  1262. virtual unsigned keyedJoinPreload()
  1263. {
  1264. return ctxKeyedJoinPreload;
  1265. }
  1266. virtual unsigned prefetchProjectPreload()
  1267. {
  1268. return ctxPrefetchProjectPreload;
  1269. }
  1270. const char *queryAuthToken()
  1271. {
  1272. return authToken.str();
  1273. }
  1274. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  1275. {
  1276. if (queryTraceLevel() > 10)
  1277. CTXLOG("CSlaveContext %p noteChildGraph %d=%p", this, id, childGraph);
  1278. childGraphs.setValue(id, childGraph);
  1279. }
  1280. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  1281. {
  1282. if (extra.embedded)
  1283. {
  1284. return factory->lookupGraph(extra.libraryName, probeManager, *this, parentActivity);
  1285. }
  1286. else
  1287. {
  1288. Owned<IQueryFactory> libraryQuery = factory->lookupLibrary(extra.libraryName, extra.interfaceHash, *this);
  1289. assertex(libraryQuery);
  1290. return libraryQuery->lookupGraph("graph1", probeManager, *this, parentActivity);
  1291. }
  1292. }
  1293. void beginGraph(const char *graphName)
  1294. {
  1295. if (debugContext)
  1296. {
  1297. probeManager.clear(); // Hack!
  1298. probeManager.setown(createDebugManager(debugContext, graphName));
  1299. debugContext->checkBreakpoint(DebugStateGraphCreate, NULL, graphName);
  1300. }
  1301. else if (probeAllRows || probeQuery != NULL)
  1302. probeManager.setown(createProbeManager());
  1303. graph.setown(factory->lookupGraph(graphName, probeManager, *this, NULL));
  1304. graph->onCreate(this, NULL); // MORE - is that right
  1305. if (debugContext)
  1306. debugContext->checkBreakpoint(DebugStateGraphStart, NULL, graphName);
  1307. }
  1308. Owned<IWUGraphProgress> graphProgress; // could make local to endGraph and pass to reset - might be cleaner
  1309. virtual void endGraph(cycle_t startCycles, bool aborting)
  1310. {
  1311. if (graph)
  1312. {
  1313. unsigned __int64 elapsedTime = cycle_to_nanosec(get_cycles_now() - startCycles);
  1314. if (debugContext)
  1315. debugContext->checkBreakpoint(aborting ? DebugStateGraphAbort : DebugStateGraphEnd, NULL, graph->queryName());
  1316. if (aborting)
  1317. graph->abort();
  1318. WorkunitUpdate progressWorkUnit(NULL);
  1319. Owned<IConstWUGraphProgress> progress;
  1320. if (workUnit)
  1321. {
  1322. progressWorkUnit.setown(&workUnit->lock());
  1323. progress.setown(progressWorkUnit->getGraphProgress(graph->queryName()));
  1324. graphProgress.setown(progress->update());
  1325. const char * graphName = graph->queryName();
  1326. StringBuffer graphDesc;
  1327. formatGraphTimerLabel(graphDesc, graphName);
  1328. updateWorkunitTimeStat(progressWorkUnit, "roxie", graphName, "time", graphDesc, elapsedTime, 1, 0);
  1329. }
  1330. graph->reset();
  1331. if (graphProgress)
  1332. {
  1333. graphProgress.clear();
  1334. progress.clear();
  1335. }
  1336. graph.clear();
  1337. childGraphs.kill();
  1338. }
  1339. }
  1340. void runGraph()
  1341. {
  1342. try
  1343. {
  1344. graph->execute();
  1345. if (probeQuery)
  1346. graph->getProbeResponse(probeQuery);
  1347. }
  1348. catch(...)
  1349. {
  1350. if (probeQuery)
  1351. graph->getProbeResponse(probeQuery);
  1352. throw;
  1353. }
  1354. }
  1355. virtual void executeGraph(const char * name, bool realThor, size32_t parentExtractSize, const void * parentExtract)
  1356. {
  1357. assertex(parentExtractSize == 0);
  1358. if (queryTraceLevel() > 8)
  1359. CTXLOG("Executing graph %s", name);
  1360. if (realThor)
  1361. {
  1362. executeThorGraph(name);
  1363. }
  1364. else
  1365. {
  1366. bool created = false;
  1367. cycle_t startCycles = get_cycles_now();
  1368. try
  1369. {
  1370. beginGraph(name);
  1371. created = true;
  1372. runGraph();
  1373. }
  1374. catch (IException *e)
  1375. {
  1376. if (e->errorAudience() == MSGAUD_operator)
  1377. EXCLOG(e, "Exception thrown in query - cleaning up"); // if an IException is throw let EXCLOG determine if a trap should be generated
  1378. else
  1379. {
  1380. StringBuffer s;
  1381. CTXLOG("Exception thrown in query - cleaning up: %d: %s", e->errorCode(), e->errorMessage(s).str());
  1382. }
  1383. if (created)
  1384. endGraph(startCycles, true);
  1385. CTXLOG("Done cleaning up");
  1386. throw;
  1387. }
  1388. catch (...)
  1389. {
  1390. CTXLOG("Exception thrown in query - cleaning up");
  1391. if (created)
  1392. endGraph(startCycles, true);
  1393. CTXLOG("Done cleaning up");
  1394. throw;
  1395. }
  1396. endGraph(startCycles, false);
  1397. }
  1398. }
  1399. virtual IActivityGraph * queryChildGraph(unsigned id)
  1400. {
  1401. if (queryTraceLevel() > 10)
  1402. CTXLOG("CSlaveContext %p resolveChildGraph %d", this, id);
  1403. if (id == 0)
  1404. return graph;
  1405. IActivityGraph *childGraph = childGraphs.getValue(id);
  1406. assertex(childGraph);
  1407. return childGraph;
  1408. }
  1409. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  1410. {
  1411. // NOTE - part of ICodeContext interface
  1412. return LINK(queryChildGraph((unsigned) activityId)->queryChildGraph());
  1413. }
  1414. virtual IEclGraphResults * resolveLocalQuery(__int64 id)
  1415. {
  1416. return queryChildGraph((unsigned) id)->queryLocalGraph();
  1417. }
  1418. virtual IRowManager &queryRowManager()
  1419. {
  1420. return *rowManager;
  1421. }
  1422. virtual void addSlavesReplyLen(unsigned len)
  1423. {
  1424. CriticalBlock b(statsCrit); // MORE: change to atomic_add, or may not need it at all?
  1425. totSlavesReplyLen += len;
  1426. }
  1427. virtual const char *loadResource(unsigned id)
  1428. {
  1429. ILoadedDllEntry *dll = factory->queryDll();
  1430. return (const char *) dll->getResource(id);
  1431. }
  1432. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1433. {
  1434. CDateTime cacheDate; // Note - this is empty meaning we don't know...
  1435. return querySlaveDynamicFileCache()->lookupDynamicFile(*this, filename, cacheDate, 0, header, isOpt, false);
  1436. }
  1437. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  1438. {
  1439. throwUnexpected(); // only support writing on the server
  1440. }
  1441. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  1442. {
  1443. // On a slave, we need to request info using our own header (not the one passed in) and need to get global rather than just local info
  1444. // (possibly we could get just local if the channel matches but not sure there is any point)
  1445. Owned<const IResolvedFile> dFile = resolveLFN(lfn, isOpt);
  1446. if (dFile)
  1447. {
  1448. MemoryBuffer mb;
  1449. mb.append(sizeof(RoxiePacketHeader), &header);
  1450. mb.append(lfn);
  1451. dFile->serializePartial(mb, header.channel, isLocal);
  1452. ((RoxiePacketHeader *) mb.toByteArray())->activityId = ROXIE_FILECALLBACK;
  1453. Owned<IRoxieQueryPacket> reply = createRoxiePacket(mb);
  1454. reply->queryHeader().retries = 0;
  1455. ROQ->sendPacket(reply, *this); // MORE - the caller's log context might be better? Should we unicast? Note that this does not release the packet
  1456. return;
  1457. }
  1458. ROQ->sendAbortCallback(header, lfn, *this);
  1459. throwUnexpected();
  1460. }
  1461. virtual ICodeContext *queryCodeContext()
  1462. {
  1463. return this;
  1464. }
  1465. virtual IRoxieServerContext *queryServerContext()
  1466. {
  1467. return NULL;
  1468. }
  1469. virtual IProbeManager *queryProbeManager() const
  1470. {
  1471. return probeManager;
  1472. }
  1473. virtual IDebuggableContext *queryDebugContext() const
  1474. {
  1475. return debugContext;
  1476. }
  1477. virtual char *getOS()
  1478. {
  1479. #ifdef _WIN32
  1480. return strdup("windows");
  1481. #else
  1482. return strdup("linux");
  1483. #endif
  1484. }
  1485. virtual const void * fromXml(IEngineRowAllocator * rowAllocator, size32_t len, const char * utf8, IXmlToRowTransformer * xmlTransformer, bool stripWhitespace)
  1486. {
  1487. return createRowFromXml(rowAllocator, len, utf8, xmlTransformer, stripWhitespace);
  1488. }
  1489. virtual IEngineContext *queryEngineContext() { return NULL; }
  1490. virtual char *getDaliServers() { throwUnexpected(); }
  1491. // The following from ICodeContext should never be executed in slave activity. If we are on Roxie server (or in child query on slave), they will be implemented by more derived CRoxieServerContext class
  1492. virtual void setResultBool(const char *name, unsigned sequence, bool value) { throwUnexpected(); }
  1493. virtual void setResultData(const char *name, unsigned sequence, int len, const void * data) { throwUnexpected(); }
  1494. virtual void setResultDecimal(const char * stepname, unsigned sequence, int len, int precision, bool isSigned, const void *val) { throwUnexpected(); }
  1495. virtual void setResultInt(const char *name, unsigned sequence, __int64 value) { throwUnexpected(); }
  1496. virtual void setResultRaw(const char *name, unsigned sequence, int len, const void * data) { throwUnexpected(); }
  1497. virtual void setResultReal(const char * stepname, unsigned sequence, double value) { throwUnexpected(); }
  1498. virtual void setResultSet(const char *name, unsigned sequence, bool isAll, size32_t len, const void * data, ISetToXmlTransformer * transformer) { throwUnexpected(); }
  1499. virtual void setResultString(const char *name, unsigned sequence, int len, const char * str) { throwUnexpected(); }
  1500. virtual void setResultUInt(const char *name, unsigned sequence, unsigned __int64 value) { throwUnexpected(); }
  1501. virtual void setResultUnicode(const char *name, unsigned sequence, int len, UChar const * str) { throwUnexpected(); }
  1502. virtual void setResultVarString(const char * name, unsigned sequence, const char * value) { throwUnexpected(); }
  1503. virtual void setResultVarUnicode(const char * name, unsigned sequence, UChar const * value) { throwUnexpected(); }
  1504. virtual unsigned getResultHash(const char * name, unsigned sequence) { throwUnexpected(); }
  1505. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence) { throwUnexpected(); }
  1506. virtual char *getWuid() { throwUnexpected(); }
  1507. virtual void getExternalResultRaw(unsigned & tlen, void * & tgt, const char * wuid, const char * stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { throwUnexpected(); }
  1508. virtual char * getExpandLogicalName(const char * logicalName) { throwUnexpected(); }
  1509. virtual void addWuException(const char * text, unsigned code, unsigned severity, const char * source) { throwUnexpected(); }
  1510. virtual void addWuAssertFailure(unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column, bool isAbort) { throwUnexpected(); }
  1511. virtual IUserDescriptor *queryUserDescriptor() { throwUnexpected(); }
  1512. virtual unsigned __int64 getDatasetHash(const char * name, unsigned __int64 hash) { throwUnexpected(); }
  1513. virtual unsigned getNodes() { throwUnexpected(); }
  1514. virtual unsigned getNodeNum() { throwUnexpected(); }
  1515. virtual char *getFilePart(const char *logicalPart, bool create=false) { throwUnexpected(); }
  1516. virtual unsigned __int64 getFileOffset(const char *logicalPart) { throwUnexpected(); }
  1517. virtual IDistributedFileTransaction *querySuperFileTransaction() { throwUnexpected(); }
  1518. virtual char *getJobName() { throwUnexpected(); }
  1519. virtual char *getJobOwner() { throwUnexpected(); }
  1520. virtual char *getClusterName() { throwUnexpected(); }
  1521. virtual char *getGroupName() { throwUnexpected(); }
  1522. virtual char * queryIndexMetaData(char const * lfn, char const * xpath) { throwUnexpected(); }
  1523. virtual unsigned getPriority() const { throwUnexpected(); }
  1524. virtual char *getPlatform() { throwUnexpected(); }
  1525. virtual char *getEnv(const char *name, const char *defaultValue) const { throwUnexpected(); }
  1526. virtual IEngineRowAllocator *getRowAllocator(IOutputMetaData * meta, unsigned activityId) const
  1527. {
  1528. return allocatorMetaCache->ensure(meta, activityId, roxiemem::RHFnone);
  1529. }
  1530. virtual const char *cloneVString(const char *str) const
  1531. {
  1532. return rowManager->cloneVString(str);
  1533. }
  1534. virtual const char *cloneVString(size32_t len, const char *str) const
  1535. {
  1536. return rowManager->cloneVString(len, str);
  1537. }
  1538. virtual void getRowXML(size32_t & lenResult, char * & result, IOutputMetaData & info, const void * row, unsigned flags)
  1539. {
  1540. convertRowToXML(lenResult, result, info, row, flags);
  1541. }
  1542. virtual IWorkUnit *updateWorkUnit() const
  1543. {
  1544. if (workUnit)
  1545. return &workUnit->lock();
  1546. else
  1547. return NULL;
  1548. }
  1549. virtual IConstWorkUnit *queryWorkUnit() const
  1550. {
  1551. return workUnit;
  1552. }
  1553. // roxiemem::IRowAllocatorMetaActIdCacheCallback
  1554. virtual IEngineRowAllocator *createAllocator(IRowAllocatorMetaActIdCache * cache, IOutputMetaData *meta, unsigned activityId, unsigned id, roxiemem::RoxieHeapFlags flags) const
  1555. {
  1556. if (checkingHeap)
  1557. return createCrcRoxieRowAllocator(cache, *rowManager, meta, activityId, id, flags);
  1558. else
  1559. return createRoxieRowAllocator(cache, *rowManager, meta, activityId, id, flags);
  1560. }
  1561. virtual void getResultRowset(size32_t & tcount, byte * * & tgt, const char * stepname, unsigned sequence, IEngineRowAllocator * _rowAllocator, bool isGrouped, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer)
  1562. {
  1563. try
  1564. {
  1565. Owned<IWorkUnitRowReader> wuReader = getWorkunitRowReader(NULL, stepname, sequence, xmlTransformer, _rowAllocator, isGrouped);
  1566. wuReader->getResultRowset(tcount, tgt);
  1567. }
  1568. catch (IException * e)
  1569. {
  1570. StringBuffer text;
  1571. e->errorMessage(text);
  1572. e->Release();
  1573. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value \"%s\". [%s]", stepname, text.str());
  1574. }
  1575. catch (...)
  1576. {
  1577. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value \"%s\"", stepname);
  1578. }
  1579. }
  1580. virtual void getResultDictionary(size32_t & tcount, byte * * & tgt, IEngineRowAllocator * _rowAllocator, const char * stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer, IHThorHashLookupInfo * hasher)
  1581. {
  1582. try
  1583. {
  1584. Owned<IWorkUnitRowReader> wuReader = getWorkunitRowReader(NULL, stepname, sequence, xmlTransformer, _rowAllocator, false);
  1585. wuReader->getResultRowset(tcount, tgt);
  1586. }
  1587. catch (IException * e)
  1588. {
  1589. StringBuffer text;
  1590. e->errorMessage(text);
  1591. e->Release();
  1592. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value \"%s\". [%s]", stepname, text.str());
  1593. }
  1594. catch (...)
  1595. {
  1596. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value \"%s\"", stepname);
  1597. }
  1598. }
  1599. virtual bool getResultBool(const char * name, unsigned sequence)
  1600. {
  1601. CriticalBlock b(contextCrit);
  1602. return useContext(sequence).getPropBool(name);
  1603. }
  1604. static unsigned hex2digit(char c)
  1605. {
  1606. // MORE - what about error cases?
  1607. if (c >= 'a')
  1608. return (c - 'a' + 10);
  1609. else if (c >= 'A')
  1610. return (c - 'A' + 10);
  1611. return (c - '0');
  1612. }
  1613. virtual void getResultData(unsigned & tlen, void * & tgt, const char * name, unsigned sequence)
  1614. {
  1615. MemoryBuffer result;
  1616. CriticalBlock b(contextCrit);
  1617. const char *val = useContext(sequence).queryProp(name);
  1618. if (val)
  1619. {
  1620. loop
  1621. {
  1622. char c0 = *val++;
  1623. if (!c0)
  1624. break;
  1625. char c1 = *val++;
  1626. if (!c1)
  1627. break; // Shouldn't really happen - we expect even length
  1628. unsigned c2 = (hex2digit(c0) << 4) | hex2digit(c1);
  1629. result.append((unsigned char) c2);
  1630. }
  1631. }
  1632. tlen = result.length();
  1633. tgt = result.detach();
  1634. }
  1635. virtual void getResultDecimal(unsigned tlen, int precision, bool isSigned, void * tgt, const char * stepname, unsigned sequence)
  1636. {
  1637. if (isSpecialResultSequence(sequence))
  1638. {
  1639. MemoryBuffer m;
  1640. CriticalBlock b(contextCrit);
  1641. useContext(sequence).getPropBin(stepname, m);
  1642. if (m.length())
  1643. {
  1644. assertex(m.length() == tlen);
  1645. m.read(tlen, tgt);
  1646. }
  1647. else
  1648. memset(tgt, 0, tlen);
  1649. }
  1650. else
  1651. {
  1652. StringBuffer x;
  1653. {
  1654. CriticalBlock b(contextCrit);
  1655. useContext(sequence).getProp(stepname, x);
  1656. }
  1657. Decimal d;
  1658. d.setString(x.length(), x.str());
  1659. if (isSigned)
  1660. d.getDecimal(tlen, precision, tgt);
  1661. else
  1662. d.getUDecimal(tlen, precision, tgt);
  1663. }
  1664. }
  1665. virtual __int64 getResultInt(const char * name, unsigned sequence)
  1666. {
  1667. CriticalBlock b(contextCrit);
  1668. const char *val = useContext(sequence).queryProp(name);
  1669. if (val)
  1670. {
  1671. // NOTE - we use this rather than getPropInt64 since it handles uint64 values up to MAX_UINT better (for our purposes)
  1672. return rtlStrToInt8(strlen(val), val);
  1673. }
  1674. else
  1675. return 0;
  1676. }
  1677. virtual double getResultReal(const char * name, unsigned sequence)
  1678. {
  1679. CriticalBlock b(contextCrit);
  1680. IPropertyTree &ctx = useContext(sequence);
  1681. double ret = 0;
  1682. if (ctx.hasProp(name))
  1683. {
  1684. if (ctx.isBinary(name))
  1685. {
  1686. MemoryBuffer buf;
  1687. ctx.getPropBin(name, buf);
  1688. buf.read(ret);
  1689. }
  1690. else
  1691. {
  1692. const char *val = ctx.queryProp(name);
  1693. if (val)
  1694. ret = atof(val);
  1695. }
  1696. }
  1697. return ret;
  1698. }
  1699. virtual void getResultSet(bool & tisAll, unsigned & tlen, void * & tgt, const char *stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer)
  1700. {
  1701. try
  1702. {
  1703. CriticalBlock b(contextCrit);
  1704. IPropertyTree &ctx = useContext(sequence);
  1705. IPropertyTree *val = ctx.queryPropTree(stepname);
  1706. doExtractRawResultX(tlen, tgt, val, sequence, xmlTransformer, csvTransformer, true);
  1707. tisAll = val ? val->getPropBool("@isAll", false) : false;
  1708. }
  1709. catch (IException * e)
  1710. {
  1711. StringBuffer text;
  1712. e->errorMessage(text);
  1713. e->Release();
  1714. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve set \"%s\". [%s]", stepname, text.str());
  1715. }
  1716. catch (...)
  1717. {
  1718. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve set \"%s\"", stepname);
  1719. }
  1720. }
  1721. virtual void getResultRaw(unsigned & tlen, void * & tgt, const char *stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer)
  1722. {
  1723. try
  1724. {
  1725. CriticalBlock b(contextCrit);
  1726. IPropertyTree &ctx = useContext(sequence);
  1727. IPropertyTree *val = ctx.queryPropTree(stepname);
  1728. doExtractRawResultX(tlen, tgt, val, sequence, xmlTransformer, csvTransformer, false);
  1729. }
  1730. catch (IException * e)
  1731. {
  1732. StringBuffer text;
  1733. e->errorMessage(text);
  1734. e->Release();
  1735. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value \"%s\". [%s]", stepname, text.str());
  1736. }
  1737. catch (...)
  1738. {
  1739. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value \"%s\"", stepname);
  1740. }
  1741. }
  1742. virtual void getResultString(unsigned & tlen, char * & tgt, const char * name, unsigned sequence)
  1743. {
  1744. MemoryBuffer x;
  1745. bool isBinary;
  1746. {
  1747. CriticalBlock b(contextCrit);
  1748. IPropertyTree &ctx = useContext(sequence);
  1749. isBinary = ctx.isBinary(name);
  1750. ctx.getPropBin(name, x);
  1751. }
  1752. if (isBinary) // No utf8 translation if previously set via setResultString
  1753. {
  1754. tlen = x.length();
  1755. tgt = (char *) x.detach();
  1756. }
  1757. else
  1758. rtlUtf8ToStrX(tlen, tgt, rtlUtf8Length(x.length(), x.toByteArray()), x.toByteArray());
  1759. }
  1760. virtual void getResultStringF(unsigned tlen, char * tgt, const char * name, unsigned sequence)
  1761. {
  1762. MemoryBuffer x;
  1763. bool isBinary;
  1764. {
  1765. CriticalBlock b(contextCrit);
  1766. IPropertyTree &ctx = useContext(sequence);
  1767. isBinary = ctx.isBinary(name);
  1768. ctx.getPropBin(name, x);
  1769. }
  1770. if (isBinary)
  1771. rtlStrToStr(tlen, tgt, x.length(), x.toByteArray());
  1772. else
  1773. rtlUtf8ToStr(tlen, tgt, rtlUtf8Length(x.length(), x.toByteArray()), x.toByteArray());
  1774. }
  1775. virtual void getResultUnicode(unsigned & tlen, UChar * & tgt, const char * name, unsigned sequence)
  1776. {
  1777. StringBuffer x;
  1778. {
  1779. CriticalBlock b(contextCrit);
  1780. useContext(sequence).getProp(name, x);
  1781. }
  1782. tgt = rtlCodepageToVUnicodeX(x.length(), x.str(), "utf-8");
  1783. tlen = rtlUnicodeStrlen(tgt);
  1784. }
  1785. virtual char *getResultVarString(const char * name, unsigned sequence)
  1786. {
  1787. CriticalBlock b(contextCrit);
  1788. IPropertyTree &ctx = useContext(sequence);
  1789. bool isBinary = ctx.isBinary(name);
  1790. if (isBinary)
  1791. {
  1792. StringBuffer s;
  1793. ctx.getProp(name, s);
  1794. return s.detach();
  1795. }
  1796. else
  1797. {
  1798. MemoryBuffer x;
  1799. ctx.getPropBin(name, x);
  1800. return rtlUtf8ToVStr(rtlUtf8Length(x.length(), x.toByteArray()), x.toByteArray());
  1801. }
  1802. }
  1803. virtual UChar *getResultVarUnicode(const char * name, unsigned sequence)
  1804. {
  1805. StringBuffer x;
  1806. CriticalBlock b(contextCrit);
  1807. useContext(sequence).getProp(name, x);
  1808. return rtlVCodepageToVUnicodeX(x.str(), "utf-8");
  1809. }
  1810. protected:
  1811. mutable CriticalSection contextCrit;
  1812. Owned<IPropertyTree> context;
  1813. IPropertyTree *persists;
  1814. IPropertyTree *temporaries;
  1815. IPropertyTree *rereadResults;
  1816. PTreeReaderOptions xmlStoredDatasetReadFlags;
  1817. CDeserializedResultStore *deserializedResultStore;
  1818. IPropertyTree &useContext(unsigned sequence)
  1819. {
  1820. checkAbort();
  1821. switch (sequence)
  1822. {
  1823. case ResultSequenceStored:
  1824. if (context)
  1825. return *context;
  1826. else
  1827. throw MakeStringException(ROXIE_CODEGEN_ERROR, "Code generation error - attempting to access stored variable on slave");
  1828. case ResultSequencePersist:
  1829. {
  1830. CriticalBlock b(contextCrit);
  1831. if (!persists)
  1832. persists = createPTree();
  1833. return *persists;
  1834. }
  1835. case ResultSequenceInternal:
  1836. {
  1837. CriticalBlock b(contextCrit);
  1838. if (!temporaries)
  1839. temporaries = createPTree();
  1840. return *temporaries;
  1841. }
  1842. case ResultSequenceOnce:
  1843. {
  1844. return factory->queryOnceContext(logctx);
  1845. }
  1846. default:
  1847. {
  1848. CriticalBlock b(contextCrit);
  1849. if (!rereadResults)
  1850. rereadResults = createPTree();
  1851. return *rereadResults;
  1852. }
  1853. }
  1854. }
  1855. IDeserializedResultStore &useResultStore(unsigned sequence)
  1856. {
  1857. checkAbort();
  1858. switch (sequence)
  1859. {
  1860. case ResultSequenceOnce:
  1861. return factory->queryOnceResultStore();
  1862. default:
  1863. // No need to have separate stores for other temporaries...
  1864. CriticalBlock b(contextCrit);
  1865. if (!deserializedResultStore)
  1866. deserializedResultStore = new CDeserializedResultStore;
  1867. return *deserializedResultStore;
  1868. }
  1869. }
  1870. void doExtractRawResultX(unsigned & tlen, void * & tgt, IPropertyTree *val, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer, bool isSet)
  1871. {
  1872. tgt = NULL;
  1873. tlen = 0;
  1874. if (val)
  1875. {
  1876. if (val->isBinary())
  1877. {
  1878. MemoryBuffer m;
  1879. val->getPropBin(NULL, m);
  1880. tlen = m.length();
  1881. tgt= m.detach();
  1882. }
  1883. else
  1884. {
  1885. const char *format = val->queryProp("@format");
  1886. if (!format || strcmp(format, "xml")==0)
  1887. {
  1888. assertex(xmlTransformer);
  1889. Variable2IDataVal result(&tlen, &tgt);
  1890. CXmlToRawTransformer rawTransformer(*xmlTransformer, xmlStoredDatasetReadFlags);
  1891. rawTransformer.transformTree(result, *val, !isSet);
  1892. }
  1893. else if (strcmp(format, "deserialized")==0)
  1894. {
  1895. IDeserializedResultStore &resultStore = useResultStore(sequence);
  1896. resultStore.serialize(tlen, tgt, val->getPropInt("@id", -1), queryCodeContext());
  1897. }
  1898. else if (strcmp(format, "csv")==0)
  1899. {
  1900. // MORE - never tested this code.....
  1901. assertex(csvTransformer);
  1902. Variable2IDataVal result(&tlen, &tgt);
  1903. MemoryBuffer m;
  1904. val->getPropBin(NULL, m);
  1905. CCsvToRawTransformer rawCsvTransformer(*csvTransformer);
  1906. rawCsvTransformer.transform(result, m.length(), m.toByteArray(), !isSet);
  1907. }
  1908. else
  1909. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "no transform function available");
  1910. }
  1911. }
  1912. }
  1913. virtual IWorkUnitRowReader *createStreamedRawRowReader(IEngineRowAllocator *rowAllocator, bool isGrouped, const char *id)
  1914. {
  1915. throwUnexpected(); // Should only see on server
  1916. }
  1917. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char *stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  1918. {
  1919. try
  1920. {
  1921. if (wuid)
  1922. {
  1923. Owned<IRoxieDaliHelper> daliHelper = connectToDali();
  1924. if (daliHelper && daliHelper->connected())
  1925. {
  1926. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  1927. Owned<IConstWorkUnit> externalWU = factory->openWorkUnit(wuid, false);
  1928. externalWU->remoteCheckAccess(queryUserDescriptor(), false);
  1929. Owned<IConstWUResult> wuResult = getWorkUnitResult(externalWU, stepname, sequence);
  1930. if (!wuResult)
  1931. throw MakeStringException(ROXIE_FILE_ERROR, "Failed to find value %s:%d in workunit %s", stepname ? stepname : "(null)", sequence, wuid);
  1932. return new WuResultDataReader(queryCodeContext(), rowAllocator, isGrouped, logctx, wuResult.getClear(), xmlTransformer);
  1933. }
  1934. else
  1935. throw MakeStringException(ROXIE_DALI_ERROR, "WorkUnit read: no dali connection available");
  1936. }
  1937. else
  1938. {
  1939. CriticalBlock b(contextCrit);
  1940. IPropertyTree &ctx = useContext(sequence);
  1941. IPropertyTree *val = ctx.queryPropTree(stepname);
  1942. if (val)
  1943. {
  1944. const char *id = val->queryProp("@id");
  1945. const char *format = val->queryProp("@format");
  1946. if (id)
  1947. {
  1948. if (!format || strcmp(format, "raw") == 0)
  1949. {
  1950. return createStreamedRawRowReader(rowAllocator, isGrouped, id);
  1951. }
  1952. else if (strcmp(format, "deserialized") == 0)
  1953. {
  1954. IDeserializedResultStore &resultStore = useResultStore(sequence);
  1955. return resultStore.createDeserializedReader(atoi(id));
  1956. }
  1957. else
  1958. throwUnexpected();
  1959. }
  1960. else
  1961. {
  1962. if (!format || strcmp(format, "xml") == 0)
  1963. {
  1964. if (xmlTransformer)
  1965. return new InlineXmlDataReader(*xmlTransformer, val, rowAllocator, isGrouped);
  1966. }
  1967. else if (strcmp(format, "raw") == 0)
  1968. {
  1969. return new InlineRawDataReader(queryCodeContext(), rowAllocator, isGrouped, logctx, val);
  1970. }
  1971. else
  1972. throwUnexpected();
  1973. }
  1974. }
  1975. }
  1976. }
  1977. catch (IException * e)
  1978. {
  1979. StringBuffer text;
  1980. e->errorMessage(text);
  1981. e->Release();
  1982. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value %s. [%s]", stepname, text.str());
  1983. }
  1984. catch (...)
  1985. {
  1986. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value %s", stepname);
  1987. }
  1988. throw MakeStringException(ROXIE_DATA_ERROR, "Failed to retrieve data value %s", stepname);
  1989. }
  1990. // Copied from eclgraph.cpp, in the hope that we will be deleting that code soon
  1991. void executeThorGraph(const char *graphName)
  1992. {
  1993. assertex(workUnit);
  1994. SCMStringBuffer wuid;
  1995. workUnit->getWuid(wuid);
  1996. SCMStringBuffer cluster;
  1997. SCMStringBuffer owner;
  1998. workUnit->getClusterName(cluster);
  1999. workUnit->getUser(owner);
  2000. int priority = workUnit->getPriorityValue();
  2001. unsigned timelimit = workUnit->getDebugValueInt("thorConnectTimeout", defaultThorConnectTimeout);
  2002. Owned<IConstWUClusterInfo> c = getTargetClusterInfo(cluster.str());
  2003. if (!c)
  2004. throw MakeStringException(0, "Invalid thor cluster %s", cluster.str());
  2005. SCMStringBuffer queueName;
  2006. c->getThorQueue(queueName);
  2007. Owned<IJobQueue> jq = createJobQueue(queueName.str());
  2008. bool resubmit;
  2009. do // loop if pause interrupted graph and needs resubmitting on resume
  2010. {
  2011. resubmit = false; // set if job interrupted in thor
  2012. class CWorkunitResumeHandler : public CInterface, implements ISDSSubscription
  2013. {
  2014. IConstWorkUnit &wu;
  2015. StringBuffer xpath;
  2016. StringAttr wuid;
  2017. SubscriptionId subId;
  2018. CriticalSection crit;
  2019. Semaphore sem;
  2020. void unsubscribe()
  2021. {
  2022. CriticalBlock b(crit);
  2023. if (subId)
  2024. {
  2025. SubscriptionId _subId = subId;
  2026. subId = 0;
  2027. querySDS().unsubscribe(_subId);
  2028. }
  2029. }
  2030. public:
  2031. IMPLEMENT_IINTERFACE;
  2032. CWorkunitResumeHandler(IConstWorkUnit &_wu) : wu(_wu)
  2033. {
  2034. xpath.append("/WorkUnits/");
  2035. SCMStringBuffer istr;
  2036. wu.getWuid(istr);
  2037. wuid.set(istr.str());
  2038. xpath.append(wuid.get()).append("/Action");
  2039. subId = 0;
  2040. }
  2041. ~CWorkunitResumeHandler()
  2042. {
  2043. unsubscribe();
  2044. }
  2045. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  2046. {
  2047. CriticalBlock b(crit);
  2048. if (0 == subId) return;
  2049. if (valueLen==strlen("resume") && (0 == strncmp("resume", (const char *)valueData, valueLen)))
  2050. sem.signal();
  2051. }
  2052. bool wait()
  2053. {
  2054. subId = querySDS().subscribe(xpath.str(), *this, false, true);
  2055. assertex(subId);
  2056. PROGLOG("Job %s paused, waiting for resume/abort", wuid.get());
  2057. bool ret = true;
  2058. while (!sem.wait(10000))
  2059. {
  2060. wu.forceReload();
  2061. if (WUStatePaused != wu.getState() || wu.aborting())
  2062. {
  2063. SCMStringBuffer str;
  2064. wu.getStateDesc(str);
  2065. PROGLOG("Aborting pause job %s, state : %s", wuid.get(), str.str());
  2066. ret = false;
  2067. break;
  2068. }
  2069. }
  2070. unsubscribe();
  2071. return ret;
  2072. }
  2073. } workunitResumeHandler(*workUnit);
  2074. if (WUStatePaused == workUnit->getState()) // check initial state - and wait if paused
  2075. {
  2076. if (!workunitResumeHandler.wait())
  2077. throw new WorkflowException(0,"User abort requested", 0, WorkflowException::ABORT, MSGAUD_user);
  2078. }
  2079. setWUState(WUStateBlocked);
  2080. class cPollThread: public Thread // MORE - why do we ned a thread here?
  2081. {
  2082. Semaphore sem;
  2083. bool stopped;
  2084. IJobQueue *jq;
  2085. IConstWorkUnit *wu;
  2086. public:
  2087. bool timedout;
  2088. CTimeMon tm;
  2089. cPollThread(IJobQueue *_jq, IConstWorkUnit *_wu, unsigned timelimit)
  2090. : tm(timelimit)
  2091. {
  2092. stopped = false;
  2093. jq = _jq;
  2094. wu = _wu;
  2095. timedout = false;
  2096. }
  2097. ~cPollThread()
  2098. {
  2099. stop();
  2100. }
  2101. int run()
  2102. {
  2103. while (!stopped) {
  2104. sem.wait(ABORT_POLL_PERIOD);
  2105. if (stopped)
  2106. break;
  2107. if (tm.timedout()) {
  2108. timedout = true;
  2109. stopped = true;
  2110. jq->cancelInitiateConversation();
  2111. }
  2112. else if (wu->aborting()) {
  2113. stopped = true;
  2114. jq->cancelInitiateConversation();
  2115. }
  2116. }
  2117. return 0;
  2118. }
  2119. void stop()
  2120. {
  2121. stopped = true;
  2122. sem.signal();
  2123. }
  2124. } pollthread(jq, workUnit, timelimit*1000);
  2125. pollthread.start();
  2126. PROGLOG("Enqueuing on %s to run wuid=%s, graph=%s, timelimit=%d seconds, priority=%d", queueName.str(), wuid.str(), graphName, timelimit, priority);
  2127. IJobQueueItem* item = createJobQueueItem(wuid.str());
  2128. item->setOwner(owner.str());
  2129. item->setPriority(priority);
  2130. Owned<IConversation> conversation = jq->initiateConversation(item);
  2131. bool got = conversation.get()!=NULL;
  2132. pollthread.stop();
  2133. pollthread.join();
  2134. if (!got)
  2135. {
  2136. if (pollthread.timedout)
  2137. throw MakeStringException(0, "Query %s failed to start within specified timelimit (%d) seconds", wuid.str(), timelimit);
  2138. throw MakeStringException(0, "Query %s cancelled (1)",wuid.str());
  2139. }
  2140. // get the thor ep from whoever picked up
  2141. SocketEndpoint thorMaster;
  2142. MemoryBuffer msg;
  2143. if (!conversation->recv(msg,1000*60)) {
  2144. throw MakeStringException(0, "Query %s cancelled (2)",wuid.str());
  2145. }
  2146. thorMaster.deserialize(msg);
  2147. msg.clear().append(graphName);
  2148. SocketEndpoint myep;
  2149. myep.setLocalHost(0);
  2150. myep.serialize(msg); // only used for tracing
  2151. if (!conversation->send(msg)) {
  2152. StringBuffer s("Failed to send query to Thor on ");
  2153. thorMaster.getUrlStr(s);
  2154. throw MakeStringExceptionDirect(-1, s.str()); // maybe retry?
  2155. }
  2156. StringBuffer eps;
  2157. PROGLOG("Thor on %s running %s",thorMaster.getUrlStr(eps).str(),wuid.str());
  2158. MemoryBuffer reply;
  2159. try
  2160. {
  2161. if (!conversation->recv(reply,INFINITE))
  2162. {
  2163. StringBuffer s("Failed to receive reply from thor ");
  2164. thorMaster.getUrlStr(s);
  2165. throw MakeStringExceptionDirect(-1, s.str());
  2166. }
  2167. }
  2168. catch (IException *e)
  2169. {
  2170. StringBuffer s("Failed to receive reply from thor ");
  2171. thorMaster.getUrlStr(s);
  2172. s.append("; (").append(e->errorCode()).append(", ");
  2173. e->errorMessage(s).append(")");
  2174. throw MakeStringExceptionDirect(-1, s.str());
  2175. }
  2176. ThorReplyCodes replyCode;
  2177. reply.read((unsigned &)replyCode);
  2178. switch (replyCode)
  2179. {
  2180. case DAMP_THOR_REPLY_PAUSED:
  2181. {
  2182. bool isException ;
  2183. reply.read(isException);
  2184. if (isException)
  2185. {
  2186. Owned<IException> e = deserializeException(reply);
  2187. VStringBuffer str("Pausing job %s caused exception", wuid.str());
  2188. EXCLOG(e, str.str());
  2189. }
  2190. WorkunitUpdate w(&workUnit->lock());
  2191. w->setState(WUStatePaused); // will trigger executeThorGraph to pause next time around.
  2192. WUAction action = w->getAction();
  2193. switch (action)
  2194. {
  2195. case WUActionPause:
  2196. case WUActionPauseNow:
  2197. w->setAction(WUActionUnknown);
  2198. }
  2199. resubmit = true; // JCSMORE - all subgraph _could_ be done, thor will check though and not rerun
  2200. break;
  2201. }
  2202. case DAMP_THOR_REPLY_GOOD:
  2203. break;
  2204. case DAMP_THOR_REPLY_ERROR:
  2205. {
  2206. throw deserializeException(reply);
  2207. }
  2208. case DAMP_THOR_REPLY_ABORT:
  2209. throw new WorkflowException(0,"User abort requested", 0, WorkflowException::ABORT, MSGAUD_user);
  2210. default:
  2211. throwUnexpected();
  2212. }
  2213. workUnit->forceReload();
  2214. }
  2215. while (resubmit); // if pause interrupted job (i.e. with pausenow action), resubmit graph
  2216. }
  2217. };
  2218. IRoxieSlaveContext *createSlaveContext(const IQueryFactory *_factory, const SlaveContextLogger &_logctx, unsigned _timeLimit, memsize_t _memoryLimit, IRoxieQueryPacket *packet)
  2219. {
  2220. return new CSlaveContext(_factory, _logctx, _timeLimit, _memoryLimit, packet, _logctx.queryTraceActivityTimes(), _logctx.queryDebuggerActive(), _logctx.queryCheckingHeap());
  2221. }
  2222. class CRoxieServerDebugContext : extends CBaseServerDebugContext
  2223. {
  2224. // Some questions:
  2225. // 1. Do we let all threads go even when say step? Probably... (may allow a thread to be suspended at some point)
  2226. // 2. Doesn't that then make a bit of a mockery of step (when there are multiple threads active)... I _think_ it actually means we DON'T try to wait for all
  2227. // threads to hit a stop, but allow any that hit stop while we are paused to be queued up to be returned by step.... perhaps actually stop them in critsec rather than
  2228. // semaphore and it all becomes easier to code... Anything calling checkBreakPoint while program state is "in debugger" will block on that critSec.
  2229. // 3. I think we need to recheck breakpoints on Roxie server but just check not deleted
  2230. public:
  2231. IRoxieSlaveContext *ctx;
  2232. CRoxieServerDebugContext(IRoxieSlaveContext *_ctx, const IContextLogger &_logctx, IPropertyTree *_queryXGMML, SafeSocket &_client)
  2233. : CBaseServerDebugContext(_logctx, _queryXGMML, _client), ctx(_ctx)
  2234. {
  2235. }
  2236. void debugCounts(IXmlWriter *output, unsigned sinceSequence, bool reset)
  2237. {
  2238. CriticalBlock b(debugCrit);
  2239. if (running)
  2240. throw MakeStringException(ROXIE_DEBUG_ERROR, "Command not available while query is running");
  2241. if (currentGraph)
  2242. currentGraph->mergeRemoteCounts(this);
  2243. CBaseServerDebugContext::debugCounts(output, sinceSequence, reset);
  2244. }
  2245. virtual void waitForDebugger(DebugState state, IActivityDebugContext *probe)
  2246. {
  2247. ctx->setWUState(WUStateDebugPaused);
  2248. CBaseServerDebugContext::waitForDebugger(state, probe);
  2249. ctx->setWUState(WUStateDebugRunning);
  2250. }
  2251. virtual bool onDebuggerTimeout()
  2252. {
  2253. return ctx->checkWuAborted();
  2254. }
  2255. virtual void debugInitialize(const char *id, const char *_queryName, bool _breakAtStart)
  2256. {
  2257. CBaseServerDebugContext::debugInitialize(id, _queryName, _breakAtStart);
  2258. queryRoxieDebugSessionManager().registerDebugId(id, this);
  2259. }
  2260. virtual void debugTerminate()
  2261. {
  2262. CriticalBlock b(debugCrit);
  2263. assertex(running);
  2264. currentState = DebugStateUnloaded;
  2265. running = false;
  2266. queryRoxieDebugSessionManager().deregisterDebugId(debugId);
  2267. if (debuggerActive)
  2268. {
  2269. debuggerSem.signal(debuggerActive);
  2270. debuggerActive = 0;
  2271. }
  2272. }
  2273. virtual IRoxieQueryPacket *onDebugCallback(const RoxiePacketHeader &header, size32_t len, char *data)
  2274. {
  2275. MemoryBuffer slaveInfo;
  2276. slaveInfo.setBuffer(len, data, false);
  2277. unsigned debugSequence;
  2278. slaveInfo.read(debugSequence);
  2279. {
  2280. CriticalBlock b(breakCrit); // we want to wait until it's our turn before updating the graph info or the counts get ahead of the current row and life is confusing
  2281. char slaveStateChar;
  2282. slaveInfo.read(slaveStateChar);
  2283. DebugState slaveState = (DebugState) slaveStateChar;
  2284. if (slaveState==DebugStateGraphFinished)
  2285. {
  2286. unsigned numCounts;
  2287. slaveInfo.read(numCounts);
  2288. while (numCounts)
  2289. {
  2290. StringAttr edgeId;
  2291. unsigned edgeCount;
  2292. slaveInfo.read(edgeId);
  2293. slaveInfo.read(edgeCount);
  2294. Owned<IGlobalEdgeRecord> thisEdge = getEdgeRecord(edgeId);
  2295. thisEdge->incrementCount(edgeCount, sequence);
  2296. numCounts--;
  2297. }
  2298. }
  2299. slaveInfo.read(currentBreakpointUID);
  2300. memsize_t slaveActivity;
  2301. unsigned channel;
  2302. __uint64 tmp;
  2303. slaveInfo.read(tmp);
  2304. slaveActivity = (memsize_t)tmp;
  2305. slaveInfo.read(channel);
  2306. assertex(currentGraph);
  2307. currentGraph->deserializeProxyGraphs(slaveState, slaveInfo, (IActivityBase *) slaveActivity, channel);
  2308. if (slaveState != DebugStateGraphFinished) // MORE - this is debatable - may (at least sometimes) want a child graph finished to be a notified event...
  2309. {
  2310. StringBuffer slaveActivityId;
  2311. slaveInfo.read(slaveActivityId);
  2312. IActivityDebugContext *slaveActivityCtx = slaveActivityId.length() ? currentGraph->lookupActivityByEdgeId(slaveActivityId.str()) : NULL;
  2313. BreakpointActionMode action = checkBreakpoint(slaveState, slaveActivityCtx , NULL);
  2314. }
  2315. }
  2316. MemoryBuffer mb;
  2317. mb.append(sizeof(RoxiePacketHeader), &header);
  2318. StringBuffer debugIdString;
  2319. debugIdString.appendf(".debug.%x", debugSequence);
  2320. mb.append(debugIdString.str());
  2321. serialize(mb);
  2322. Owned<IRoxieQueryPacket> reply = createRoxiePacket(mb);
  2323. reply->queryHeader().activityId = ROXIE_DEBUGCALLBACK;
  2324. reply->queryHeader().retries = 0;
  2325. return reply.getClear();
  2326. }
  2327. virtual void debugPrintVariable(IXmlWriter *output, const char *name, const char *type) const
  2328. {
  2329. CriticalBlock b(debugCrit);
  2330. if (running)
  2331. throw MakeStringException(ROXIE_DEBUG_ERROR, "Command not available while query is running");
  2332. output->outputBeginNested("Variables", true);
  2333. if (!type || stricmp(type, "temporary"))
  2334. {
  2335. output->outputBeginNested("Temporary", true);
  2336. ctx->printResults(output, name, (unsigned) ResultSequenceInternal);
  2337. output->outputEndNested("Temporary");
  2338. }
  2339. if (!type || stricmp(type, "global"))
  2340. {
  2341. output->outputBeginNested("Global", true);
  2342. ctx->printResults(output, name, (unsigned) ResultSequenceStored);
  2343. output->outputEndNested("Global");
  2344. }
  2345. output->outputEndNested("Variables");
  2346. }
  2347. };
  2348. class CRoxieServerContext : public CSlaveContext, implements IRoxieServerContext, implements IGlobalCodeContext
  2349. {
  2350. const IQueryFactory *serverQueryFactory;
  2351. CriticalSection daliUpdateCrit;
  2352. StringAttr querySetName;
  2353. TextMarkupFormat mlFmt;
  2354. bool isRaw;
  2355. bool sendHeartBeats;
  2356. unsigned warnTimeLimit;
  2357. unsigned lastSocketCheckTime;
  2358. unsigned lastHeartBeat;
  2359. protected:
  2360. Owned<CRoxieWorkflowMachine> workflow;
  2361. mutable MapStringToMyClass<IResolvedFile> fileCache;
  2362. SafeSocket *client;
  2363. bool isBlocked;
  2364. bool isHttp;
  2365. bool trim;
  2366. void doPostProcess()
  2367. {
  2368. CriticalBlock b(resultsCrit); // Probably not needed
  2369. if (!isRaw && !isBlocked)
  2370. {
  2371. ForEachItemIn(seq, resultMap)
  2372. {
  2373. FlushingStringBuffer *result = resultMap.item(seq);
  2374. if (result)
  2375. result->flush(true);
  2376. }
  2377. }
  2378. if (probeQuery)
  2379. {
  2380. FlushingStringBuffer response(client, isBlocked, MarkupFmt_XML, false, isHttp, *this);
  2381. // create output stream
  2382. response.startDataset("_Probe", NULL, (unsigned) -1); // initialize it
  2383. // loop through all of the graphs and create a _Probe to output each xgmml
  2384. Owned<IPropertyTreeIterator> graphs = probeQuery->getElements("Graph");
  2385. ForEach(*graphs)
  2386. {
  2387. IPropertyTree &graph = graphs->query();
  2388. StringBuffer xgmml;
  2389. _toXML(&graph, xgmml, 0);
  2390. response.append("\n");
  2391. response.append(xgmml.str());
  2392. }
  2393. }
  2394. }
  2395. void addWuException(IException *E)
  2396. {
  2397. if (workUnit)
  2398. ::addWuException(workUnit, E);
  2399. }
  2400. void init()
  2401. {
  2402. client = NULL;
  2403. totSlavesReplyLen = 0;
  2404. mlFmt = MarkupFmt_XML;
  2405. isRaw = false;
  2406. isBlocked = false;
  2407. isHttp = false;
  2408. trim = false;
  2409. priority = 0;
  2410. sendHeartBeats = false;
  2411. timeLimit = serverQueryFactory->getTimeLimit();
  2412. if (!timeLimit)
  2413. timeLimit = defaultTimeLimit[priority];
  2414. warnTimeLimit = serverQueryFactory->getWarnTimeLimit();
  2415. if (!warnTimeLimit)
  2416. warnTimeLimit = defaultWarnTimeLimit[priority];
  2417. lastSocketCheckTime = startTime;
  2418. lastHeartBeat = startTime;
  2419. ctxParallelJoinPreload = defaultParallelJoinPreload;
  2420. ctxFullKeyedJoinPreload = defaultFullKeyedJoinPreload;
  2421. ctxKeyedJoinPreload = defaultKeyedJoinPreload;
  2422. ctxConcatPreload = defaultConcatPreload;
  2423. ctxFetchPreload = defaultFetchPreload;
  2424. ctxPrefetchProjectPreload = defaultPrefetchProjectPreload;
  2425. traceActivityTimes = false;
  2426. timeActivities = defaultTimeActivities;
  2427. }
  2428. void startWorkUnit()
  2429. {
  2430. WorkunitUpdate wu(&workUnit->lock());
  2431. wu->subscribe(SubscribeOptionAbort);
  2432. wu->addTimeStamp("Roxie", GetCachedHostName(), "Started");
  2433. if (!context->getPropBool("@outputToSocket", false))
  2434. client = NULL;
  2435. updateSuppliedXmlParams(wu);
  2436. SCMStringBuffer wuParams;
  2437. if (workUnit->getXmlParams(wuParams).length())
  2438. {
  2439. // Merge in params from WU. Ones on command line take precedence though...
  2440. Owned<IPropertyTree> wuParamTree = createPTreeFromXMLString(wuParams.str(), ipt_caseInsensitive);
  2441. Owned<IPropertyTreeIterator> params = wuParamTree ->getElements("*");
  2442. ForEach(*params)
  2443. {
  2444. IPropertyTree &param = params->query();
  2445. if (!context->hasProp(param.queryName()))
  2446. context->addPropTree(param.queryName(), LINK(&param));
  2447. }
  2448. }
  2449. if (workUnit->getDebugValueBool("Debug", false))
  2450. {
  2451. bool breakAtStart = workUnit->getDebugValueBool("BreakAtStart", true);
  2452. wu->setState(WUStateDebugRunning);
  2453. SCMStringBuffer wuid;
  2454. initDebugMode(breakAtStart, workUnit->getWuid(wuid).str());
  2455. }
  2456. else
  2457. wu->setState(WUStateRunning);
  2458. }
  2459. void initDebugMode(bool breakAtStart, const char *debugUID)
  2460. {
  2461. if (!debugPermitted || !ownEP.port)
  2462. throw MakeStringException(ROXIE_ACCESS_ERROR, "Debug queries are not permitted on this system");
  2463. debugContext.setown(new CRoxieServerDebugContext(this, logctx, factory->cloneQueryXGMML(), *client));
  2464. debugContext->debugInitialize(debugUID, factory->queryQueryName(), breakAtStart);
  2465. if (workUnit)
  2466. {
  2467. WorkunitUpdate wu(&workUnit->lock());
  2468. wu->setDebugAgentListenerPort(ownEP.port); //tells debugger what port to write commands to
  2469. StringBuffer sb;
  2470. ownEP.getIpText(sb);
  2471. wu->setDebugAgentListenerIP(sb); //tells debugger what IP to write commands to
  2472. }
  2473. timeLimit = 0;
  2474. warnTimeLimit = 0;
  2475. }
  2476. public:
  2477. IMPLEMENT_IINTERFACE;
  2478. CRoxieServerContext(const IQueryFactory *_factory, const ContextLogger &_logctx)
  2479. : CSlaveContext(_factory, _logctx, 0, 0, NULL, false, false, false), serverQueryFactory(_factory)
  2480. {
  2481. init();
  2482. rowManager->setMemoryLimit(serverQueryFactory->getMemoryLimit());
  2483. workflow.setown(_factory->createWorkflowMachine(workUnit, true, logctx));
  2484. context.setown(createPTree(ipt_caseInsensitive));
  2485. }
  2486. CRoxieServerContext(IConstWorkUnit *_workUnit, const IQueryFactory *_factory, const ContextLogger &_logctx)
  2487. : CSlaveContext(_factory, _logctx, 0, 0, NULL, false, false, false), serverQueryFactory(_factory)
  2488. {
  2489. init();
  2490. workUnit.set(_workUnit);
  2491. rowManager->setMemoryLimit(serverQueryFactory->getMemoryLimit());
  2492. workflow.setown(_factory->createWorkflowMachine(workUnit, false, logctx));
  2493. context.setown(createPTree(ipt_caseInsensitive));
  2494. //MORE: Use various debug settings to override settings:
  2495. rowManager->setActivityTracking(workUnit->getDebugValueBool("traceRoxiePeakMemory", false));
  2496. startWorkUnit();
  2497. }
  2498. CRoxieServerContext(IPropertyTree *_context, const IQueryFactory *_factory, SafeSocket &_client, TextMarkupFormat _mlFmt, bool _isRaw, bool _isBlocked, HttpHelper &httpHelper, bool _trim, unsigned _priority, const ContextLogger &_logctx, PTreeReaderOptions _xmlReadFlags, const char *_querySetName)
  2499. : CSlaveContext(_factory, _logctx, 0, 0, NULL, false, false, false), serverQueryFactory(_factory), querySetName(_querySetName)
  2500. {
  2501. init();
  2502. context.set(_context);
  2503. client = &_client;
  2504. mlFmt = _mlFmt;
  2505. isRaw = _isRaw;
  2506. isBlocked = _isBlocked;
  2507. isHttp = httpHelper.isHttp();
  2508. trim = _trim;
  2509. priority = _priority;
  2510. xmlStoredDatasetReadFlags = _xmlReadFlags;
  2511. sendHeartBeats = enableHeartBeat && isRaw && isBlocked && priority==0;
  2512. timeLimit = context->getPropInt("_TimeLimit", timeLimit);
  2513. warnTimeLimit = context->getPropInt("_warnTimeLimit", warnTimeLimit);
  2514. const char *wuid = context->queryProp("@wuid");
  2515. if (wuid)
  2516. {
  2517. IRoxieDaliHelper *daliHelper = checkDaliConnection();
  2518. assertex(daliHelper );
  2519. workUnit.setown(daliHelper->attachWorkunit(wuid, _factory->queryDll()));
  2520. if (!workUnit)
  2521. throw MakeStringException(ROXIE_DALI_ERROR, "Failed to open workunit %s", wuid);
  2522. startWorkUnit();
  2523. }
  2524. else if (context->getPropBool("@debug", false))
  2525. {
  2526. bool breakAtStart = context->getPropBool("@break", true);
  2527. const char *debugUID = context->queryProp("@uid");
  2528. if (debugUID && *debugUID)
  2529. initDebugMode(breakAtStart, debugUID);
  2530. }
  2531. else if (context->getPropBool("_Probe", false))
  2532. probeQuery.setown(_factory->cloneQueryXGMML());
  2533. // MORE some of these might be appropriate in wu case too?
  2534. rowManager->setActivityTracking(context->getPropBool("_TraceMemory", false));
  2535. rowManager->setMemoryLimit((memsize_t) context->getPropInt64("_MemoryLimit", _factory->getMemoryLimit()));
  2536. authToken.append(httpHelper.queryAuthToken());
  2537. workflow.setown(_factory->createWorkflowMachine(workUnit, false, logctx));
  2538. ctxParallelJoinPreload = context->getPropInt("_ParallelJoinPreload", defaultParallelJoinPreload);
  2539. ctxFullKeyedJoinPreload = context->getPropInt("_FullKeyedJoinPreload", defaultFullKeyedJoinPreload);
  2540. ctxKeyedJoinPreload = context->getPropInt("_KeyedJoinPreload", defaultKeyedJoinPreload);
  2541. ctxConcatPreload = context->getPropInt("_ConcatPreload", defaultConcatPreload);
  2542. ctxFetchPreload = context->getPropInt("_FetchPreload", defaultFetchPreload);
  2543. ctxPrefetchProjectPreload = context->getPropInt("_PrefetchProjectPreload", defaultPrefetchProjectPreload);
  2544. checkingHeap = context->getPropBool("_CheckingHeap", defaultCheckingHeap) || context->getPropBool("@checkingHeap", defaultCheckingHeap);
  2545. traceActivityTimes = context->getPropBool("_TraceActivityTimes", false) || context->getPropBool("@timing", false);
  2546. timeActivities = context->getPropBool("@timeActivities", defaultTimeActivities);
  2547. if (traceActivityTimes && !timeActivities)
  2548. timeActivities = true;
  2549. }
  2550. virtual roxiemem::IRowManager &queryRowManager()
  2551. {
  2552. return *rowManager;
  2553. }
  2554. virtual IRoxieDaliHelper *checkDaliConnection()
  2555. {
  2556. CriticalBlock b(daliUpdateCrit);
  2557. if (!daliHelperLink)
  2558. daliHelperLink.setown(::connectToDali());
  2559. return daliHelperLink;
  2560. }
  2561. virtual void checkAbort()
  2562. {
  2563. CSlaveContext::checkAbort();
  2564. unsigned ticksNow = msTick();
  2565. if (warnTimeLimit)
  2566. {
  2567. unsigned elapsed = ticksNow - startTime;
  2568. if (elapsed > warnTimeLimit)
  2569. {
  2570. CriticalBlock b(abortLock);
  2571. if (elapsed > warnTimeLimit) // we don't want critsec on the first check (for efficiency) but check again inside the critsec
  2572. {
  2573. logOperatorException(NULL, NULL, 0, "SLOW (%d ms): %s", elapsed, factory->queryQueryName());
  2574. warnTimeLimit = elapsed + warnTimeLimit;
  2575. }
  2576. }
  2577. }
  2578. if (client)
  2579. {
  2580. if (socketCheckInterval)
  2581. {
  2582. if (ticksNow - lastSocketCheckTime > socketCheckInterval)
  2583. {
  2584. CriticalBlock b(abortLock);
  2585. if (!client->checkConnection())
  2586. throw MakeStringException(ROXIE_CLIENT_CLOSED, "Client socket closed");
  2587. lastSocketCheckTime = ticksNow;
  2588. }
  2589. }
  2590. if (sendHeartBeats)
  2591. {
  2592. unsigned hb = ticksNow - lastHeartBeat;
  2593. if (hb > 30000)
  2594. {
  2595. lastHeartBeat = msTick();
  2596. client->sendHeartBeat(*this);
  2597. }
  2598. }
  2599. }
  2600. }
  2601. virtual unsigned getXmlFlags() const
  2602. {
  2603. return trim ? XWFtrim|XWFopt : XWFexpandempty;
  2604. }
  2605. virtual const IProperties *queryXmlns(unsigned seqNo)
  2606. {
  2607. IConstWorkUnit *cw = serverQueryFactory->queryWorkUnit();
  2608. if (cw)
  2609. {
  2610. Owned<IConstWUResult> result = cw->getResultBySequence(seqNo);
  2611. if (result)
  2612. return result->queryXmlns();
  2613. }
  2614. return NULL;
  2615. }
  2616. virtual unsigned getMemoryUsage()
  2617. {
  2618. return rowManager->getMemoryUsage();
  2619. }
  2620. virtual unsigned getSlavesReplyLen()
  2621. {
  2622. return totSlavesReplyLen;
  2623. }
  2624. virtual void process()
  2625. {
  2626. EclProcessFactory pf = (EclProcessFactory) factory->queryDll()->getEntry("createProcess");
  2627. Owned<IEclProcess> p = pf();
  2628. try
  2629. {
  2630. if (debugContext)
  2631. debugContext->checkBreakpoint(DebugStateReady, NULL, NULL);
  2632. if (workflow)
  2633. workflow->perform(this, p);
  2634. else
  2635. p->perform(this, 0);
  2636. }
  2637. catch(WorkflowException *E)
  2638. {
  2639. if (debugContext)
  2640. debugContext->checkBreakpoint(DebugStateException, NULL, static_cast<IException *>(E));
  2641. addWuException(E);
  2642. doPostProcess();
  2643. throw;
  2644. }
  2645. catch(IException *E)
  2646. {
  2647. if (debugContext)
  2648. debugContext->checkBreakpoint(DebugStateException, NULL, E);
  2649. addWuException(E);
  2650. doPostProcess();
  2651. throw;
  2652. }
  2653. catch(...)
  2654. {
  2655. if (debugContext)
  2656. debugContext->checkBreakpoint(DebugStateFailed, NULL, NULL);
  2657. if (workUnit)
  2658. {
  2659. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerContext::process");
  2660. addWuException(E);
  2661. }
  2662. doPostProcess();
  2663. throw;
  2664. }
  2665. if (debugContext)
  2666. debugContext->checkBreakpoint(DebugStateFinished, NULL, NULL);
  2667. doPostProcess();
  2668. }
  2669. virtual void done(bool failed)
  2670. {
  2671. if (debugContext)
  2672. debugContext->debugTerminate();
  2673. if (workUnit)
  2674. {
  2675. WorkunitUpdate w(&workUnit->lock());
  2676. w->setState(aborted ? WUStateAborted : (failed ? WUStateFailed : WUStateCompleted));
  2677. w->addTimeStamp("Roxie", GetCachedHostName(), "Finished");
  2678. ITimeReporter *timer = logctx.queryTimer();
  2679. updateWorkunitTimings(w, timer, "roxie");
  2680. logctx.dumpStats(w);
  2681. WuStatisticTarget statsTarget(w, "roxie");
  2682. rowManager->reportPeakStatistics(statsTarget, 0);
  2683. }
  2684. }
  2685. virtual ICodeContext *queryCodeContext()
  2686. {
  2687. return this;
  2688. }
  2689. virtual IRoxieServerContext *queryServerContext()
  2690. {
  2691. return this;
  2692. }
  2693. virtual IGlobalCodeContext *queryGlobalCodeContext()
  2694. {
  2695. return this;
  2696. }
  2697. // interface ICodeContext
  2698. virtual FlushingStringBuffer *queryResult(unsigned sequence)
  2699. {
  2700. if (!client && workUnit)
  2701. return NULL; // when outputting to workunit only, don't output anything to stdout
  2702. CriticalBlock procedure(resultsCrit);
  2703. while (!resultMap.isItem(sequence))
  2704. resultMap.append(NULL);
  2705. FlushingStringBuffer *result = resultMap.item(sequence);
  2706. if (!result)
  2707. {
  2708. result = new FlushingStringBuffer(client, isBlocked, mlFmt, isRaw, isHttp, *this);
  2709. result->isSoap = isHttp;
  2710. result->trim = trim;
  2711. result->queryName.set(context->queryName());
  2712. resultMap.replace(result, sequence);
  2713. }
  2714. return result;
  2715. }
  2716. virtual char *getDaliServers()
  2717. {
  2718. //MORE: Should this now be implemented using IRoxieDaliHelper?
  2719. throwUnexpected();
  2720. }
  2721. virtual void setResultBool(const char *name, unsigned sequence, bool value)
  2722. {
  2723. if (isSpecialResultSequence(sequence))
  2724. {
  2725. CriticalBlock b(contextCrit);
  2726. useContext(sequence).setPropBool(name, value);
  2727. }
  2728. else
  2729. {
  2730. FlushingStringBuffer *r = queryResult(sequence);
  2731. if (r)
  2732. {
  2733. r->startScalar(name, sequence);
  2734. if (isRaw)
  2735. r->append(sizeof(value), (char *)&value);
  2736. else
  2737. r->append(value ? "true" : "false");
  2738. }
  2739. }
  2740. if (workUnit)
  2741. {
  2742. try
  2743. {
  2744. WorkunitUpdate wu(&workUnit->lock());
  2745. CriticalBlock b(daliUpdateCrit); // MORE - do we really need these locks?
  2746. wu->setResultBool(name, sequence, value);
  2747. }
  2748. catch(IException *e)
  2749. {
  2750. StringBuffer text;
  2751. e->errorMessage(text);
  2752. CTXLOG("Error trying to update dali: %s", text.str());
  2753. e->Release();
  2754. }
  2755. catch(...)
  2756. {
  2757. CTXLOG("Unknown exception trying to update dali");
  2758. }
  2759. }
  2760. }
  2761. virtual void setResultData(const char *name, unsigned sequence, int len, const void * data)
  2762. {
  2763. static char hexchar[] = "0123456789ABCDEF";
  2764. if (isSpecialResultSequence(sequence))
  2765. {
  2766. StringBuffer s;
  2767. const byte *field = (const byte *) data;
  2768. for (int i = 0; i < len; i++)
  2769. s.append(hexchar[field[i] >> 4]).append(hexchar[field[i] & 0x0f]);
  2770. CriticalBlock b(contextCrit);
  2771. IPropertyTree &ctx = useContext(sequence);
  2772. ctx.setProp(name, s.str());
  2773. }
  2774. else
  2775. {
  2776. FlushingStringBuffer *r = queryResult(sequence);
  2777. if (r)
  2778. {
  2779. r->startScalar(name, sequence);
  2780. if (isRaw)
  2781. r->append(len, (const char *) data);
  2782. else
  2783. {
  2784. const byte *field = (const byte *) data;
  2785. for (int i = 0; i < len; i++)
  2786. {
  2787. r->append(hexchar[field[i] >> 4]);
  2788. r->append(hexchar[field[i] & 0x0f]);
  2789. }
  2790. }
  2791. }
  2792. }
  2793. if (workUnit)
  2794. {
  2795. try
  2796. {
  2797. WorkunitUpdate wu(&workUnit->lock());
  2798. CriticalBlock b(daliUpdateCrit);
  2799. wu->setResultData(name, sequence, len, data);
  2800. }
  2801. catch(IException *e)
  2802. {
  2803. StringBuffer text;
  2804. e->errorMessage(text);
  2805. CTXLOG("Error trying to update dali: %s", text.str());
  2806. e->Release();
  2807. }
  2808. catch(...)
  2809. {
  2810. CTXLOG("Unknown exception trying to update dali");
  2811. }
  2812. }
  2813. }
  2814. virtual void appendResultDeserialized(const char *name, unsigned sequence, size32_t count, rowset_t data, bool extend, IOutputMetaData *meta)
  2815. {
  2816. CriticalBlock b(contextCrit);
  2817. IPropertyTree &ctx = useContext(sequence);
  2818. IDeserializedResultStore &resultStore = useResultStore(sequence);
  2819. IPropertyTree *val = ctx.queryPropTree(name);
  2820. if (extend && val)
  2821. {
  2822. int oldId = val->getPropInt("@id", -1);
  2823. const char * oldFormat = val->queryProp("@format");
  2824. assertex(oldId != -1);
  2825. assertex(oldFormat && strcmp(oldFormat, "deserialized")==0);
  2826. size32_t oldCount;
  2827. rowset_t oldData;
  2828. resultStore.queryResult(oldId, oldCount, oldData);
  2829. Owned<IEngineRowAllocator> allocator = getRowAllocator(meta, 0);
  2830. RtlLinkedDatasetBuilder builder(allocator);
  2831. builder.appendRows(oldCount, oldData);
  2832. builder.appendRows(count, data);
  2833. rtlReleaseRowset(count, data);
  2834. val->setPropInt("@id", resultStore.addResult(builder.getcount(), builder.linkrows(), meta));
  2835. }
  2836. else
  2837. {
  2838. if (!val)
  2839. val = ctx.addPropTree(name, createPTree());
  2840. val->setProp("@format", "deserialized");
  2841. val->setPropInt("@id", resultStore.addResult(count, data, meta));
  2842. }
  2843. }
  2844. virtual void appendResultRawContext(const char *name, unsigned sequence, int len, const void * data, int numRows, bool extend, bool saveInContext)
  2845. {
  2846. if (saveInContext)
  2847. {
  2848. CriticalBlock b(contextCrit);
  2849. IPropertyTree &ctx = useContext(sequence);
  2850. ctx.appendPropBin(name, len, data);
  2851. ctx.queryPropTree(name)->setProp("@format", "raw");
  2852. }
  2853. if (workUnit)
  2854. {
  2855. try
  2856. {
  2857. WorkunitUpdate wu(&workUnit->lock());
  2858. CriticalBlock b(daliUpdateCrit);
  2859. wu->setResultDataset(name, sequence, len, data, numRows, extend);
  2860. }
  2861. catch(IException *e)
  2862. {
  2863. StringBuffer text;
  2864. e->errorMessage(text);
  2865. CTXLOG("Error trying to update dali: %s", text.str());
  2866. e->Release();
  2867. }
  2868. catch(...)
  2869. {
  2870. CTXLOG("Unknown exception trying to update dali");
  2871. }
  2872. }
  2873. }
  2874. virtual void setResultRaw(const char *name, unsigned sequence, int len, const void * data)
  2875. {
  2876. if (isSpecialResultSequence(sequence))
  2877. {
  2878. CriticalBlock b(contextCrit);
  2879. IPropertyTree &ctx = useContext(sequence);
  2880. ctx.setPropBin(name, len, data);
  2881. ctx.queryPropTree(name)->setProp("@format", "raw");
  2882. }
  2883. else
  2884. {
  2885. FlushingStringBuffer *r = queryResult(sequence);
  2886. if (r)
  2887. {
  2888. r->startScalar(name, sequence);
  2889. if (isRaw)
  2890. r->append(len, (const char *) data);
  2891. else
  2892. UNIMPLEMENTED;
  2893. }
  2894. }
  2895. if (workUnit)
  2896. {
  2897. try
  2898. {
  2899. WorkunitUpdate wu(&workUnit->lock());
  2900. CriticalBlock b(daliUpdateCrit);
  2901. wu->setResultRaw(name, sequence, len, data);
  2902. }
  2903. catch(IException *e)
  2904. {
  2905. StringBuffer text;
  2906. e->errorMessage(text);
  2907. CTXLOG("Error trying to update dali: %s", text.str());
  2908. e->Release();
  2909. }
  2910. catch(...)
  2911. {
  2912. CTXLOG("Unknown exception trying to update dali");
  2913. }
  2914. }
  2915. }
  2916. virtual void setResultSet(const char *name, unsigned sequence, bool isAll, size32_t len, const void * data, ISetToXmlTransformer * transformer)
  2917. {
  2918. if (isSpecialResultSequence(sequence))
  2919. {
  2920. CriticalBlock b(contextCrit);
  2921. IPropertyTree &ctx = useContext(sequence);
  2922. ctx.setPropBin(name, len, data);
  2923. ctx.queryPropTree(name)->setProp("@format", "raw");
  2924. ctx.queryPropTree(name)->setPropBool("@isAll", isAll);
  2925. }
  2926. else
  2927. {
  2928. FlushingStringBuffer *r = queryResult(sequence);
  2929. if (r)
  2930. {
  2931. r->startScalar(name, sequence);
  2932. if (isRaw)
  2933. r->append(len, (char *)data);
  2934. else if (mlFmt==MarkupFmt_XML)
  2935. {
  2936. assertex(transformer);
  2937. CommonXmlWriter writer(getXmlFlags()|XWFnoindent, 0);
  2938. transformer->toXML(isAll, len, (byte *)data, writer);
  2939. r->append(writer.str());
  2940. }
  2941. else if (mlFmt==MarkupFmt_JSON)
  2942. {
  2943. assertex(transformer);
  2944. CommonJsonWriter writer(getXmlFlags()|XWFnoindent, 0);
  2945. transformer->toXML(isAll, len, (byte *)data, writer);
  2946. r->append(writer.str());
  2947. }
  2948. else
  2949. {
  2950. assertex(transformer);
  2951. r->append('[');
  2952. if (isAll)
  2953. r->appendf("*]");
  2954. else
  2955. {
  2956. SimpleOutputWriter x;
  2957. transformer->toXML(isAll, len, (const byte *) data, x);
  2958. r->appendf("%s]", x.str());
  2959. }
  2960. }
  2961. }
  2962. }
  2963. if (workUnit)
  2964. {
  2965. try
  2966. {
  2967. WorkunitUpdate wu(&workUnit->lock());
  2968. CriticalBlock b(daliUpdateCrit);
  2969. wu->setResultSet(name, sequence, isAll, len, data, transformer);
  2970. }
  2971. catch(IException *e)
  2972. {
  2973. StringBuffer text;
  2974. e->errorMessage(text);
  2975. CTXLOG("Error trying to update dali: %s", text.str());
  2976. e->Release();
  2977. }
  2978. catch(...)
  2979. {
  2980. CTXLOG("Unknown exception trying to update dali");
  2981. }
  2982. }
  2983. }
  2984. virtual void setResultXml(const char *name, unsigned sequence, const char *xml)
  2985. {
  2986. CriticalBlock b(contextCrit);
  2987. useContext(sequence).setPropTree(name, createPTreeFromXMLString(xml, ipt_caseInsensitive));
  2988. }
  2989. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  2990. {
  2991. if (isSpecialResultSequence(sequence))
  2992. {
  2993. MemoryBuffer m;
  2994. serializeFixedData(len, val, m);
  2995. CriticalBlock b(contextCrit);
  2996. useContext(sequence).setPropBin(name, m.length(), m.toByteArray());
  2997. }
  2998. else
  2999. {
  3000. FlushingStringBuffer *r = queryResult(sequence);
  3001. if (r)
  3002. {
  3003. r->startScalar(name, sequence);
  3004. if (isRaw)
  3005. r->append(len, (char *)val);
  3006. else
  3007. {
  3008. StringBuffer s;
  3009. if (isSigned)
  3010. outputXmlDecimal(val, len, precision, NULL, s);
  3011. else
  3012. outputXmlUDecimal(val, len, precision, NULL, s);
  3013. r->append(s);
  3014. }
  3015. }
  3016. }
  3017. if (workUnit)
  3018. {
  3019. try
  3020. {
  3021. WorkunitUpdate wu(&workUnit->lock());
  3022. CriticalBlock b(daliUpdateCrit);
  3023. wu->setResultDecimal(name, sequence, len, precision, isSigned, val);
  3024. }
  3025. catch(IException *e)
  3026. {
  3027. StringBuffer text;
  3028. e->errorMessage(text);
  3029. CTXLOG("Error trying to update dali: %s", text.str());
  3030. e->Release();
  3031. }
  3032. catch(...)
  3033. {
  3034. CTXLOG("Unknown exception trying to update dali");
  3035. }
  3036. }
  3037. }
  3038. virtual void setResultInt(const char *name, unsigned sequence, __int64 value)
  3039. {
  3040. if (isSpecialResultSequence(sequence))
  3041. {
  3042. CriticalBlock b(contextCrit);
  3043. useContext(sequence).setPropInt64(name, value);
  3044. }
  3045. else
  3046. {
  3047. FlushingStringBuffer *r = queryResult(sequence);
  3048. if (r)
  3049. {
  3050. r->startScalar(name, sequence);
  3051. if (isRaw)
  3052. r->append(sizeof(value), (char *)&value);
  3053. else
  3054. r->appendf("%"I64F"d", value);
  3055. }
  3056. }
  3057. if (workUnit)
  3058. {
  3059. try
  3060. {
  3061. WorkunitUpdate wu(&workUnit->lock());
  3062. CriticalBlock b(daliUpdateCrit);
  3063. wu->setResultInt(name, sequence, value);
  3064. }
  3065. catch(IException *e)
  3066. {
  3067. StringBuffer text;
  3068. e->errorMessage(text);
  3069. CTXLOG("Error trying to update dali: %s", text.str());
  3070. e->Release();
  3071. }
  3072. catch(...)
  3073. {
  3074. CTXLOG("Unknown exception trying to update dali");
  3075. }
  3076. }
  3077. }
  3078. virtual void setResultUInt(const char *name, unsigned sequence, unsigned __int64 value)
  3079. {
  3080. if (isSpecialResultSequence(sequence))
  3081. {
  3082. CriticalBlock b(contextCrit);
  3083. useContext(sequence).setPropInt64(name, value);
  3084. }
  3085. else
  3086. {
  3087. FlushingStringBuffer *r = queryResult(sequence);
  3088. if (r)
  3089. {
  3090. r->startScalar(name, sequence);
  3091. if (isRaw)
  3092. r->append(sizeof(value), (char *)&value);
  3093. else
  3094. r->appendf("%"I64F"u", value);
  3095. }
  3096. }
  3097. if (workUnit)
  3098. {
  3099. try
  3100. {
  3101. WorkunitUpdate wu(&workUnit->lock());
  3102. CriticalBlock b(daliUpdateCrit);
  3103. wu->setResultUInt(name, sequence, value);
  3104. }
  3105. catch(IException *e)
  3106. {
  3107. StringBuffer text;
  3108. e->errorMessage(text);
  3109. CTXLOG("Error trying to update dali: %s", text.str());
  3110. e->Release();
  3111. }
  3112. catch(...)
  3113. {
  3114. CTXLOG("Unknown exception trying to update dali");
  3115. }
  3116. }
  3117. }
  3118. virtual void setResultReal(const char *name, unsigned sequence, double value)
  3119. {
  3120. if (isSpecialResultSequence(sequence))
  3121. {
  3122. CriticalBlock b(contextCrit);
  3123. useContext(sequence).setPropBin(name, sizeof(value), &value);
  3124. }
  3125. else
  3126. {
  3127. StringBuffer v;
  3128. v.append(value);
  3129. FlushingStringBuffer *r = queryResult(sequence);
  3130. if (r)
  3131. {
  3132. r->startScalar(name, sequence);
  3133. if (r->isRaw)
  3134. r->append(sizeof(value), (char *)&value);
  3135. else
  3136. r->appendf("%s", v.str());
  3137. }
  3138. }
  3139. if (workUnit)
  3140. {
  3141. try
  3142. {
  3143. WorkunitUpdate wu(&workUnit->lock());
  3144. CriticalBlock b(daliUpdateCrit);
  3145. wu->setResultReal(name, sequence, value);
  3146. }
  3147. catch(IException *e)
  3148. {
  3149. StringBuffer text;
  3150. e->errorMessage(text);
  3151. CTXLOG("Error trying to update dali: %s", text.str());
  3152. e->Release();
  3153. }
  3154. catch(...)
  3155. {
  3156. CTXLOG("Unknown exception trying to update dali");
  3157. }
  3158. }
  3159. }
  3160. virtual void setResultString(const char *name, unsigned sequence, int len, const char * str)
  3161. {
  3162. if (isSpecialResultSequence(sequence))
  3163. {
  3164. CriticalBlock b(contextCrit);
  3165. useContext(sequence).setPropBin(name, len, str);
  3166. }
  3167. else
  3168. {
  3169. FlushingStringBuffer *r = queryResult(sequence);
  3170. if (r)
  3171. {
  3172. r->startScalar(name, sequence);
  3173. if (r->isRaw)
  3174. {
  3175. r->append(len, str);
  3176. }
  3177. else
  3178. {
  3179. r->encodeXML(str, 0, len);
  3180. }
  3181. }
  3182. }
  3183. if (workUnit)
  3184. {
  3185. try
  3186. {
  3187. WorkunitUpdate wu(&workUnit->lock());
  3188. CriticalBlock b(daliUpdateCrit);
  3189. wu->setResultString(name, sequence, len, str);
  3190. }
  3191. catch(IException *e)
  3192. {
  3193. StringBuffer text;
  3194. e->errorMessage(text);
  3195. CTXLOG("Error trying to update dali: %s", text.str());
  3196. e->Release();
  3197. }
  3198. catch(...)
  3199. {
  3200. CTXLOG("Unknown exception trying to update dali");
  3201. }
  3202. }
  3203. }
  3204. virtual void setResultUnicode(const char *name, unsigned sequence, int len, UChar const * str)
  3205. {
  3206. if (isSpecialResultSequence(sequence))
  3207. {
  3208. rtlDataAttr buff;
  3209. unsigned bufflen = 0;
  3210. rtlUnicodeToCodepageX(bufflen, buff.refstr(), len, str, "utf-8");
  3211. CriticalBlock b(contextCrit);
  3212. useContext(sequence).setPropBin(name, bufflen, buff.getstr());
  3213. }
  3214. else
  3215. {
  3216. FlushingStringBuffer *r = queryResult(sequence);
  3217. if (r)
  3218. {
  3219. r->startScalar(name, sequence);
  3220. if (r->isRaw)
  3221. {
  3222. r->append(len*2, (const char *) str);
  3223. }
  3224. else
  3225. {
  3226. rtlDataAttr buff;
  3227. unsigned bufflen = 0;
  3228. rtlUnicodeToCodepageX(bufflen, buff.refstr(), len, str, "utf-8");
  3229. r->encodeXML(buff.getstr(), 0, bufflen, true); // output as UTF-8
  3230. }
  3231. }
  3232. }
  3233. if (workUnit)
  3234. {
  3235. try
  3236. {
  3237. WorkunitUpdate wu(&workUnit->lock());
  3238. CriticalBlock b(daliUpdateCrit);
  3239. wu->setResultUnicode(name, sequence, len, str);
  3240. }
  3241. catch(IException *e)
  3242. {
  3243. StringBuffer text;
  3244. e->errorMessage(text);
  3245. CTXLOG("Error trying to update dali: %s", text.str());
  3246. e->Release();
  3247. }
  3248. catch(...)
  3249. {
  3250. CTXLOG("Unknown exception trying to update dali");
  3251. }
  3252. }
  3253. }
  3254. virtual void setResultVarString(const char * name, unsigned sequence, const char * value)
  3255. {
  3256. setResultString(name, sequence, strlen(value), value);
  3257. }
  3258. virtual void setResultVarUnicode(const char * name, unsigned sequence, UChar const * value)
  3259. {
  3260. setResultUnicode(name, sequence, rtlUnicodeStrlen(value), value);
  3261. }
  3262. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *data, unsigned numRows, bool extend)
  3263. {
  3264. appendResultRawContext(name, sequence, len, data, numRows, extend, true);
  3265. }
  3266. virtual IWorkUnitRowReader *createStreamedRawRowReader(IEngineRowAllocator *rowAllocator, bool isGrouped, const char *id)
  3267. {
  3268. return new StreamedRawDataReader(this, rowAllocator, isGrouped, logctx, *client, id);
  3269. }
  3270. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  3271. {
  3272. CriticalBlock b(contextCrit);
  3273. IPropertyTree &tree = useContext(sequence);
  3274. if (name)
  3275. {
  3276. const char *val = tree.queryProp(name);
  3277. if (val)
  3278. output->outputCString(val, name);
  3279. }
  3280. else
  3281. {
  3282. StringBuffer hack;
  3283. toXML(&tree, hack);
  3284. output->outputString(0, NULL, NULL); // Hack upon hack...
  3285. output->outputQuoted(hack.str());
  3286. }
  3287. }
  3288. virtual const IResolvedFile *resolveLFN(const char *fileName, bool isOpt)
  3289. {
  3290. CriticalBlock b(contextCrit);
  3291. StringBuffer expandedName;
  3292. expandLogicalFilename(expandedName, fileName, workUnit, false);
  3293. Linked<const IResolvedFile> ret = fileCache.getValue(expandedName);
  3294. if (!ret)
  3295. {
  3296. ret.setown(factory->queryPackage().lookupFileName(fileName, isOpt, false, false, workUnit));
  3297. if (ret)
  3298. {
  3299. IResolvedFile *add = const_cast<IResolvedFile *>(ret.get());
  3300. fileCache.setValue(expandedName, add);
  3301. }
  3302. }
  3303. return ret.getClear();
  3304. }
  3305. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  3306. {
  3307. return factory->queryPackage().createFileName(filename, overwrite, extend, clusters, workUnit);
  3308. }
  3309. virtual void endGraph(cycle_t startCycles, bool aborting)
  3310. {
  3311. fileCache.kill();
  3312. CSlaveContext::endGraph(startCycles, aborting);
  3313. }
  3314. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  3315. {
  3316. Owned<const IResolvedFile> dFile = resolveLFN(lfn, isOpt);
  3317. if (dFile)
  3318. {
  3319. MemoryBuffer mb;
  3320. mb.append(sizeof(RoxiePacketHeader), &header);
  3321. mb.append(lfn);
  3322. dFile->serializePartial(mb, header.channel, isLocal);
  3323. ((RoxiePacketHeader *) mb.toByteArray())->activityId = ROXIE_FILECALLBACK;
  3324. Owned<IRoxieQueryPacket> reply = createRoxiePacket(mb);
  3325. reply->queryHeader().retries = 0;
  3326. ROQ->sendPacket(reply, *this); // MORE - the caller's log context might be better? Should we unicast? Note that this does not release the packet
  3327. return;
  3328. }
  3329. ROQ->sendAbortCallback(header, lfn, *this);
  3330. throwUnexpected();
  3331. }
  3332. virtual void getExternalResultRaw(unsigned & tlen, void * & tgt, const char * wuid, const char * stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer)
  3333. {
  3334. UNIMPLEMENTED;
  3335. }
  3336. virtual void addWuException(const char * text, unsigned code, unsigned _severity, const char * source)
  3337. {
  3338. WUExceptionSeverity severity = (WUExceptionSeverity) _severity;
  3339. CTXLOG("%s", text);
  3340. if (severity > ExceptionSeverityInformation)
  3341. OERRLOG("%d - %s", code, text);
  3342. if (workUnit)
  3343. {
  3344. WorkunitUpdate wu(&workUnit->lock());
  3345. addExceptionToWorkunit(wu, severity, source, code, text, NULL, 0 ,0);
  3346. }
  3347. }
  3348. virtual void addWuAssertFailure(unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column, bool isAbort)
  3349. {
  3350. CTXLOG("%s", text);
  3351. OERRLOG("%d - %s", code, text);
  3352. if (workUnit)
  3353. {
  3354. WorkunitUpdate wu(&workUnit->lock());
  3355. addExceptionToWorkunit(wu, ExceptionSeverityError, "user", code, text, filename, lineno, column);
  3356. }
  3357. if (isAbort)
  3358. rtlFailOnAssert(); // minimal implementation
  3359. }
  3360. IUserDescriptor *queryUserDescriptor()
  3361. {
  3362. return NULL; // TBD - Richard, where do user credentials for a roxie query come from
  3363. }
  3364. virtual bool isResult(const char * name, unsigned sequence)
  3365. {
  3366. CriticalBlock b(contextCrit);
  3367. return useContext(sequence).hasProp(name);
  3368. }
  3369. virtual char *getClusterName()
  3370. {
  3371. if (workUnit)
  3372. {
  3373. SCMStringBuffer out;
  3374. workUnit->getClusterName(out);
  3375. return out.s.detach(); // detach will return "" rather than NULL
  3376. }
  3377. else
  3378. {
  3379. // predeployed queries with no workunit should return the querySet name
  3380. return strdup(querySetName.sget()); // sget will return "" rather than NULL
  3381. }
  3382. }
  3383. virtual char *getGroupName() { throwUnexpected(); }
  3384. virtual char *queryIndexMetaData(char const * lfn, char const * xpath) { throwUnexpected(); }
  3385. virtual char *getEnv(const char *name, const char *defaultValue) const
  3386. {
  3387. return serverQueryFactory->getEnv(name, defaultValue);
  3388. }
  3389. virtual char *getJobName()
  3390. {
  3391. return strdup(factory->queryQueryName());
  3392. }
  3393. virtual char *getJobOwner() { throwUnexpected(); }
  3394. virtual char *getPlatform()
  3395. {
  3396. return strdup("roxie");
  3397. }
  3398. virtual char *getWuid()
  3399. {
  3400. if (workUnit)
  3401. {
  3402. SCMStringBuffer wuid;
  3403. workUnit->getWuid(wuid);
  3404. return strdup(wuid.str());
  3405. }
  3406. else
  3407. {
  3408. return strdup("");
  3409. }
  3410. }
  3411. // persist-related code
  3412. virtual char * getExpandLogicalName(const char * logicalName)
  3413. {
  3414. StringBuffer lfn;
  3415. expandLogicalFilename(lfn, logicalName, workUnit, false);
  3416. return lfn.detach();
  3417. }
  3418. virtual void setWorkflowCondition(bool value) { if(workflow) workflow->setCondition(value); }
  3419. virtual void returnPersistVersion(const char * logicalName, unsigned eclCRC, unsigned __int64 allCRC, bool isFile)
  3420. {
  3421. if (workflow)
  3422. workflow->returnPersistVersion(logicalName, eclCRC, allCRC, isFile);
  3423. }
  3424. virtual void fail(int code, const char *text)
  3425. {
  3426. addWuException(text, code, 2, "user");
  3427. }
  3428. virtual unsigned getWorkflowId() { return workflow->queryCurrentWfid(); }
  3429. void doNotify(char const * name, char const * text)
  3430. {
  3431. doNotify(name, text, NULL);
  3432. }
  3433. void doNotify(char const * name, char const * text, const char * target)
  3434. {
  3435. Owned<IRoxieDaliHelper> daliHelper = connectToDali();
  3436. if (daliHelper && daliHelper->connected())
  3437. {
  3438. Owned<IScheduleEventPusher> pusher(getScheduleEventPusher());
  3439. pusher->push(name, text, target);
  3440. }
  3441. else
  3442. throw MakeStringException(ROXIE_DALI_ERROR, "doNotify: no dali connection available");
  3443. }
  3444. virtual void doWait(unsigned code, char const * extra) { UNIMPLEMENTED; }
  3445. virtual void doWaitCond(unsigned code, char const * extra, int sequence, char const * alias, unsigned wfid) { UNIMPLEMENTED; }
  3446. static unsigned __int64 crcLogicalFileTime(IDistributedFile * file, unsigned __int64 crc, const char * filename)
  3447. {
  3448. CDateTime dt;
  3449. file->getModificationTime(dt);
  3450. unsigned __int64 modifiedTime = dt.getSimple();
  3451. return rtlHash64Data(sizeof(modifiedTime), &modifiedTime, crc);
  3452. }
  3453. virtual unsigned __int64 getDatasetHash(const char * logicalName, unsigned __int64 crc)
  3454. {
  3455. StringBuffer fullname;
  3456. expandLogicalFilename(fullname, logicalName, workUnit, false);
  3457. Owned<IDistributedFile> file = queryDistributedFileDirectory().lookup(fullname.str(),queryUserDescriptor());
  3458. if (file)
  3459. {
  3460. WorkunitUpdate wu = updateWorkUnit();
  3461. wu->noteFileRead(file);
  3462. IDistributedSuperFile * super = file->querySuperFile();
  3463. if (super)
  3464. {
  3465. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(true);
  3466. ForEach(*iter)
  3467. {
  3468. IDistributedFile & cur = iter->query();
  3469. const char * name = cur.queryLogicalName();
  3470. crc = rtlHash64Data(strlen(name), name, crc);
  3471. crc = crcLogicalFileTime(&cur, crc, name);
  3472. }
  3473. }
  3474. else
  3475. crc = crcLogicalFileTime(file, crc, fullname.str());
  3476. }
  3477. return crc;
  3478. }
  3479. virtual int queryLastFailCode() { UNIMPLEMENTED; }
  3480. virtual void getLastFailMessage(size32_t & outLen, char * &outStr, const char * tag) { UNIMPLEMENTED; }
  3481. virtual void getEventName(size32_t & outLen, char * & outStr) { UNIMPLEMENTED; }
  3482. virtual void getEventExtra(size32_t & outLen, char * & outStr, const char * tag) { UNIMPLEMENTED; }
  3483. virtual bool fileExists(const char * filename) { throwUnexpected(); }
  3484. virtual void deleteFile(const char * logicalName) { throwUnexpected(); }
  3485. virtual unsigned getNodes() { return numChannels; }
  3486. virtual unsigned getNodeNum() { return 0; }
  3487. virtual char *getFilePart(const char *logicalPart, bool create=false) { UNIMPLEMENTED; }
  3488. virtual unsigned __int64 getFileOffset(const char *logicalPart) { throwUnexpected(); }
  3489. virtual IDistributedFileTransaction *querySuperFileTransaction()
  3490. {
  3491. CriticalBlock b(contextCrit);
  3492. if (!superfileTransaction.get())
  3493. superfileTransaction.setown(createDistributedFileTransaction(queryUserDescriptor()));
  3494. return superfileTransaction.get();
  3495. }
  3496. virtual void flush(unsigned seqNo) { throwUnexpected(); }
  3497. virtual unsigned getPriority() const { return priority; }
  3498. virtual IConstWorkUnit *queryWorkUnit() const { return workUnit; }
  3499. virtual bool outputResultsToSocket() const { return client != NULL; }
  3500. virtual void selectCluster(const char * cluster) { throwUnexpected(); }
  3501. virtual void restoreCluster() { throwUnexpected(); }
  3502. };
  3503. //================================================================================================
  3504. class CSoapRoxieServerContext : public CRoxieServerContext
  3505. {
  3506. private:
  3507. StringAttr queryName;
  3508. public:
  3509. CSoapRoxieServerContext(IPropertyTree *_context, const IQueryFactory *_factory, SafeSocket &_client, HttpHelper &httpHelper, unsigned _priority, const ContextLogger &_logctx, PTreeReaderOptions xmlReadFlags, const char *_querySetName)
  3510. : CRoxieServerContext(_context, _factory, _client, MarkupFmt_XML, false, false, httpHelper, true, _priority, _logctx, xmlReadFlags, _querySetName)
  3511. {
  3512. queryName.set(_context->queryName());
  3513. }
  3514. virtual void process()
  3515. {
  3516. EclProcessFactory pf = (EclProcessFactory) factory->queryDll()->getEntry("createProcess");
  3517. Owned<IEclProcess> p = pf();
  3518. if (workflow)
  3519. workflow->perform(this, p);
  3520. else
  3521. p->perform(this, 0);
  3522. }
  3523. virtual void flush(unsigned seqNo)
  3524. {
  3525. CriticalBlock b(resultsCrit);
  3526. CriticalBlock b1(client->queryCrit());
  3527. StringBuffer responseHead, responseTail;
  3528. responseHead.append("<").append(queryName).append("Response");
  3529. responseHead.append(" sequence=\"").append(seqNo).append("\"");
  3530. responseHead.append(" xmlns=\"urn:hpccsystems:ecl:").appendLower(queryName.length(), queryName.sget()).append("\">");
  3531. responseHead.append("<Results><Result>");
  3532. unsigned len = responseHead.length();
  3533. client->write(responseHead.detach(), len, true);
  3534. ForEachItemIn(seq, resultMap)
  3535. {
  3536. FlushingStringBuffer *result = resultMap.item(seq);
  3537. if (result)
  3538. {
  3539. result->flush(true);
  3540. for(;;)
  3541. {
  3542. size32_t length;
  3543. void *payload = result->getPayload(length);
  3544. if (!length)
  3545. break;
  3546. client->write(payload, length, true);
  3547. }
  3548. }
  3549. }
  3550. responseTail.append("</Result></Results>");
  3551. responseTail.append("</").append(queryName).append("Response>");
  3552. len = responseTail.length();
  3553. client->write(responseTail.detach(), len, true);
  3554. }
  3555. };
  3556. class CJsonRoxieServerContext : public CRoxieServerContext
  3557. {
  3558. private:
  3559. StringAttr queryName;
  3560. public:
  3561. CJsonRoxieServerContext(IPropertyTree *_context, const IQueryFactory *_factory, SafeSocket &_client, HttpHelper &httpHelper, unsigned _priority, const ContextLogger &_logctx, PTreeReaderOptions xmlReadFlags, const char *_querySetName)
  3562. : CRoxieServerContext(_context, _factory, _client, MarkupFmt_JSON, false, false, httpHelper, true, _priority, _logctx, xmlReadFlags, _querySetName)
  3563. {
  3564. queryName.set(_context->queryName());
  3565. }
  3566. virtual void process()
  3567. {
  3568. EclProcessFactory pf = (EclProcessFactory) factory->queryDll()->getEntry("createProcess");
  3569. Owned<IEclProcess> p = pf();
  3570. if (workflow)
  3571. workflow->perform(this, p);
  3572. else
  3573. p->perform(this, 0);
  3574. }
  3575. virtual void flush(unsigned seqNo)
  3576. {
  3577. CriticalBlock b(resultsCrit);
  3578. CriticalBlock b1(client->queryCrit());
  3579. StringBuffer responseHead, responseTail;
  3580. appendfJSONName(responseHead, "%sResponse", queryName.get()).append(" {");
  3581. appendJSONValue(responseHead, "sequence", seqNo);
  3582. appendJSONName(responseHead, "Results").append(" {");
  3583. unsigned len = responseHead.length();
  3584. client->write(responseHead.detach(), len, true);
  3585. bool needDelimiter = false;
  3586. ForEachItemIn(seq, resultMap)
  3587. {
  3588. FlushingStringBuffer *result = resultMap.item(seq);
  3589. if (result)
  3590. {
  3591. result->flush(true);
  3592. for(;;)
  3593. {
  3594. size32_t length;
  3595. void *payload = result->getPayload(length);
  3596. if (!length)
  3597. break;
  3598. if (needDelimiter)
  3599. {
  3600. StringAttr s(","); //write() will take ownership of buffer
  3601. size32_t len = s.length();
  3602. client->write((void *)s.detach(), len, true);
  3603. needDelimiter=false;
  3604. }
  3605. client->write(payload, length, true);
  3606. }
  3607. needDelimiter=true;
  3608. }
  3609. }
  3610. responseTail.append("}}");
  3611. len = responseTail.length();
  3612. client->write(responseTail.detach(), len, true);
  3613. }
  3614. virtual FlushingStringBuffer *queryResult(unsigned sequence)
  3615. {
  3616. if (!client && workUnit)
  3617. return NULL; // when outputting to workunit only, don't output anything to stdout
  3618. CriticalBlock procedure(resultsCrit);
  3619. while (!resultMap.isItem(sequence))
  3620. resultMap.append(NULL);
  3621. FlushingStringBuffer *result = resultMap.item(sequence);
  3622. if (!result)
  3623. {
  3624. result = new FlushingJsonBuffer(client, isBlocked, isHttp, *this);
  3625. result->trim = trim;
  3626. result->queryName.set(context->queryName());
  3627. resultMap.replace(result, sequence);
  3628. }
  3629. return result;
  3630. }
  3631. };
  3632. IRoxieServerContext *createRoxieServerContext(IPropertyTree *context, const IQueryFactory *factory, SafeSocket &client, bool isXml, bool isRaw, bool isBlocked, HttpHelper &httpHelper, bool trim, unsigned priority, const ContextLogger &_logctx, PTreeReaderOptions readFlags, const char *querySetName)
  3633. {
  3634. if (httpHelper.isHttp())
  3635. {
  3636. if (httpHelper.queryContentFormat()==MarkupFmt_JSON)
  3637. return new CJsonRoxieServerContext(context, factory, client, httpHelper, priority, _logctx, readFlags, querySetName);
  3638. return new CSoapRoxieServerContext(context, factory, client, httpHelper, priority, _logctx, readFlags, querySetName);
  3639. }
  3640. else
  3641. return new CRoxieServerContext(context, factory, client, isXml ? MarkupFmt_XML : MarkupFmt_Unknown, isRaw, isBlocked, httpHelper, trim, priority, _logctx, readFlags, querySetName);
  3642. }
  3643. IRoxieServerContext *createOnceServerContext(const IQueryFactory *factory, const ContextLogger &_logctx)
  3644. {
  3645. return new CRoxieServerContext(factory, _logctx);
  3646. }
  3647. IRoxieServerContext *createWorkUnitServerContext(IConstWorkUnit *wu, const IQueryFactory *factory, const ContextLogger &_logctx)
  3648. {
  3649. return new CRoxieServerContext(wu, factory, _logctx);
  3650. }