ccdstate.cpp 125 KB

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