ccdstate.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include <platform.h>
  14. #include <jlib.hpp>
  15. #include "build-config.h"
  16. #include "jisem.hpp"
  17. #include "jsort.hpp"
  18. #include "jregexp.hpp"
  19. #include "ccd.hpp"
  20. #include "ccdquery.hpp"
  21. #include "ccdstate.hpp"
  22. #include "ccdqueue.ipp"
  23. #include "ccdlistener.hpp"
  24. #include "ccdfile.hpp"
  25. #include "ccdsnmp.hpp"
  26. #include "hqlplugins.hpp"
  27. #include "thorplugin.hpp"
  28. #include "eclrtl.hpp"
  29. #include "dafdesc.hpp"
  30. #include "dautils.hpp"
  31. #include "rmtfile.hpp"
  32. #include "pkgimpl.hpp"
  33. #include "roxiehelper.hpp"
  34. //-------------------------------------------------------------------------------------------
  35. // class CRoxiePluginCtx - provide the environments for plugins loaded by roxie.
  36. // Base class handles making sure memory allocation comes from the right heap.
  37. // implement get/set properties to allow plugin configuration information to be retrieved from Roxie topology file
  38. //-------------------------------------------------------------------------------------------
  39. class CRoxiePluginCtx : public SimplePluginCtx
  40. {
  41. public:
  42. virtual int ctxGetPropInt(const char *propName, int defaultValue) const
  43. {
  44. return topology->getPropInt(propName, defaultValue);
  45. }
  46. virtual const char *ctxQueryProp(const char *propName) const
  47. {
  48. return topology->queryProp(propName);
  49. }
  50. } PluginCtx;
  51. SafePluginMap *plugins;
  52. //================================================================================================
  53. // In legacy state files, the original file names passed in _fileName or _indexFileName may have been translated into _superFileName or _superKeyName,
  54. // 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
  55. // if the files resolve to single file/key, or if we are using new embedded wu system
  56. // 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
  57. // iterator on the xgmml node to get the list.
  58. // These two helper functions will return the original filenames placed in the XGMML by the codegen, regardless of how/if roxieconfig resolved them
  59. static const char *_queryNodeFileName(const IPropertyTree &graphNode)
  60. {
  61. if (graphNode.hasProp("att[@name='_file_dynamic']"))
  62. return NULL;
  63. else
  64. return graphNode.queryProp("att[@name='_fileName']/@value");
  65. }
  66. static const char *_queryNodeIndexName(const IPropertyTree &graphNode)
  67. {
  68. if (graphNode.hasProp("att[@name='_indexFile_dynamic']"))
  69. return NULL;
  70. else
  71. return graphNode.queryProp("att[@name='_indexFileName']/@value");
  72. }
  73. static bool isSimpleIndexActivity(ThorActivityKind kind)
  74. {
  75. switch (kind)
  76. {
  77. case TAKindexaggregate:
  78. case TAKindexcount:
  79. case TAKindexexists:
  80. case TAKindexgroupaggregate:
  81. case TAKindexgroupcount:
  82. case TAKindexgroupexists:
  83. case TAKindexnormalize:
  84. case TAKindexread:
  85. return true;
  86. default:
  87. return false;
  88. }
  89. }
  90. const char *queryNodeFileName(const IPropertyTree &graphNode, ThorActivityKind kind)
  91. {
  92. if (isSimpleIndexActivity(kind))
  93. return NULL;
  94. else
  95. return _queryNodeFileName(graphNode);
  96. }
  97. const char *queryNodeIndexName(const IPropertyTree &graphNode, ThorActivityKind kind)
  98. {
  99. if (isSimpleIndexActivity(kind))
  100. return _queryNodeFileName(graphNode);
  101. else
  102. return _queryNodeIndexName(graphNode);
  103. }
  104. // DelayedReleaser mechanism hangs on to a link to an object for a while...
  105. class DelayedReleaseQueueItem : public CInterfaceOf<IInterface>
  106. {
  107. Owned<IInterface> goer;
  108. time_t goTime;
  109. public:
  110. DelayedReleaseQueueItem(IInterface *_goer, unsigned delaySeconds)
  111. : goer(_goer)
  112. {
  113. time(&goTime);
  114. goTime += delaySeconds;
  115. }
  116. unsigned remaining()
  117. {
  118. time_t now;
  119. time(&now);
  120. if (now > goTime)
  121. return 0;
  122. else
  123. return (unsigned)(goTime - now);
  124. }
  125. };
  126. class DelayedReleaserThread : public Thread
  127. {
  128. private:
  129. bool closing;
  130. bool started;
  131. CriticalSection lock;
  132. IArrayOf<DelayedReleaseQueueItem> queue;
  133. Semaphore sem;
  134. public:
  135. DelayedReleaserThread() : Thread("DelayedReleaserThread")
  136. {
  137. closing = false;
  138. started = false;
  139. }
  140. ~DelayedReleaserThread()
  141. {
  142. stop();
  143. }
  144. virtual int run()
  145. {
  146. if (traceLevel)
  147. DBGLOG("DelayedReleaserThread %p starting", this);
  148. unsigned nextTimeout = INFINITE;
  149. while (!closing)
  150. {
  151. sem.wait(nextTimeout);
  152. CriticalBlock b(lock);
  153. nextTimeout = INFINITE;
  154. ForEachItemInRev(idx, queue)
  155. {
  156. DelayedReleaseQueueItem &goer = queue.item(idx);
  157. unsigned timeRemaining = goer.remaining();
  158. if (!timeRemaining)
  159. queue.remove(idx);
  160. else if (timeRemaining < nextTimeout)
  161. nextTimeout = timeRemaining;
  162. }
  163. if (nextTimeout != INFINITE)
  164. nextTimeout = nextTimeout * 1000;
  165. clearKeyStoreCache(false); // Allows us to fully release files we no longer need because of unloaded queries
  166. }
  167. if (traceLevel)
  168. DBGLOG("DelayedReleaserThread %p exiting", this);
  169. return 0;
  170. }
  171. void stop()
  172. {
  173. if (started)
  174. {
  175. closing = true;
  176. sem.signal();
  177. join();
  178. }
  179. }
  180. void delayedRelease(IInterface *goer, unsigned delaySeconds)
  181. {
  182. if (goer)
  183. {
  184. CriticalBlock b(lock);
  185. if (!started)
  186. {
  187. start();
  188. started = true;
  189. }
  190. queue.append(*new DelayedReleaseQueueItem(goer, delaySeconds));
  191. sem.signal();
  192. }
  193. }
  194. };
  195. Owned<DelayedReleaserThread> delayedReleaser;
  196. void createDelayedReleaser()
  197. {
  198. delayedReleaser.setown(new DelayedReleaserThread);
  199. }
  200. void stopDelayedReleaser()
  201. {
  202. if (delayedReleaser)
  203. delayedReleaser->stop();
  204. delayedReleaser.clear();
  205. }
  206. //-------------------------------------------------------------------------
  207. class CSimpleSuperFileArray : implements ISimpleSuperFileEnquiry, public CInterface
  208. {
  209. IArrayOf<IPropertyTree> subFiles;
  210. public:
  211. IMPLEMENT_IINTERFACE;
  212. CSimpleSuperFileArray(IPropertyTreeIterator &_subs)
  213. {
  214. ForEach(_subs)
  215. {
  216. IPropertyTree &sub = _subs.query();
  217. sub.Link();
  218. subFiles.append(sub);
  219. }
  220. }
  221. virtual unsigned numSubFiles() const
  222. {
  223. return subFiles.length();
  224. }
  225. virtual bool getSubFileName(unsigned num, StringBuffer &name) const
  226. {
  227. if (subFiles.isItem(num))
  228. {
  229. name.append(subFiles.item(num).queryProp("@value"));
  230. return true;
  231. }
  232. else
  233. return false;
  234. }
  235. virtual unsigned findSubName(const char *subname) const
  236. {
  237. ForEachItemIn(idx, subFiles)
  238. {
  239. if (stricmp(subFiles.item(idx).queryProp("@value"), subname))
  240. return idx;
  241. }
  242. return NotFound;
  243. }
  244. virtual unsigned getContents(StringArray &contents) const
  245. {
  246. ForEachItemIn(idx, subFiles)
  247. {
  248. contents.append(subFiles.item(idx).queryProp("@value"));
  249. }
  250. return subFiles.length();
  251. }
  252. };
  253. //-------------------------------------------------------------------------------------------
  254. // class CRoxiePackage - provide the environment in which file names and query options are interpreted
  255. // by a roxie query.
  256. // File names are resolved into IResolvedFile objects. A cache is used to ensure that the IResolvedFile is
  257. // shared wherever possible.
  258. // Effective environment is precomputed in mergedEnvironment for efficient recall by queries
  259. // Packages are described using XML files - see documentation for details.
  260. //-------------------------------------------------------------------------------------------
  261. /**
  262. * Packages are hierarchical - they are searched recursively to get the info you want
  263. * A PackageMap defines the entire environment - potentially each query that uses that PackageMap will pick a different package within it
  264. * A particular instantiation of a roxie query (i.e. a IQueryFactory) will have a pointer to the specific IRoxiePackage within the active PackageMap
  265. * that is providing its environment.
  266. *
  267. * 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.
  268. *
  269. * A PackageSet is a list of PackageMap id's, and is used to tell Roxie what PackageMaps to load.
  270. * A Roxie can have multiple PackageMap's active. When updating the data, you might:
  271. * - create a new PackageMap to refer to the new data
  272. * - once it has loaded, mark it active, and mark the previous one as inactive
  273. * - Once sure no queries in flight, unload the previous one
  274. *
  275. * Each Roxie will load all PackageMaps that are in any PackageSet whose @process attribute matches the cluster name.
  276. *
  277. * All package information is stored in Dali (and cached locally)
  278. *
  279. * <PackageSets>
  280. * <PackageSet id = 'ps1' process='*'> # use this packageset for all roxies (same as omitting process)
  281. * <PackageMap id='pm1b' querySet='qs1' active='true'/> # Use the PackageMap pm1b for QuerySet qs1 and make it active
  282. * <PackageMap id='pm1a' querySet='qs1' active='false'/> # Use the PackageMap pm1a for QuerySet qs1 but don't make it active
  283. * <PackageMap id='pm2' querySet='dev*' active='true'/> # Use the PackageMap pm1a for all QuerySets with names starting dev and make it active
  284. * </PackageMapSet>
  285. * </PackageSets>
  286. *
  287. * <PackageMaps>
  288. * <PackageMap id='pm1a'>
  289. * <Package id='package1'>
  290. * ...
  291. * </Package>
  292. * <Package id='package2'>
  293. * </Package>
  294. * </PackageMap>
  295. * <PackageMap id='pm2'>
  296. * </PackageMap>
  297. * <PackageMap id='pm3'>
  298. * </PackageMap>
  299. * </PackageMaps>
  300. */
  301. class CResolvedFileCache : implements IResolvedFileCache
  302. {
  303. CriticalSection cacheLock;
  304. CopyMapStringToMyClass<IResolvedFile> files;
  305. public:
  306. // Retrieve number of files in cache
  307. inline unsigned count() const
  308. {
  309. return files.count();
  310. }
  311. // Add a filename and the corresponding IResolvedFile to the cache
  312. virtual void addCache(const char *filename, const IResolvedFile *file)
  313. {
  314. CriticalBlock b(cacheLock);
  315. IResolvedFile *add = const_cast<IResolvedFile *>(file);
  316. add->setCache(this);
  317. files.setValue(filename, add);
  318. }
  319. // Remove an IResolvedFile from the cache
  320. virtual void removeCache(const IResolvedFile *file)
  321. {
  322. CriticalBlock b(cacheLock);
  323. if (traceLevel > 9)
  324. DBGLOG("removeCache %s", file->queryFileName());
  325. // NOTE: it's theoretically possible for the final release to happen after a replacement has been inserted into hash table.
  326. // So only remove from hash table if what we find there matches the item that is being deleted.
  327. IResolvedFile *goer = files.getValue(file->queryFileName());
  328. if (goer == file)
  329. files.remove(file->queryFileName());
  330. // 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
  331. }
  332. // Lookup a filename in the cache
  333. virtual IResolvedFile *lookupCache(const char *filename)
  334. {
  335. CriticalBlock b(cacheLock);
  336. IResolvedFile *cache = files.getValue(filename);
  337. if (cache)
  338. {
  339. LINK(cache);
  340. if (cache->isAlive())
  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)
  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);
  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);
  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) const
  477. {
  478. IResolvedFile *result = lookupFile(fileName, useCache, cacheResult, writeAccess, alwaysCreate);
  479. if (!result && (!checkCompulsory || !isCompulsory()))
  480. result = resolveLFNusingDaliOrLocal(fileName, useCache, cacheResult, writeAccess, alwaysCreate, resolveLocally());
  481. return result;
  482. }
  483. IResolvedFile *lookupFile(const char *fileName, bool useCache, bool cacheResult, bool writeAccess, bool alwaysCreate) 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); // 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);
  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. ForEach(*supers)
  557. {
  558. IPropertyTree &super = supers->query();
  559. const char *name = super.queryProp("@id");
  560. if (name)
  561. {
  562. try
  563. {
  564. const IResolvedFile *resolved = lookupFileName(name, false, true, true, NULL, true);
  565. if (resolved)
  566. {
  567. files.append(*const_cast<IResolvedFile *>(resolved));
  568. Owned<IPropertyTreeIterator> it = ccdChannels->getElements("RoxieSlaveProcess");
  569. ForEach(*it)
  570. {
  571. unsigned channelNo = it->query().getPropInt("@channel", 0);
  572. assertex(channelNo);
  573. doPreload(channelNo, 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) 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);
  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) const
  635. {
  636. StringBuffer fileName;
  637. expandLogicalFilename(fileName, _fileName, wu, false, false);
  638. Owned<IResolvedFile> resolved = lookupFile(fileName, false, false, true, true);
  639. if (!resolved)
  640. resolved.setown(resolveLFNusingDaliOrLocal(fileName, false, false, true, true, resolveLocally()));
  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);
  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(StringArray &queryids, StringArray &wrn, StringArray &err, StringArray &unmatchedQueries, StringArray &unusedPackages, StringArray &unmatchedFiles) const
  752. {
  753. return BASE::validate(queryids, wrn, err, unmatchedQueries, unusedPackages, unmatchedFiles);
  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. CriticalBlock b(ccdChannelsCrit);
  1055. managers = new CRoxieSlaveQuerySetManager *[numChannels];
  1056. memset(managers, 0, sizeof(CRoxieSlaveQuerySetManager *) * numChannels);
  1057. Owned<IPropertyTreeIterator> it = ccdChannels->getElements("RoxieSlaveProcess");
  1058. ForEach(*it)
  1059. {
  1060. unsigned channelNo = it->query().getPropInt("@channel", 0);
  1061. assertex(channelNo>0 && channelNo<=numChannels);
  1062. if (managers[channelNo-1] == NULL)
  1063. managers[channelNo-1] = new CRoxieSlaveQuerySetManager(channelNo, querySetName);
  1064. else
  1065. throw MakeStringException(ROXIE_INVALID_TOPOLOGY, "Invalid topology file - channel %d repeated for this slave", channelNo);
  1066. }
  1067. }
  1068. ~CRoxieSlaveQuerySetManagerSet()
  1069. {
  1070. for (unsigned channel = 0; channel < numChannels; channel++)
  1071. ::Release(managers[channel]);
  1072. delete [] managers;
  1073. }
  1074. inline CRoxieSlaveQuerySetManager *item(int idx)
  1075. {
  1076. return managers[idx];
  1077. }
  1078. virtual void load(const IPropertyTree *querySets, const IRoxiePackageMap &packages, hash64_t &hash, bool forceRetry)
  1079. {
  1080. for (unsigned channel = 0; channel < numChannels; channel++)
  1081. if (managers[channel])
  1082. managers[channel]->load(querySets, packages, hash, forceRetry); // MORE - this means the hash depends on the number of channels. Is that desirable?
  1083. }
  1084. virtual void getQueries(const char *id, IArrayOf<IQueryFactory> &queries, const IRoxieContextLogger &logctx) const
  1085. {
  1086. for (unsigned channel = 0; channel < numChannels; channel++)
  1087. if (managers[channel])
  1088. {
  1089. IQueryFactory *query = managers[channel]->getQuery(id, NULL, logctx);
  1090. if (query)
  1091. queries.append(*query);
  1092. }
  1093. }
  1094. private:
  1095. unsigned numChannels;
  1096. CRoxieSlaveQuerySetManager **managers;
  1097. };
  1098. //===============================================================================================================
  1099. class CRoxieDebugSessionManager : implements IRoxieDebugSessionManager, public CInterface
  1100. {
  1101. protected:
  1102. ReadWriteLock debugLock;
  1103. MapStringToMyClass<IDebuggerContext> debuggerContexts;
  1104. public:
  1105. IMPLEMENT_IINTERFACE;
  1106. void getActiveQueries(StringBuffer &reply)
  1107. {
  1108. HashIterator q(debuggerContexts);
  1109. for (q.first(); q.isValid(); q.next())
  1110. {
  1111. IDebuggerContext *ctx = debuggerContexts.mapToValue(&q.query());
  1112. reply.appendf(" <Query id='%s' uid='%s' debug='1'/>\n", ctx->queryQueryName(), ctx->queryDebugId());
  1113. }
  1114. }
  1115. virtual void registerDebugId(const char *id, IDebuggerContext *ctx)
  1116. {
  1117. WriteLockBlock block(debugLock);
  1118. debuggerContexts.setValue(id, ctx);
  1119. }
  1120. virtual void deregisterDebugId(const char *id)
  1121. {
  1122. WriteLockBlock block(debugLock);
  1123. debuggerContexts.remove(id);
  1124. }
  1125. virtual IDebuggerContext *lookupDebuggerContext(const char *id)
  1126. {
  1127. ReadLockBlock block(debugLock);
  1128. IDebuggerContext *ctx = debuggerContexts.getValue(id);
  1129. if (ctx)
  1130. return LINK(ctx);
  1131. else
  1132. {
  1133. #ifdef _DEBUG
  1134. // In a debug environment, it is convenient to be able to use '*' to mean 'the only active debug session'...
  1135. if (strcmp(id, "*")==0 && debuggerContexts.count()==1)
  1136. {
  1137. HashIterator q(debuggerContexts);
  1138. for (q.first(); q.isValid(); q.next())
  1139. {
  1140. IDebuggerContext *ctx = debuggerContexts.mapToValue(&q.query());
  1141. return LINK(ctx);
  1142. }
  1143. }
  1144. #endif
  1145. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Debug context %s not found", id);
  1146. }
  1147. }
  1148. };
  1149. //===============================================================================================
  1150. /*----------------------------------------------------------------------------------------------
  1151. * A CRoxieQueryPackageManager object manages all the queries that are currently runnable via XML.
  1152. * There may be more than one in existence, but only one will be active and therefore used to
  1153. * look up queries that are received - this corresponds to the currently active package.
  1154. *-----------------------------------------------------------------------------------------------*/
  1155. static hash64_t hashXML(const IPropertyTree *tree)
  1156. {
  1157. StringBuffer xml;
  1158. toXML(tree, xml, 0, XML_SortTags);
  1159. return rtlHash64Data(xml.length(), xml.str(), 877029);
  1160. }
  1161. class CRoxieQueryPackageManager : public CInterface
  1162. {
  1163. public:
  1164. CRoxieQueryPackageManager(unsigned _numChannels, const char *_querySet, const IRoxiePackageMap *_packages, hash64_t _xmlHash)
  1165. : numChannels(_numChannels), packages(_packages), querySet(_querySet), xmlHash(_xmlHash)
  1166. {
  1167. queryHash = 0;
  1168. }
  1169. ~CRoxieQueryPackageManager()
  1170. {
  1171. }
  1172. inline const char *queryPackageId() const
  1173. {
  1174. return packages->queryPackageId();
  1175. }
  1176. virtual void reload()
  1177. {
  1178. // Default is to do nothing...
  1179. }
  1180. virtual void load(bool forceReload) = 0;
  1181. bool matches(hash64_t _xmlHash, bool _active) const
  1182. {
  1183. return _xmlHash == xmlHash && _active==packages->isActive();
  1184. }
  1185. virtual hash64_t getHash()
  1186. {
  1187. CriticalBlock b2(updateCrit);
  1188. return queryHash;
  1189. }
  1190. IRoxieQuerySetManager* getRoxieServerManager()
  1191. {
  1192. CriticalBlock b2(updateCrit);
  1193. return serverManager.getLink();
  1194. }
  1195. IRoxieQuerySetManagerSet* getRoxieSlaveManagers()
  1196. {
  1197. CriticalBlock b2(updateCrit);
  1198. return slaveManagers.getLink();
  1199. }
  1200. void getInfo(StringBuffer &reply, const IRoxieContextLogger &logctx) const
  1201. {
  1202. reply.appendf(" <PackageSet id=\"%s\" querySet=\"%s\"", queryPackageId(), querySet.get());
  1203. if (!packages || !packages->getPartIds().ordinality())
  1204. {
  1205. reply.append("/>\n");
  1206. return;
  1207. }
  1208. reply.append(">\n");
  1209. const StringArray &parts = packages->getPartIds();
  1210. ForEachItemIn(i, parts)
  1211. reply.appendf(" <Part id='%s'/>\n", parts.item(i));
  1212. reply.append(" </PackageSet>\n");
  1213. }
  1214. bool resetStats(const char *queryId, const IRoxieContextLogger &logctx)
  1215. {
  1216. CriticalBlock b(updateCrit);
  1217. if (queryId)
  1218. {
  1219. Owned<IQueryFactory> query = serverManager->getQuery(queryId, NULL, logctx);
  1220. if (!query)
  1221. return false;
  1222. const char *id = query->queryQueryName();
  1223. serverManager->resetQueryTimings(id, logctx);
  1224. for (unsigned channel = 0; channel < numChannels; channel++)
  1225. if (slaveManagers->item(channel))
  1226. {
  1227. slaveManagers->item(channel)->resetQueryTimings(id, logctx);
  1228. }
  1229. }
  1230. else
  1231. {
  1232. serverManager->resetAllQueryTimings();
  1233. for (unsigned channel = 0; channel < numChannels; channel++)
  1234. if (slaveManagers->item(channel))
  1235. slaveManagers->item(channel)->resetAllQueryTimings();
  1236. }
  1237. return true;
  1238. }
  1239. bool getStats(const char *queryId, const char *action, const char *graphName, StringBuffer &reply, const IRoxieContextLogger &logctx) const
  1240. {
  1241. CriticalBlock b2(updateCrit);
  1242. if (serverManager->isActive())
  1243. {
  1244. Owned<IQueryFactory> query = serverManager->getQuery(queryId, NULL, logctx);
  1245. if (query)
  1246. {
  1247. StringBuffer freply;
  1248. serverManager->getStats(queryId, graphName, freply, logctx);
  1249. Owned<IPropertyTree> stats = createPTreeFromXMLString(freply.str(), ipt_fast);
  1250. for (unsigned channel = 0; channel < numChannels; channel++)
  1251. if (slaveManagers->item(channel))
  1252. {
  1253. StringBuffer sreply;
  1254. slaveManagers->item(channel)->getStats(queryId, graphName, sreply, logctx);
  1255. Owned<IPropertyTree> cstats = createPTreeFromXMLString(sreply.str(), ipt_fast);
  1256. mergeStats(stats, cstats, 1);
  1257. }
  1258. toXML(stats, reply);
  1259. return true;
  1260. }
  1261. }
  1262. return false;
  1263. }
  1264. void getActivityMetrics(StringBuffer &reply) const
  1265. {
  1266. CriticalBlock b2(updateCrit);
  1267. serverManager->getActivityMetrics(reply);
  1268. for (unsigned channel = 0; channel < numChannels; channel++)
  1269. {
  1270. if (slaveManagers->item(channel))
  1271. {
  1272. slaveManagers->item(channel)->getActivityMetrics(reply);
  1273. }
  1274. }
  1275. }
  1276. void getAllQueryInfo(StringBuffer &reply, bool full, const IRoxieContextLogger &logctx) const
  1277. {
  1278. CriticalBlock b2(updateCrit);
  1279. serverManager->getAllQueryInfo(reply, full, slaveManagers, logctx);
  1280. }
  1281. const char *queryQuerySetName()
  1282. {
  1283. return querySet;
  1284. }
  1285. protected:
  1286. void reloadQueryManagers(CRoxieSlaveQuerySetManagerSet *newSlaveManagers, IRoxieQuerySetManager *newServerManager, hash64_t newHash)
  1287. {
  1288. Owned<CRoxieSlaveQuerySetManagerSet> oldSlaveManagers;
  1289. Owned<IRoxieQuerySetManager> oldServerManager;
  1290. {
  1291. // Atomically, replace the existing query managers with the new ones
  1292. CriticalBlock b2(updateCrit);
  1293. oldSlaveManagers.setown(slaveManagers.getClear()); // so that the release happens outside the critblock
  1294. oldServerManager.setown(serverManager.getClear()); // so that the release happens outside the critblock
  1295. slaveManagers.setown(newSlaveManagers);
  1296. serverManager.setown(newServerManager);
  1297. queryHash = newHash;
  1298. }
  1299. if (slaveQueryReleaseDelaySeconds)
  1300. delayedReleaser->delayedRelease(oldSlaveManagers.getClear(), slaveQueryReleaseDelaySeconds);
  1301. }
  1302. mutable CriticalSection updateCrit; // protects updates of slaveManagers and serverManager
  1303. Owned<CRoxieSlaveQuerySetManagerSet> slaveManagers;
  1304. Owned<IRoxieQuerySetManager> serverManager;
  1305. Owned<const IRoxiePackageMap> packages;
  1306. unsigned numChannels;
  1307. hash64_t queryHash;
  1308. hash64_t xmlHash;
  1309. StringAttr querySet;
  1310. };
  1311. /**
  1312. * class CRoxieDaliQueryPackageManager - manages queries specified in QuerySets, for a given package set.
  1313. *
  1314. * If the QuerySet is modified, it will be reloaded.
  1315. * There is one CRoxieDaliQueryPackageManager for every PackageSet - only one will be active for query lookup
  1316. * at a given time (the one associated with the active PackageSet).
  1317. *
  1318. * To deploy new data, typically we will load a new PackageSet, make it active, then release the old one
  1319. * A packageSet is not modified while loaded, to avoid timing issues between slaves and server.
  1320. *
  1321. * We need to be able to spot a change (in dali) to the active package indicator (and switch the active CRoxieDaliQueryPackageManager)
  1322. * We need to be able to spot a change (in dali) that adds a new PackageSet
  1323. * 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
  1324. * encourage changing in the right sequence). In which case a change to the package info in dali means reload all global package
  1325. * managers (and then discard the old ones). Hash-based queries means everything should work ok.
  1326. * -> If the active ptr changes, just change what is active
  1327. * If any change to any package set, reload all globalResourceManagers and discard prior
  1328. * The query caching code should ensure that it is quick enough to do so
  1329. *
  1330. **/
  1331. class CRoxieDaliQueryPackageManager : public CRoxieQueryPackageManager, implements ISDSSubscription
  1332. {
  1333. Owned<IRoxieDaliHelper> daliHelper;
  1334. Owned<IDaliPackageWatcher> notifier;
  1335. public:
  1336. IMPLEMENT_IINTERFACE;
  1337. CRoxieDaliQueryPackageManager(unsigned _numChannels, const IRoxiePackageMap *_packages, const char *_querySet, hash64_t _xmlHash)
  1338. : CRoxieQueryPackageManager(_numChannels, _querySet, _packages, _xmlHash)
  1339. {
  1340. daliHelper.setown(connectToDali());
  1341. }
  1342. ~CRoxieDaliQueryPackageManager()
  1343. {
  1344. if (notifier)
  1345. daliHelper->releaseSubscription(notifier);
  1346. }
  1347. virtual void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  1348. {
  1349. reload(false);
  1350. daliHelper->commitCache();
  1351. }
  1352. virtual void load(bool forceReload)
  1353. {
  1354. notifier.setown(daliHelper->getQuerySetSubscription(querySet, this));
  1355. reload(forceReload);
  1356. }
  1357. virtual void reload(bool forceRetry)
  1358. {
  1359. hash64_t newHash = numChannels;
  1360. Owned<IPropertyTree> newQuerySet = daliHelper->getQuerySet(querySet);
  1361. Owned<CRoxieSlaveQuerySetManagerSet> newSlaveManagers = new CRoxieSlaveQuerySetManagerSet(numChannels, querySet);
  1362. Owned<IRoxieQuerySetManager> newServerManager = createServerManager(querySet);
  1363. newServerManager->load(newQuerySet, *packages, newHash, forceRetry);
  1364. newSlaveManagers->load(newQuerySet, *packages, newHash, forceRetry);
  1365. reloadQueryManagers(newSlaveManagers.getClear(), newServerManager.getClear(), newHash);
  1366. clearKeyStoreCache(false); // Allows us to fully release files we no longer need because of unloaded queries
  1367. }
  1368. };
  1369. class CStandaloneQueryPackageManager : public CRoxieQueryPackageManager
  1370. {
  1371. Owned<IPropertyTree> standaloneDll;
  1372. public:
  1373. CStandaloneQueryPackageManager(unsigned _numChannels, const char *_querySet, const IRoxiePackageMap *_packages, IPropertyTree *_standaloneDll)
  1374. : CRoxieQueryPackageManager(_numChannels, _querySet, _packages, 0), standaloneDll(_standaloneDll)
  1375. {
  1376. assertex(standaloneDll);
  1377. }
  1378. ~CStandaloneQueryPackageManager()
  1379. {
  1380. }
  1381. virtual void load(bool forceReload)
  1382. {
  1383. hash64_t newHash = numChannels;
  1384. Owned<IPropertyTree> newQuerySet = createPTree("QuerySet", ipt_lowmem);
  1385. newQuerySet->setProp("@name", "_standalone");
  1386. newQuerySet->addPropTree("Query", standaloneDll.getLink());
  1387. Owned<CRoxieSlaveQuerySetManagerSet> newSlaveManagers = new CRoxieSlaveQuerySetManagerSet(numChannels, querySet);
  1388. Owned<IRoxieQuerySetManager> newServerManager = createServerManager(querySet);
  1389. newServerManager->load(newQuerySet, *packages, newHash, forceReload);
  1390. newSlaveManagers->load(newQuerySet, *packages, newHash, forceReload);
  1391. reloadQueryManagers(newSlaveManagers.getClear(), newServerManager.getClear(), newHash);
  1392. }
  1393. };
  1394. static SpinLock roxieDebugSessionManagerLock;
  1395. extern IRoxieDebugSessionManager &queryRoxieDebugSessionManager()
  1396. {
  1397. SpinBlock b(roxieDebugSessionManagerLock);
  1398. if (!debugSessionManager)
  1399. debugSessionManager = new CRoxieDebugSessionManager();
  1400. return *debugSessionManager;
  1401. }
  1402. class CRoxiePackageSetWatcher : public CInterface
  1403. {
  1404. public:
  1405. CRoxiePackageSetWatcher(IRoxieDaliHelper *_daliHelper, unsigned numChannels, CRoxiePackageSetWatcher *oldPackages, bool forceReload)
  1406. : stateHash(0), daliHelper(_daliHelper)
  1407. {
  1408. ForEachItemIn(idx, allQuerySetNames)
  1409. {
  1410. createQueryPackageManagers(numChannels, allQuerySetNames.item(idx), oldPackages, forceReload);
  1411. }
  1412. }
  1413. CRoxiePackageSetWatcher(IRoxieDaliHelper *_daliHelper, const IQueryDll *standAloneDll, unsigned numChannels, const char *querySet, bool forceReload)
  1414. : stateHash(0), daliHelper(_daliHelper)
  1415. {
  1416. Owned<IPropertyTree> standAloneDllTree;
  1417. standAloneDllTree.setown(createPTree("Query", ipt_lowmem));
  1418. standAloneDllTree->setProp("@id", "roxie");
  1419. standAloneDllTree->setProp("@dll", standAloneDll->queryDll()->queryName());
  1420. Owned<CRoxieQueryPackageManager> qpm = new CStandaloneQueryPackageManager(numChannels, querySet, LINK(&queryEmptyRoxiePackageMap()), standAloneDllTree.getClear());
  1421. qpm->load(forceReload);
  1422. stateHash = rtlHash64Data(sizeof(stateHash), &stateHash, qpm->getHash());
  1423. allQueryPackages.append(*qpm.getClear());
  1424. }
  1425. IQueryFactory *lookupLibrary(const char *libraryName, unsigned expectedInterfaceHash, const IRoxieContextLogger &logctx) const
  1426. {
  1427. ForEachItemIn(idx, allQueryPackages)
  1428. {
  1429. Owned<IRoxieQuerySetManager> sm = allQueryPackages.item(idx).getRoxieServerManager();
  1430. if (sm->isActive())
  1431. {
  1432. Owned<IQueryFactory> library = sm->getQuery(libraryName, NULL, logctx);
  1433. if (library)
  1434. {
  1435. if (library->isQueryLibrary())
  1436. {
  1437. unsigned foundInterfaceHash = library->getQueryLibraryInterfaceHash();
  1438. if (!foundInterfaceHash || (foundInterfaceHash == expectedInterfaceHash))
  1439. return library.getClear();
  1440. else
  1441. throw MakeStringException(ROXIE_LIBRARY_ERROR, "The library interface found in %s is not compatible (found %d, expected %d)", libraryName, foundInterfaceHash, expectedInterfaceHash);
  1442. }
  1443. else
  1444. throw MakeStringException(ROXIE_LIBRARY_ERROR, "The query resolved by %s is not a library", libraryName);
  1445. }
  1446. }
  1447. }
  1448. throw MakeStringException(ROXIE_LIBRARY_ERROR, "No library available for %s", libraryName);
  1449. }
  1450. IQueryFactory *getQuery(const char *id, StringBuffer *querySet, IArrayOf<IQueryFactory> *slaveQueries, const IRoxieContextLogger &logctx) const
  1451. {
  1452. if (querySet && querySet->length() && !allQuerySetNames.contains(querySet->str()))
  1453. throw MakeStringException(ROXIE_INVALID_TARGET, "Target %s not found", querySet->str());
  1454. ForEachItemIn(idx, allQueryPackages)
  1455. {
  1456. Owned<IRoxieQuerySetManager> sm = allQueryPackages.item(idx).getRoxieServerManager();
  1457. if (sm->isActive())
  1458. {
  1459. IQueryFactory *query = sm->getQuery(id, querySet, logctx);
  1460. if (query)
  1461. {
  1462. if (slaveQueries)
  1463. {
  1464. Owned<IRoxieQuerySetManagerSet> slaveManagers = allQueryPackages.item(idx).getRoxieSlaveManagers();
  1465. slaveManagers->getQueries(id, *slaveQueries, logctx);
  1466. }
  1467. return query;
  1468. }
  1469. }
  1470. }
  1471. return NULL;
  1472. }
  1473. int getActivePackageCount() const
  1474. {
  1475. int count = 0;
  1476. ForEachItemIn(idx, allQueryPackages)
  1477. {
  1478. Owned<IRoxieQuerySetManager> sm = allQueryPackages.item(idx).getRoxieServerManager();
  1479. if (sm->isActive())
  1480. count++;
  1481. }
  1482. return count;
  1483. }
  1484. inline hash64_t queryHash() const
  1485. {
  1486. return stateHash;
  1487. }
  1488. void getAllQueryInfo(StringBuffer &reply, bool full, const IRoxieContextLogger &logctx) const
  1489. {
  1490. ForEachItemIn(idx, allQueryPackages)
  1491. {
  1492. Owned<IRoxieQuerySetManager> serverManager = allQueryPackages.item(idx).getRoxieServerManager();
  1493. if (serverManager->isActive())
  1494. {
  1495. Owned<IRoxieQuerySetManagerSet> slaveManagers = allQueryPackages.item(idx).getRoxieSlaveManagers();
  1496. serverManager->getAllQueryInfo(reply, full, slaveManagers, logctx);
  1497. }
  1498. }
  1499. }
  1500. void getActivityMetrics(StringBuffer &reply) const
  1501. {
  1502. ForEachItemIn(idx, allQueryPackages)
  1503. {
  1504. CRoxieQueryPackageManager &qpm = allQueryPackages.item(idx);
  1505. qpm.getActivityMetrics(reply);
  1506. }
  1507. }
  1508. void getInfo(StringBuffer &reply, const IRoxieContextLogger &logctx) const
  1509. {
  1510. reply.append("<PackageSets>\n");
  1511. ForEachItemIn(idx, allQueryPackages)
  1512. {
  1513. allQueryPackages.item(idx).getInfo(reply, logctx);
  1514. }
  1515. reply.append("</PackageSets>\n");
  1516. }
  1517. void getStats(StringBuffer &reply, const char *id, const char *action, const char *graphName, const IRoxieContextLogger &logctx) const
  1518. {
  1519. ForEachItemIn(idx, allQueryPackages)
  1520. {
  1521. if (allQueryPackages.item(idx).getStats(id, action, graphName, reply, logctx))
  1522. return;
  1523. }
  1524. }
  1525. void resetStats(const char *target, const char *id, const IRoxieContextLogger &logctx) const
  1526. {
  1527. bool matched = false;
  1528. ForEachItemIn(idx, allQueryPackages)
  1529. {
  1530. CRoxieQueryPackageManager &queryPackage = allQueryPackages.item(idx);
  1531. if (target && *target && !strieq(queryPackage.queryQuerySetName(), target))
  1532. continue;
  1533. if (allQueryPackages.item(idx).resetStats(id, logctx))
  1534. {
  1535. if (target && *target)
  1536. return;
  1537. matched = true;
  1538. }
  1539. }
  1540. if (!matched && id && *id)
  1541. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", id);
  1542. }
  1543. private:
  1544. CIArrayOf<CRoxieQueryPackageManager> allQueryPackages;
  1545. Linked<IRoxieDaliHelper> daliHelper;
  1546. hash64_t stateHash;
  1547. CRoxieQueryPackageManager *getPackageManager(const char *id)
  1548. {
  1549. ForEachItemIn(idx, allQueryPackages)
  1550. {
  1551. CRoxieQueryPackageManager &pm = allQueryPackages.item(idx);
  1552. if (strcmp(pm.queryPackageId(), id)==0)
  1553. return LINK(&pm);
  1554. }
  1555. return NULL;
  1556. }
  1557. void createQueryPackageManager(unsigned numChannels, const IRoxiePackageMap *packageMap, const char *querySet, hash64_t xmlHash, bool forceReload)
  1558. {
  1559. Owned<CRoxieQueryPackageManager> qpm = new CRoxieDaliQueryPackageManager(numChannels, packageMap, querySet, xmlHash);
  1560. qpm->load(forceReload);
  1561. stateHash = rtlHash64Data(sizeof(stateHash), &stateHash, qpm->getHash());
  1562. allQueryPackages.append(*qpm.getClear());
  1563. }
  1564. void createQueryPackageManagers(unsigned numChannels, const char *querySet, CRoxiePackageSetWatcher *oldPackages, bool forceReload)
  1565. {
  1566. int loadedPackages = 0;
  1567. int activePackages = 0;
  1568. Owned<IPropertyTree> packageTree = daliHelper->getPackageSets();
  1569. Owned<IPropertyTreeIterator> packageSets = packageTree->getElements("PackageSet");
  1570. ForEach(*packageSets)
  1571. {
  1572. IPropertyTree &ps = packageSets->query();
  1573. const char *packageSetSpec = ps.queryProp("@process");
  1574. if (!packageSetSpec || WildMatch(roxieName, packageSetSpec, false))
  1575. {
  1576. if (traceLevel)
  1577. {
  1578. DBGLOG("Loading package set %s, process spec %s", ps.queryProp("@id") ? ps.queryProp("@id") : "<no-id>",
  1579. packageSetSpec ? packageSetSpec : "<*>");
  1580. }
  1581. Owned<IPropertyTreeIterator> packageMaps = ps.getElements("PackageMap");
  1582. ForEach(*packageMaps)
  1583. {
  1584. IPropertyTree &pm = packageMaps->query();
  1585. const char *packageMapId = pm.queryProp("@id");
  1586. const char *packageMapFilter = pm.queryProp("@querySet");
  1587. if (packageMapId && *packageMapId && (!packageMapFilter || WildMatch(querySet, packageMapFilter, false)))
  1588. {
  1589. try
  1590. {
  1591. bool isActive = pm.getPropBool("@active", true);
  1592. Owned<IPropertyTree> xml = daliHelper->getPackageMap(packageMapId);
  1593. hash64_t xmlHash = hashXML(xml);
  1594. Owned<CRoxieQueryPackageManager> oldPackageManager;
  1595. if (oldPackages)
  1596. {
  1597. oldPackageManager.setown(oldPackages->getPackageManager(packageMapId));
  1598. }
  1599. if (oldPackageManager && oldPackageManager->matches(xmlHash, isActive))
  1600. {
  1601. if (traceLevel)
  1602. DBGLOG("Package map %s, active %s already loaded", packageMapId, isActive ? "true" : "false");
  1603. stateHash = rtlHash64Data(sizeof(stateHash), &stateHash, oldPackageManager->getHash());
  1604. allQueryPackages.append(*oldPackageManager.getClear());
  1605. }
  1606. else
  1607. {
  1608. if (traceLevel)
  1609. DBGLOG("Loading package map %s, active %s", packageMapId, isActive ? "true" : "false");
  1610. Owned<CRoxiePackageMap> packageMap = new CRoxiePackageMap(packageMapId, packageMapFilter, isActive);
  1611. packageMap->load(xml);
  1612. createQueryPackageManager(numChannels, packageMap.getLink(), querySet, xmlHash, forceReload);
  1613. }
  1614. loadedPackages++;
  1615. if (isActive)
  1616. activePackages++;
  1617. }
  1618. catch (IException *E)
  1619. {
  1620. StringBuffer msg;
  1621. msg.appendf("Failed to load package map %s", packageMapId);
  1622. EXCLOG(E, msg.str());
  1623. E->Release();
  1624. }
  1625. }
  1626. }
  1627. }
  1628. }
  1629. if (!loadedPackages)
  1630. {
  1631. if (traceLevel)
  1632. DBGLOG("Loading empty package for QuerySet %s", querySet);
  1633. createQueryPackageManager(numChannels, LINK(&queryEmptyRoxiePackageMap()), querySet, 0, forceReload);
  1634. }
  1635. else if (traceLevel)
  1636. DBGLOG("Loaded %d packages (%d active)", loadedPackages, activePackages);
  1637. }
  1638. };
  1639. class CRoxiePackageSetManager : implements IRoxieQueryPackageManagerSet, implements ISDSSubscription, public CInterface
  1640. {
  1641. Owned<IDaliPackageWatcher> pSetsNotifier;
  1642. Owned<IDaliPackageWatcher> pMapsNotifier;
  1643. public:
  1644. IMPLEMENT_IINTERFACE;
  1645. CRoxiePackageSetManager(const IQueryDll *_standAloneDll) :
  1646. autoReloadThread(*this), standAloneDll(_standAloneDll)
  1647. {
  1648. if (topology && topology->getPropBool("@lockDali", false))
  1649. daliHelper.setown(connectToDali());
  1650. else
  1651. daliHelper.setown(connectToDali(ROXIE_DALI_CONNECT_TIMEOUT));
  1652. atomic_set(&autoPending, 0);
  1653. atomic_set(&autoSignalsPending, 0);
  1654. forcePending = false;
  1655. pSetsNotifier.setown(daliHelper->getPackageSetsSubscription(this));
  1656. pMapsNotifier.setown(daliHelper->getPackageMapsSubscription(this));
  1657. }
  1658. ~CRoxiePackageSetManager()
  1659. {
  1660. autoReloadThread.stop();
  1661. autoReloadThread.join();
  1662. }
  1663. void requestReload(bool signal, bool force)
  1664. {
  1665. if (force)
  1666. forcePending = true;
  1667. if (signal)
  1668. atomic_inc(&autoSignalsPending);
  1669. atomic_inc(&autoPending);
  1670. autoReloadTrigger.signal();
  1671. if (signal)
  1672. autoReloadComplete.wait();
  1673. }
  1674. virtual void load()
  1675. {
  1676. try
  1677. {
  1678. reload(false);
  1679. daliHelper->commitCache();
  1680. controlSem.signal();
  1681. autoReloadThread.start(); // Don't want to overlap auto-reloads with the initial load
  1682. }
  1683. catch(IException *E)
  1684. {
  1685. EXCLOG(E, "No configuration could be loaded");
  1686. controlSem.interrupt();
  1687. throw; // Roxie will refuse to start up if configuration invalid
  1688. }
  1689. }
  1690. virtual void doControlMessage(IPropertyTree *xml, StringBuffer &reply, const IRoxieContextLogger &logctx)
  1691. {
  1692. if (!controlSem.wait(20000))
  1693. throw MakeStringException(ROXIE_TIMEOUT, "Timed out waiting for current control query to complete");
  1694. try
  1695. {
  1696. _doControlMessage(xml, reply, logctx);
  1697. reply.append(" <Status>ok</Status>\n");
  1698. }
  1699. catch(IException *E)
  1700. {
  1701. controlSem.signal();
  1702. EXCLOG(E);
  1703. throw;
  1704. }
  1705. catch(...)
  1706. {
  1707. controlSem.signal();
  1708. throw;
  1709. }
  1710. controlSem.signal();
  1711. }
  1712. virtual IQueryFactory *lookupLibrary(const char *libraryName, unsigned expectedInterfaceHash, const IRoxieContextLogger &logctx) const
  1713. {
  1714. ReadLockBlock b(packageCrit);
  1715. return allQueryPackages->lookupLibrary(libraryName, expectedInterfaceHash, logctx);
  1716. }
  1717. virtual IQueryFactory *getQuery(const char *id, StringBuffer *querySet, IArrayOf<IQueryFactory> *slaveQueries, const IRoxieContextLogger &logctx) const
  1718. {
  1719. ReadLockBlock b(packageCrit);
  1720. return allQueryPackages->getQuery(id, querySet, slaveQueries, logctx);
  1721. }
  1722. virtual int getActivePackageCount() const
  1723. {
  1724. ReadLockBlock b(packageCrit);
  1725. return allQueryPackages->getActivePackageCount();
  1726. }
  1727. virtual void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  1728. {
  1729. requestReload(false, false);
  1730. }
  1731. private:
  1732. Owned<const IQueryDll> standAloneDll;
  1733. Owned<CRoxieDebugSessionManager> debugSessionManager;
  1734. Owned<IRoxieDaliHelper> daliHelper;
  1735. mutable ReadWriteLock packageCrit;
  1736. InterruptableSemaphore controlSem;
  1737. Owned<CRoxiePackageSetWatcher> allQueryPackages;
  1738. Semaphore autoReloadTrigger;
  1739. Semaphore autoReloadComplete;
  1740. atomic_t autoSignalsPending;
  1741. atomic_t autoPending;
  1742. bool forcePending;
  1743. class AutoReloadThread : public Thread
  1744. {
  1745. bool closing;
  1746. CRoxiePackageSetManager &owner;
  1747. public:
  1748. AutoReloadThread(CRoxiePackageSetManager &_owner)
  1749. : owner(_owner), Thread("AutoReloadThread")
  1750. {
  1751. closing = false;
  1752. }
  1753. virtual int run()
  1754. {
  1755. if (traceLevel)
  1756. DBGLOG("AutoReloadThread %p starting", this);
  1757. while (!closing)
  1758. {
  1759. owner.autoReloadTrigger.wait();
  1760. if (closing)
  1761. break;
  1762. unsigned signalsPending = atomic_read(&owner.autoSignalsPending);
  1763. if (!signalsPending)
  1764. Sleep(500); // Typically notifications come in clumps - this avoids reloading too often
  1765. if (atomic_read(&owner.autoPending))
  1766. {
  1767. atomic_set(&owner.autoPending, 0);
  1768. try
  1769. {
  1770. owner.reload(owner.forcePending);
  1771. }
  1772. catch (IException *E)
  1773. {
  1774. if (!closing)
  1775. EXCLOG(MCoperatorError, E, "AutoReloadThread: ");
  1776. E->Release();
  1777. }
  1778. catch (...)
  1779. {
  1780. DBGLOG("Unknown exception in AutoReloadThread");
  1781. }
  1782. owner.forcePending = false;
  1783. }
  1784. if (signalsPending)
  1785. {
  1786. atomic_dec(&owner.autoSignalsPending);
  1787. owner.autoReloadComplete.signal();
  1788. }
  1789. }
  1790. if (traceLevel)
  1791. DBGLOG("AutoReloadThread %p exiting", this);
  1792. return 0;
  1793. }
  1794. void stop()
  1795. {
  1796. closing = true;
  1797. owner.autoReloadTrigger.signal();
  1798. }
  1799. } autoReloadThread;
  1800. void reload(bool forceRetry)
  1801. {
  1802. clearDaliMisses();
  1803. // We want to kill the old packages, but not until we have created the new ones
  1804. // So that the query/dll caching will work for anything that is not affected by the changes
  1805. Owned<CRoxiePackageSetWatcher> newPackages;
  1806. if (standAloneDll)
  1807. newPackages.setown(new CRoxiePackageSetWatcher(daliHelper, standAloneDll, numChannels, "roxie", forceRetry));
  1808. else
  1809. {
  1810. Owned<CRoxiePackageSetWatcher> currentPackages;
  1811. {
  1812. ReadLockBlock b(packageCrit);
  1813. currentPackages.setown(allQueryPackages.getLink());
  1814. }
  1815. newPackages.setown(new CRoxiePackageSetWatcher(daliHelper, numChannels, currentPackages, forceRetry));
  1816. }
  1817. // Hold the lock for as little time as we can
  1818. // Note that we must NOT hold the lock during the delete of the old object - or we deadlock.
  1819. // Hence the slightly convoluted code below
  1820. Owned<CRoxiePackageSetWatcher> oldPackages; // NB Destroyed outside the WriteLockBlock
  1821. {
  1822. WriteLockBlock b(packageCrit);
  1823. oldPackages.setown(allQueryPackages.getLink()); // Ensure we don't delete the old packages until after we have loaded the new
  1824. allQueryPackages.setown(newPackages.getClear());
  1825. }
  1826. daliHelper->commitCache();
  1827. }
  1828. // Common code used by control:queries and control:getQueryXrefInfo
  1829. void getQueryInfo(IPropertyTree *control, StringBuffer &reply, bool full, const IRoxieContextLogger &logctx) const
  1830. {
  1831. Owned<IPropertyTreeIterator> ids = control->getElements("Query");
  1832. reply.append("<Queries reporting='1'>\n");
  1833. if (ids->first())
  1834. {
  1835. ForEach(*ids)
  1836. {
  1837. const char *id = ids->query().queryProp("@id");
  1838. if (id)
  1839. {
  1840. IArrayOf<IQueryFactory> slaveQueries;
  1841. Owned<IQueryFactory> query = getQuery(id, NULL, &slaveQueries, logctx);
  1842. if (query)
  1843. query->getQueryInfo(reply, full, &slaveQueries, logctx);
  1844. else
  1845. reply.appendf(" <Query id=\"%s\" error=\"Query not found\"/>\n", id);
  1846. }
  1847. }
  1848. }
  1849. else
  1850. {
  1851. ReadLockBlock readBlock(packageCrit);
  1852. allQueryPackages->getAllQueryInfo(reply, full, logctx);
  1853. }
  1854. reply.append("</Queries>\n");
  1855. }
  1856. void _doControlMessage(IPropertyTree *control, StringBuffer &reply, const IRoxieContextLogger &logctx)
  1857. {
  1858. const char *queryName = control->queryName();
  1859. logctx.CTXLOG("doControlMessage - %s", queryName);
  1860. assertex(memicmp(queryName, "control:", 8) == 0);
  1861. bool unknown = false;
  1862. switch (_toupper(queryName[8]))
  1863. {
  1864. case 'A':
  1865. if (stricmp(queryName, "control:aclupdate") == 0)
  1866. {
  1867. // MORE - do nothing for now - possibly needed in the future - leave this so no exception is thrown
  1868. }
  1869. else if (stricmp(queryName, "control:activeQueries")==0)
  1870. {
  1871. if (debugSessionManager)
  1872. debugSessionManager->getActiveQueries(reply);
  1873. }
  1874. else if (stricmp(queryName, "control:activitymetrics")==0)
  1875. {
  1876. ReadLockBlock readBlock(packageCrit);
  1877. allQueryPackages->getActivityMetrics(reply);
  1878. }
  1879. else if (stricmp(queryName, "control:alive")==0)
  1880. {
  1881. reply.appendf("<Alive restarts='%d'/>", restarts);
  1882. }
  1883. else
  1884. unknown = true;
  1885. break;
  1886. case 'B':
  1887. if (stricmp(queryName, "control:blobCacheMem")==0)
  1888. {
  1889. blobCacheMB = control->getPropInt("@val", 0);
  1890. topology->setPropInt("@blobCacheMem", blobCacheMB);
  1891. setBlobCacheMem(blobCacheMB * 0x100000);
  1892. }
  1893. else
  1894. unknown = true;
  1895. break;
  1896. case 'C':
  1897. if (stricmp(queryName, "control:checkCompleted")==0)
  1898. {
  1899. checkCompleted = control->getPropBool("@val", true);
  1900. topology->setPropBool("@checkCompleted", checkCompleted );
  1901. }
  1902. else if (stricmp(queryName, "control:checkingHeap")==0)
  1903. {
  1904. defaultCheckingHeap = control->getPropBool("@val", true);
  1905. topology->setPropInt("@checkingHeap", defaultCheckingHeap);
  1906. }
  1907. else if (stricmp(queryName, "control:clearIndexCache")==0)
  1908. {
  1909. bool clearAll = control->getPropBool("@clearAll", true);
  1910. clearKeyStoreCache(clearAll);
  1911. }
  1912. else if (stricmp(queryName, "control:closedown")==0)
  1913. {
  1914. closedown();
  1915. }
  1916. else if (stricmp(queryName, "control:closeExpired")==0)
  1917. {
  1918. queryFileCache().closeExpired(false);
  1919. queryFileCache().closeExpired(true);
  1920. }
  1921. else if (stricmp(queryName, "control:closeLocalExpired")==0)
  1922. {
  1923. queryFileCache().closeExpired(false);
  1924. }
  1925. else if (stricmp(queryName, "control:closeRemoteExpired")==0)
  1926. {
  1927. queryFileCache().closeExpired(true);
  1928. }
  1929. else
  1930. unknown = true;
  1931. break;
  1932. case 'D':
  1933. if (stricmp(queryName, "control:dafilesrvLookupTimeout")==0)
  1934. {
  1935. dafilesrvLookupTimeout = control->getPropInt("@val", 10000);
  1936. topology->setPropInt("@dafilesrvLookupTimeout", dafilesrvLookupTimeout);
  1937. setRemoteFileTimeouts(dafilesrvLookupTimeout, 0);
  1938. }
  1939. else if (stricmp(queryName, "control:defaultConcatPreload")==0)
  1940. {
  1941. defaultConcatPreload = control->getPropInt("@val", 0);
  1942. topology->setPropInt("@defaultConcatPreload", defaultConcatPreload);
  1943. }
  1944. else if (stricmp(queryName, "control:defaultFetchPreload")==0)
  1945. {
  1946. defaultFetchPreload = control->getPropInt("@val", 0);
  1947. topology->setPropInt("@defaultFetchPreload", defaultFetchPreload);
  1948. }
  1949. else if (stricmp(queryName, "control:defaultFullKeyedJoinPreload")==0)
  1950. {
  1951. defaultFullKeyedJoinPreload = control->getPropInt("@val", 0);
  1952. topology->setPropInt("@defaultFullKeyedJoinPreload", defaultFullKeyedJoinPreload);
  1953. }
  1954. else if (stricmp(queryName, "control:defaultHighPriorityTimeLimit")==0)
  1955. {
  1956. defaultTimeLimit[1] = control->getPropInt("@limit", 0);
  1957. topology->setPropInt("@defaultHighPriorityTimeLimit", defaultTimeLimit[1]);
  1958. }
  1959. else if (stricmp(queryName, "control:defaultHighPriorityTimeWarning")==0)
  1960. {
  1961. defaultWarnTimeLimit[1] = control->getPropInt("@limit", 0);
  1962. topology->setPropInt("@defaultHighPriorityTimeWarning", defaultWarnTimeLimit[1]);
  1963. }
  1964. else if (stricmp(queryName, "control:defaultKeyedJoinPreload")==0)
  1965. {
  1966. defaultKeyedJoinPreload = control->getPropInt("@val", 0);
  1967. topology->setPropInt("@defaultKeyedJoinPreload", defaultKeyedJoinPreload);
  1968. }
  1969. else if (stricmp(queryName, "control:defaultLowPriorityTimeLimit")==0)
  1970. {
  1971. defaultTimeLimit[0] = control->getPropInt("@limit", 0);
  1972. topology->setPropInt("@defaultLowPriorityTimeLimit", defaultTimeLimit[0]);
  1973. }
  1974. else if (stricmp(queryName, "control:defaultLowPriorityTimeWarning")==0)
  1975. {
  1976. defaultWarnTimeLimit[0] = control->getPropInt("@limit", 0);
  1977. topology->setPropInt("@defaultLowPriorityTimeWarning", defaultWarnTimeLimit[0]);
  1978. }
  1979. else if (stricmp(queryName, "control:defaultParallelJoinPreload")==0)
  1980. {
  1981. defaultParallelJoinPreload = control->getPropInt("@val", 0);
  1982. topology->setPropInt("@defaultParallelJoinPreload", defaultParallelJoinPreload);
  1983. }
  1984. else if (stricmp(queryName, "control:defaultSLAPriorityTimeLimit")==0)
  1985. {
  1986. defaultTimeLimit[2] = control->getPropInt("@limit", 0);
  1987. topology->setPropInt("@defaultSLAPriorityTimeLimit", defaultTimeLimit[2]);
  1988. }
  1989. else if (stricmp(queryName, "control:defaultSLAPriorityTimeWarning")==0)
  1990. {
  1991. defaultWarnTimeLimit[2] = control->getPropInt("@limit", 0);
  1992. topology->setPropInt("@defaultSLAPriorityTimeWarning", defaultWarnTimeLimit[2]);
  1993. }
  1994. else if (stricmp(queryName, "control:deleteUnneededPhysicalFiles")==0)
  1995. {
  1996. UNIMPLEMENTED;
  1997. }
  1998. else if (stricmp(queryName, "control:deleteUnneededQueryCacheFiles")==0)
  1999. {
  2000. UNIMPLEMENTED;
  2001. }
  2002. else if (stricmp(queryName, "control:doIbytiDelay")==0)
  2003. { // WARNING: use with extra care only during inactivity on system
  2004. doIbytiDelay = control->getPropBool("@val", true);
  2005. topology->setPropBool("@doIbytiDelay", doIbytiDelay);
  2006. }
  2007. else
  2008. unknown = true;
  2009. break;
  2010. case 'E':
  2011. if (stricmp(queryName, "control:enableKeyDiff")==0)
  2012. {
  2013. enableKeyDiff = control->getPropBool("@val", true);
  2014. topology->setPropBool("@enableKeyDiff", enableKeyDiff);
  2015. }
  2016. else
  2017. unknown = true;
  2018. break;
  2019. case 'F':
  2020. if (stricmp(queryName, "control:fieldTranslationEnabled")==0)
  2021. {
  2022. const char *val = control->queryProp("@val");
  2023. if (val)
  2024. fieldTranslationEnabled = getTranslationMode(val);
  2025. else
  2026. fieldTranslationEnabled = RecordTranslationMode::Payload;
  2027. val = getTranslationModeText(fieldTranslationEnabled);
  2028. topology->setProp("@fieldTranslationEnabled", val);
  2029. }
  2030. else if (stricmp(queryName, "control:flushJHtreeCacheOnOOM")==0)
  2031. {
  2032. flushJHtreeCacheOnOOM = control->getPropBool("@val", true);
  2033. topology->setPropInt("@flushJHtreeCacheOnOOM", flushJHtreeCacheOnOOM);
  2034. }
  2035. else
  2036. unknown = true;
  2037. break;
  2038. case 'G':
  2039. if (stricmp(queryName, "control:getACLinfo") == 0)
  2040. {
  2041. // MORE - do nothing for now - possibly needed in the future - leave this so no exception is thrown
  2042. }
  2043. else if (stricmp(queryName, "control:getClusterName")==0)
  2044. {
  2045. reply.appendf("<clusterName id='%s'/>", roxieName.str());
  2046. }
  2047. else if (stricmp(queryName, "control:getQueryXrefInfo")==0)
  2048. {
  2049. getQueryInfo(control, reply, true, logctx);
  2050. }
  2051. else if (stricmp(queryName, "control:getQuery")==0)
  2052. {
  2053. const char* id = control->queryProp("@id");
  2054. if (!id)
  2055. throw MakeStringException(ROXIE_MISSING_PARAMS, "No query name specified");
  2056. Owned<IQueryFactory> q = getQuery(id, NULL, NULL, logctx);
  2057. if (q)
  2058. {
  2059. Owned<IPropertyTree> tempTree = q->cloneQueryXGMML();
  2060. tempTree->setProp("@roxieName", roxieName.str());
  2061. toXML(tempTree, reply);
  2062. }
  2063. else
  2064. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", id);
  2065. }
  2066. else if (stricmp(queryName, "control:getQueryWarningTime")==0)
  2067. {
  2068. const char *id = control->queryProp("Query/@id");
  2069. if (!id)
  2070. badFormat();
  2071. Owned<IQueryFactory> f = getQuery(id, NULL, NULL, logctx);
  2072. if (f)
  2073. {
  2074. unsigned warnLimit = f->queryOptions().warnTimeLimit;
  2075. reply.appendf("<QueryTimeWarning val='%d'/>", warnLimit);
  2076. }
  2077. }
  2078. else if (stricmp(queryName, "control:getBuildVersion")==0)
  2079. {
  2080. reply.appendf("<version id='%s'/>", BUILD_TAG);
  2081. }
  2082. else
  2083. unknown = true;
  2084. break;
  2085. case 'I':
  2086. if (stricmp(queryName, "control:indexmetrics")==0)
  2087. {
  2088. getIndexMetrics(reply);
  2089. }
  2090. else if (stricmp(queryName, "control:inMemoryKeysEnabled")==0)
  2091. {
  2092. inMemoryKeysEnabled = control->getPropBool("@val", true);
  2093. topology->setPropBool("@inMemoryKeysEnabled", inMemoryKeysEnabled);
  2094. }
  2095. else
  2096. unknown = true;
  2097. break;
  2098. case 'L':
  2099. if (stricmp(queryName, "control:leafCacheMem")==0)
  2100. {
  2101. leafCacheMB = control->getPropInt("@val", 50);
  2102. topology->setPropInt("@leafCacheMem", leafCacheMB);
  2103. setLeafCacheMem(leafCacheMB * 0x100000);
  2104. }
  2105. else if (stricmp(queryName, "control:listFileOpenErrors")==0)
  2106. {
  2107. // this just creates a delta state file to remove references to Keys / Files we now longer have interest in
  2108. StringAttrMapping *mapping = queryFileCache().queryFileErrorList();
  2109. HashIterator iter(*mapping);
  2110. StringBuffer err;
  2111. for (iter.first(); iter.isValid(); iter.next())
  2112. {
  2113. IMapping &cur = iter.query();
  2114. StringAttr *item = mapping->mapToValue(&cur);
  2115. const char *filename = (const char*)cur.getKey();
  2116. const char *filetype = item->get();
  2117. reply.appendf("<file><name>%s</name><type>%s</type></file>", filename, filetype);
  2118. }
  2119. }
  2120. else if (stricmp(queryName, "control:listUnusedFiles")==0)
  2121. {
  2122. UNIMPLEMENTED;
  2123. }
  2124. else if (stricmp(queryName, "control:lockDali")==0)
  2125. {
  2126. topology->setPropBool("@lockDali", true);
  2127. if (daliHelper)
  2128. daliHelper->disconnect();
  2129. saveTopology();
  2130. }
  2131. else if (stricmp(queryName, "control:logfullqueries")==0)
  2132. {
  2133. logFullQueries = control->getPropBool("@val", true);
  2134. topology->setPropBool("@logFullQueries", logFullQueries);
  2135. }
  2136. else
  2137. unknown = true;
  2138. break;
  2139. case 'M':
  2140. if (stricmp(queryName, "control:memoryStatsInterval")==0)
  2141. {
  2142. memoryStatsInterval = (unsigned) control->getPropInt64("@val", 0);
  2143. roxiemem::setMemoryStatsInterval(memoryStatsInterval);
  2144. topology->setPropInt64("@memoryStatsInterval", memoryStatsInterval);
  2145. }
  2146. else if (stricmp(queryName, "control:memtrace")==0)
  2147. {
  2148. unsigned memTraceLevel = control->getPropInt("@level", 0);
  2149. roxiemem::setMemTraceLevel(memTraceLevel);
  2150. topology->setPropInt("@memTraceLevel", memTraceLevel);
  2151. }
  2152. else if (stricmp(queryName, "control:memtracesizelimit")==0)
  2153. {
  2154. memsize_t memTraceSizeLimit = (memsize_t) control->getPropInt64("@val", control->getPropInt64("@value", 0)); // used to accept @value so coded like this for backward compatibility
  2155. roxiemem::setMemTraceSizeLimit(memTraceSizeLimit);
  2156. topology->setPropInt64("@memTraceSizeLimit", memTraceSizeLimit);
  2157. }
  2158. else if (stricmp(queryName, "control:metrics")==0)
  2159. {
  2160. roxieMetrics->getMetrics(reply);
  2161. }
  2162. else if (stricmp(queryName, "control:minFreeDiskSpace")==0)
  2163. {
  2164. minFreeDiskSpace = (unsigned) control->getPropInt64("@val", 1048576);
  2165. topology->setPropInt64("@minFreeDiskSpace", minFreeDiskSpace);
  2166. }
  2167. else if (stricmp(queryName, "control:misctrace")==0)
  2168. {
  2169. miscDebugTraceLevel = control->getPropInt("@level", 0);
  2170. topology->setPropInt("@miscDebugTraceLevel", miscDebugTraceLevel);
  2171. }
  2172. else
  2173. unknown = true;
  2174. break;
  2175. case 'N':
  2176. if (stricmp(queryName, "control:nodeCachePreload")==0)
  2177. {
  2178. nodeCachePreload = control->getPropBool("@val", true);
  2179. topology->setPropBool("@nodeCachePreload", nodeCachePreload);
  2180. setNodeCachePreload(nodeCachePreload);
  2181. }
  2182. else if (stricmp(queryName, "control:nodeCacheMem")==0)
  2183. {
  2184. nodeCacheMB = control->getPropInt("@val", 100);
  2185. topology->setPropInt("@nodeCacheMem", nodeCacheMB);
  2186. setNodeCacheMem(nodeCacheMB * 0x100000);
  2187. }
  2188. else if (stricmp(queryName, "control:numFilesToProcess")==0)
  2189. {
  2190. int numFiles = queryFileCache().numFilesToCopy();
  2191. reply.appendf("<FilesToProcess value='%d'/>", numFiles);
  2192. }
  2193. else
  2194. unknown = true;
  2195. break;
  2196. case 'P':
  2197. if (stricmp(queryName, "control:parallelAggregate")==0)
  2198. {
  2199. parallelAggregate = control->getPropInt("@val", 0);
  2200. if (!parallelAggregate)
  2201. parallelAggregate = hdwInfo.numCPUs;
  2202. if (!parallelAggregate)
  2203. parallelAggregate = 1;
  2204. topology->setPropInt("@parallelAggregate", parallelAggregate);
  2205. }
  2206. else if (stricmp(queryName, "control:pingInterval")==0)
  2207. {
  2208. unsigned newInterval = (unsigned) control->getPropInt64("@val", 0);
  2209. if (newInterval && !pingInterval)
  2210. {
  2211. pingInterval = newInterval; // best to set before the start...
  2212. startPingTimer();
  2213. }
  2214. else if (pingInterval && !newInterval)
  2215. stopPingTimer(); // but after the stop
  2216. pingInterval = newInterval;
  2217. topology->setPropInt64("@pingInterval", pingInterval);
  2218. }
  2219. else if (stricmp(queryName, "control:preabortIndexReadsThreshold")==0)
  2220. {
  2221. preabortIndexReadsThreshold = control->getPropInt("@val", 100);
  2222. topology->setPropInt("@preabortIndexReadsThreshold", preabortIndexReadsThreshold);
  2223. }
  2224. else if (stricmp(queryName, "control:preabortKeyedJoinsThreshold")==0)
  2225. {
  2226. preabortKeyedJoinsThreshold = control->getPropInt("@val", 100);
  2227. topology->setPropInt("@preabortKeyedJoinsThreshold", preabortKeyedJoinsThreshold);
  2228. }
  2229. else if (stricmp(queryName, "control:probeAllRows")==0)
  2230. {
  2231. probeAllRows = control->getPropBool("@val", true);
  2232. }
  2233. else
  2234. unknown = true;
  2235. break;
  2236. case 'Q':
  2237. if (stricmp(queryName, "control:queries")==0)
  2238. {
  2239. getQueryInfo(control, reply, false, logctx);
  2240. }
  2241. else if (stricmp(queryName, "control:queryAggregates")==0)
  2242. {
  2243. time_t from;
  2244. const char *fromTime = control->queryProp("@from");
  2245. if (fromTime)
  2246. {
  2247. CDateTime f;
  2248. f.setString(fromTime, NULL, true);
  2249. from = f.getSimple();
  2250. }
  2251. else
  2252. from = startupTime;
  2253. time_t to;
  2254. const char *toTime = control->queryProp("@to");
  2255. if (toTime)
  2256. {
  2257. CDateTime t;
  2258. t.setString(toTime, NULL, true);
  2259. to = t.getSimple();
  2260. }
  2261. else
  2262. time(&to);
  2263. const char *id = control->queryProp("Query/@id");
  2264. if (id)
  2265. {
  2266. Owned<IQueryFactory> f = getQuery(id, NULL, NULL, logctx);
  2267. if (f)
  2268. {
  2269. Owned<const IPropertyTree> stats = f->getQueryStats(from, to);
  2270. toXML(stats, reply);
  2271. }
  2272. else
  2273. throw MakeStringException(ROXIE_CONTROL_MSG_ERROR, "Unknown query %s", id);
  2274. }
  2275. else
  2276. {
  2277. bool includeAllQueries = control->getPropBool("@all", true);
  2278. Owned<const IPropertyTree> stats = getAllQueryStats(includeAllQueries, from, to);
  2279. toXML(stats, reply);
  2280. }
  2281. }
  2282. else if (stricmp(queryName, "control:queryPackageInfo")==0)
  2283. {
  2284. ReadLockBlock readBlock(packageCrit);
  2285. allQueryPackages->getInfo(reply, logctx);
  2286. }
  2287. else if (stricmp(queryName, "control:queryStats")==0)
  2288. {
  2289. const char *id = control->queryProp("Query/@id");
  2290. if (!id)
  2291. badFormat();
  2292. const char *action = control->queryProp("Query/@action");
  2293. const char *graphName = 0;
  2294. if (action)
  2295. {
  2296. if (stricmp(action, "listGraphNames") == 0)
  2297. {
  2298. Owned<IQueryFactory> query = getQuery(id, NULL, NULL, logctx);
  2299. if (query)
  2300. {
  2301. reply.appendf("<Query id='%s'>\n", id);
  2302. StringArray graphNames;
  2303. query->getGraphNames(graphNames);
  2304. ForEachItemIn(idx, graphNames)
  2305. {
  2306. const char *graphName = graphNames.item(idx);
  2307. reply.appendf("<Graph id='%s'/>", graphName);
  2308. }
  2309. reply.appendf("</Query>\n");
  2310. }
  2311. return; // done
  2312. }
  2313. else if (stricmp(action, "selectGraph") == 0)
  2314. graphName = control->queryProp("Query/@name");
  2315. else if (stricmp(action, "allGraphs") != 0) // if we get here and its NOT allgraphs - then error
  2316. throw MakeStringException(ROXIE_CONTROL_MSG_ERROR, "invalid action in control:queryStats %s", action);
  2317. }
  2318. ReadLockBlock readBlock(packageCrit);
  2319. allQueryPackages->getStats(reply, id, action, graphName, logctx);
  2320. }
  2321. else if (stricmp(queryName, "control:queryWuid")==0)
  2322. {
  2323. UNIMPLEMENTED;
  2324. }
  2325. else
  2326. unknown = true;
  2327. break;
  2328. case 'R':
  2329. if (stricmp(queryName, "control:reload")==0)
  2330. {
  2331. requestReload(true, control->getPropBool("@forceRetry", false));
  2332. if (daliHelper && daliHelper->connected())
  2333. reply.appendf("<Dali connected='1'/>");
  2334. else
  2335. reply.appendf("<Dali connected='0'/>");
  2336. unsigned __int64 thash = getTopologyHash();
  2337. unsigned __int64 shash;
  2338. {
  2339. ReadLockBlock readBlock(packageCrit);
  2340. shash = allQueryPackages->queryHash();
  2341. }
  2342. reply.appendf("<State hash='%" I64F "u' topologyHash='%" I64F "u'/>", shash, thash);
  2343. }
  2344. else if (stricmp(queryName, "control:resetcache")==0)
  2345. {
  2346. releaseSlaveDynamicFileCache();
  2347. }
  2348. else if (stricmp(queryName, "control:resetindexmetrics")==0)
  2349. {
  2350. resetIndexMetrics();
  2351. }
  2352. else if (stricmp(queryName, "control:resetmetrics")==0)
  2353. {
  2354. roxieMetrics->resetMetrics();
  2355. }
  2356. else if (stricmp(queryName, "control:resetquerystats")==0)
  2357. {
  2358. ReadLockBlock readBlock(packageCrit);
  2359. Owned<IPropertyTreeIterator> queries = control->getElements("Query");
  2360. if (queries->first())
  2361. {
  2362. while (queries->isValid())
  2363. {
  2364. IPropertyTree &query = queries->query();
  2365. const char *id = query.queryProp("@id");
  2366. const char *target = query.queryProp("@target");
  2367. if (!id)
  2368. badFormat();
  2369. allQueryPackages->resetStats(target, id, logctx);
  2370. queries->next();
  2371. }
  2372. }
  2373. else
  2374. allQueryPackages->resetStats(NULL, NULL, logctx);
  2375. }
  2376. else if (stricmp(queryName, "control:resetremotedalicache")==0)
  2377. {
  2378. queryNamedGroupStore().resetCache();
  2379. }
  2380. else if (stricmp(queryName, "control:restart")==0)
  2381. {
  2382. FatalError("Roxie process restarted by operator request");
  2383. }
  2384. else if (stricmp(queryName, "control:retrieveActivityDetails")==0)
  2385. {
  2386. UNIMPLEMENTED;
  2387. }
  2388. else if (stricmp(queryName, "control:retrieveFileInfo")==0)
  2389. {
  2390. UNIMPLEMENTED;
  2391. }
  2392. else if (stricmp(queryName, "control:roxiememstats") == 0)
  2393. {
  2394. StringBuffer memStats;
  2395. queryMemoryPoolStats(memStats);
  2396. reply.append("<MemoryStats>").append(memStats.str()).append("</MemoryStats>\n");
  2397. }
  2398. else
  2399. unknown = true;
  2400. break;
  2401. case 'S':
  2402. if (stricmp(queryName, "control:setAffinity")==0)
  2403. {
  2404. __uint64 affinity = control->getPropBool("@val", true);
  2405. topology->setPropInt64("@affinity", affinity);
  2406. updateAffinity(affinity);
  2407. }
  2408. else if (stricmp(queryName, "control:setCopyResources")==0)
  2409. {
  2410. copyResources = control->getPropBool("@val", true);
  2411. topology->setPropBool("@copyResources", copyResources);
  2412. }
  2413. else if (stricmp(queryName, "control:simpleLocalKeyedJoins")==0)
  2414. {
  2415. simpleLocalKeyedJoins = control->getPropBool("@val", true);
  2416. }
  2417. else if (stricmp(queryName, "control:soapInfo")==0)
  2418. {
  2419. UNIMPLEMENTED;
  2420. }
  2421. else if (stricmp(queryName, "control:soapTrace")==0)
  2422. {
  2423. soapTraceLevel = control->getPropInt("@level", 0);
  2424. topology->setPropInt("@soapTraceLevel", soapTraceLevel);
  2425. }
  2426. else if (stricmp(queryName, "control:socketCheckInterval")==0)
  2427. {
  2428. socketCheckInterval = (unsigned) control->getPropInt64("@val", 0);
  2429. topology->setPropInt64("@socketCheckInterval", socketCheckInterval);
  2430. }
  2431. else if (stricmp(queryName, "control:state")==0)
  2432. {
  2433. if (daliHelper && daliHelper->connected())
  2434. reply.appendf("<Dali connected='1'/>");
  2435. else
  2436. reply.appendf("<Dali connected='0'/>");
  2437. unsigned __int64 thash = getTopologyHash();
  2438. unsigned __int64 shash;
  2439. {
  2440. ReadLockBlock readBlock(packageCrit);
  2441. shash = allQueryPackages->queryHash();
  2442. }
  2443. reply.appendf("<State hash='%" I64F "u' topologyHash='%" I64F "u'/>", shash, thash);
  2444. }
  2445. else if (stricmp(queryName, "control:steppingEnabled")==0)
  2446. {
  2447. steppingEnabled = control->getPropBool("@val", true);
  2448. }
  2449. else if (stricmp(queryName, "control:suspendChannel")==0)
  2450. {
  2451. if (control->hasProp("@channel") && control->hasProp("@suspend"))
  2452. {
  2453. unsigned channel = control->getPropInt("@channel", 0);
  2454. bool suspend = control->getPropBool("@suspend", true);
  2455. CriticalBlock b(ccdChannelsCrit);
  2456. if (channel)
  2457. {
  2458. StringBuffer xpath;
  2459. IPropertyTree *slaveNode = ccdChannels->queryPropTree(xpath.appendf("RoxieSlaveProcess[@channel='%u']", channel).str());
  2460. if (slaveNode)
  2461. {
  2462. ROQ->suspendChannel(channel, suspend, logctx);
  2463. slaveNode->setPropBool("@suspended", suspend);
  2464. }
  2465. else
  2466. throw MakeStringException(ROXIE_INVALID_INPUT, "Unknown channel %u", channel);
  2467. }
  2468. else
  2469. {
  2470. Owned<IPropertyTreeIterator> slaves = ccdChannels->getElements("RoxieSlaveProcess");
  2471. ForEach(*slaves)
  2472. {
  2473. IPropertyTree &slaveNode = slaves->query();
  2474. channel = slaveNode.getPropInt("@channel", 0);
  2475. ROQ->suspendChannel(channel, suspend, logctx);
  2476. slaveNode.setPropBool("@suspended", suspend);
  2477. }
  2478. }
  2479. toXML(ccdChannels, reply);
  2480. }
  2481. else
  2482. badFormat();
  2483. }
  2484. else if (stricmp(queryName, "control:suspendServer")==0)
  2485. {
  2486. if (control->hasProp("@port") && control->hasProp("@suspend"))
  2487. {
  2488. unsigned port = control->getPropInt("@port", 0);
  2489. bool suspend = control->getPropBool("@suspend", true);
  2490. CriticalBlock b(ccdChannelsCrit);
  2491. if (port)
  2492. {
  2493. StringBuffer xpath;
  2494. IPropertyTree *serverNode = ccdChannels->queryPropTree(xpath.appendf("RoxieServerProcess[@port='%u']", port).str());
  2495. if (serverNode)
  2496. {
  2497. suspendRoxieListener(port, suspend);
  2498. serverNode->setPropBool("@suspended", suspend);
  2499. }
  2500. else
  2501. throw MakeStringException(ROXIE_INVALID_INPUT, "Unknown Roxie server port %u", port);
  2502. }
  2503. else
  2504. {
  2505. Owned<IPropertyTreeIterator> servers = ccdChannels->getElements("RoxieServerProcess");
  2506. ForEach(*servers)
  2507. {
  2508. IPropertyTree &serverNode = servers->query();
  2509. port = serverNode.getPropInt("@port", 0);
  2510. suspendRoxieListener(port, suspend);
  2511. serverNode.setPropBool("@suspended", suspend);
  2512. }
  2513. }
  2514. toXML(ccdChannels, reply);
  2515. }
  2516. else
  2517. badFormat();
  2518. }
  2519. else if (stricmp(queryName, "control:systemMonitor")==0)
  2520. {
  2521. unsigned interval = control->getPropInt("@interval", 60000);
  2522. bool enable = control->getPropBool("@enable", true);
  2523. if (enable)
  2524. startPerformanceMonitor(interval, PerfMonStandard, perfMonHook);
  2525. else
  2526. stopPerformanceMonitor();
  2527. }
  2528. //MORE: control:stats??
  2529. else
  2530. unknown = true;
  2531. break;
  2532. case 'T':
  2533. if (stricmp(queryName, "control:testSlaveFailure")==0)
  2534. {
  2535. testSlaveFailure = control->getPropInt("@val", 20);
  2536. }
  2537. else if (stricmp(queryName, "control:timeActivities")==0)
  2538. {
  2539. defaultTimeActivities = control->getPropBool("@val", true);
  2540. topology->setPropInt("@timeActivities", defaultTimeActivities);
  2541. }
  2542. else if (stricmp(queryName, "control:timings")==0)
  2543. {
  2544. reply.append("<Timings>");
  2545. queryActiveTimer()->getTimings(reply);
  2546. reply.append("</Timings>");
  2547. if (control->getPropBool("@reset", false))
  2548. {
  2549. queryActiveTimer()->reset();
  2550. }
  2551. }
  2552. else if (stricmp(queryName, "control:topology")==0)
  2553. {
  2554. toXML(topology, reply);
  2555. }
  2556. else if (stricmp(queryName, "control:trace")==0)
  2557. {
  2558. traceLevel = control->getPropInt("@level", 0);
  2559. if (traceLevel > MAXTRACELEVEL)
  2560. traceLevel = MAXTRACELEVEL;
  2561. topology->setPropInt("@traceLevel", traceLevel);
  2562. }
  2563. else if (stricmp(queryName, "control:traceServerSideCache")==0)
  2564. {
  2565. traceServerSideCache = control->getPropBool("@val", true);
  2566. topology->setPropInt("@traceServerSideCache", traceServerSideCache);
  2567. }
  2568. else if (stricmp(queryName, "control:traceSmartStepping")==0)
  2569. {
  2570. traceSmartStepping = control->getPropBool("@val", true);
  2571. topology->setPropInt("@traceSmartStepping", traceSmartStepping);
  2572. }
  2573. else if (stricmp(queryName, "control:traceStartStop")==0)
  2574. {
  2575. traceStartStop = control->getPropBool("@val", true);
  2576. topology->setPropInt("@traceStartStop", traceStartStop);
  2577. }
  2578. else
  2579. unknown = true;
  2580. break;
  2581. case 'U':
  2582. if (stricmp(queryName, "control:udptrace")==0)
  2583. {
  2584. udpTraceLevel = control->getPropInt("@level", 0);
  2585. topology->setPropInt("@udpTraceLevel", udpTraceLevel);
  2586. }
  2587. else if (stricmp(queryName, "control:unlockDali")==0)
  2588. {
  2589. topology->setPropBool("@lockDali", false);
  2590. // Dali will reattach via the timer that checks every so often if can reattach...
  2591. saveTopology();
  2592. }
  2593. else if (stricmp(queryName, "control:unsuspend")==0)
  2594. {
  2595. UNIMPLEMENTED;
  2596. }
  2597. else if (stricmp(queryName, "control:userMetric")==0)
  2598. {
  2599. const char *name = control->queryProp("@name");
  2600. const char *regex= control->queryProp("@regex");
  2601. if (name && regex)
  2602. {
  2603. roxieMetrics->addUserMetric(name, regex);
  2604. // MORE - we could add to topology, we could check for dups, and we could support removing them.
  2605. }
  2606. else
  2607. throw MakeStringException(ROXIE_MISSING_PARAMS, "Metric name or regex missing");
  2608. }
  2609. else
  2610. unknown = true;
  2611. break;
  2612. case 'W':
  2613. if (stricmp(queryName, "control:watchActivityId")==0)
  2614. {
  2615. watchActivityId = control->getPropInt("@id", true);
  2616. }
  2617. else
  2618. unknown = true;
  2619. break;
  2620. default:
  2621. unknown = true;
  2622. break;
  2623. }
  2624. if (unknown)
  2625. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown query %s", queryName);
  2626. }
  2627. void badFormat()
  2628. {
  2629. throw MakeStringException(ROXIE_INVALID_INPUT, "Badly formated control query");
  2630. }
  2631. hash64_t getTopologyHash()
  2632. {
  2633. StringBuffer xml;
  2634. toXML(topology, xml, 0, XML_SortTags);
  2635. return rtlHash64Data(xml.length(), xml.str(), 707018);
  2636. }
  2637. };
  2638. extern IRoxieQueryPackageManagerSet *createRoxiePackageSetManager(const IQueryDll *standAloneDll)
  2639. {
  2640. return new CRoxiePackageSetManager(standAloneDll);
  2641. }
  2642. IRoxieQueryPackageManagerSet *globalPackageSetManager = NULL;
  2643. extern void loadPlugins()
  2644. {
  2645. DBGLOG("Preloading plugins from %s", pluginDirectory.str());
  2646. if (pluginDirectory.length())
  2647. {
  2648. plugins = new SafePluginMap(&PluginCtx, traceLevel >= 1);
  2649. plugins->loadFromList(pluginDirectory);
  2650. }
  2651. }
  2652. extern void cleanupPlugins()
  2653. {
  2654. delete plugins;
  2655. plugins = NULL;
  2656. }
  2657. /*=======================================================================================================
  2658. * mergeStats and associated code is used to combine the graph stats from multiple nodes in a cluster into
  2659. * a single aggregate structure
  2660. * It should be moved into ccdquery.cpp really
  2661. *========================================================================================================*/
  2662. typedef void (*mergefunc)(IPropertyTree *s1, IPropertyTree *s2, unsigned level);
  2663. struct MergeInfo
  2664. {
  2665. const char *element;
  2666. const char *attribute;
  2667. mergefunc f;
  2668. };
  2669. void mergeSubGraphs(IPropertyTree *s1, IPropertyTree *s2, unsigned);
  2670. void mergeNodes(IPropertyTree *s1, IPropertyTree *s2)
  2671. {
  2672. Owned<IPropertyTreeIterator> elems = s1->getElements("att");
  2673. ForEach(*elems)
  2674. {
  2675. IPropertyTree &e1 = elems->query();
  2676. unsigned __int64 v1 = e1.getPropInt64("@value", 0);
  2677. const char *name = e1.queryProp("@name");
  2678. if (stricmp(name, "_kind")==0 && v1 == TAKsubgraph)
  2679. {
  2680. IPropertyTree *s1child = s1->queryPropTree("att/graph");
  2681. IPropertyTree *s2child = s2->queryPropTree("att[@name='_kind']/graph");
  2682. if (s1child && s2child)
  2683. {
  2684. mergeSubGraphs(s1child, s2child, 0);
  2685. s2->removeProp("att[@name='_kind']");
  2686. }
  2687. }
  2688. else
  2689. {
  2690. StringBuffer xpath;
  2691. xpath.appendf("att[@name='%s']", name);
  2692. const char *type = e1.queryProp("@type");
  2693. if (type)
  2694. {
  2695. IPropertyTree *e2 = s2->queryPropTree(xpath.str());
  2696. if (e2)
  2697. {
  2698. unsigned __int64 v2 = e2->getPropInt64("@value", 0);
  2699. if (strcmp(name, "max")==0)
  2700. {
  2701. if (v2 > v1)
  2702. e1.setPropInt64("@value", v2);
  2703. }
  2704. else if (strcmp(type, "min")==0)
  2705. {
  2706. if (v2 < v1)
  2707. e1.setPropInt64("@value", v2);
  2708. }
  2709. else if (strcmp(type, "sum")==0)
  2710. e1.setPropInt64("@value", v1+v2);
  2711. else
  2712. throw MakeStringException(ROXIE_UNKNOWN_QUERY, "Unknown type %s in graph statistics", type);
  2713. s2->removeTree(e2);
  2714. }
  2715. }
  2716. else
  2717. {
  2718. // remove from s2 any complete dups
  2719. const char *s1val = e1.queryProp("@value");
  2720. Owned<IPropertyTreeIterator> s2elems = s2->getElements(xpath.str());
  2721. IArrayOf<IPropertyTree> goers;
  2722. ForEach(*s2elems)
  2723. {
  2724. IPropertyTree &e2 = s2elems->query();
  2725. const char *s2val = e2.queryProp("@value");
  2726. if ((!s1val && !s2val) || (s1val && s2val && strcmp(s1val, s2val)==0))
  2727. goers.append(*LINK(&e2));
  2728. }
  2729. ForEachItemIn(idx, goers)
  2730. {
  2731. s2->removeTree(&goers.item(idx));
  2732. }
  2733. }
  2734. }
  2735. }
  2736. elems.setown(s2->getElements("*"));
  2737. ForEach(*elems)
  2738. {
  2739. IPropertyTree &e2 = elems->query();
  2740. s1->addPropTree(e2.queryName(), LINK(&e2));
  2741. }
  2742. }
  2743. void mergeSubGraphs(IPropertyTree *s1, IPropertyTree *s2, unsigned)
  2744. {
  2745. Owned<IPropertyTreeIterator> elems = s1->getElements("*");
  2746. ForEach(*elems)
  2747. {
  2748. IPropertyTree &e1 = elems->query();
  2749. const char *elemName = e1.queryName();
  2750. StringBuffer xpath;
  2751. if (strcmp(elemName, "att")==0)
  2752. {
  2753. xpath.appendf("att[@name='%s']", e1.queryProp("@name"));
  2754. IPropertyTree *e2 = s2->queryPropTree(xpath.str());
  2755. if (e2)
  2756. s2->removeTree(e2);
  2757. }
  2758. else
  2759. {
  2760. xpath.appendf("%s[@id='%s']", elemName, e1.queryProp("@id"));
  2761. IPropertyTree *e2 = s2->queryPropTree(xpath.str());
  2762. if (e2)
  2763. {
  2764. mergeNodes(&e1, e2);
  2765. s2->removeTree(e2);
  2766. }
  2767. }
  2768. }
  2769. elems.setown(s2->getElements("*"));
  2770. ForEach(*elems)
  2771. {
  2772. IPropertyTree &e2 = elems->query();
  2773. s1->addPropTree(e2.queryName(), LINK(&e2));
  2774. }
  2775. }
  2776. void mergeNode(IPropertyTree *s1, IPropertyTree *s2, unsigned level);
  2777. MergeInfo mergeTable[] =
  2778. {
  2779. {"Query", "@id", mergeStats},
  2780. {"Graph", "@id", mergeStats},
  2781. {"xgmml", NULL, mergeStats},
  2782. {"graph", NULL, mergeStats},
  2783. {"node", "@id", mergeNode},
  2784. {"att", NULL, mergeStats},
  2785. {"graph", NULL, mergeSubGraphs},
  2786. };
  2787. void mergeNode(IPropertyTree *s1, IPropertyTree *s2, unsigned level)
  2788. {
  2789. if (s1->hasProp("att/@name"))
  2790. mergeNodes(s1, s2);
  2791. else
  2792. mergeStats(s1, s2, level);
  2793. }
  2794. void mergeStats(IPropertyTree *s1, IPropertyTree *s2, unsigned level)
  2795. {
  2796. MergeInfo & mi = mergeTable[level];
  2797. Owned<IPropertyTreeIterator> elems = s2->getElements(mi.element);
  2798. ForEach(*elems)
  2799. {
  2800. IPropertyTree &e2 = elems->query();
  2801. StringBuffer xpath;
  2802. if (mi.attribute)
  2803. xpath.appendf("%s[%s='%s']", mi.element, mi.attribute, e2.queryProp(mi.attribute));
  2804. else
  2805. xpath.append(mi.element);
  2806. IPropertyTree *e1 = s1->queryPropTree(xpath.str());
  2807. if (e1)
  2808. {
  2809. mi.f(e1, &e2, level+1);
  2810. }
  2811. else
  2812. s1->addPropTree(mi.element, LINK(&e2));
  2813. }
  2814. }
  2815. void mergeStats(IPropertyTree *s1, IPropertyTree *s2)
  2816. {
  2817. Owned<IPropertyTreeIterator> elems = s2->getElements("Exception");
  2818. ForEach(*elems)
  2819. {
  2820. s1->addPropTree("Exception", LINK(&elems->query()));
  2821. }
  2822. mergeStats(s1, s2, 0);
  2823. }
  2824. void mergeQueries(IPropertyTree *dest, IPropertyTree *src)
  2825. {
  2826. Owned<IPropertyTreeIterator> elems = src->getElements("Exception");
  2827. ForEach(*elems)
  2828. {
  2829. dest->addPropTree("Exception", LINK(&elems->query()));
  2830. }
  2831. IPropertyTree *destQueries = ensurePTree(dest, "Queries");
  2832. IPropertyTree *srcQueries = src->queryPropTree("Queries");
  2833. if (!srcQueries)
  2834. return;
  2835. destQueries->setPropInt("@reporting", destQueries->getPropInt("@reporting") + srcQueries->getPropInt("@reporting"));
  2836. Owned<IPropertyTreeIterator> queries = srcQueries->getElements("Query");
  2837. ForEach(*queries)
  2838. {
  2839. IPropertyTree *srcQuery = &queries->query();
  2840. const char *id = srcQuery->queryProp("@id");
  2841. if (!id || !*id)
  2842. continue;
  2843. VStringBuffer xpath("Query[@id='%s']", id);
  2844. IPropertyTree *destQuery = destQueries->queryPropTree(xpath);
  2845. if (!destQuery)
  2846. {
  2847. destQueries->addPropTree("Query", LINK(srcQuery));
  2848. continue;
  2849. }
  2850. int suspended = destQuery->getPropInt("@suspended") + srcQuery->getPropInt("@suspended"); //keep count to recognize "partially suspended" queries
  2851. mergePTree(destQuery, srcQuery);
  2852. if (suspended)
  2853. destQuery->setPropInt("@suspended", suspended);
  2854. }
  2855. Owned<IPropertyTreeIterator> aliases = srcQueries->getElements("Alias");
  2856. ForEach(*aliases)
  2857. {
  2858. IPropertyTree *srcQuery = &aliases->query();
  2859. const char *id = srcQuery->queryProp("@id");
  2860. if (!id || !*id)
  2861. continue;
  2862. VStringBuffer xpath("Alias[@id='%s']", id);
  2863. IPropertyTree *destQuery = destQueries->queryPropTree(xpath);
  2864. if (!destQuery)
  2865. {
  2866. destQueries->addPropTree("Alias", LINK(srcQuery));
  2867. continue;
  2868. }
  2869. mergePTree(destQuery, srcQuery);
  2870. }
  2871. }
  2872. #ifdef _USE_CPPUNIT
  2873. #include <cppunit/extensions/HelperMacros.h>
  2874. static const char *g1 =
  2875. "<Stats>"
  2876. "<Query id='stats'>"
  2877. "<Graph id='graph1'>"
  2878. "<xgmml>"
  2879. "<graph>"
  2880. "<node id='1'>"
  2881. "<att>"
  2882. "<graph>"
  2883. "<node id='2' label='Temp Table'>"
  2884. "<att name='name' value='d'/>"
  2885. "<att name='_kind' value='25'/>"
  2886. "<att name='helper' value='f2'/>"
  2887. "</node>"
  2888. "<node id='2a'>"
  2889. " <att name='_kind' value='1'>" // TAKsubgraph
  2890. " <graph>"
  2891. " <node id='7696' label='Nested'>"
  2892. " <att name='seeks' value='15' type='sum'/>"
  2893. " </node>"
  2894. " </graph>"
  2895. " </att>"
  2896. "</node>"
  2897. "<node id='3' label='Filter'>"
  2898. "<att name='name' value='ds'/>"
  2899. "<att name='_kind' value='5'/>"
  2900. "<att name='helper' value='f3'/>"
  2901. "</node>"
  2902. "<att name='rootGraph' value='1'/>"
  2903. "<edge id='2_0' source='2' target='3'>"
  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='3_0' source='3' target='5'>"
  2909. "<att name='count' value='15' type='sum'/>"
  2910. "<att name='started' value='1'/>"
  2911. "<att name='stopped' value='1'/>"
  2912. "</edge>"
  2913. "<edge id='5_0' source='5' target='6'>"
  2914. "<att name='count' value='3' type='sum'/>"
  2915. "<att name='started' value='1'/>"
  2916. "<att name='stopped' value='1'/>"
  2917. "</edge>"
  2918. "<edge id='5_1' source='5' target='7'>"
  2919. "<att name='_sourceIndex' value='1'/>"
  2920. "<att name='count' value='15' type='sum'/>"
  2921. "<att name='started' value='1'/>"
  2922. "<att name='stopped' value='1'/>"
  2923. "</edge>"
  2924. "</graph>"
  2925. "</att>"
  2926. "</node>"
  2927. "</graph>"
  2928. "</xgmml>"
  2929. "</Graph>"
  2930. "</Query>"
  2931. "</Stats>";
  2932. static const char *g2 =
  2933. "<Stats>"
  2934. "<Query id='stats'>"
  2935. "<Graph id='graph1'>"
  2936. "<xgmml>"
  2937. "<graph>"
  2938. "<node id='1'>"
  2939. "<att>"
  2940. "<graph>"
  2941. "<node id='2' label='Temp Table'>"
  2942. "<att name='name' value='d'/>"
  2943. "<att name='_kind' value='25'/>"
  2944. "<att name='helper' value='f2'/>"
  2945. "</node>"
  2946. "<node id='2a'>"
  2947. " <att name='_kind' value='1'>" // TAKsubgraph
  2948. " <graph>"
  2949. " <node id='7696' label='Nested'>"
  2950. " <att name='seeks' value='25' type='sum'/>"
  2951. " </node>"
  2952. " </graph>"
  2953. " </att>"
  2954. "</node>"
  2955. "<node id='4' label='Filter2'>"
  2956. "<att name='name' value='ds2'/>"
  2957. "<att name='_kind' value='53'/>"
  2958. "<att name='helper' value='f23'/>"
  2959. "</node>"
  2960. "<att name='rootGraph' value='1'/>"
  2961. "<edge id='2_0' source='2' target='3'>"
  2962. "<att name='count' value='15' type='sum'/>"
  2963. "<att name='started' value='1'/>"
  2964. "<att name='stopped' value='1'/>"
  2965. "</edge>"
  2966. "<edge id='3_0' source='3' target='5'>"
  2967. "<att name='count' value='15' type='sum'/>"
  2968. "<att name='started' value='1'/>"
  2969. "<att name='stopped' value='1'/>"
  2970. "</edge>"
  2971. "<edge id='5_0' source='5' target='6'>"
  2972. "<att name='count' value='3' 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. static const char *expected =
  2985. "<Stats>"
  2986. "<Query id='stats'>"
  2987. "<Graph id='graph1'>"
  2988. "<xgmml>"
  2989. "<graph>"
  2990. "<node id='1'>"
  2991. "<att>"
  2992. "<graph>"
  2993. "<node id='2' label='Temp Table'>"
  2994. "<att name='name' value='d'/>"
  2995. "<att name='_kind' value='25'/>"
  2996. "<att name='helper' value='f2'/>"
  2997. "</node>"
  2998. "<node id='2a'>"
  2999. " <att name='_kind' value='1'>" // TAKsubgraph
  3000. " <graph>"
  3001. " <node id='7696' label='Nested'>"
  3002. " <att name='seeks' type='sum' value='40'/>"
  3003. " </node>"
  3004. " </graph>"
  3005. " </att>"
  3006. "</node>"
  3007. "<node id='3' label='Filter'>"
  3008. "<att name='name' value='ds'/>"
  3009. "<att name='_kind' value='5'/>"
  3010. "<att name='helper' value='f3'/>"
  3011. "</node>"
  3012. "<node id='4' label='Filter2'>"
  3013. "<att name='name' value='ds2'/>"
  3014. "<att name='_kind' value='53'/>"
  3015. "<att name='helper' value='f23'/>"
  3016. "</node>"
  3017. "<att name='rootGraph' value='1'/>"
  3018. "<edge id='2_0' source='2' target='3'>"
  3019. "<att name='count' value='30' type='sum'/>"
  3020. "<att name='started' value='1'/>"
  3021. "<att name='stopped' value='1'/>"
  3022. "</edge>"
  3023. "<edge id='3_0' source='3' target='5'>"
  3024. "<att name='count' value='30' type='sum'/>"
  3025. "<att name='started' value='1'/>"
  3026. "<att name='stopped' value='1'/>"
  3027. "</edge>"
  3028. "<edge id='5_0' source='5' target='6'>"
  3029. "<att name='count' value='6' type='sum'/>"
  3030. "<att name='started' value='1'/>"
  3031. "<att name='stopped' value='1'/>"
  3032. "</edge>"
  3033. "<edge id='5_1' source='5' target='7'>"
  3034. "<att name='_sourceIndex' value='1'/>"
  3035. "<att name='count' value='15' type='sum'/>"
  3036. "<att name='started' value='1'/>"
  3037. "<att name='stopped' value='1'/>"
  3038. "</edge>"
  3039. "</graph>"
  3040. "</att>"
  3041. "</node>"
  3042. "</graph>"
  3043. "</xgmml>"
  3044. "</Graph>"
  3045. "</Query>"
  3046. "</Stats>"
  3047. ;
  3048. class MergeStatsTest : public CppUnit::TestFixture
  3049. {
  3050. CPPUNIT_TEST_SUITE( MergeStatsTest );
  3051. CPPUNIT_TEST(test1);
  3052. // CPPUNIT_TEST(test2); Handy for debugging problem cases...
  3053. CPPUNIT_TEST_SUITE_END();
  3054. protected:
  3055. void test1()
  3056. {
  3057. Owned<IPropertyTree> p1 = createPTreeFromXMLString(g1);
  3058. Owned<IPropertyTree> p2 = createPTreeFromXMLString(g2);
  3059. Owned<IPropertyTree> e = createPTreeFromXMLString(expected);
  3060. mergeStats(p1, p2);
  3061. StringBuffer s1, s2;
  3062. toXML(p1, s1);
  3063. toXML(e, s2);
  3064. CPPUNIT_ASSERT(strcmp(s1, s2)==0);
  3065. }
  3066. void test2()
  3067. {
  3068. Owned<IPropertyTree> mergedReply = createPTree("Merged");
  3069. Owned<IPropertyTree> p1 = createPTreeFromXMLFile("stats1.xml");
  3070. Owned<IPropertyTreeIterator> meat = p1->getElements("Endpoint");
  3071. ForEach(*meat)
  3072. {
  3073. if (mergedReply)
  3074. {
  3075. mergeStats(mergedReply, &meat->query());
  3076. }
  3077. }
  3078. Owned<IPropertyTree> p2 = createPTreeFromXMLFile("stats2.xml");
  3079. meat.setown(p2->getElements("Endpoint"));
  3080. ForEach(*meat)
  3081. {
  3082. if (mergedReply)
  3083. {
  3084. mergeStats(mergedReply, &meat->query());
  3085. }
  3086. }
  3087. StringBuffer s1;
  3088. toXML(mergedReply, s1);
  3089. //toXML(e, s2);
  3090. //CPPUNIT_ASSERT(strcmp(s1, s2)==0);
  3091. printf("%s", s1.str());
  3092. }
  3093. };
  3094. CPPUNIT_TEST_SUITE_REGISTRATION( MergeStatsTest );
  3095. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( MergeStatsTest, "MergeStatsTest" );
  3096. #endif