ccdstate.cpp 116 KB

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