ccdstate.cpp 122 KB

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