ccdstate.cpp 122 KB

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