ccdstate.cpp 115 KB

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