ccdstate.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include <platform.h>
  14. #include <jlib.hpp>
  15. #include "build-config.h"
  16. #include "jisem.hpp"
  17. #include "jsort.hpp"
  18. #include "jregexp.hpp"
  19. #include "ccd.hpp"
  20. #include "ccdquery.hpp"
  21. #include "ccdstate.hpp"
  22. #include "ccdqueue.ipp"
  23. #include "ccdlistener.hpp"
  24. #include "ccdfile.hpp"
  25. #include "ccdsnmp.hpp"
  26. #include "hqlplugins.hpp"
  27. #include "thorplugin.hpp"
  28. #include "eclrtl.hpp"
  29. #include "dafdesc.hpp"
  30. #include "dautils.hpp"
  31. #include "pkgimpl.hpp"
  32. #include "roxiehelper.hpp"
  33. //-------------------------------------------------------------------------------------------
  34. // class CRoxiePluginCtx - provide the environments for plugins loaded by roxie.
  35. // Base class handles making sure memory allocation comes from the right heap.
  36. // implement get/set properties to allow plugin configuration information to be retrieved from Roxie topology file
  37. //-------------------------------------------------------------------------------------------
  38. class CRoxiePluginCtx : public SimplePluginCtx
  39. {
  40. public:
  41. virtual int ctxGetPropInt(const char *propName, int defaultValue) const
  42. {
  43. return topology->getPropInt(propName, defaultValue);
  44. }
  45. virtual const char *ctxQueryProp(const char *propName) const
  46. {
  47. return topology->queryProp(propName);
  48. }
  49. } PluginCtx;
  50. SafePluginMap *plugins;
  51. //================================================================================================
  52. // In legacy state files, the original file names passed in _fileName or _indexFileName may have been translated into _superFileName or _superKeyName,
  53. // and then 0 or more (max 1 for subfiles, no limit for subkeys) _fileName or _indexFileName will have been added. This translation will not take place
  54. // if the files resolve to single file/key, or if we are using new embedded wu system
  55. // Basic mode of operation therefore is to get the original name, see if it can be resolved by package into a list of subfiles, and if not, use
  56. // iterator on the xgmml node to get the list.
  57. // These two helper functions will return the original filenames placed in the XGMML by the codegen, regardless of how/if roxieconfig resolved them
  58. static const char *_queryNodeFileName(const IPropertyTree &graphNode)
  59. {
  60. if (graphNode.hasProp("att[@name='_file_dynamic']"))
  61. return NULL;
  62. else
  63. return graphNode.queryProp("att[@name='_fileName']/@value");
  64. }
  65. static const char *_queryNodeIndexName(const IPropertyTree &graphNode)
  66. {
  67. if (graphNode.hasProp("att[@name='_indexFile_dynamic']"))
  68. return NULL;
  69. else
  70. return graphNode.queryProp("att[@name='_indexFileName']/@value");
  71. }
  72. static bool isSimpleIndexActivity(ThorActivityKind kind)
  73. {
  74. switch (kind)
  75. {
  76. case TAKindexaggregate:
  77. case TAKindexcount:
  78. case TAKindexexists:
  79. case TAKindexgroupaggregate:
  80. case TAKindexgroupcount:
  81. case TAKindexgroupexists:
  82. case TAKindexnormalize:
  83. case TAKindexread:
  84. return true;
  85. default:
  86. return false;
  87. }
  88. }
  89. const char *queryNodeFileName(const IPropertyTree &graphNode, ThorActivityKind kind)
  90. {
  91. if (isSimpleIndexActivity(kind))
  92. return NULL;
  93. else
  94. return _queryNodeFileName(graphNode);
  95. }
  96. const char *queryNodeIndexName(const IPropertyTree &graphNode, ThorActivityKind kind)
  97. {
  98. if (isSimpleIndexActivity(kind))
  99. return _queryNodeFileName(graphNode);
  100. else
  101. return _queryNodeIndexName(graphNode);
  102. }
  103. // DelayedReleaser mechanism hangs on to a link to an object for a while...
  104. class DelayedReleaseQueueItem : public CInterfaceOf<IInterface>
  105. {
  106. Owned<IInterface> goer;
  107. time_t goTime;
  108. public:
  109. DelayedReleaseQueueItem(IInterface *_goer, unsigned delaySeconds)
  110. : goer(_goer)
  111. {
  112. time(&goTime);
  113. goTime += delaySeconds;
  114. }
  115. unsigned remaining()
  116. {
  117. time_t now;
  118. time(&now);
  119. if (now > goTime)
  120. return 0;
  121. else
  122. return goTime - now;
  123. }
  124. };
  125. class DelayedReleaserThread : public Thread
  126. {
  127. private:
  128. bool closing;
  129. bool started;
  130. CriticalSection lock;
  131. IArrayOf<DelayedReleaseQueueItem> queue;
  132. Semaphore sem;
  133. public:
  134. DelayedReleaserThread() : Thread("DelayedReleaserThread")
  135. {
  136. closing = false;
  137. started = false;
  138. }
  139. ~DelayedReleaserThread()
  140. {
  141. stop();
  142. }
  143. virtual int run()
  144. {
  145. if (traceLevel)
  146. DBGLOG("DelayedReleaserThread %p starting", this);
  147. unsigned nextTimeout = INFINITE;
  148. while (!closing)
  149. {
  150. sem.wait(nextTimeout);
  151. CriticalBlock b(lock);
  152. nextTimeout = INFINITE;
  153. ForEachItemInRev(idx, queue)
  154. {
  155. DelayedReleaseQueueItem &goer = queue.item(idx);
  156. unsigned timeRemaining = goer.remaining();
  157. if (!timeRemaining)
  158. queue.remove(idx);
  159. else if (timeRemaining < nextTimeout)
  160. nextTimeout = timeRemaining;
  161. }
  162. if (nextTimeout != INFINITE)
  163. nextTimeout = nextTimeout * 1000;
  164. }
  165. if (traceLevel)
  166. DBGLOG("DelayedReleaserThread %p exiting", this);
  167. return 0;
  168. }
  169. void stop()
  170. {
  171. if (started)
  172. {
  173. closing = true;
  174. sem.signal();
  175. join();
  176. }
  177. }
  178. void delayedRelease(IInterface *goer, unsigned delaySeconds)
  179. {
  180. if (goer)
  181. {
  182. CriticalBlock b(lock);
  183. if (!started)
  184. {
  185. start();
  186. started = true;
  187. }
  188. queue.append(*new DelayedReleaseQueueItem(goer, delaySeconds));
  189. sem.signal();
  190. }
  191. }
  192. };
  193. Owned<DelayedReleaserThread> delayedReleaser;
  194. void createDelayedReleaser()
  195. {
  196. delayedReleaser.setown(new DelayedReleaserThread);
  197. }
  198. void stopDelayedReleaser()
  199. {
  200. if (delayedReleaser)
  201. delayedReleaser->stop();
  202. delayedReleaser.clear();
  203. }
  204. //-------------------------------------------------------------------------
  205. class CSimpleSuperFileArray : public CInterface, implements ISimpleSuperFileEnquiry
  206. {
  207. IArrayOf<IPropertyTree> subFiles;
  208. public:
  209. IMPLEMENT_IINTERFACE;
  210. CSimpleSuperFileArray(IPropertyTreeIterator &_subs)
  211. {
  212. ForEach(_subs)
  213. {
  214. IPropertyTree &sub = _subs.query();
  215. sub.Link();
  216. subFiles.append(sub);
  217. }
  218. }
  219. virtual unsigned numSubFiles() const
  220. {
  221. return subFiles.length();
  222. }
  223. virtual bool getSubFileName(unsigned num, StringBuffer &name) const
  224. {
  225. if (subFiles.isItem(num))
  226. {
  227. name.append(subFiles.item(num).queryProp("@value"));
  228. return true;
  229. }
  230. else
  231. return false;
  232. }
  233. virtual unsigned findSubName(const char *subname) const
  234. {
  235. ForEachItemIn(idx, subFiles)
  236. {
  237. if (stricmp(subFiles.item(idx).queryProp("@value"), subname))
  238. return idx;
  239. }
  240. return NotFound;
  241. }
  242. virtual unsigned getContents(StringArray &contents) const
  243. {
  244. ForEachItemIn(idx, subFiles)
  245. {
  246. contents.append(subFiles.item(idx).queryProp("@value"));
  247. }
  248. return subFiles.length();
  249. }
  250. };
  251. //-------------------------------------------------------------------------------------------
  252. // class CRoxiePackage - provide the environment in which file names and query options are interpreted
  253. // by a roxie query.
  254. // File names are resolved into IResolvedFile objects. A cache is used to ensure that the IResolvedFile is
  255. // shared wherever possible.
  256. // Effective environment is precomputed in mergedEnvironment for efficient recall by queries
  257. // Packages are described using XML files - see documentation for details.
  258. //-------------------------------------------------------------------------------------------
  259. /**
  260. * Packages are hierarchical - they are searched recursively to get the info you want
  261. * A PackageMap defines the entire environment - potentially each query that uses that PackageMap will pick a different package within it
  262. * A particular instantiation of a roxie query (i.e. a IQueryFactory) will have a pointer to the specific IRoxiePackage within the active PackageMap
  263. * that is providing its environment.
  264. *
  265. * A PackageMap can also indicate the name of the QuerySet it applies to. If not specified, at will apply to all QuerySets on the Roxie.
  266. *
  267. * A PackageSet is a list of PackageMap id's, and is used to tell Roxie what PackageMaps to load.
  268. * A Roxie can have multiple PackageMap's active. When updating the data, you might:
  269. * - create a new PackageMap to refer to the new data
  270. * - once it has loaded, mark it active, and mark the previous one as inactive
  271. * - Once sure no queries in flight, unload the previous one
  272. *
  273. * Each Roxie will load all PackageMaps that are in any PackageSet whose @process attribute matches the cluster name.
  274. *
  275. * All package information is stored in Dali (and cached locally)
  276. *
  277. * <PackageSets>
  278. * <PackageSet id = 'ps1' process='*'> # use this packageset for all roxies (same as omitting process)
  279. * <PackageMap id='pm1b' querySet='qs1' active='true'/> # Use the PackageMap pm1b for QuerySet qs1 and make it active
  280. * <PackageMap id='pm1a' querySet='qs1' active='false'/> # Use the PackageMap pm1a for QuerySet qs1 but don't make it active
  281. * <PackageMap id='pm2' querySet='dev*' active='true'/> # Use the PackageMap pm1a for all QuerySets with names starting dev and make it active
  282. * </PackageMapSet>
  283. * </PackageSets>
  284. *
  285. * <PackageMaps>
  286. * <PackageMap id='pm1a'>
  287. * <Package id='package1'>
  288. * ...
  289. * </Package>
  290. * <Package id='package2'>
  291. * </Package>
  292. * </PackageMap>
  293. * <PackageMap id='pm2'>
  294. * </PackageMap>
  295. * <PackageMap id='pm3'>
  296. * </PackageMap>
  297. * </PackageMaps>
  298. */
  299. class CResolvedFileCache : implements IResolvedFileCache
  300. {
  301. CriticalSection cacheLock;
  302. CopyMapStringToMyClass<IResolvedFile> files;
  303. public:
  304. // Retrieve number of files in cache
  305. inline unsigned count() const
  306. {
  307. return files.count();
  308. }
  309. // Add a filename and the corresponding IResolvedFile to the cache
  310. virtual void addCache(const char *filename, const IResolvedFile *file)
  311. {
  312. CriticalBlock b(cacheLock);
  313. IResolvedFile *add = const_cast<IResolvedFile *>(file);
  314. add->setCache(this);
  315. files.setValue(filename, add);
  316. }
  317. // Remove an IResolvedFile from the cache
  318. virtual void removeCache(const IResolvedFile *file)
  319. {
  320. CriticalBlock b(cacheLock);
  321. if (traceLevel > 9)
  322. DBGLOG("removeCache %s", file->queryFileName());
  323. // NOTE: it's theoretically possible for the final release to happen after a replacement has been inserted into hash table.
  324. // So only remove from hash table if what we find there matches the item that is being deleted.
  325. IResolvedFile *goer = files.getValue(file->queryFileName());
  326. if (goer == file)
  327. files.remove(file->queryFileName());
  328. // You might want to remove files from the daliServer cache too, but it's not safe to do so here as there may be multiple package caches
  329. }
  330. // Lookup a filename in the cache
  331. virtual IResolvedFile *lookupCache(const char *filename)
  332. {
  333. CriticalBlock b(cacheLock);
  334. IResolvedFile *cache = files.getValue(filename);
  335. if (cache)
  336. {
  337. LINK(cache);
  338. if (cache->isAlive())
  339. return cache;
  340. if (traceLevel)
  341. DBGLOG("Not returning %s from cache as isAlive() returned false", filename);
  342. }
  343. return NULL;
  344. }
  345. };
  346. // Note - we use a separate cache for the misses rather than any clever attempts to overload
  347. // the one cache with a "special" value, since (among other reasons) the misses are cleared
  348. // prior to a package reload, but the hits need not be (as the file will be locked as long as it
  349. // is in the cache)
  350. static CriticalSection daliMissesCrit;
  351. static Owned<KeptLowerCaseAtomTable> daliMisses;
  352. static void noteDaliMiss(const char *filename)
  353. {
  354. CriticalBlock b(daliMissesCrit);
  355. if (traceLevel > 9)
  356. DBGLOG("noteDaliMiss %s", filename);
  357. daliMisses->addAtom(filename);
  358. }
  359. static bool checkCachedDaliMiss(const char *filename)
  360. {
  361. CriticalBlock b(daliMissesCrit);
  362. bool ret = daliMisses->find(filename) != NULL;
  363. if (traceLevel > 9)
  364. DBGLOG("checkCachedDaliMiss %s returns %d", filename, ret);
  365. return ret;
  366. }
  367. static void clearDaliMisses()
  368. {
  369. CriticalBlock b(daliMissesCrit);
  370. if (traceLevel)
  371. DBGLOG("Clearing dali misses cache");
  372. daliMisses.setown(new KeptLowerCaseAtomTable);
  373. }
  374. class CRoxiePackageNode : extends CPackageNode, implements IRoxiePackage
  375. {
  376. protected:
  377. static CResolvedFileCache daliFiles;
  378. mutable CResolvedFileCache fileCache;
  379. virtual aindex_t getBaseCount() const = 0;
  380. virtual const CRoxiePackageNode *getBaseNode(aindex_t pos) const = 0;
  381. virtual bool getSysFieldTranslationEnabled() const {return fieldTranslationEnabled;} //roxie configured value
  382. // Use local package file only to resolve subfile into physical file info
  383. IResolvedFile *resolveLFNusingPackage(const char *fileName) const
  384. {
  385. if (node)
  386. {
  387. StringBuffer xpath;
  388. IPropertyTree *fileInfo = node->queryPropTree(xpath.appendf("File[@id='%s']", fileName).str());
  389. if (fileInfo)
  390. {
  391. Owned <IResolvedFileCreator> result = createResolvedFile(fileName, NULL, false);
  392. result->addSubFile(createFileDescriptorFromRoxieXML(fileInfo), NULL);
  393. return result.getClear();
  394. }
  395. }
  396. return NULL;
  397. }
  398. // Use dali to resolve subfile into physical file info
  399. static IResolvedFile *resolveLFNusingDaliOrLocal(const char *fileName, bool useCache, bool cacheResult, bool writeAccess, bool alwaysCreate)
  400. {
  401. // MORE - look at alwaysCreate... This may be useful to implement earlier locking semantics.
  402. if (traceLevel > 9)
  403. DBGLOG("resolveLFNusingDaliOrLocal %s %d %d %d %d", fileName, useCache, cacheResult, writeAccess, alwaysCreate);
  404. IResolvedFile* result = NULL;
  405. if (useCache)
  406. {
  407. result = daliFiles.lookupCache(fileName);
  408. if (result)
  409. {
  410. if (traceLevel > 9)
  411. DBGLOG("resolveLFNusingDaliOrLocal %s - cache hit", fileName);
  412. return result;
  413. }
  414. }
  415. if (alwaysCreate || !useCache || !checkCachedDaliMiss(fileName))
  416. {
  417. Owned<IRoxieDaliHelper> daliHelper = connectToDali();
  418. if (daliHelper)
  419. {
  420. if (daliHelper->connected())
  421. {
  422. Owned<IDistributedFile> dFile = daliHelper->resolveLFN(fileName, cacheResult, writeAccess);
  423. if (dFile)
  424. result = createResolvedFile(fileName, NULL, dFile.getClear(), daliHelper, !useCache, cacheResult, writeAccess);
  425. }
  426. else if (!writeAccess) // If we need write access and expect a dali, but don't have one, we should probably fail
  427. {
  428. // we have no dali, we can't lock..
  429. Owned<IFileDescriptor> fd = daliHelper->resolveCachedLFN(fileName);
  430. if (fd)
  431. {
  432. Owned <IResolvedFileCreator> creator = createResolvedFile(fileName, NULL, false);
  433. Owned<IFileDescriptor> remoteFDesc = daliHelper->checkClonedFromRemote(fileName, fd, cacheResult);
  434. creator->addSubFile(fd.getClear(), remoteFDesc.getClear());
  435. result = creator.getClear();
  436. }
  437. }
  438. }
  439. if (!result)
  440. {
  441. StringBuffer useName;
  442. bool wasDFS = false;
  443. if (strstr(fileName,"::"))
  444. {
  445. makeSinglePhysicalPartName(fileName, useName, true, wasDFS);
  446. }
  447. else
  448. useName.append(fileName);
  449. bool exists = checkFileExists(useName);
  450. if (exists || alwaysCreate)
  451. {
  452. Owned <IResolvedFileCreator> creator = createResolvedFile(fileName, wasDFS ? NULL : useName.str(), false);
  453. if (exists)
  454. creator->addSubFile(useName);
  455. result = creator.getClear();
  456. }
  457. }
  458. }
  459. if (cacheResult)
  460. {
  461. if (traceLevel > 9)
  462. DBGLOG("resolveLFNusingDaliOrLocal %s - cache add %d", fileName, result != NULL);
  463. if (result)
  464. daliFiles.addCache(fileName, result);
  465. else
  466. noteDaliMiss(fileName);
  467. }
  468. return result;
  469. }
  470. // Use local package and its bases to resolve existing file into physical file info via all supported resolvers
  471. IResolvedFile *lookupExpandedFileName(const char *fileName, bool useCache, bool cacheResult, bool writeAccess, bool alwaysCreate, bool checkCompulsory) const
  472. {
  473. IResolvedFile *result = lookupFile(fileName, useCache, cacheResult, writeAccess, alwaysCreate);
  474. if (!result && (!checkCompulsory || !isCompulsory()))
  475. result = resolveLFNusingDaliOrLocal(fileName, useCache, cacheResult, writeAccess, alwaysCreate);
  476. return result;
  477. }
  478. IResolvedFile *lookupFile(const char *fileName, bool useCache, bool cacheResult, bool writeAccess, bool alwaysCreate) const
  479. {
  480. // Order of resolution:
  481. // 1. Files named in package
  482. // 2. Files named in bases
  483. IResolvedFile* result = useCache ? fileCache.lookupCache(fileName) : NULL;
  484. if (result)
  485. return result;
  486. Owned<const ISimpleSuperFileEnquiry> subFileInfo = resolveSuperFile(fileName);
  487. if (subFileInfo)
  488. {
  489. unsigned numSubFiles = subFileInfo->numSubFiles();
  490. // Note: do not try to optimize the common case of a single subfile
  491. // as we still want to report the superfile info from the resolvedFile
  492. Owned<IResolvedFileCreator> super;
  493. for (unsigned idx = 0; idx < numSubFiles; idx++)
  494. {
  495. StringBuffer subFileName;
  496. subFileInfo->getSubFileName(idx, subFileName);
  497. if (subFileName.length()) // Empty subfile names can come from package file - just ignore
  498. {
  499. if (subFileName.charAt(0)=='~')
  500. {
  501. // implies that a package file had ~ in subfile names - shouldn't really, but we allow it (and just strip the ~)
  502. subFileName.remove(0,1);
  503. }
  504. if (traceLevel > 9)
  505. DBGLOG("Looking up subfile %s", subFileName.str());
  506. Owned<const IResolvedFile> subFileInfo = lookupExpandedFileName(subFileName, useCache, cacheResult, false, false, false); // NOTE - overwriting a superfile does NOT require write access to subfiles
  507. if (subFileInfo)
  508. {
  509. if (!super)
  510. super.setown(createResolvedFile(fileName, NULL, true));
  511. super->addSubFile(subFileInfo);
  512. }
  513. }
  514. }
  515. if (super && cacheResult)
  516. fileCache.addCache(fileName, super);
  517. return super.getClear();
  518. }
  519. result = resolveLFNusingPackage(fileName);
  520. if (result)
  521. {
  522. if (cacheResult)
  523. fileCache.addCache(fileName, result);
  524. return result;
  525. }
  526. aindex_t count = getBaseCount();
  527. for (aindex_t i = 0; i < count; i++)
  528. {
  529. const CRoxiePackageNode *basePackage = getBaseNode(i);
  530. if (!basePackage)
  531. continue;
  532. IResolvedFile *result = basePackage->lookupFile(fileName, useCache, cacheResult, writeAccess, alwaysCreate);
  533. if (result)
  534. return result;
  535. }
  536. return NULL;
  537. }
  538. // default constructor for derived class use
  539. CRoxiePackageNode()
  540. {
  541. }
  542. public:
  543. IMPLEMENT_IINTERFACE;
  544. CRoxiePackageNode(IPropertyTree *p) : CPackageNode(p)
  545. {
  546. }
  547. ~CRoxiePackageNode()
  548. {
  549. assertex(fileCache.count()==0);
  550. // If it's possible for cached objects to outlive the cache I think there is a problem...
  551. // we could set the cache field to null here for any objects still in cache but there would be a race condition
  552. }
  553. virtual IPropertyTreeIterator *getInMemoryIndexInfo(const IPropertyTree &graphNode) const
  554. {
  555. StringBuffer xpath;
  556. xpath.append("SuperFile[@id='").append(queryNodeFileName(graphNode, getActivityKind(graphNode))).append("']");
  557. return lookupElements(xpath.str(), "MemIndex");
  558. }
  559. virtual const IResolvedFile *lookupFileName(const char *_fileName, bool opt, bool useCache, bool cacheResult, IConstWorkUnit *wu) const
  560. {
  561. StringBuffer fileName;
  562. expandLogicalFilename(fileName, _fileName, wu, false);
  563. if (traceLevel > 5)
  564. DBGLOG("lookupFileName %s", fileName.str());
  565. const IResolvedFile *result = lookupExpandedFileName(fileName, useCache, cacheResult, false, false, true);
  566. if (!result)
  567. {
  568. StringBuffer compulsoryMsg;
  569. if (isCompulsory())
  570. compulsoryMsg.append(" (Package is compulsory)");
  571. if (!opt)
  572. throw MakeStringException(ROXIE_FILE_ERROR, "Could not resolve filename %s%s", fileName.str(), compulsoryMsg.str());
  573. if (traceLevel > 4)
  574. DBGLOG("Could not resolve OPT filename %s%s", fileName.str(), compulsoryMsg.str());
  575. }
  576. return result;
  577. }
  578. virtual IRoxieWriteHandler *createFileName(const char *_fileName, bool overwrite, bool extend, const StringArray &clusters, IConstWorkUnit *wu) const
  579. {
  580. StringBuffer fileName;
  581. expandLogicalFilename(fileName, _fileName, wu, false);
  582. Owned<IResolvedFile> resolved = lookupFile(fileName, false, false, true, true);
  583. if (!resolved)
  584. resolved.setown(resolveLFNusingDaliOrLocal(fileName, false, false, true, true));
  585. if (resolved)
  586. {
  587. if (resolved->exists())
  588. {
  589. if (!overwrite)
  590. throw MakeStringException(99, "Cannot write %s, file already exists (missing OVERWRITE attribute?)", resolved->queryFileName());
  591. if (extend)
  592. UNIMPLEMENTED; // How does extend fit in with the clusterwritemanager stuff? They can't specify cluster and extend together...
  593. resolved->setCache(NULL);
  594. resolved->remove();
  595. }
  596. if (resolved->queryPhysicalName())
  597. fileName.clear().append(resolved->queryPhysicalName()); // if it turned out to be a local file
  598. resolved.clear();
  599. }
  600. else
  601. throw MakeStringException(ROXIE_FILE_ERROR, "Cannot write %s", fileName.str());
  602. // filename by now may be a local filename, or a dali one
  603. Owned<IRoxieDaliHelper> daliHelper = connectToDali();
  604. Owned<ILocalOrDistributedFile> ldFile = createLocalOrDistributedFile(fileName, NULL, false, false, true);
  605. if (!ldFile)
  606. throw MakeStringException(ROXIE_FILE_ERROR, "Cannot write %s", fileName.str());
  607. return createRoxieWriteHandler(daliHelper, ldFile.getClear(), clusters);
  608. }
  609. //map ambiguous IHpccPackage
  610. virtual ISimpleSuperFileEnquiry *resolveSuperFile(const char *superFileName) const
  611. {
  612. return CPackageNode::resolveSuperFile(superFileName);
  613. }
  614. virtual const char *queryEnv(const char *varname) const
  615. {
  616. return CPackageNode::queryEnv(varname);
  617. }
  618. virtual bool getEnableFieldTranslation() const
  619. {
  620. return CPackageNode::getEnableFieldTranslation();
  621. }
  622. virtual const IPropertyTree *queryTree() const
  623. {
  624. return CPackageNode::queryTree();
  625. }
  626. virtual hash64_t queryHash() const
  627. {
  628. return CPackageNode::queryHash();
  629. }
  630. virtual const char *queryId() const
  631. {
  632. return CPackageNode::queryId();
  633. }
  634. };
  635. CResolvedFileCache CRoxiePackageNode::daliFiles;
  636. typedef CResolvedPackage<CRoxiePackageNode> CRoxiePackage;
  637. IRoxiePackage *createRoxiePackage(IPropertyTree *p, IRoxiePackageMap *packages)
  638. {
  639. Owned<CRoxiePackage> pkg = new CRoxiePackage(p);
  640. if (packages)
  641. pkg->resolveBases(packages);
  642. return pkg.getClear();
  643. }
  644. //================================================================================================
  645. // CPackageMap - an implementation of IPackageMap using a string map
  646. //================================================================================================
  647. class CRoxiePackageMap : public CPackageMapOf<CRoxiePackageNode, IRoxiePackage>, implements IRoxiePackageMap
  648. {
  649. public:
  650. IMPLEMENT_IINTERFACE;
  651. typedef CPackageMapOf<CRoxiePackageNode, IRoxiePackage> BASE;
  652. CRoxiePackageMap(const char *_packageId, const char *_querySet, bool _active)
  653. : BASE(_packageId, _querySet, _active)
  654. {
  655. }
  656. //map ambiguous IHpccPackageMap interface
  657. virtual const IHpccPackage *queryPackage(const char *name) const
  658. {
  659. return BASE::queryPackage(name);
  660. }
  661. virtual const IHpccPackage *matchPackage(const char *name) const
  662. {
  663. return BASE::matchPackage(name);
  664. }
  665. virtual const char *queryPackageId() const
  666. {
  667. return BASE::queryPackageId();
  668. }
  669. virtual bool isActive() const
  670. {
  671. return BASE::isActive();
  672. }
  673. virtual bool validate(StringArray &queryids, StringArray &wrn, StringArray &err, StringArray &unmatchedQueries, StringArray &unusedPackages, StringArray &unmatchedFiles) const
  674. {
  675. return BASE::validate(queryids, wrn, err, unmatchedQueries, unusedPackages, unmatchedFiles);
  676. }
  677. virtual void gatherFileMappingForQuery(const char *queryname, IPropertyTree *fileInfo) const
  678. {
  679. BASE::gatherFileMappingForQuery(queryname, fileInfo);
  680. }
  681. virtual const IRoxiePackage *queryRoxiePackage(const char *name) const
  682. {
  683. return queryResolvedPackage(name);
  684. }
  685. virtual const IRoxiePackage *matchRoxiePackage(const char *name) const
  686. {
  687. return matchResolvedPackage(name);
  688. }
  689. };
  690. static CRoxiePackageMap *emptyPackageMap;
  691. static CRoxiePackage *rootPackage;
  692. static SpinLock emptyPackageMapCrit;
  693. static IRoxieDebugSessionManager *debugSessionManager;
  694. extern const IRoxiePackage &queryRootRoxiePackage()
  695. {
  696. SpinBlock b(emptyPackageMapCrit);
  697. if (!rootPackage)
  698. {
  699. // Set up the root package. This contains global settings from topology file
  700. rootPackage = new CRoxiePackage(topology); // attributes become control: environment settings. Rest of topology ignored.
  701. rootPackage->resolveBases(NULL);
  702. }
  703. return *rootPackage;
  704. }
  705. extern const IRoxiePackageMap &queryEmptyRoxiePackageMap()
  706. {
  707. SpinBlock b(emptyPackageMapCrit);
  708. if (!emptyPackageMap)
  709. emptyPackageMap = new CRoxiePackageMap("<none>", NULL, true);
  710. return *emptyPackageMap;
  711. }
  712. MODULE_INIT(INIT_PRIORITY_STANDARD)
  713. {
  714. emptyPackageMap = NULL;
  715. debugSessionManager = NULL;
  716. return true;
  717. }
  718. MODULE_EXIT()
  719. {
  720. ::Release(emptyPackageMap); // You can't use static Owned to release anything that may own a IPropertyTree
  721. ::Release(rootPackage);
  722. ::Release(debugSessionManager);
  723. }
  724. // IRoxieQuerySetManager
  725. // - CRoxieQuerySetManager -
  726. // - CRoxieServerQuerySetManager
  727. // - CRoxieSlaveQuerySetManager
  728. //
  729. // Manages a set of instantiated queries and allows us to look them up by queryname or alias
  730. //
  731. // IRoxieQuerySetManagerSet
  732. // - CRoxieSlaveQuerySetManagerSet
  733. //
  734. // Manages the IRoxieQuerySetManager for multiple channels
  735. //
  736. // CRoxieQueryPackageManager
  737. // - CRoxieDaliQueryPackageManager
  738. // - CStandaloneQueryPackageManager
  739. //
  740. // Groups a server resource manager and a set of slave resource managers (one per channel) together.
  741. // There is one per PackageMap
  742. //
  743. // CQueryPackageSetManager at outer level
  744. // There will be exactly one of these. It will reload the CQueryPackageManager's if dali Package info changes
  745. //================================================================================================
  746. // CRoxieQuerySetManager - shared base class for slave and server query set manager classes
  747. // Manages a set of instantiated queries and allows us to look them up by queryname or alias,
  748. // as well as controlling their lifespan
  749. //================================================================================================
  750. class CRoxieQuerySetManager : public CInterface, implements IRoxieQuerySetManager
  751. {
  752. protected:
  753. MapStringToMyClass<IQueryFactory> queries;
  754. MapStringToMyClass<IQueryFactory> aliases; // Do we gain anything by having two tables?
  755. unsigned channelNo;
  756. bool active;
  757. StringAttr querySetName;
  758. void addQuery(const char *id, IQueryFactory *n, hash64_t &hash)
  759. {
  760. hash = rtlHash64Data(sizeof(hash), &hash, n->queryHash());
  761. queries.setValue(id, n);
  762. n->Release(); // setValue links
  763. }
  764. void addAlias(const char *alias, const char *original, hash64_t &hash)
  765. {
  766. if (original && alias)
  767. {
  768. IQueryFactory *orig = queries.getValue(original);
  769. if (orig)
  770. {
  771. hash = rtlHash64VStr(alias, hash);
  772. hash = rtlHash64Data(sizeof(hash), &hash, orig->queryHash());
  773. aliases.setValue(alias, orig);
  774. }
  775. else
  776. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", original);
  777. }
  778. else
  779. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Invalid parameters to addAlias");
  780. }
  781. virtual IQueryFactory *loadQueryFromDll(const char *id, const IQueryDll *dll, const IRoxiePackage &package, const IPropertyTree *stateInfo, bool forceRetry) = 0;
  782. public:
  783. IMPLEMENT_IINTERFACE;
  784. CRoxieQuerySetManager(unsigned _channelNo, const char *_querySetName)
  785. : queries(true), aliases(true), active(false), querySetName(_querySetName)
  786. {
  787. channelNo = _channelNo;
  788. }
  789. virtual const char *queryId() const
  790. {
  791. return querySetName;
  792. }
  793. virtual bool isActive() const
  794. {
  795. return active;
  796. }
  797. virtual void load(const IPropertyTree *querySet, const IRoxiePackageMap &packages, hash64_t &hash, bool forceRetry)
  798. {
  799. Owned<IPropertyTreeIterator> queryNames = querySet->getElements("Query");
  800. ForEach (*queryNames)
  801. {
  802. const IPropertyTree &query = queryNames->query();
  803. const char *id = query.queryProp("@id");
  804. const char *dllName = query.queryProp("@dll");
  805. try
  806. {
  807. if (!id || !*id || !dllName || !*dllName)
  808. throw MakeStringException(ROXIE_QUERY_MODIFICATION, "dll and id must be specified");
  809. Owned<const IQueryDll> queryDll = createQueryDll(dllName);
  810. const IHpccPackage *package = NULL;
  811. const char *packageName = query.queryProp("@package");
  812. if (packageName && *packageName)
  813. {
  814. package = packages.queryPackage(packageName); // if a package is specified, require exact match
  815. if (!package)
  816. throw MakeStringException(ROXIE_QUERY_MODIFICATION, "Package %s specified by query %s not found", packageName, id);
  817. }
  818. else
  819. {
  820. package = packages.queryPackage(id); // Look for an exact match, then a fuzzy match, using query name as the package id
  821. if(!package) package = packages.matchPackage(id);
  822. if (!package) package = &queryRootRoxiePackage();
  823. }
  824. assertex(package && QUERYINTERFACE(package, const IRoxiePackage));
  825. addQuery(id, loadQueryFromDll(id, queryDll.getClear(), *QUERYINTERFACE(package, const IRoxiePackage), &query, forceRetry), hash);
  826. }
  827. catch (IException *E)
  828. {
  829. // we don't want a single bad query in the set to stop us loading all the others
  830. StringBuffer msg;
  831. msg.appendf("Failed to load query %s from %s", id ? id : "(null)", dllName ? dllName : "(null)");
  832. EXCLOG(E, msg.str());
  833. if (id)
  834. {
  835. StringBuffer emsg;
  836. E->errorMessage(emsg);
  837. Owned<IQueryFactory> dummyQuery = loadQueryFromDll(id, NULL, queryRootRoxiePackage(), NULL, false);
  838. dummyQuery->suspend(emsg.str());
  839. addQuery(id, dummyQuery.getClear(), hash);
  840. }
  841. E->Release();
  842. }
  843. }
  844. Owned<IPropertyTreeIterator> a = querySet->getElements("Alias");
  845. ForEach(*a)
  846. {
  847. IPropertyTree &item = a->query();
  848. const char *alias = item.queryProp("@name");
  849. const char *original = item.queryProp("@id");
  850. try
  851. {
  852. addAlias(alias, original, hash);
  853. }
  854. catch (IException *E)
  855. {
  856. // we don't want a single bad alias in the set to stop us loading all the others
  857. VStringBuffer msg("Failed to set alias %s on %s", alias, original);
  858. EXCLOG(E, msg.str());
  859. E->Release();
  860. }
  861. }
  862. active = packages.isActive();
  863. if (active)
  864. hash = rtlHash64VStr("active", hash);
  865. }
  866. virtual void getStats(const char *queryName, const char *graphName, StringBuffer &reply, const IRoxieContextLogger &logctx) const
  867. {
  868. Owned<IQueryFactory> f = getQuery(queryName, NULL, logctx);
  869. if (f)
  870. {
  871. reply.appendf("<Query id='%s'>\n", queryName);
  872. f->getStats(reply, graphName);
  873. reply.append("</Query>\n");
  874. }
  875. else
  876. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", queryName);
  877. }
  878. virtual void resetQueryTimings(const char *queryName, const IRoxieContextLogger &logctx)
  879. {
  880. Owned<IQueryFactory> f = getQuery(queryName, NULL, logctx);
  881. if (f)
  882. f->resetQueryTimings();
  883. else
  884. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", queryName);
  885. }
  886. virtual void resetAllQueryTimings()
  887. {
  888. HashIterator elems(queries);
  889. for (elems.first(); elems.isValid(); elems.next())
  890. {
  891. IMapping &cur = elems.query();
  892. queries.mapToValue(&cur)->resetQueryTimings();
  893. }
  894. }
  895. virtual void getActivityMetrics(StringBuffer &reply) const
  896. {
  897. HashIterator elems(queries);
  898. for (elems.first(); elems.isValid(); elems.next())
  899. {
  900. IMapping &cur = elems.query();
  901. queries.mapToValue(&cur)->getActivityMetrics(reply);
  902. }
  903. }
  904. virtual void getAllQueryInfo(StringBuffer &reply, bool full, const IRoxieContextLogger &logctx) const
  905. {
  906. HashIterator elems(queries);
  907. for (elems.first(); elems.isValid(); elems.next())
  908. {
  909. IMapping &cur = elems.query();
  910. IQueryFactory *query = queries.mapToValue(&cur);
  911. query->getQueryInfo(reply, full, logctx);
  912. }
  913. HashIterator aliasIterator(aliases);
  914. for (aliasIterator.first(); aliasIterator.isValid(); aliasIterator.next())
  915. {
  916. IMapping &cur = aliasIterator.query();
  917. reply.appendf(" <Alias id='%s' query='%s'/>\n", (const char *) cur.getKey(), aliases.mapToValue(&cur)->queryQueryName());
  918. }
  919. }
  920. virtual IQueryFactory *getQuery(const char *id, StringBuffer *querySet, const IRoxieContextLogger &logctx) const
  921. {
  922. IQueryFactory *ret;
  923. ret = aliases.getValue(id);
  924. if (ret && logctx.queryTraceLevel() > 5)
  925. logctx.CTXLOG("Found query alias %s => %s", id, ret->queryQueryName());
  926. if (!ret)
  927. ret = queries.getValue(id);
  928. if (ret && querySet)
  929. querySet->set(querySetName);
  930. return LINK(ret);
  931. }
  932. };
  933. //===============================================================================================================
  934. class CRoxieServerQuerySetManager : public CRoxieQuerySetManager
  935. {
  936. public:
  937. IMPLEMENT_IINTERFACE;
  938. CRoxieServerQuerySetManager(const char *_querySetName)
  939. : CRoxieQuerySetManager(0, _querySetName)
  940. {
  941. }
  942. virtual IQueryFactory * loadQueryFromDll(const char *id, const IQueryDll *dll, const IRoxiePackage &package, const IPropertyTree *stateInfo, bool forceRetry)
  943. {
  944. return createServerQueryFactory(id, dll, package, stateInfo, false, forceRetry);
  945. }
  946. };
  947. extern IRoxieQuerySetManager *createServerManager(const char *querySet)
  948. {
  949. return new CRoxieServerQuerySetManager(querySet);
  950. }
  951. //===============================================================================================================
  952. class CRoxieSlaveQuerySetManager : public CRoxieQuerySetManager
  953. {
  954. public:
  955. IMPLEMENT_IINTERFACE;
  956. CRoxieSlaveQuerySetManager(unsigned _channelNo, const char *_querySetName)
  957. : CRoxieQuerySetManager(_channelNo, _querySetName)
  958. {
  959. channelNo = _channelNo;
  960. }
  961. virtual IQueryFactory *loadQueryFromDll(const char *id, const IQueryDll *dll, const IRoxiePackage &package, const IPropertyTree *stateInfo, bool forceRetry)
  962. {
  963. return createSlaveQueryFactory(id, dll, package, channelNo, stateInfo, false, forceRetry);
  964. }
  965. };
  966. class CRoxieSlaveQuerySetManagerSet : public CInterface, implements IRoxieQuerySetManagerSet
  967. {
  968. public:
  969. IMPLEMENT_IINTERFACE;
  970. CRoxieSlaveQuerySetManagerSet(unsigned _numChannels, const char *querySetName)
  971. : numChannels(_numChannels)
  972. {
  973. CriticalBlock b(ccdChannelsCrit);
  974. managers = new CRoxieSlaveQuerySetManager *[numChannels];
  975. memset(managers, 0, sizeof(CRoxieSlaveQuerySetManager *) * numChannels);
  976. Owned<IPropertyTreeIterator> it = ccdChannels->getElements("RoxieSlaveProcess");
  977. ForEach(*it)
  978. {
  979. unsigned channelNo = it->query().getPropInt("@channel", 0);
  980. assertex(channelNo>0 && channelNo<=numChannels);
  981. if (managers[channelNo-1] == NULL)
  982. managers[channelNo-1] = new CRoxieSlaveQuerySetManager(channelNo, querySetName);
  983. else
  984. throw MakeStringException(ROXIE_INVALID_TOPOLOGY, "Invalid topology file - channel %d repeated for this slave", channelNo);
  985. }
  986. }
  987. ~CRoxieSlaveQuerySetManagerSet()
  988. {
  989. for (unsigned channel = 0; channel < numChannels; channel++)
  990. ::Release(managers[channel]);
  991. delete [] managers;
  992. }
  993. inline CRoxieSlaveQuerySetManager *item(int idx)
  994. {
  995. return managers[idx];
  996. }
  997. virtual void load(const IPropertyTree *querySets, const IRoxiePackageMap &packages, hash64_t &hash, bool forceRetry)
  998. {
  999. for (unsigned channel = 0; channel < numChannels; channel++)
  1000. if (managers[channel])
  1001. managers[channel]->load(querySets, packages, hash, forceRetry); // MORE - this means the hash depends on the number of channels. Is that desirable?
  1002. }
  1003. private:
  1004. unsigned numChannels;
  1005. CRoxieSlaveQuerySetManager **managers;
  1006. };
  1007. //===============================================================================================================
  1008. class CRoxieDebugSessionManager : public CInterface, implements IRoxieDebugSessionManager
  1009. {
  1010. protected:
  1011. ReadWriteLock debugLock;
  1012. MapStringToMyClass<IDebuggerContext> debuggerContexts;
  1013. public:
  1014. IMPLEMENT_IINTERFACE;
  1015. void getActiveQueries(StringBuffer &reply)
  1016. {
  1017. HashIterator q(debuggerContexts);
  1018. for (q.first(); q.isValid(); q.next())
  1019. {
  1020. IDebuggerContext *ctx = debuggerContexts.mapToValue(&q.query());
  1021. reply.appendf(" <Query id='%s' uid='%s' debug='1'/>\n", ctx->queryQueryName(), ctx->queryDebugId());
  1022. }
  1023. }
  1024. virtual void registerDebugId(const char *id, IDebuggerContext *ctx)
  1025. {
  1026. WriteLockBlock block(debugLock);
  1027. debuggerContexts.setValue(id, ctx);
  1028. }
  1029. virtual void deregisterDebugId(const char *id)
  1030. {
  1031. WriteLockBlock block(debugLock);
  1032. debuggerContexts.remove(id);
  1033. }
  1034. virtual IDebuggerContext *lookupDebuggerContext(const char *id)
  1035. {
  1036. ReadLockBlock block(debugLock);
  1037. IDebuggerContext *ctx = debuggerContexts.getValue(id);
  1038. if (ctx)
  1039. return LINK(ctx);
  1040. else
  1041. {
  1042. #ifdef _DEBUG
  1043. // In a debug environment, it is convenient to be able to use '*' to mean 'the only active debug session'...
  1044. if (strcmp(id, "*")==0 && debuggerContexts.count()==1)
  1045. {
  1046. HashIterator q(debuggerContexts);
  1047. for (q.first(); q.isValid(); q.next())
  1048. {
  1049. IDebuggerContext *ctx = debuggerContexts.mapToValue(&q.query());
  1050. return LINK(ctx);
  1051. }
  1052. }
  1053. #endif
  1054. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Debug context %s not found", id);
  1055. }
  1056. }
  1057. };
  1058. //===============================================================================================
  1059. /*----------------------------------------------------------------------------------------------
  1060. * A CRoxieQueryPackageManager object manages all the queries that are currently runnable via XML.
  1061. * There may be more than one in existence, but only one will be active and therefore used to
  1062. * look up queries that are received - this corresponds to the currently active package.
  1063. *-----------------------------------------------------------------------------------------------*/
  1064. class CRoxieQueryPackageManager : public CInterface
  1065. {
  1066. public:
  1067. IMPLEMENT_IINTERFACE;
  1068. CRoxieQueryPackageManager(unsigned _numChannels, const char *_querySet, const IRoxiePackageMap *_packages)
  1069. : numChannels(_numChannels), packages(_packages), querySet(_querySet)
  1070. {
  1071. queryHash = 0;
  1072. }
  1073. ~CRoxieQueryPackageManager()
  1074. {
  1075. }
  1076. inline const char *queryPackageId() const
  1077. {
  1078. return packages->queryPackageId();
  1079. }
  1080. virtual void reload()
  1081. {
  1082. // Default is to do nothing...
  1083. }
  1084. virtual void load(bool forceReload) = 0;
  1085. virtual hash64_t getHash()
  1086. {
  1087. CriticalBlock b2(updateCrit);
  1088. return queryHash;
  1089. }
  1090. IRoxieQuerySetManager* getRoxieServerManager()
  1091. {
  1092. CriticalBlock b2(updateCrit);
  1093. return serverManager.getLink();
  1094. }
  1095. void getInfo(StringBuffer &reply, const IRoxieContextLogger &logctx) const
  1096. {
  1097. reply.appendf(" <PackageSet id=\"%s\" querySet=\"%s\"/>\n", queryPackageId(), querySet.get());
  1098. }
  1099. void resetStats(const char *queryId, const IRoxieContextLogger &logctx)
  1100. {
  1101. CriticalBlock b(updateCrit);
  1102. if (queryId)
  1103. {
  1104. Owned<IQueryFactory> query = serverManager->getQuery(queryId, NULL, logctx);
  1105. if (query)
  1106. {
  1107. const char *id = query->queryQueryName();
  1108. serverManager->resetQueryTimings(id, logctx);
  1109. for (unsigned channel = 0; channel < numChannels; channel++)
  1110. if (slaveManagers->item(channel))
  1111. {
  1112. slaveManagers->item(channel)->resetQueryTimings(id, logctx);
  1113. }
  1114. }
  1115. }
  1116. else
  1117. {
  1118. serverManager->resetAllQueryTimings();
  1119. for (unsigned channel = 0; channel < numChannels; channel++)
  1120. if (slaveManagers->item(channel))
  1121. slaveManagers->item(channel)->resetAllQueryTimings();
  1122. }
  1123. }
  1124. void getStats(const char *queryId, const char *action, const char *graphName, StringBuffer &reply, const IRoxieContextLogger &logctx) const
  1125. {
  1126. CriticalBlock b2(updateCrit);
  1127. Owned<IQueryFactory> query = serverManager->getQuery(queryId, NULL, logctx);
  1128. if (query)
  1129. {
  1130. StringBuffer freply;
  1131. serverManager->getStats(queryId, graphName, freply, logctx);
  1132. Owned<IPropertyTree> stats = createPTreeFromXMLString(freply.str());
  1133. for (unsigned channel = 0; channel < numChannels; channel++)
  1134. if (slaveManagers->item(channel))
  1135. {
  1136. StringBuffer sreply;
  1137. slaveManagers->item(channel)->getStats(queryId, graphName, sreply, logctx);
  1138. Owned<IPropertyTree> cstats = createPTreeFromXMLString(sreply.str());
  1139. mergeStats(stats, cstats, 1);
  1140. }
  1141. toXML(stats, reply);
  1142. }
  1143. }
  1144. void getActivityMetrics(StringBuffer &reply) const
  1145. {
  1146. CriticalBlock b2(updateCrit);
  1147. serverManager->getActivityMetrics(reply);
  1148. for (unsigned channel = 0; channel < numChannels; channel++)
  1149. {
  1150. if (slaveManagers->item(channel))
  1151. {
  1152. slaveManagers->item(channel)->getActivityMetrics(reply);
  1153. }
  1154. }
  1155. }
  1156. void getAllQueryInfo(StringBuffer &reply, bool full, const IRoxieContextLogger &logctx) const
  1157. {
  1158. CriticalBlock b2(updateCrit);
  1159. serverManager->getAllQueryInfo(reply, full, logctx);
  1160. }
  1161. protected:
  1162. void reloadQueryManagers(CRoxieSlaveQuerySetManagerSet *newSlaveManagers, IRoxieQuerySetManager *newServerManager, hash64_t newHash)
  1163. {
  1164. Owned<CRoxieSlaveQuerySetManagerSet> oldSlaveManagers;
  1165. Owned<IRoxieQuerySetManager> oldServerManager;
  1166. {
  1167. // Atomically, replace the existing query managers with the new ones
  1168. CriticalBlock b2(updateCrit);
  1169. oldSlaveManagers.setown(slaveManagers.getClear()); // so that the release happens outside the critblock
  1170. oldServerManager.setown(serverManager.getClear()); // so that the release happens outside the critblock
  1171. slaveManagers.setown(newSlaveManagers);
  1172. serverManager.setown(newServerManager);
  1173. queryHash = newHash;
  1174. }
  1175. if (slaveQueryReleaseDelaySeconds)
  1176. delayedReleaser->delayedRelease(oldSlaveManagers.getClear(), slaveQueryReleaseDelaySeconds);
  1177. }
  1178. mutable CriticalSection updateCrit; // protects updates of slaveManagers and serverManager
  1179. Owned<CRoxieSlaveQuerySetManagerSet> slaveManagers;
  1180. Owned<IRoxieQuerySetManager> serverManager;
  1181. Owned<const IRoxiePackageMap> packages;
  1182. unsigned numChannels;
  1183. hash64_t queryHash;
  1184. StringAttr querySet;
  1185. };
  1186. /**
  1187. * class CRoxieDaliQueryPackageManager - manages queries specified in QuerySets, for a given package set.
  1188. *
  1189. * If the QuerySet is modified, it will be reloaded.
  1190. * There is one CRoxieDaliQueryPackageManager for every PackageSet - only one will be active for query lookup
  1191. * at a given time (the one associated with the active PackageSet).
  1192. *
  1193. * To deploy new data, typically we will load a new PackageSet, make it active, then release the old one
  1194. * A packageSet is not modified while loaded, to avoid timing issues between slaves and server.
  1195. *
  1196. * We need to be able to spot a change (in dali) to the active package indicator (and switch the active CRoxieDaliQueryPackageManager)
  1197. * We need to be able to spot a change (in dali) that adds a new PackageSet
  1198. * We need to decide what to do about a change (in dali) to an existing PackageSet. Maybe we allow it (leave it up to the gui to
  1199. * encourage changing in the right sequence). In which case a change to the package info in dali means reload all global package
  1200. * managers (and then discard the old ones). Hash-based queries means everything should work ok.
  1201. * -> If the active ptr changes, just change what is active
  1202. * If any change to any package set, reload all globalResourceManagers and discard prior
  1203. * The query caching code should ensure that it is quick enough to do so
  1204. *
  1205. **/
  1206. class CRoxieDaliQueryPackageManager : public CRoxieQueryPackageManager, implements ISDSSubscription
  1207. {
  1208. Owned<IRoxieDaliHelper> daliHelper;
  1209. Owned<IDaliPackageWatcher> notifier;
  1210. public:
  1211. IMPLEMENT_IINTERFACE;
  1212. CRoxieDaliQueryPackageManager(unsigned _numChannels, const IRoxiePackageMap *_packages, const char *_querySet)
  1213. : CRoxieQueryPackageManager(_numChannels, _querySet, _packages)
  1214. {
  1215. daliHelper.setown(connectToDali());
  1216. }
  1217. ~CRoxieDaliQueryPackageManager()
  1218. {
  1219. if (notifier)
  1220. daliHelper->releaseSubscription(notifier);
  1221. }
  1222. virtual void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  1223. {
  1224. reload(false);
  1225. daliHelper->commitCache();
  1226. }
  1227. virtual void load(bool forceReload)
  1228. {
  1229. notifier.setown(daliHelper->getQuerySetSubscription(querySet, this));
  1230. reload(forceReload);
  1231. }
  1232. virtual void reload(bool forceRetry)
  1233. {
  1234. hash64_t newHash = numChannels;
  1235. Owned<IPropertyTree> newQuerySet = daliHelper->getQuerySet(querySet);
  1236. Owned<CRoxieSlaveQuerySetManagerSet> newSlaveManagers = new CRoxieSlaveQuerySetManagerSet(numChannels, querySet);
  1237. Owned<IRoxieQuerySetManager> newServerManager = createServerManager(querySet);
  1238. newServerManager->load(newQuerySet, *packages, newHash, forceRetry);
  1239. newSlaveManagers->load(newQuerySet, *packages, newHash, forceRetry);
  1240. reloadQueryManagers(newSlaveManagers.getClear(), newServerManager.getClear(), newHash);
  1241. clearKeyStoreCache(false); // Allows us to fully release files we no longer need because of unloaded queries
  1242. }
  1243. };
  1244. class CStandaloneQueryPackageManager : public CRoxieQueryPackageManager
  1245. {
  1246. Owned<IPropertyTree> standaloneDll;
  1247. public:
  1248. IMPLEMENT_IINTERFACE;
  1249. CStandaloneQueryPackageManager(unsigned _numChannels, const char *_querySet, const IRoxiePackageMap *_packages, IPropertyTree *_standaloneDll)
  1250. : CRoxieQueryPackageManager(_numChannels, _querySet, _packages), standaloneDll(_standaloneDll)
  1251. {
  1252. assertex(standaloneDll);
  1253. }
  1254. ~CStandaloneQueryPackageManager()
  1255. {
  1256. }
  1257. virtual void load(bool forceReload)
  1258. {
  1259. hash64_t newHash = numChannels;
  1260. Owned<IPropertyTree> newQuerySet = createPTree("QuerySet");
  1261. newQuerySet->setProp("@name", "_standalone");
  1262. newQuerySet->addPropTree("Query", standaloneDll.getLink());
  1263. Owned<CRoxieSlaveQuerySetManagerSet> newSlaveManagers = new CRoxieSlaveQuerySetManagerSet(numChannels, querySet);
  1264. Owned<IRoxieQuerySetManager> newServerManager = createServerManager(querySet);
  1265. newServerManager->load(newQuerySet, *packages, newHash, forceReload);
  1266. newSlaveManagers->load(newQuerySet, *packages, newHash, forceReload);
  1267. reloadQueryManagers(newSlaveManagers.getClear(), newServerManager.getClear(), newHash);
  1268. }
  1269. };
  1270. static SpinLock roxieDebugSessionManagerLock;
  1271. extern IRoxieDebugSessionManager &queryRoxieDebugSessionManager()
  1272. {
  1273. SpinBlock b(roxieDebugSessionManagerLock);
  1274. if (!debugSessionManager)
  1275. debugSessionManager = new CRoxieDebugSessionManager();
  1276. return *debugSessionManager;
  1277. }
  1278. class CRoxiePackageSetWatcher : public CInterface, implements ISDSSubscription
  1279. {
  1280. public:
  1281. IMPLEMENT_IINTERFACE;
  1282. CRoxiePackageSetWatcher(IRoxieDaliHelper *_daliHelper, ISDSSubscription *_owner, unsigned numChannels, bool forceReload)
  1283. : stateHash(0), daliHelper(_daliHelper), owner(_owner)
  1284. {
  1285. Owned<IDaliPackageWatcher> notifier = daliHelper->getPackageSetsSubscription(this);
  1286. if (notifier)
  1287. notifiers.append(*notifier.getClear());
  1288. ForEachItemIn(idx, allQuerySetNames)
  1289. {
  1290. createQueryPackageManagers(numChannels, allQuerySetNames.item(idx), forceReload);
  1291. }
  1292. }
  1293. CRoxiePackageSetWatcher(IRoxieDaliHelper *_daliHelper, ISDSSubscription *_owner, const IQueryDll *standAloneDll, unsigned numChannels, const char *querySet, bool forceReload)
  1294. : stateHash(0), daliHelper(_daliHelper), owner(_owner)
  1295. {
  1296. Owned<IPropertyTree> standAloneDllTree;
  1297. standAloneDllTree.setown(createPTree("Query"));
  1298. standAloneDllTree->setProp("@id", "roxie");
  1299. standAloneDllTree->setProp("@dll", standAloneDll->queryDll()->queryName());
  1300. Owned<CRoxieQueryPackageManager> qpm = new CStandaloneQueryPackageManager(numChannels, querySet, LINK(&queryEmptyRoxiePackageMap()), standAloneDllTree.getClear());
  1301. qpm->load(forceReload);
  1302. stateHash = rtlHash64Data(sizeof(stateHash), &stateHash, qpm->getHash());
  1303. allQueryPackages.append(*qpm.getClear());
  1304. }
  1305. ~CRoxiePackageSetWatcher()
  1306. {
  1307. unsubscribe();
  1308. }
  1309. virtual void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  1310. {
  1311. owner->notify(id, xpath, flags, valueLen, valueData);
  1312. }
  1313. IQueryFactory *lookupLibrary(const char *libraryName, unsigned expectedInterfaceHash, const IRoxieContextLogger &logctx) const
  1314. {
  1315. ForEachItemIn(idx, allQueryPackages)
  1316. {
  1317. Owned<IRoxieQuerySetManager> sm = allQueryPackages.item(idx).getRoxieServerManager();
  1318. if (sm->isActive())
  1319. {
  1320. Owned<IQueryFactory> library = sm->getQuery(libraryName, NULL, logctx);
  1321. if (library)
  1322. {
  1323. if (library->isQueryLibrary())
  1324. {
  1325. unsigned foundInterfaceHash = library->getQueryLibraryInterfaceHash();
  1326. if (!foundInterfaceHash || (foundInterfaceHash == expectedInterfaceHash))
  1327. return library.getClear();
  1328. else
  1329. throw MakeStringException(ROXIE_LIBRARY_ERROR, "The library interface found in %s is not compatible (found %d, expected %d)", libraryName, foundInterfaceHash, expectedInterfaceHash);
  1330. }
  1331. else
  1332. throw MakeStringException(ROXIE_LIBRARY_ERROR, "The query resolved by %s is not a library", libraryName);
  1333. }
  1334. }
  1335. }
  1336. throw MakeStringException(ROXIE_LIBRARY_ERROR, "No library available for %s", libraryName);
  1337. }
  1338. IQueryFactory *getQuery(const char *id, StringBuffer *querySet, const IRoxieContextLogger &logctx) const
  1339. {
  1340. ForEachItemIn(idx, allQueryPackages)
  1341. {
  1342. Owned<IRoxieQuerySetManager> sm = allQueryPackages.item(idx).getRoxieServerManager();
  1343. if (sm->isActive())
  1344. {
  1345. IQueryFactory *query = sm->getQuery(id, querySet, logctx);
  1346. if (query)
  1347. return query;
  1348. }
  1349. }
  1350. return NULL;
  1351. }
  1352. int getActivePackageCount() const
  1353. {
  1354. int count = 0;
  1355. ForEachItemIn(idx, allQueryPackages)
  1356. {
  1357. Owned<IRoxieQuerySetManager> sm = allQueryPackages.item(idx).getRoxieServerManager();
  1358. if (sm->isActive())
  1359. count++;
  1360. }
  1361. return count;
  1362. }
  1363. inline hash64_t queryHash() const
  1364. {
  1365. return stateHash;
  1366. }
  1367. void getAllQueryInfo(StringBuffer &reply, bool full, const IRoxieContextLogger &logctx) const
  1368. {
  1369. ForEachItemIn(idx, allQueryPackages)
  1370. {
  1371. Owned<IRoxieQuerySetManager> sm = allQueryPackages.item(idx).getRoxieServerManager();
  1372. sm->getAllQueryInfo(reply, full, logctx);
  1373. }
  1374. }
  1375. void getActivityMetrics(StringBuffer &reply) const
  1376. {
  1377. ForEachItemIn(idx, allQueryPackages)
  1378. {
  1379. CRoxieQueryPackageManager &qpm = allQueryPackages.item(idx);
  1380. qpm.getActivityMetrics(reply);
  1381. }
  1382. }
  1383. void getInfo(StringBuffer &reply, const IRoxieContextLogger &logctx) const
  1384. {
  1385. reply.append("<PackageSets>\n");
  1386. ForEachItemIn(idx, allQueryPackages)
  1387. {
  1388. allQueryPackages.item(idx).getInfo(reply, logctx);
  1389. }
  1390. reply.append("</PackageSets>\n");
  1391. }
  1392. void getStats(StringBuffer &reply, const char *id, const char *action, const char *graphName, const IRoxieContextLogger &logctx) const
  1393. {
  1394. ForEachItemIn(idx, allQueryPackages)
  1395. {
  1396. allQueryPackages.item(idx).getStats(id, action, graphName, reply, logctx);
  1397. }
  1398. }
  1399. void resetStats(const char *id, const IRoxieContextLogger &logctx) const
  1400. {
  1401. ForEachItemIn(idx, allQueryPackages)
  1402. {
  1403. allQueryPackages.item(idx).resetStats(id, logctx);
  1404. }
  1405. }
  1406. private:
  1407. ISDSSubscription *owner;
  1408. CIArrayOf<CRoxieQueryPackageManager> allQueryPackages;
  1409. IArrayOf<IDaliPackageWatcher> notifiers;
  1410. Linked<IRoxieDaliHelper> daliHelper;
  1411. hash64_t stateHash;
  1412. void createQueryPackageManager(unsigned numChannels, const IRoxiePackageMap *packageMap, const char *querySet, bool forceReload)
  1413. {
  1414. Owned<CRoxieQueryPackageManager> qpm = new CRoxieDaliQueryPackageManager(numChannels, packageMap, querySet);
  1415. qpm->load(forceReload);
  1416. stateHash = rtlHash64Data(sizeof(stateHash), &stateHash, qpm->getHash());
  1417. allQueryPackages.append(*qpm.getClear());
  1418. }
  1419. void createQueryPackageManagers(unsigned numChannels, const char *querySet, bool forceReload)
  1420. {
  1421. int loadedPackages = 0;
  1422. int activePackages = 0;
  1423. Owned<IPropertyTree> packageTree = daliHelper->getPackageSets();
  1424. Owned<IPropertyTreeIterator> packageSets = packageTree->getElements("PackageSet");
  1425. ForEach(*packageSets)
  1426. {
  1427. IPropertyTree &ps = packageSets->query();
  1428. const char *packageSetSpec = ps.queryProp("@process");
  1429. if (!packageSetSpec || WildMatch(roxieName, packageSetSpec, false))
  1430. {
  1431. if (traceLevel)
  1432. {
  1433. DBGLOG("Loading package set %s, process spec %s", ps.queryProp("@id") ? ps.queryProp("@id") : "<no-id>",
  1434. packageSetSpec ? packageSetSpec : "<*>");
  1435. }
  1436. Owned<IPropertyTreeIterator> packageMaps = ps.getElements("PackageMap");
  1437. ForEach(*packageMaps)
  1438. {
  1439. IPropertyTree &pm = packageMaps->query();
  1440. const char *packageMapId = pm.queryProp("@id");
  1441. const char *packageMapFilter = pm.queryProp("@querySet");
  1442. if (packageMapId && *packageMapId && (!packageMapFilter || WildMatch(querySet, packageMapFilter, false)))
  1443. {
  1444. bool isActive = pm.getPropBool("@active", true);
  1445. if (traceLevel)
  1446. DBGLOG("Loading package map %s, active %s", packageMapId, isActive ? "true" : "false");
  1447. try
  1448. {
  1449. Owned<CRoxiePackageMap> packageMap = new CRoxiePackageMap(packageMapId, packageMapFilter, isActive);
  1450. Owned<IPropertyTree> xml = daliHelper->getPackageMap(packageMapId);
  1451. packageMap->load(xml);
  1452. createQueryPackageManager(numChannels, packageMap.getLink(), querySet, forceReload);
  1453. loadedPackages++;
  1454. if (isActive)
  1455. activePackages++;
  1456. notifiers.append(*daliHelper->getPackageMapSubscription(packageMapId, this));
  1457. }
  1458. catch (IException *E)
  1459. {
  1460. StringBuffer msg;
  1461. msg.appendf("Failed to load package map %s", packageMapId);
  1462. EXCLOG(E, msg.str());
  1463. E->Release();
  1464. }
  1465. }
  1466. }
  1467. }
  1468. }
  1469. if (!loadedPackages)
  1470. {
  1471. if (traceLevel)
  1472. DBGLOG("Loading empty package for QuerySet %s", querySet);
  1473. createQueryPackageManager(numChannels, LINK(&queryEmptyRoxiePackageMap()), querySet, forceReload);
  1474. }
  1475. else if (traceLevel)
  1476. DBGLOG("Loaded %d packages (%d active)", loadedPackages, activePackages);
  1477. }
  1478. void unsubscribe()
  1479. {
  1480. ForEachItemIn(idx, notifiers)
  1481. {
  1482. daliHelper->releaseSubscription(&notifiers.item(idx));
  1483. }
  1484. notifiers.kill();
  1485. }
  1486. };
  1487. class CRoxiePackageSetManager : public CInterface, implements IRoxieQueryPackageManagerSet, implements ISDSSubscription
  1488. {
  1489. public:
  1490. IMPLEMENT_IINTERFACE;
  1491. CRoxiePackageSetManager(const IQueryDll *_standAloneDll) :
  1492. autoReloadThread(*this), standAloneDll(_standAloneDll)
  1493. {
  1494. daliHelper.setown(connectToDali(ROXIE_DALI_CONNECT_TIMEOUT));
  1495. atomic_set(&autoPending, 0);
  1496. autoReloadThread.start();
  1497. }
  1498. ~CRoxiePackageSetManager()
  1499. {
  1500. autoReloadThread.stop();
  1501. autoReloadThread.join();
  1502. }
  1503. virtual void requestReload()
  1504. {
  1505. atomic_inc(&autoPending);
  1506. autoReloadTrigger.signal();
  1507. }
  1508. virtual void load()
  1509. {
  1510. try
  1511. {
  1512. reload(false);
  1513. daliHelper->commitCache();
  1514. controlSem.signal();
  1515. }
  1516. catch(IException *E)
  1517. {
  1518. EXCLOG(E, "No configuration could be loaded");
  1519. controlSem.interrupt();
  1520. throw; // Roxie will refuse to start up if configuration invalid
  1521. }
  1522. }
  1523. virtual void doControlMessage(IPropertyTree *xml, StringBuffer &reply, const IRoxieContextLogger &logctx)
  1524. {
  1525. if (!controlSem.wait(20000))
  1526. throw MakeStringException(ROXIE_TIMEOUT, "Timed out waiting for current control query to complete");
  1527. try
  1528. {
  1529. _doControlMessage(xml, reply, logctx);
  1530. reply.append(" <Status>ok</Status>\n");
  1531. }
  1532. catch(IException *E)
  1533. {
  1534. controlSem.signal();
  1535. EXCLOG(E);
  1536. throw;
  1537. }
  1538. catch(...)
  1539. {
  1540. controlSem.signal();
  1541. throw;
  1542. }
  1543. controlSem.signal();
  1544. }
  1545. virtual IQueryFactory *lookupLibrary(const char *libraryName, unsigned expectedInterfaceHash, const IRoxieContextLogger &logctx) const
  1546. {
  1547. ReadLockBlock b(packageCrit);
  1548. return allQueryPackages->lookupLibrary(libraryName, expectedInterfaceHash, logctx);
  1549. }
  1550. virtual IQueryFactory *getQuery(const char *id, StringBuffer *querySet, const IRoxieContextLogger &logctx) const
  1551. {
  1552. ReadLockBlock b(packageCrit);
  1553. return allQueryPackages->getQuery(id, querySet, logctx);
  1554. }
  1555. virtual int getActivePackageCount() const
  1556. {
  1557. ReadLockBlock b(packageCrit);
  1558. return allQueryPackages->getActivePackageCount();
  1559. }
  1560. virtual void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  1561. {
  1562. requestReload();
  1563. }
  1564. private:
  1565. Owned<const IQueryDll> standAloneDll;
  1566. Owned<CRoxieDebugSessionManager> debugSessionManager;
  1567. Owned<IRoxieDaliHelper> daliHelper;
  1568. mutable ReadWriteLock packageCrit;
  1569. InterruptableSemaphore controlSem;
  1570. Owned<CRoxiePackageSetWatcher> allQueryPackages;
  1571. Semaphore autoReloadTrigger;
  1572. atomic_t autoPending;
  1573. class AutoReloadThread : public Thread
  1574. {
  1575. bool closing;
  1576. CRoxiePackageSetManager &owner;
  1577. public:
  1578. AutoReloadThread(CRoxiePackageSetManager &_owner)
  1579. : owner(_owner), Thread("AutoReloadThread")
  1580. {
  1581. closing = false;
  1582. }
  1583. virtual int run()
  1584. {
  1585. if (traceLevel)
  1586. DBGLOG("AutoReloadThread %p starting", this);
  1587. while (!closing)
  1588. {
  1589. owner.autoReloadTrigger.wait();
  1590. if (atomic_read(&owner.autoPending))
  1591. {
  1592. atomic_set(&owner.autoPending, 0);
  1593. try
  1594. {
  1595. owner.reload(false); // Arguably true should be better...
  1596. }
  1597. catch (IException *E)
  1598. {
  1599. if (!closing)
  1600. EXCLOG(MCoperatorError, E, "AutoReloadThread: ");
  1601. E->Release();
  1602. }
  1603. catch (...)
  1604. {
  1605. DBGLOG("Unknown exception in AutoReloadThread");
  1606. }
  1607. }
  1608. }
  1609. if (traceLevel)
  1610. DBGLOG("AutoReloadThread %p exiting", this);
  1611. return 0;
  1612. }
  1613. void stop()
  1614. {
  1615. closing = true;
  1616. owner.autoReloadTrigger.signal();
  1617. }
  1618. } autoReloadThread;
  1619. void reload(bool forceRetry)
  1620. {
  1621. clearDaliMisses();
  1622. // We want to kill the old packages, but not until we have created the new ones
  1623. // So that the query/dll caching will work for anything that is not affected by the changes
  1624. Owned<CRoxiePackageSetWatcher> newPackages;
  1625. if (standAloneDll)
  1626. newPackages.setown(new CRoxiePackageSetWatcher(daliHelper, this, standAloneDll, numChannels, "roxie", forceRetry));
  1627. else
  1628. newPackages.setown(new CRoxiePackageSetWatcher(daliHelper, this, numChannels, forceRetry));
  1629. // Hold the lock for as little time as we can
  1630. // Note that we must NOT hold the lock during the delete of the old object - or we deadlock.
  1631. // Hence the slightly convoluted code below
  1632. Owned<CRoxiePackageSetWatcher> oldPackages; // NB Destroyed outside the WriteLockBlock
  1633. {
  1634. WriteLockBlock b(packageCrit);
  1635. oldPackages.setown(allQueryPackages.getLink()); // To ensure that the setown just below does not delete it
  1636. allQueryPackages.setown(newPackages.getClear());
  1637. }
  1638. daliHelper->commitCache();
  1639. }
  1640. // Common code used by control:queries and control:getQueryXrefInfo
  1641. void getQueryInfo(IPropertyTree *control, StringBuffer &reply, bool full, const IRoxieContextLogger &logctx) const
  1642. {
  1643. Owned<IPropertyTreeIterator> ids = control->getElements("Query");
  1644. reply.append("<Queries reporting='1'>\n");
  1645. if (ids->first())
  1646. {
  1647. ForEach(*ids)
  1648. {
  1649. const char *id = ids->query().queryProp("@id");
  1650. if (id)
  1651. {
  1652. Owned<IQueryFactory> query = getQuery(id, NULL, logctx);
  1653. if (query)
  1654. query->getQueryInfo(reply, full, logctx);
  1655. else
  1656. reply.appendf(" <Query id=\"%s\" error=\"Query not found\"/>\n", id);
  1657. }
  1658. }
  1659. }
  1660. else
  1661. {
  1662. ReadLockBlock readBlock(packageCrit);
  1663. allQueryPackages->getAllQueryInfo(reply, full, logctx);
  1664. }
  1665. reply.append("</Queries>\n");
  1666. }
  1667. void _doControlMessage(IPropertyTree *control, StringBuffer &reply, const IRoxieContextLogger &logctx)
  1668. {
  1669. const char *queryName = control->queryName();
  1670. logctx.CTXLOG("doControlMessage - %s", queryName);
  1671. assertex(memicmp(queryName, "control:", 8) == 0);
  1672. bool unknown = false;
  1673. switch (_toupper(queryName[8]))
  1674. {
  1675. case 'A':
  1676. if (stricmp(queryName, "control:aclupdate") == 0)
  1677. {
  1678. // MORE - do nothing for now - possibly needed in the future - leave this so no exception is thrown
  1679. }
  1680. else if (stricmp(queryName, "control:activeQueries")==0)
  1681. {
  1682. if (debugSessionManager)
  1683. debugSessionManager->getActiveQueries(reply);
  1684. }
  1685. else if (stricmp(queryName, "control:activitymetrics")==0)
  1686. {
  1687. ReadLockBlock readBlock(packageCrit);
  1688. allQueryPackages->getActivityMetrics(reply);
  1689. }
  1690. else if (stricmp(queryName, "control:alive")==0)
  1691. {
  1692. reply.appendf("<Alive restarts='%d'/>", restarts);
  1693. }
  1694. else
  1695. unknown = true;
  1696. break;
  1697. case 'B':
  1698. if (stricmp(queryName, "control:blobCacheMem")==0)
  1699. {
  1700. blobCacheMB = control->getPropInt("@val", 0);
  1701. topology->setPropInt("@blobCacheMem", blobCacheMB);
  1702. setBlobCacheMem(blobCacheMB * 0x100000);
  1703. }
  1704. else
  1705. unknown = true;
  1706. break;
  1707. case 'C':
  1708. if (stricmp(queryName, "control:checkCompleted")==0)
  1709. {
  1710. checkCompleted = control->getPropBool("@val", true);
  1711. topology->setPropBool("@checkCompleted", checkCompleted );
  1712. }
  1713. else if (stricmp(queryName, "control:checkingHeap")==0)
  1714. {
  1715. defaultCheckingHeap = control->getPropBool("@val", true);
  1716. topology->setPropInt("@checkingHeap", defaultCheckingHeap);
  1717. }
  1718. else if (stricmp(queryName, "control:clearIndexCache")==0)
  1719. {
  1720. bool clearAll = control->getPropBool("@clearAll", true);
  1721. clearKeyStoreCache(clearAll);
  1722. }
  1723. else if (stricmp(queryName, "control:closedown")==0)
  1724. {
  1725. closedown();
  1726. }
  1727. else if (stricmp(queryName, "control:closeExpired")==0)
  1728. {
  1729. queryFileCache().closeExpired(false);
  1730. queryFileCache().closeExpired(true);
  1731. }
  1732. else if (stricmp(queryName, "control:closeLocalExpired")==0)
  1733. {
  1734. queryFileCache().closeExpired(false);
  1735. }
  1736. else if (stricmp(queryName, "control:closeRemoteExpired")==0)
  1737. {
  1738. queryFileCache().closeExpired(true);
  1739. }
  1740. else
  1741. unknown = true;
  1742. break;
  1743. case 'D':
  1744. if (stricmp(queryName, "control:dafilesrvLookupTimeout")==0)
  1745. {
  1746. dafilesrvLookupTimeout = control->getPropInt("@val", 10000);
  1747. topology->setPropInt("@dafilesrvLookupTimeout", dafilesrvLookupTimeout);
  1748. }
  1749. else if (stricmp(queryName, "control:defaultConcatPreload")==0)
  1750. {
  1751. defaultConcatPreload = control->getPropInt("@val", 0);
  1752. topology->setPropInt("@defaultConcatPreload", defaultConcatPreload);
  1753. }
  1754. else if (stricmp(queryName, "control:defaultFetchPreload")==0)
  1755. {
  1756. defaultFetchPreload = control->getPropInt("@val", 0);
  1757. topology->setPropInt("@defaultFetchPreload", defaultFetchPreload);
  1758. }
  1759. else if (stricmp(queryName, "control:defaultFullKeyedJoinPreload")==0)
  1760. {
  1761. defaultFullKeyedJoinPreload = control->getPropInt("@val", 0);
  1762. topology->setPropInt("@defaultFullKeyedJoinPreload", defaultFullKeyedJoinPreload);
  1763. }
  1764. else if (stricmp(queryName, "control:defaultHighPriorityTimeLimit")==0)
  1765. {
  1766. defaultTimeLimit[1] = control->getPropInt("@limit", 0);
  1767. topology->setPropInt("@defaultHighPriorityTimeLimit", defaultTimeLimit[1]);
  1768. }
  1769. else if (stricmp(queryName, "control:defaultHighPriorityTimeWarning")==0)
  1770. {
  1771. defaultWarnTimeLimit[1] = control->getPropInt("@limit", 0);
  1772. topology->setPropInt("@defaultHighPriorityTimeWarning", defaultWarnTimeLimit[1]);
  1773. }
  1774. else if (stricmp(queryName, "control:defaultKeyedJoinPreload")==0)
  1775. {
  1776. defaultKeyedJoinPreload = control->getPropInt("@val", 0);
  1777. topology->setPropInt("@defaultKeyedJoinPreload", defaultKeyedJoinPreload);
  1778. }
  1779. else if (stricmp(queryName, "control:defaultLowPriorityTimeLimit")==0)
  1780. {
  1781. defaultTimeLimit[0] = control->getPropInt("@limit", 0);
  1782. topology->setPropInt("@defaultLowPriorityTimeLimit", defaultTimeLimit[0]);
  1783. }
  1784. else if (stricmp(queryName, "control:defaultLowPriorityTimeWarning")==0)
  1785. {
  1786. defaultWarnTimeLimit[0] = control->getPropInt("@limit", 0);
  1787. topology->setPropInt("@defaultLowPriorityTimeWarning", defaultWarnTimeLimit[0]);
  1788. }
  1789. else if (stricmp(queryName, "control:defaultParallelJoinPreload")==0)
  1790. {
  1791. defaultParallelJoinPreload = control->getPropInt("@val", 0);
  1792. topology->setPropInt("@defaultParallelJoinPreload", defaultParallelJoinPreload);
  1793. }
  1794. else if (stricmp(queryName, "control:defaultSLAPriorityTimeLimit")==0)
  1795. {
  1796. defaultTimeLimit[2] = control->getPropInt("@limit", 0);
  1797. topology->setPropInt("@defaultSLAPriorityTimeLimit", defaultTimeLimit[2]);
  1798. }
  1799. else if (stricmp(queryName, "control:defaultSLAPriorityTimeWarning")==0)
  1800. {
  1801. defaultWarnTimeLimit[2] = control->getPropInt("@limit", 0);
  1802. topology->setPropInt("@defaultSLAPriorityTimeWarning", defaultWarnTimeLimit[2]);
  1803. }
  1804. else if (stricmp(queryName, "control:deleteUnneededPhysicalFiles")==0)
  1805. {
  1806. UNIMPLEMENTED;
  1807. }
  1808. else if (stricmp(queryName, "control:deleteUnneededQueryCacheFiles")==0)
  1809. {
  1810. UNIMPLEMENTED;
  1811. }
  1812. else if (stricmp(queryName, "control:doIbytiDelay")==0)
  1813. { // WARNING: use with extra care only during inactivity on system
  1814. doIbytiDelay = control->getPropBool("@val", true);
  1815. topology->setPropBool("@doIbytiDelay", doIbytiDelay);
  1816. }
  1817. else
  1818. unknown = true;
  1819. break;
  1820. case 'E':
  1821. if (stricmp(queryName, "control:enableKeyDiff")==0)
  1822. {
  1823. enableKeyDiff = control->getPropBool("@val", true);
  1824. topology->setPropBool("@enableKeyDiff", enableKeyDiff);
  1825. }
  1826. else
  1827. unknown = true;
  1828. break;
  1829. case 'F':
  1830. if (stricmp(queryName, "control:fieldTranslationEnabled")==0)
  1831. {
  1832. fieldTranslationEnabled = control->getPropBool("@val", true);
  1833. topology->setPropInt("@fieldTranslationEnabled", fieldTranslationEnabled);
  1834. }
  1835. else if (stricmp(queryName, "control:flushJHtreeCacheOnOOM")==0)
  1836. {
  1837. flushJHtreeCacheOnOOM = control->getPropBool("@val", true);
  1838. topology->setPropInt("@flushJHtreeCacheOnOOM", flushJHtreeCacheOnOOM);
  1839. }
  1840. else
  1841. unknown = true;
  1842. break;
  1843. case 'G':
  1844. if (stricmp(queryName, "control:getACLinfo") == 0)
  1845. {
  1846. // MORE - do nothing for now - possibly needed in the future - leave this so no exception is thrown
  1847. }
  1848. else if (stricmp(queryName, "control:getClusterName")==0)
  1849. {
  1850. reply.appendf("<clusterName id='%s'/>", roxieName.str());
  1851. }
  1852. else if (stricmp(queryName, "control:getKeyInfo")==0)
  1853. {
  1854. reportInMemoryIndexStatistics(reply, control->queryProp("@id"), control->getPropInt("@count", 10));
  1855. }
  1856. else if (stricmp(queryName, "control:getQueryXrefInfo")==0)
  1857. {
  1858. getQueryInfo(control, reply, true, logctx);
  1859. }
  1860. else if (stricmp(queryName, "control:getQuery")==0)
  1861. {
  1862. const char* id = control->queryProp("@id");
  1863. if (!id)
  1864. throw MakeStringException(ROXIE_MISSING_PARAMS, "No query name specified");
  1865. Owned<IQueryFactory> q = getQuery(id, NULL, logctx);
  1866. if (q)
  1867. {
  1868. Owned<IPropertyTree> tempTree = q->cloneQueryXGMML();
  1869. tempTree->setProp("@roxieName", roxieName.str());
  1870. toXML(tempTree, reply);
  1871. }
  1872. else
  1873. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", id);
  1874. }
  1875. else if (stricmp(queryName, "control:getQueryWarningTime")==0)
  1876. {
  1877. const char *id = control->queryProp("Query/@id");
  1878. if (!id)
  1879. badFormat();
  1880. Owned<IQueryFactory> f = getQuery(id, NULL, logctx);
  1881. if (f)
  1882. {
  1883. unsigned warnLimit = f->getWarnTimeLimit();
  1884. reply.appendf("<QueryTimeWarning val='%d'/>", warnLimit);
  1885. }
  1886. }
  1887. else if (stricmp(queryName, "control:getBuildVersion")==0)
  1888. {
  1889. reply.appendf("<version id='%s'/>", BUILD_TAG);
  1890. }
  1891. else
  1892. unknown = true;
  1893. break;
  1894. case 'I':
  1895. if (stricmp(queryName, "control:indexmetrics")==0)
  1896. {
  1897. getIndexMetrics(reply);
  1898. }
  1899. else if (stricmp(queryName, "control:inMemoryKeysEnabled")==0)
  1900. {
  1901. inMemoryKeysEnabled = control->getPropBool("@val", true);
  1902. topology->setPropBool("@inMemoryKeysEnabled", inMemoryKeysEnabled);
  1903. }
  1904. else
  1905. unknown = true;
  1906. break;
  1907. case 'L':
  1908. if (stricmp(queryName, "control:leafCacheMem")==0)
  1909. {
  1910. leafCacheMB = control->getPropInt("@val", 50);
  1911. topology->setPropInt("@leafCacheMem", leafCacheMB);
  1912. setLeafCacheMem(leafCacheMB * 0x100000);
  1913. }
  1914. else if (stricmp(queryName, "control:listFileOpenErrors")==0)
  1915. {
  1916. // this just creates a delta state file to remove references to Keys / Files we now longer have interest in
  1917. StringAttrMapping *mapping = queryFileCache().queryFileErrorList();
  1918. HashIterator iter(*mapping);
  1919. StringBuffer err;
  1920. for (iter.first(); iter.isValid(); iter.next())
  1921. {
  1922. IMapping &cur = iter.query();
  1923. StringAttr *item = mapping->mapToValue(&cur);
  1924. const char *filename = (const char*)cur.getKey();
  1925. const char *filetype = item->get();
  1926. reply.appendf("<file><name>%s</name><type>%s</type></file>", filename, filetype);
  1927. }
  1928. }
  1929. else if (stricmp(queryName, "control:listUnusedFiles")==0)
  1930. {
  1931. UNIMPLEMENTED;
  1932. }
  1933. else if (stricmp(queryName, "control:lockDali")==0)
  1934. {
  1935. topology->setPropBool("@lockDali", true);
  1936. if (daliHelper)
  1937. daliHelper->disconnect();
  1938. saveTopology();
  1939. }
  1940. else if (stricmp(queryName, "control:logfullqueries")==0)
  1941. {
  1942. logFullQueries = control->getPropBool("@val", true);
  1943. topology->setPropBool("@logFullQueries", logFullQueries);
  1944. }
  1945. else
  1946. unknown = true;
  1947. break;
  1948. case 'M':
  1949. if (stricmp(queryName, "control:memoryStatsInterval")==0)
  1950. {
  1951. memoryStatsInterval = (unsigned) control->getPropInt64("@val", 0);
  1952. roxiemem::setMemoryStatsInterval(memoryStatsInterval);
  1953. topology->setPropInt64("@memoryStatsInterval", memoryStatsInterval);
  1954. }
  1955. else if (stricmp(queryName, "control:memtrace")==0)
  1956. {
  1957. roxiemem::memTraceLevel = control->getPropInt("@level", 0);
  1958. topology->setPropInt("@memTraceLevel", roxiemem::memTraceLevel);
  1959. }
  1960. else if (stricmp(queryName, "control:memtracesizelimit")==0)
  1961. {
  1962. roxiemem::memTraceSizeLimit = (memsize_t) control->getPropInt64("@val", control->getPropInt64("@value", 0)); // used to accept @value so coded like this for backward compatibility
  1963. topology->setPropInt64("@memTraceSizeLimit", roxiemem::memTraceSizeLimit);
  1964. }
  1965. else if (stricmp(queryName, "control:metrics")==0)
  1966. {
  1967. roxieMetrics->getMetrics(reply);
  1968. }
  1969. else if (stricmp(queryName, "control:minFreeDiskSpace")==0)
  1970. {
  1971. minFreeDiskSpace = (unsigned) control->getPropInt64("@val", 1048576);
  1972. topology->setPropInt64("@minFreeDiskSpace", minFreeDiskSpace);
  1973. }
  1974. else if (stricmp(queryName, "control:misctrace")==0)
  1975. {
  1976. miscDebugTraceLevel = control->getPropInt("@level", 0);
  1977. topology->setPropInt("@miscDebugTraceLevel", miscDebugTraceLevel);
  1978. }
  1979. else
  1980. unknown = true;
  1981. break;
  1982. case 'N':
  1983. if (stricmp(queryName, "control:nodeCachePreload")==0)
  1984. {
  1985. nodeCachePreload = control->getPropBool("@val", true);
  1986. topology->setPropBool("@nodeCachePreload", nodeCachePreload);
  1987. setNodeCachePreload(nodeCachePreload);
  1988. }
  1989. else if (stricmp(queryName, "control:nodeCacheMem")==0)
  1990. {
  1991. nodeCacheMB = control->getPropInt("@val", 100);
  1992. topology->setPropInt("@nodeCacheMem", nodeCacheMB);
  1993. setNodeCacheMem(nodeCacheMB * 0x100000);
  1994. }
  1995. else if (stricmp(queryName, "control:numFilesToProcess")==0)
  1996. {
  1997. int numFiles = queryFileCache().numFilesToCopy();
  1998. reply.appendf("<FilesToProcess value='%d'/>", numFiles);
  1999. }
  2000. else
  2001. unknown = true;
  2002. break;
  2003. case 'P':
  2004. if (stricmp(queryName, "control:parallelAggregate")==0)
  2005. {
  2006. parallelAggregate = control->getPropInt("@val", 0);
  2007. if (!parallelAggregate)
  2008. parallelAggregate = hdwInfo.numCPUs;
  2009. if (!parallelAggregate)
  2010. parallelAggregate = 1;
  2011. topology->setPropInt("@parallelAggregate", parallelAggregate);
  2012. }
  2013. else if (stricmp(queryName, "control:pingInterval")==0)
  2014. {
  2015. unsigned newInterval = (unsigned) control->getPropInt64("@val", 0);
  2016. if (newInterval && !pingInterval)
  2017. {
  2018. pingInterval = newInterval; // best to set before the start...
  2019. startPingTimer();
  2020. }
  2021. else if (pingInterval && !newInterval)
  2022. stopPingTimer(); // but after the stop
  2023. pingInterval = newInterval;
  2024. topology->setPropInt64("@pingInterval", pingInterval);
  2025. }
  2026. else if (stricmp(queryName, "control:preabortIndexReadsThreshold")==0)
  2027. {
  2028. preabortIndexReadsThreshold = control->getPropInt("@val", 100);
  2029. topology->setPropInt("@preabortIndexReadsThreshold", preabortIndexReadsThreshold);
  2030. }
  2031. else if (stricmp(queryName, "control:preabortKeyedJoinsThreshold")==0)
  2032. {
  2033. preabortKeyedJoinsThreshold = control->getPropInt("@val", 100);
  2034. topology->setPropInt("@preabortKeyedJoinsThreshold", preabortKeyedJoinsThreshold);
  2035. }
  2036. else if (stricmp(queryName, "control:probeAllRows")==0)
  2037. {
  2038. probeAllRows = control->getPropBool("@val", true);
  2039. }
  2040. else
  2041. unknown = true;
  2042. break;
  2043. case 'Q':
  2044. if (stricmp(queryName, "control:queries")==0)
  2045. {
  2046. getQueryInfo(control, reply, false, logctx);
  2047. }
  2048. else if (stricmp(queryName, "control:queryAggregates")==0)
  2049. {
  2050. time_t from;
  2051. const char *fromTime = control->queryProp("@from");
  2052. if (fromTime)
  2053. {
  2054. CDateTime f;
  2055. f.setString(fromTime, NULL, true);
  2056. from = f.getSimple();
  2057. }
  2058. else
  2059. from = startupTime;
  2060. time_t to;
  2061. const char *toTime = control->queryProp("@to");
  2062. if (toTime)
  2063. {
  2064. CDateTime t;
  2065. t.setString(toTime, NULL, true);
  2066. to = t.getSimple();
  2067. }
  2068. else
  2069. time(&to);
  2070. const char *id = control->queryProp("Query/@id");
  2071. if (id)
  2072. {
  2073. Owned<IQueryFactory> f = getQuery(id, NULL, logctx);
  2074. if (f)
  2075. {
  2076. Owned<const IPropertyTree> stats = f->getQueryStats(from, to);
  2077. toXML(stats, reply);
  2078. }
  2079. else
  2080. throw MakeStringException(ROXIE_CONTROL_MSG_ERROR, "Unknown query %s", id);
  2081. }
  2082. else
  2083. {
  2084. bool includeAllQueries = control->getPropBool("@all", true);
  2085. Owned<const IPropertyTree> stats = getAllQueryStats(includeAllQueries, from, to);
  2086. toXML(stats, reply);
  2087. }
  2088. }
  2089. else if (stricmp(queryName, "control:queryPackageInfo")==0)
  2090. {
  2091. ReadLockBlock readBlock(packageCrit);
  2092. allQueryPackages->getInfo(reply, logctx);
  2093. }
  2094. else if (stricmp(queryName, "control:queryStats")==0)
  2095. {
  2096. const char *id = control->queryProp("Query/@id");
  2097. if (!id)
  2098. badFormat();
  2099. const char *action = control->queryProp("Query/@action");
  2100. const char *graphName = 0;
  2101. if (action)
  2102. {
  2103. if (stricmp(action, "listGraphNames") == 0)
  2104. {
  2105. Owned<IQueryFactory> query = getQuery(id, NULL, logctx);
  2106. if (query)
  2107. {
  2108. reply.appendf("<Query id='%s'>\n", id);
  2109. StringArray graphNames;
  2110. query->getGraphNames(graphNames);
  2111. ForEachItemIn(idx, graphNames)
  2112. {
  2113. const char *graphName = graphNames.item(idx);
  2114. reply.appendf("<Graph id='%s'/>", graphName);
  2115. }
  2116. reply.appendf("</Query>\n");
  2117. }
  2118. return; // done
  2119. }
  2120. else if (stricmp(action, "selectGraph") == 0)
  2121. graphName = control->queryProp("Query/@name");
  2122. else if (stricmp(action, "allGraphs") != 0) // if we get here and its NOT allgraphs - then error
  2123. throw MakeStringException(ROXIE_CONTROL_MSG_ERROR, "invalid action in control:queryStats %s", action);
  2124. }
  2125. ReadLockBlock readBlock(packageCrit);
  2126. allQueryPackages->getStats(reply, id, action, graphName, logctx);
  2127. }
  2128. else if (stricmp(queryName, "control:queryWuid")==0)
  2129. {
  2130. UNIMPLEMENTED;
  2131. }
  2132. else
  2133. unknown = true;
  2134. break;
  2135. case 'R':
  2136. if (stricmp(queryName, "control:reload")==0)
  2137. {
  2138. reload(control->getPropBool("@forceRetry", false));
  2139. if (daliHelper && daliHelper->connected())
  2140. reply.appendf("<Dali connected='1'/>");
  2141. else
  2142. reply.appendf("<Dali connected='0'/>");
  2143. ReadLockBlock readBlock(packageCrit);
  2144. reply.appendf("<State hash='%"I64F"u'/>", (unsigned __int64) allQueryPackages->queryHash());
  2145. }
  2146. else if (stricmp(queryName, "control:resetindexmetrics")==0)
  2147. {
  2148. resetIndexMetrics();
  2149. }
  2150. else if (stricmp(queryName, "control:resetmetrics")==0)
  2151. {
  2152. roxieMetrics->resetMetrics();
  2153. }
  2154. else if (stricmp(queryName, "control:resetquerystats")==0)
  2155. {
  2156. ReadLockBlock readBlock(packageCrit);
  2157. Owned<IPropertyTreeIterator> queries = control->getElements("Query");
  2158. if (queries->first())
  2159. {
  2160. while (queries->isValid())
  2161. {
  2162. IPropertyTree &query = queries->query();
  2163. const char *id = query.queryProp("@id");
  2164. if (!id)
  2165. badFormat();
  2166. allQueryPackages->resetStats(id, logctx);
  2167. queries->next();
  2168. }
  2169. }
  2170. else
  2171. allQueryPackages->resetStats(NULL, logctx);
  2172. }
  2173. else if (stricmp(queryName, "control:resetremotedalicache")==0)
  2174. {
  2175. queryNamedGroupStore().resetCache();
  2176. }
  2177. else if (stricmp(queryName, "control:restart")==0)
  2178. {
  2179. FatalError("Roxie process restarted by operator request");
  2180. }
  2181. else if (stricmp(queryName, "control:retrieveActivityDetails")==0)
  2182. {
  2183. UNIMPLEMENTED;
  2184. }
  2185. else if (stricmp(queryName, "control:retrieveFileInfo")==0)
  2186. {
  2187. UNIMPLEMENTED;
  2188. }
  2189. else if (stricmp(queryName, "control:roxiememstats") == 0)
  2190. {
  2191. StringBuffer memStats;
  2192. queryMemoryPoolStats(memStats);
  2193. reply.append("<MemoryStats>").append(memStats.str()).append("</MemoryStats>\n");
  2194. }
  2195. else
  2196. unknown = true;
  2197. break;
  2198. case 'S':
  2199. if (stricmp(queryName, "control:setCopyResources")==0)
  2200. {
  2201. copyResources = control->getPropBool("@val", true);
  2202. topology->setPropBool("@copyResources", copyResources);
  2203. }
  2204. else if (stricmp(queryName, "control:simpleLocalKeyedJoins")==0)
  2205. {
  2206. simpleLocalKeyedJoins = control->getPropBool("@val", true);
  2207. }
  2208. else if (stricmp(queryName, "control:soapInfo")==0)
  2209. {
  2210. UNIMPLEMENTED;
  2211. }
  2212. else if (stricmp(queryName, "control:soapTrace")==0)
  2213. {
  2214. soapTraceLevel = control->getPropInt("@level", 0);
  2215. topology->setPropInt("@soapTraceLevel", soapTraceLevel);
  2216. }
  2217. else if (stricmp(queryName, "control:socketCheckInterval")==0)
  2218. {
  2219. socketCheckInterval = (unsigned) control->getPropInt64("@val", 0);
  2220. topology->setPropInt64("@socketCheckInterval", socketCheckInterval);
  2221. }
  2222. else if (stricmp(queryName, "control:state")==0)
  2223. {
  2224. if (daliHelper && daliHelper->connected())
  2225. reply.appendf("<Dali connected='1'/>");
  2226. else
  2227. reply.appendf("<Dali connected='0'/>");
  2228. ReadLockBlock readBlock(packageCrit);
  2229. reply.appendf("<State hash='%"I64F"u'/>", (unsigned __int64) allQueryPackages->queryHash());
  2230. }
  2231. else if (stricmp(queryName, "control:steppingEnabled")==0)
  2232. {
  2233. steppingEnabled = control->getPropBool("@val", true);
  2234. }
  2235. else if (stricmp(queryName, "control:suspend")==0)
  2236. {
  2237. StringBuffer id(control->queryProp("Query/@id"));
  2238. if (!id.length())
  2239. badFormat();
  2240. {
  2241. Owned<IQueryFactory> f = getQuery(id, NULL, logctx);
  2242. if (f)
  2243. id.clear().append(f->queryQueryName()); // use the spelling of the query stored with the query factory
  2244. }
  2245. UNIMPLEMENTED;
  2246. }
  2247. else if (stricmp(queryName, "control:suspendChannel")==0)
  2248. {
  2249. if (control->hasProp("@channel") && control->hasProp("@suspend"))
  2250. {
  2251. unsigned channel = control->getPropInt("@channel", 0);
  2252. bool suspend = control->getPropBool("@suspend", true);
  2253. CriticalBlock b(ccdChannelsCrit);
  2254. if (channel)
  2255. {
  2256. StringBuffer xpath;
  2257. IPropertyTree *slaveNode = ccdChannels->queryPropTree(xpath.appendf("RoxieSlaveProcess[@channel='%u']", channel).str());
  2258. if (slaveNode)
  2259. {
  2260. ROQ->suspendChannel(channel, suspend, logctx);
  2261. slaveNode->setPropBool("@suspended", suspend);
  2262. }
  2263. else
  2264. throw MakeStringException(ROXIE_INVALID_INPUT, "Unknown channel %u", channel);
  2265. }
  2266. else
  2267. {
  2268. Owned<IPropertyTreeIterator> slaves = ccdChannels->getElements("RoxieSlaveProcess");
  2269. ForEach(*slaves)
  2270. {
  2271. IPropertyTree &slaveNode = slaves->query();
  2272. channel = slaveNode.getPropInt("@channel", 0);
  2273. ROQ->suspendChannel(channel, suspend, logctx);
  2274. slaveNode.setPropBool("@suspended", suspend);
  2275. }
  2276. }
  2277. toXML(ccdChannels, reply);
  2278. }
  2279. else
  2280. badFormat();
  2281. }
  2282. else if (stricmp(queryName, "control:suspendServer")==0)
  2283. {
  2284. if (control->hasProp("@port") && control->hasProp("@suspend"))
  2285. {
  2286. unsigned port = control->getPropInt("@port", 0);
  2287. bool suspend = control->getPropBool("@suspend", true);
  2288. CriticalBlock b(ccdChannelsCrit);
  2289. if (port)
  2290. {
  2291. StringBuffer xpath;
  2292. IPropertyTree *serverNode = ccdChannels->queryPropTree(xpath.appendf("RoxieServerProcess[@port='%u']", port).str());
  2293. if (serverNode)
  2294. {
  2295. suspendRoxieListener(port, suspend);
  2296. serverNode->setPropBool("@suspended", suspend);
  2297. }
  2298. else
  2299. throw MakeStringException(ROXIE_INVALID_INPUT, "Unknown Roxie server port %u", port);
  2300. }
  2301. else
  2302. {
  2303. Owned<IPropertyTreeIterator> servers = ccdChannels->getElements("RoxieServerProcess");
  2304. ForEach(*servers)
  2305. {
  2306. IPropertyTree &serverNode = servers->query();
  2307. port = serverNode.getPropInt("@port", 0);
  2308. suspendRoxieListener(port, suspend);
  2309. serverNode.setPropBool("@suspended", suspend);
  2310. }
  2311. }
  2312. toXML(ccdChannels, reply);
  2313. }
  2314. else
  2315. badFormat();
  2316. }
  2317. else if (stricmp(queryName, "control:systemMonitor")==0)
  2318. {
  2319. unsigned interval = control->getPropInt("@interval", 60000);
  2320. bool enable = control->getPropBool("@enable", true);
  2321. if (enable)
  2322. startPerformanceMonitor(interval);
  2323. else
  2324. stopPerformanceMonitor();
  2325. }
  2326. //MORE: control:stats??
  2327. else
  2328. unknown = true;
  2329. break;
  2330. case 'T':
  2331. if (stricmp(queryName, "control:testSlaveFailure")==0)
  2332. {
  2333. testSlaveFailure = control->getPropInt("@val", 20);
  2334. }
  2335. else if (stricmp(queryName, "control:timeActivities")==0)
  2336. {
  2337. defaultTimeActivities = control->getPropBool("@val", true);
  2338. topology->setPropInt("@timeActivities", defaultTimeActivities);
  2339. }
  2340. else if (stricmp(queryName, "control:timings")==0)
  2341. {
  2342. reply.append("<Timings>");
  2343. timer->getTimings(reply);
  2344. reply.append("</Timings>");
  2345. if (control->getPropBool("@reset", false))
  2346. {
  2347. timer->reset();
  2348. }
  2349. }
  2350. else if (stricmp(queryName, "control:topology")==0)
  2351. {
  2352. toXML(topology, reply);
  2353. }
  2354. else if (stricmp(queryName, "control:trace")==0)
  2355. {
  2356. traceLevel = control->getPropInt("@level", 0);
  2357. if (traceLevel > MAXTRACELEVEL)
  2358. traceLevel = MAXTRACELEVEL;
  2359. topology->setPropInt("@traceLevel", traceLevel);
  2360. }
  2361. else if (stricmp(queryName, "control:traceServerSideCache")==0)
  2362. {
  2363. traceServerSideCache = control->getPropBool("@val", true);
  2364. topology->setPropInt("@traceServerSideCache", traceServerSideCache);
  2365. }
  2366. else if (stricmp(queryName, "control:traceJHtreeAllocations")==0)
  2367. {
  2368. traceJHtreeAllocations = control->getPropBool("@val", true);
  2369. topology->setPropInt("@traceJHtreeAllocations", traceJHtreeAllocations);
  2370. }
  2371. else if (stricmp(queryName, "control:traceSmartStepping")==0)
  2372. {
  2373. traceSmartStepping = control->getPropBool("@val", true);
  2374. topology->setPropInt("@traceSmartStepping", traceSmartStepping);
  2375. }
  2376. else if (stricmp(queryName, "control:traceStartStop")==0)
  2377. {
  2378. traceStartStop = control->getPropBool("@val", true);
  2379. topology->setPropInt("@traceStartStop", traceStartStop);
  2380. }
  2381. else
  2382. unknown = true;
  2383. break;
  2384. case 'U':
  2385. if (stricmp(queryName, "control:udptrace")==0)
  2386. {
  2387. udpTraceLevel = control->getPropInt("@level", 0);
  2388. topology->setPropInt("@udpTraceLevel", udpTraceLevel);
  2389. }
  2390. else if (stricmp(queryName, "control:unlockDali")==0)
  2391. {
  2392. topology->setPropBool("@lockDali", false);
  2393. // Dali will reattach via the timer that checks every so often if can reattach...
  2394. saveTopology();
  2395. }
  2396. else if (stricmp(queryName, "control:unsuspend")==0)
  2397. {
  2398. UNIMPLEMENTED;
  2399. }
  2400. else if (stricmp(queryName, "control:userMetric")==0)
  2401. {
  2402. const char *name = control->queryProp("@name");
  2403. const char *regex= control->queryProp("@regex");
  2404. if (name && regex)
  2405. {
  2406. roxieMetrics->addUserMetric(name, regex);
  2407. // MORE - we could add to topology, we could check for dups, and we could support removing them.
  2408. }
  2409. else
  2410. throw MakeStringException(ROXIE_MISSING_PARAMS, "Metric name or regex missing");
  2411. }
  2412. else if (stricmp(queryName, "control:useTreeCopy")==0)
  2413. {
  2414. useTreeCopy = control->getPropBool("@val", true);
  2415. topology->setPropInt("@useTreeCopy", useTreeCopy);
  2416. }
  2417. else
  2418. unknown = true;
  2419. break;
  2420. case 'W':
  2421. if (stricmp(queryName, "control:watchActivityId")==0)
  2422. {
  2423. watchActivityId = control->getPropInt("@id", true);
  2424. }
  2425. else
  2426. unknown = true;
  2427. break;
  2428. default:
  2429. unknown = true;
  2430. break;
  2431. }
  2432. if (unknown)
  2433. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", queryName);
  2434. }
  2435. void badFormat()
  2436. {
  2437. throw MakeStringException(ROXIE_INVALID_INPUT, "Badly formated control query");
  2438. }
  2439. };
  2440. extern IRoxieQueryPackageManagerSet *createRoxiePackageSetManager(const IQueryDll *standAloneDll)
  2441. {
  2442. return new CRoxiePackageSetManager(standAloneDll);
  2443. }
  2444. IRoxieQueryPackageManagerSet *globalPackageSetManager = NULL;
  2445. extern void loadPlugins()
  2446. {
  2447. if (pluginDirectory.length() && isDirectory(pluginDirectory.str()))
  2448. {
  2449. plugins = new SafePluginMap(&PluginCtx, traceLevel >= 1);
  2450. plugins->loadFromDirectory(pluginDirectory);
  2451. }
  2452. }
  2453. extern void cleanupPlugins()
  2454. {
  2455. delete plugins;
  2456. plugins = NULL;
  2457. }
  2458. /*=======================================================================================================
  2459. * mergeStats and associated code is used to combine the graph stats from multiple nodes in a cluster into
  2460. * a single aggregate structure
  2461. * It should be moved into ccdquery.cpp really
  2462. *========================================================================================================*/
  2463. typedef void (*mergefunc)(IPropertyTree *s1, IPropertyTree *s2, unsigned level);
  2464. struct MergeInfo
  2465. {
  2466. const char *element;
  2467. const char *attribute;
  2468. mergefunc f;
  2469. };
  2470. void mergeSubGraphs(IPropertyTree *s1, IPropertyTree *s2, unsigned);
  2471. void mergeNodes(IPropertyTree *s1, IPropertyTree *s2)
  2472. {
  2473. Owned<IPropertyTreeIterator> elems = s1->getElements("att");
  2474. ForEach(*elems)
  2475. {
  2476. IPropertyTree &e1 = elems->query();
  2477. unsigned __int64 v1 = e1.getPropInt64("@value", 0);
  2478. const char *name = e1.queryProp("@name");
  2479. if (stricmp(name, "_kind")==0 && v1 == TAKsubgraph)
  2480. {
  2481. IPropertyTree *s1child = s1->queryPropTree("att/graph");
  2482. IPropertyTree *s2child = s2->queryPropTree("att[@name='_kind']/graph");
  2483. if (s1child && s2child)
  2484. {
  2485. mergeSubGraphs(s1child, s2child, 0);
  2486. s2->removeProp("att[@name='_kind']");
  2487. }
  2488. }
  2489. else
  2490. {
  2491. StringBuffer xpath;
  2492. xpath.appendf("att[@name='%s']", name);
  2493. const char *type = e1.queryProp("@type");
  2494. if (type)
  2495. {
  2496. IPropertyTree *e2 = s2->queryPropTree(xpath.str());
  2497. if (e2)
  2498. {
  2499. unsigned __int64 v2 = e2->getPropInt64("@value", 0);
  2500. if (strcmp(name, "max")==0)
  2501. {
  2502. if (v2 > v1)
  2503. e1.setPropInt64("@value", v2);
  2504. }
  2505. else if (strcmp(type, "min")==0)
  2506. {
  2507. if (v2 < v1)
  2508. e1.setPropInt64("@value", v2);
  2509. }
  2510. else if (strcmp(type, "sum")==0)
  2511. e1.setPropInt64("@value", v1+v2);
  2512. else
  2513. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown type %s in graph statistics", type);
  2514. s2->removeTree(e2);
  2515. }
  2516. }
  2517. else
  2518. {
  2519. // remove from s2 any complete dups
  2520. const char *s1val = e1.queryProp("@value");
  2521. Owned<IPropertyTreeIterator> s2elems = s2->getElements(xpath.str());
  2522. IArrayOf<IPropertyTree> goers;
  2523. ForEach(*s2elems)
  2524. {
  2525. IPropertyTree &e2 = s2elems->query();
  2526. const char *s2val = e2.queryProp("@value");
  2527. if ((!s1val && !s2val) || (s1val && s2val && strcmp(s1val, s2val)==0))
  2528. goers.append(*LINK(&e2));
  2529. }
  2530. ForEachItemIn(idx, goers)
  2531. {
  2532. s2->removeTree(&goers.item(idx));
  2533. }
  2534. }
  2535. }
  2536. }
  2537. elems.setown(s2->getElements("*"));
  2538. ForEach(*elems)
  2539. {
  2540. IPropertyTree &e2 = elems->query();
  2541. s1->addPropTree(e2.queryName(), LINK(&e2));
  2542. }
  2543. }
  2544. void mergeSubGraphs(IPropertyTree *s1, IPropertyTree *s2, unsigned)
  2545. {
  2546. Owned<IPropertyTreeIterator> elems = s1->getElements("*");
  2547. ForEach(*elems)
  2548. {
  2549. IPropertyTree &e1 = elems->query();
  2550. const char *elemName = e1.queryName();
  2551. StringBuffer xpath;
  2552. if (strcmp(elemName, "att")==0)
  2553. {
  2554. xpath.appendf("att[@name='%s']", e1.queryProp("@name"));
  2555. IPropertyTree *e2 = s2->queryPropTree(xpath.str());
  2556. if (e2)
  2557. s2->removeTree(e2);
  2558. }
  2559. else
  2560. {
  2561. xpath.appendf("%s[@id='%s']", elemName, e1.queryProp("@id"));
  2562. IPropertyTree *e2 = s2->queryPropTree(xpath.str());
  2563. if (e2)
  2564. {
  2565. mergeNodes(&e1, e2);
  2566. s2->removeTree(e2);
  2567. }
  2568. }
  2569. }
  2570. elems.setown(s2->getElements("*"));
  2571. ForEach(*elems)
  2572. {
  2573. IPropertyTree &e2 = elems->query();
  2574. s1->addPropTree(e2.queryName(), LINK(&e2));
  2575. }
  2576. }
  2577. void mergeNode(IPropertyTree *s1, IPropertyTree *s2, unsigned level);
  2578. MergeInfo mergeTable[] =
  2579. {
  2580. {"Query", "@id", mergeStats},
  2581. {"Graph", "@id", mergeStats},
  2582. {"xgmml", NULL, mergeStats},
  2583. {"graph", NULL, mergeStats},
  2584. {"node", "@id", mergeNode},
  2585. {"att", NULL, mergeStats},
  2586. {"graph", NULL, mergeSubGraphs},
  2587. };
  2588. void mergeNode(IPropertyTree *s1, IPropertyTree *s2, unsigned level)
  2589. {
  2590. if (s1->hasProp("att/@name"))
  2591. mergeNodes(s1, s2);
  2592. else
  2593. mergeStats(s1, s2, level);
  2594. }
  2595. void mergeStats(IPropertyTree *s1, IPropertyTree *s2, unsigned level)
  2596. {
  2597. MergeInfo & mi = mergeTable[level];
  2598. Owned<IPropertyTreeIterator> elems = s1->getElements(mi.element);
  2599. ForEach(*elems)
  2600. {
  2601. IPropertyTree &e1 = elems->query();
  2602. StringBuffer xpath;
  2603. if (mi.attribute)
  2604. xpath.appendf("%s[%s='%s']", mi.element, mi.attribute, e1.queryProp(mi.attribute));
  2605. else
  2606. xpath.append(mi.element);
  2607. IPropertyTree *e2 = s2->queryPropTree(xpath.str());
  2608. if (e2)
  2609. {
  2610. mi.f(&e1, e2, level+1);
  2611. s2->removeTree(e2);
  2612. }
  2613. }
  2614. elems.setown(s2->getElements(mi.element));
  2615. ForEach(*elems)
  2616. {
  2617. IPropertyTree &e2 = elems->query();
  2618. s1->addPropTree(mi.element, LINK(&e2));
  2619. }
  2620. }
  2621. void mergeStats(IPropertyTree *s1, IPropertyTree *s2)
  2622. {
  2623. Owned<IPropertyTreeIterator> elems = s2->getElements("Exception");
  2624. ForEach(*elems)
  2625. {
  2626. s1->addPropTree("Exception", LINK(&elems->query()));
  2627. }
  2628. mergeStats(s1, s2, 0);
  2629. }
  2630. void mergeQueries(IPropertyTree *dest, IPropertyTree *src)
  2631. {
  2632. IPropertyTree *destQueries = ensurePTree(dest, "Queries");
  2633. IPropertyTree *srcQueries = src->queryPropTree("Queries");
  2634. if (!srcQueries)
  2635. return;
  2636. destQueries->setPropInt("@reporting", destQueries->getPropInt("@reporting") + srcQueries->getPropInt("@reporting"));
  2637. Owned<IPropertyTreeIterator> it = srcQueries->getElements("Query");
  2638. ForEach(*it)
  2639. {
  2640. IPropertyTree *srcQuery = &it->query();
  2641. const char *id = srcQuery->queryProp("@id");
  2642. if (!id || !*id)
  2643. continue;
  2644. VStringBuffer xpath("Query[@id='%s']", id);
  2645. IPropertyTree *destQuery = destQueries->queryPropTree(xpath);
  2646. if (!destQuery)
  2647. {
  2648. destQueries->addPropTree("Query", LINK(srcQuery));
  2649. continue;
  2650. }
  2651. int suspended = destQuery->getPropInt("@suspended") + srcQuery->getPropInt("@suspended"); //keep count to recognize "partially suspended" queries
  2652. mergePTree(destQuery, srcQuery);
  2653. if (suspended)
  2654. destQuery->setPropInt("@suspended", suspended);
  2655. }
  2656. }
  2657. #ifdef _USE_CPPUNIT
  2658. #include <cppunit/extensions/HelperMacros.h>
  2659. static const char *g1 =
  2660. "<Stats>"
  2661. "<Query id='stats'>"
  2662. "<Graph id='graph1'>"
  2663. "<xgmml>"
  2664. "<graph>"
  2665. "<node id='1'>"
  2666. "<att>"
  2667. "<graph>"
  2668. "<node id='2' label='Temp Table'>"
  2669. "<att name='name' value='d'/>"
  2670. "<att name='_kind' value='25'/>"
  2671. "<att name='helper' value='f2'/>"
  2672. "</node>"
  2673. "<node id='2a'>"
  2674. " <att name='_kind' value='1'>" // TAKsubgraph
  2675. " <graph>"
  2676. " <node id='7696' label='Nested'>"
  2677. " <att name='seeks' value='15' type='sum'/>"
  2678. " </node>"
  2679. " </graph>"
  2680. " </att>"
  2681. "</node>"
  2682. "<node id='3' label='Filter'>"
  2683. "<att name='name' value='ds'/>"
  2684. "<att name='_kind' value='5'/>"
  2685. "<att name='helper' value='f3'/>"
  2686. "</node>"
  2687. "<att name='rootGraph' value='1'/>"
  2688. "<edge id='2_0' source='2' target='3'>"
  2689. "<att name='count' value='15' type='sum'/>"
  2690. "<att name='started' value='1'/>"
  2691. "<att name='stopped' value='1'/>"
  2692. "</edge>"
  2693. "<edge id='3_0' source='3' target='5'>"
  2694. "<att name='count' value='15' type='sum'/>"
  2695. "<att name='started' value='1'/>"
  2696. "<att name='stopped' value='1'/>"
  2697. "</edge>"
  2698. "<edge id='5_0' source='5' target='6'>"
  2699. "<att name='count' value='3' type='sum'/>"
  2700. "<att name='started' value='1'/>"
  2701. "<att name='stopped' value='1'/>"
  2702. "</edge>"
  2703. "<edge id='5_1' source='5' target='7'>"
  2704. "<att name='_sourceIndex' value='1'/>"
  2705. "<att name='count' value='15' type='sum'/>"
  2706. "<att name='started' value='1'/>"
  2707. "<att name='stopped' value='1'/>"
  2708. "</edge>"
  2709. "</graph>"
  2710. "</att>"
  2711. "</node>"
  2712. "</graph>"
  2713. "</xgmml>"
  2714. "</Graph>"
  2715. "</Query>"
  2716. "</Stats>";
  2717. static const char *g2 =
  2718. "<Stats>"
  2719. "<Query id='stats'>"
  2720. "<Graph id='graph1'>"
  2721. "<xgmml>"
  2722. "<graph>"
  2723. "<node id='1'>"
  2724. "<att>"
  2725. "<graph>"
  2726. "<node id='2' label='Temp Table'>"
  2727. "<att name='name' value='d'/>"
  2728. "<att name='_kind' value='25'/>"
  2729. "<att name='helper' value='f2'/>"
  2730. "</node>"
  2731. "<node id='2a'>"
  2732. " <att name='_kind' value='1'>" // TAKsubgraph
  2733. " <graph>"
  2734. " <node id='7696' label='Nested'>"
  2735. " <att name='seeks' value='25' type='sum'/>"
  2736. " </node>"
  2737. " </graph>"
  2738. " </att>"
  2739. "</node>"
  2740. "<node id='4' label='Filter2'>"
  2741. "<att name='name' value='ds2'/>"
  2742. "<att name='_kind' value='53'/>"
  2743. "<att name='helper' value='f23'/>"
  2744. "</node>"
  2745. "<att name='rootGraph' value='1'/>"
  2746. "<edge id='2_0' source='2' target='3'>"
  2747. "<att name='count' value='15' type='sum'/>"
  2748. "<att name='started' value='1'/>"
  2749. "<att name='stopped' value='1'/>"
  2750. "</edge>"
  2751. "<edge id='3_0' source='3' target='5'>"
  2752. "<att name='count' value='15' type='sum'/>"
  2753. "<att name='started' value='1'/>"
  2754. "<att name='stopped' value='1'/>"
  2755. "</edge>"
  2756. "<edge id='5_0' source='5' target='6'>"
  2757. "<att name='count' value='3' type='sum'/>"
  2758. "<att name='started' value='1'/>"
  2759. "<att name='stopped' value='1'/>"
  2760. "</edge>"
  2761. "</graph>"
  2762. "</att>"
  2763. "</node>"
  2764. "</graph>"
  2765. "</xgmml>"
  2766. "</Graph>"
  2767. "</Query>"
  2768. "</Stats>";
  2769. static const char *expected =
  2770. "<Stats>"
  2771. "<Query id='stats'>"
  2772. "<Graph id='graph1'>"
  2773. "<xgmml>"
  2774. "<graph>"
  2775. "<node id='1'>"
  2776. "<att>"
  2777. "<graph>"
  2778. "<node id='2' label='Temp Table'>"
  2779. "<att name='name' value='d'/>"
  2780. "<att name='_kind' value='25'/>"
  2781. "<att name='helper' value='f2'/>"
  2782. "</node>"
  2783. "<node id='2a'>"
  2784. " <att name='_kind' value='1'>" // TAKsubgraph
  2785. " <graph>"
  2786. " <node id='7696' label='Nested'>"
  2787. " <att name='seeks' type='sum' value='40'/>"
  2788. " </node>"
  2789. " </graph>"
  2790. " </att>"
  2791. "</node>"
  2792. "<node id='3' label='Filter'>"
  2793. "<att name='name' value='ds'/>"
  2794. "<att name='_kind' value='5'/>"
  2795. "<att name='helper' value='f3'/>"
  2796. "</node>"
  2797. "<node id='4' label='Filter2'>"
  2798. "<att name='name' value='ds2'/>"
  2799. "<att name='_kind' value='53'/>"
  2800. "<att name='helper' value='f23'/>"
  2801. "</node>"
  2802. "<att name='rootGraph' value='1'/>"
  2803. "<edge id='2_0' source='2' target='3'>"
  2804. "<att name='count' value='30' type='sum'/>"
  2805. "<att name='started' value='1'/>"
  2806. "<att name='stopped' value='1'/>"
  2807. "</edge>"
  2808. "<edge id='3_0' source='3' target='5'>"
  2809. "<att name='count' value='30' type='sum'/>"
  2810. "<att name='started' value='1'/>"
  2811. "<att name='stopped' value='1'/>"
  2812. "</edge>"
  2813. "<edge id='5_0' source='5' target='6'>"
  2814. "<att name='count' value='6' type='sum'/>"
  2815. "<att name='started' value='1'/>"
  2816. "<att name='stopped' value='1'/>"
  2817. "</edge>"
  2818. "<edge id='5_1' source='5' target='7'>"
  2819. "<att name='_sourceIndex' value='1'/>"
  2820. "<att name='count' value='15' type='sum'/>"
  2821. "<att name='started' value='1'/>"
  2822. "<att name='stopped' value='1'/>"
  2823. "</edge>"
  2824. "</graph>"
  2825. "</att>"
  2826. "</node>"
  2827. "</graph>"
  2828. "</xgmml>"
  2829. "</Graph>"
  2830. "</Query>"
  2831. "</Stats>"
  2832. ;
  2833. class MergeStatsTest : public CppUnit::TestFixture
  2834. {
  2835. CPPUNIT_TEST_SUITE( MergeStatsTest );
  2836. CPPUNIT_TEST(test1);
  2837. CPPUNIT_TEST_SUITE_END();
  2838. protected:
  2839. void test1()
  2840. {
  2841. Owned<IPropertyTree> p1 = createPTreeFromXMLString(g1);
  2842. Owned<IPropertyTree> p2 = createPTreeFromXMLString(g2);
  2843. Owned<IPropertyTree> e = createPTreeFromXMLString(expected);
  2844. mergeStats(p1, p2);
  2845. StringBuffer s1, s2;
  2846. toXML(p1, s1);
  2847. toXML(e, s2);
  2848. CPPUNIT_ASSERT(strcmp(s1, s2)==0);
  2849. }
  2850. };
  2851. CPPUNIT_TEST_SUITE_REGISTRATION( MergeStatsTest );
  2852. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( MergeStatsTest, "MergeStatsTest" );
  2853. #endif