ws_workunitsHelpers.cpp 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114
  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 "jlib.hpp"
  14. #include "ws_workunitsHelpers.hpp"
  15. #include "exception_util.hpp"
  16. #include "daclient.hpp"
  17. #include "dalienv.hpp"
  18. #include "daaudit.hpp"
  19. #include "portlist.h"
  20. #include "dadfs.hpp"
  21. #include "fileview.hpp"
  22. #include "wuwebview.hpp"
  23. #include "dllserver.hpp"
  24. #include "wujobq.hpp"
  25. #include "hqlexpr.hpp"
  26. #ifdef _USE_ZLIB
  27. #include "zcrypt.hpp"
  28. #endif
  29. namespace ws_workunits {
  30. SecAccessFlags chooseWuAccessFlagsByOwnership(const char *user, const char *owner, SecAccessFlags accessOwn, SecAccessFlags accessOthers)
  31. {
  32. return (isEmpty(owner) || (user && streq(user, owner))) ? accessOwn : accessOthers;
  33. }
  34. SecAccessFlags chooseWuAccessFlagsByOwnership(const char *user, IConstWorkUnit& cw, SecAccessFlags accessOwn, SecAccessFlags accessOthers)
  35. {
  36. SCMStringBuffer owner;
  37. return chooseWuAccessFlagsByOwnership(user, cw.getUser(owner).str(), accessOwn, accessOthers);
  38. }
  39. const char *getWuAccessType(const char *owner, const char *user)
  40. {
  41. return (isEmpty(owner) || (user && streq(user, owner))) ? OWN_WU_ACCESS : OTHERS_WU_ACCESS;
  42. }
  43. const char *getWuAccessType(IConstWorkUnit& cw, const char *user)
  44. {
  45. SCMStringBuffer owner;
  46. return getWuAccessType(cw.getUser(owner).str(), user);
  47. }
  48. void getUserWuAccessFlags(IEspContext& context, SecAccessFlags& accessOwn, SecAccessFlags& accessOthers, bool except)
  49. {
  50. if (!context.authorizeFeature(OWN_WU_ACCESS, accessOwn))
  51. accessOwn = SecAccess_None;
  52. if (!context.authorizeFeature(OTHERS_WU_ACCESS, accessOthers))
  53. accessOthers = SecAccess_None;
  54. if (except && (accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  55. {
  56. AuditSystemAccess(context.queryUserId(), false, "Access Denied: User can't view any workunits");
  57. VStringBuffer msg("Access Denied: User %s does not have rights to access workunits.", context.queryUserId());
  58. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "%s", msg.str());
  59. }
  60. }
  61. SecAccessFlags getWsWorkunitAccess(IEspContext& cxt, IConstWorkUnit& cw)
  62. {
  63. SecAccessFlags accessFlag = SecAccess_None;
  64. cxt.authorizeFeature(getWuAccessType(cw, cxt.queryUserId()), accessFlag);
  65. return accessFlag;
  66. }
  67. void ensureWsWorkunitAccessByOwnerId(IEspContext& cxt, const char* owner, SecAccessFlags minAccess)
  68. {
  69. if (!cxt.validateFeatureAccess(getWuAccessType(owner, cxt.queryUserId()), minAccess, false))
  70. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to access workunit. Permission denied.");
  71. }
  72. void ensureWsWorkunitAccess(IEspContext& cxt, IConstWorkUnit& cw, SecAccessFlags minAccess)
  73. {
  74. if (!cxt.validateFeatureAccess(getWuAccessType(cw, cxt.queryUserId()), minAccess, false))
  75. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to access workunit. Permission denied.");
  76. }
  77. void ensureWsWorkunitAccess(IEspContext& context, const char* wuid, SecAccessFlags minAccess)
  78. {
  79. Owned<IWorkUnitFactory> wf = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  80. Owned<IConstWorkUnit> cw = wf->openWorkUnit(wuid, false);
  81. if (!cw)
  82. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Failed to open workunit %s when ensuring workunit access", wuid);
  83. ensureWsWorkunitAccess(context, *cw, minAccess);
  84. }
  85. void ensureWsCreateWorkunitAccess(IEspContext& cxt)
  86. {
  87. if (!cxt.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  88. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  89. }
  90. StringBuffer &getWuidFromLogicalFileName(IEspContext &context, const char *logicalName, StringBuffer &wuid)
  91. {
  92. Owned<IUserDescriptor> userdesc = createUserDescriptor();
  93. userdesc->set(context.queryUserId(), context.queryPassword());
  94. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(logicalName, userdesc);
  95. if (!df)
  96. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",logicalName);
  97. return wuid.append(df->queryAttributes().queryProp("@workunit"));
  98. }
  99. void formatDuration(StringBuffer &s, unsigned ms)
  100. {
  101. unsigned days = ms / (1000*60*60*24);
  102. ms %= (1000*60*60*24);
  103. unsigned hours = ms / (1000*60*60);
  104. ms %= (1000*60*60);
  105. unsigned mins = ms / (1000*60);
  106. ms %= (1000*60);
  107. unsigned secs = ms / 1000;
  108. ms %= 1000;
  109. if (days)
  110. s.appendf("%d days ", days);
  111. if (hours || s.length())
  112. s.appendf("%d:", hours);
  113. if (mins || s.length())
  114. s.appendf("%d:", mins);
  115. if (s.length())
  116. s.appendf("%02d.%03d", secs, ms);
  117. else
  118. s.appendf("%d.%03d", secs, ms);
  119. }
  120. WsWUExceptions::WsWUExceptions(IConstWorkUnit& wu): numerr(0), numwrn(0), numinf(0), numalert(0)
  121. {
  122. Owned<IConstWUExceptionIterator> it = &wu.getExceptions();
  123. ForEach(*it)
  124. {
  125. SCMStringBuffer src, msg, file;
  126. Owned<IEspECLException> e= createECLException("","");
  127. e->setCode(it->query().getExceptionCode());
  128. e->setSource(it->query().getExceptionSource(src).str());
  129. e->setMessage(it->query().getExceptionMessage(msg).str());
  130. e->setFileName(it->query().getExceptionFileName(file).str());
  131. e->setLineNo(it->query().getExceptionLineNo());
  132. e->setColumn(it->query().getExceptionColumn());
  133. const char * label = "";
  134. switch (it->query().getSeverity())
  135. {
  136. default:
  137. case SeverityError: label = "Error"; numerr++; break;
  138. case SeverityWarning: label = "Warning"; numwrn++; break;
  139. case SeverityInformation: label = "Info"; numinf++; break;
  140. case SeverityAlert: label = "Alert"; numalert++; break;
  141. }
  142. e->setSeverity(label);
  143. errors.append(*e.getLink());
  144. }
  145. }
  146. #define SDS_LOCK_TIMEOUT 30000
  147. void getSashaNode(SocketEndpoint &ep)
  148. {
  149. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  150. Owned<IConstEnvironment> env = factory->openEnvironment();
  151. if (!env)
  152. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO,"Cannot get environment information.");
  153. Owned<IPropertyTree> root = &env->getPTree();
  154. IPropertyTree *pt = root->queryPropTree("Software/SashaServerProcess[1]/Instance[1]");
  155. if (!pt)
  156. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND, "Archive Server not found.");
  157. ep.set(pt->queryProp("@netAddress"), pt->getPropInt("@port",DEFAULT_SASHA_PORT));
  158. }
  159. void WsWuInfo::getSourceFiles(IEspECLWorkunit &info, unsigned flags)
  160. {
  161. if (!(flags & WUINFO_IncludeSourceFiles))
  162. return;
  163. try
  164. {
  165. Owned<IUserDescriptor> userdesc;
  166. StringBuffer username;
  167. context.getUserID(username);
  168. const char* passwd = context.queryPassword();
  169. userdesc.setown(createUserDescriptor());
  170. userdesc->set(username.str(), passwd);
  171. IArrayOf<IEspECLSourceFile> files;
  172. if (version < 1.27)
  173. {
  174. Owned<IPropertyTreeIterator> f=&cw->getFilesReadIterator();
  175. ForEach(*f)
  176. {
  177. IPropertyTree &query = f->query();
  178. const char *clusterName = query.queryProp("@cluster");
  179. const char *fileName = query.queryProp("@name");
  180. int fileCount = query.getPropInt("@useCount");
  181. Owned<IEspECLSourceFile> file= createECLSourceFile("","");
  182. if(clusterName && *clusterName)
  183. {
  184. file->setFileCluster(clusterName);
  185. }
  186. if (version > 1.11)
  187. {
  188. Owned<IPropertyTreeIterator> filetrees= query.getElements("Subfile");
  189. if (filetrees->first())
  190. file->setIsSuperFile(true);
  191. }
  192. if (fileName && *fileName)
  193. {
  194. file->setName(fileName);
  195. }
  196. file->setCount(fileCount);
  197. files.append(*file.getLink());
  198. }
  199. }
  200. else
  201. {
  202. StringArray fileNames;
  203. Owned<IPropertyTreeIterator> f=&cw->getFilesReadIterator();
  204. ForEach(*f)
  205. {
  206. IPropertyTree &query = f->query();
  207. const char *clusterName = query.queryProp("@cluster");
  208. const char *fileName = query.queryProp("@name");
  209. int fileCount = query.getPropInt("@useCount");
  210. bool bFound = false;
  211. if (fileName && *fileName && (fileNames.length() > 0))
  212. {
  213. for (unsigned i = 0; i < fileNames.length(); i++ )
  214. {
  215. const char *fileName0 = fileNames.item(i);
  216. if (!stricmp(fileName, fileName0))
  217. {
  218. bFound = true;
  219. break;
  220. }
  221. }
  222. }
  223. if (bFound)
  224. continue;
  225. Owned<IEspECLSourceFile> file= createECLSourceFile("","");
  226. if(clusterName && *clusterName)
  227. {
  228. file->setFileCluster(clusterName);
  229. }
  230. if (fileName && *fileName)
  231. {
  232. file->setName(fileName);
  233. }
  234. file->setCount(fileCount);
  235. Owned<IPropertyTreeIterator> filetrees= query.getElements("Subfile");
  236. if (filetrees->first())
  237. {
  238. file->setIsSuperFile(true);
  239. getSubFiles(filetrees, file, fileNames);
  240. }
  241. files.append(*file.getLink());
  242. }
  243. }
  244. info.setSourceFiles(files);
  245. }
  246. catch(IException* e)
  247. {
  248. StringBuffer eMsg;
  249. ERRLOG("%s", e->errorMessage(eMsg).str());
  250. info.setSourceFilesDesc(eMsg.str());
  251. e->Release();
  252. }
  253. }
  254. void WsWuInfo::getExceptions(IEspECLWorkunit &info, unsigned flags)
  255. {
  256. if ((flags & WUINFO_IncludeExceptions) || version > 1.16)
  257. {
  258. WsWUExceptions errors(*cw);
  259. if (version > 1.16)
  260. {
  261. info.setErrorCount(errors.ErrCount());
  262. info.setWarningCount(errors.WrnCount());
  263. info.setInfoCount(errors.InfCount());
  264. info.setAlertCount(errors.AlertCount());
  265. }
  266. if ((flags & WUINFO_IncludeExceptions))
  267. info.setExceptions(errors);
  268. }
  269. }
  270. void WsWuInfo::getVariables(IEspECLWorkunit &info, unsigned flags)
  271. {
  272. if (!(flags & WUINFO_IncludeVariables))
  273. return;
  274. try
  275. {
  276. IArrayOf<IEspECLResult> results;
  277. Owned<IConstWUResultIterator> vars = &cw->getVariables();
  278. ForEach(*vars)
  279. getResult(vars->query(), results, flags);
  280. info.setVariables(results);
  281. results.kill();
  282. }
  283. catch(IException* e)
  284. {
  285. StringBuffer eMsg;
  286. ERRLOG("%s", e->errorMessage(eMsg).str());
  287. info.setVariablesDesc(eMsg.str());
  288. e->Release();
  289. }
  290. }
  291. void WsWuInfo::addTimerToList(SCMStringBuffer& name, const char * scope, IConstWUStatistic & stat, IArrayOf<IEspECLTimer>& timers)
  292. {
  293. StringBuffer fd;
  294. formatStatistic(fd, stat.getValue(), stat.getMeasure());
  295. Owned<IEspECLTimer> t= createECLTimer("","");
  296. name.s.replace('_', ' '); // yuk!
  297. t->setName(name.str());
  298. t->setValue(fd.str());
  299. //Theoretically this could overflow, in practice it is unlikely - fix in the new stats interface when implemented
  300. t->setCount((unsigned)stat.getCount());
  301. if (version > 1.19)
  302. {
  303. StringAttr graphName;
  304. unsigned graphNum;
  305. unsigned subGraphNum = 0;
  306. unsigned subId = 0;
  307. if (parseGraphScope(scope, graphName, graphNum, subId) ||
  308. parseGraphTimerLabel(name.str(), graphName, graphNum, subGraphNum, subId)) // leacy
  309. {
  310. if (graphName.length() > 0)
  311. t->setGraphName(graphName);
  312. if (subId > 0)
  313. t->setSubGraphId((int)subId);
  314. }
  315. }
  316. timers.append(*t.getLink());
  317. }
  318. void WsWuInfo::getTimers(IEspECLWorkunit &info, unsigned flags)
  319. {
  320. if (!(flags & WUINFO_IncludeTimers))
  321. return;
  322. try
  323. {
  324. unsigned __int64 totalThorTimeValue = 0;
  325. unsigned __int64 totalThorTimerCount = 0; //Do we need this?
  326. IArrayOf<IEspECLTimer> timers;
  327. StatisticsFilter filter;
  328. filter.setScopeDepth(1, 2);
  329. filter.setMeasure(SMeasureTimeNs);
  330. Owned<IConstWUStatisticIterator> it = &cw->getStatistics(&filter);
  331. if (it->first())
  332. {
  333. ForEach(*it)
  334. {
  335. IConstWUStatistic & cur = it->query();
  336. SCMStringBuffer name, scope;
  337. cur.getDescription(name, true);
  338. cur.getScope(scope);
  339. bool isThorTiming = false;//Should it be renamed as isClusterTiming?
  340. if ((cur.getCreatorType() == SCTsummary) && (cur.getKind() == StTimeElapsed) && streq(scope.str(), GLOBAL_SCOPE))
  341. {
  342. SCMStringBuffer creator;
  343. cur.getCreator(creator);
  344. if (streq(creator.str(), "thor") || streq(creator.str(), "hthor") ||
  345. streq(creator.str(), "roxie"))
  346. isThorTiming = true;
  347. }
  348. else if (strieq(name.str(), TOTALTHORTIME)) // legacy
  349. isThorTiming = true;
  350. if (isThorTiming)
  351. {
  352. totalThorTimeValue += cur.getValue();
  353. totalThorTimerCount += cur.getCount();
  354. }
  355. else
  356. addTimerToList(name, scope.str(), cur, timers);
  357. }
  358. }
  359. if (totalThorTimeValue > 0)
  360. {
  361. StringBuffer totalThorTimeText;
  362. formatStatistic(totalThorTimeText, totalThorTimeValue, SMeasureTimeNs);
  363. Owned<IEspECLTimer> t= createECLTimer("","");
  364. if (version > 1.52)
  365. t->setName(TOTALCLUSTERTIME);
  366. else
  367. t->setName(TOTALTHORTIME);
  368. t->setValue(totalThorTimeText.str());
  369. t->setCount((unsigned)totalThorTimerCount);
  370. timers.append(*t.getLink());
  371. }
  372. info.setTimers(timers);
  373. }
  374. catch(IException* e)
  375. {
  376. StringBuffer eMsg;
  377. ERRLOG("%s", e->errorMessage(eMsg).str());
  378. info.setTimersDesc(eMsg.str());
  379. e->Release();
  380. }
  381. }
  382. unsigned WsWuInfo::getTimerCount()
  383. {
  384. unsigned numTimers = 0;
  385. try
  386. {
  387. //This filter must match the filter in the function above, otherwise it will be inconsistent
  388. StatisticsFilter filter;
  389. filter.setScopeDepth(1, 2);
  390. filter.setMeasure(SMeasureTimeNs);
  391. Owned<IConstWUStatisticIterator> it = &cw->getStatistics(&filter);
  392. ForEach(*it)
  393. numTimers++;
  394. }
  395. catch(IException* e)
  396. {
  397. StringBuffer eMsg;
  398. ERRLOG("%s", e->errorMessage(eMsg).str());
  399. e->Release();
  400. }
  401. return numTimers;
  402. }
  403. struct mapEnums { int val; const char *str; };
  404. mapEnums queryFileTypes[] = {
  405. { FileTypeCpp, "cpp" },
  406. { FileTypeDll, "dll" },
  407. { FileTypeResText, "res" },
  408. { FileTypeHintXml, "hint" },
  409. { FileTypeXml, "xml" },
  410. { FileTypeSize, NULL },
  411. };
  412. const char *getEnumText(int value, mapEnums *map)
  413. {
  414. const char *defval = map->str;
  415. while (map->str)
  416. {
  417. if (value==map->val)
  418. return map->str;
  419. map++;
  420. }
  421. assertex(!"Unexpected value in setEnum");
  422. return defval;
  423. }
  424. void WsWuInfo::getHelpers(IEspECLWorkunit &info, unsigned flags)
  425. {
  426. try
  427. {
  428. IArrayOf<IEspECLHelpFile> helpers;
  429. Owned <IConstWUQuery> query = cw->getQuery();
  430. if(!query)
  431. {
  432. ERRLOG("Cannot get Query for this workunit.");
  433. info.setHelpersDesc("Cannot get Query for this workunit.");
  434. }
  435. else
  436. {
  437. SCMStringBuffer qname;
  438. query->getQueryShortText(qname);
  439. if(qname.length())
  440. {
  441. if((flags & WUINFO_TruncateEclTo64k) && (qname.length() > 64000))
  442. qname.setLen(qname.str(), 64000);
  443. IEspECLQuery* q=&info.updateQuery();
  444. q->setText(qname.str());
  445. }
  446. if (version > 1.34)
  447. {
  448. SCMStringBuffer mainDefinition;
  449. query->getQueryMainDefinition(mainDefinition);
  450. if(mainDefinition.length())
  451. {
  452. IEspECLQuery* q=&info.updateQuery();
  453. q->setQueryMainDefinition(mainDefinition.str());
  454. }
  455. }
  456. if (version > 1.30)
  457. {
  458. SCMStringBuffer qText;
  459. query->getQueryText(qText);
  460. if ((qText.length() > 0) && isArchiveQuery(qText.str()))
  461. info.setHasArchiveQuery(true);
  462. }
  463. for (unsigned i = 0; i < FileTypeSize; i++)
  464. getHelpFiles(query, (WUFileType) i, helpers);
  465. }
  466. getWorkunitThorLogInfo(helpers, info);
  467. if (cw->getWuidVersion() > 0)
  468. {
  469. Owned<IPropertyTreeIterator> eclAgents = cw->getProcesses("EclAgent", NULL);
  470. ForEach (*eclAgents)
  471. {
  472. StringBuffer logName;
  473. IPropertyTree& eclAgent = eclAgents->query();
  474. eclAgent.getProp("@log",logName);
  475. if (!logName.length())
  476. continue;
  477. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  478. h->setName(logName.str());
  479. h->setType(File_EclAgentLog);
  480. if (version >= 1.43)
  481. {
  482. offset_t fileSize;
  483. if (getFileSize(logName.str(), NULL, fileSize))
  484. h->setFileSize(fileSize);
  485. if (version >= 1.44)
  486. {
  487. if (eclAgent.hasProp("@pid"))
  488. h->setPID(eclAgent.getPropInt("@pid"));
  489. else
  490. h->setPID(cw->getAgentPID());
  491. }
  492. }
  493. helpers.append(*h.getLink());
  494. }
  495. }
  496. else // legacy wuid
  497. {
  498. Owned<IStringIterator> eclAgentLogs = cw->getLogs("EclAgent");
  499. ForEach (*eclAgentLogs)
  500. {
  501. SCMStringBuffer name;
  502. eclAgentLogs->str(name);
  503. if (name.length() < 1)
  504. continue;
  505. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  506. h->setName(name.str());
  507. h->setType(File_EclAgentLog);
  508. if (version >= 1.43)
  509. {
  510. offset_t fileSize;
  511. if (getFileSize(name.str(), NULL, fileSize))
  512. h->setFileSize(fileSize);
  513. }
  514. helpers.append(*h.getLink());
  515. break;
  516. }
  517. }
  518. info.setHelpers(helpers);
  519. }
  520. catch(IException* e)
  521. {
  522. StringBuffer eMsg;
  523. ERRLOG("%s", e->errorMessage(eMsg).str());
  524. info.setHelpersDesc(eMsg.str());
  525. e->Release();
  526. }
  527. }
  528. void WsWuInfo::getApplicationValues(IEspECLWorkunit &info, unsigned flags)
  529. {
  530. if (!(flags & WUINFO_IncludeApplicationValues))
  531. return;
  532. try
  533. {
  534. IArrayOf<IEspApplicationValue> av;
  535. Owned<IConstWUAppValueIterator> app(&cw->getApplicationValues());
  536. ForEach(*app)
  537. {
  538. IConstWUAppValue& val=app->query();
  539. SCMStringBuffer buf;
  540. Owned<IEspApplicationValue> t= createApplicationValue("","");
  541. t->setApplication(val.getApplication(buf).str());
  542. t->setValue(val.getValue(buf).str());
  543. t->setName(val.getName(buf).str());
  544. t->setValue(val.getValue(buf).str());
  545. av.append(*t.getLink());
  546. }
  547. info.setApplicationValues(av);
  548. }
  549. catch(IException* e)
  550. {
  551. StringBuffer eMsg;
  552. ERRLOG("%s", e->errorMessage(eMsg).str());
  553. info.setApplicationValuesDesc(eMsg.str());
  554. e->Release();
  555. }
  556. }
  557. void WsWuInfo::getDebugValues(IEspECLWorkunit &info, unsigned flags)
  558. {
  559. if (!(flags & WUINFO_IncludeDebugValues))
  560. {
  561. if (version >= 1.50)
  562. {
  563. unsigned debugValueCount = 0;
  564. Owned<IStringIterator> debugs(&cw->getDebugValues());
  565. ForEach(*debugs)
  566. debugValueCount++;
  567. info.setDebugValueCount(debugValueCount);
  568. }
  569. return;
  570. }
  571. try
  572. {
  573. IArrayOf<IEspDebugValue> dv;
  574. Owned<IStringIterator> debugs(&cw->getDebugValues());
  575. ForEach(*debugs)
  576. {
  577. SCMStringBuffer name, val;
  578. debugs->str(name);
  579. cw->getDebugValue(name.str(),val);
  580. Owned<IEspDebugValue> t= createDebugValue("","");
  581. t->setName(name.str());
  582. t->setValue(val.str());
  583. dv.append(*t.getLink());
  584. }
  585. if (version >= 1.50)
  586. info.setDebugValueCount(dv.length());
  587. info.setDebugValues(dv);
  588. }
  589. catch(IException* e)
  590. {
  591. StringBuffer eMsg;
  592. ERRLOG("%s", e->errorMessage(eMsg).str());
  593. info.setDebugValuesDesc(eMsg.str());
  594. e->Release();
  595. }
  596. }
  597. const char *getGraphNum(const char *s,unsigned &num)
  598. {
  599. while (*s && !isdigit(*s))
  600. s++;
  601. num = 0;
  602. while (isdigit(*s))
  603. {
  604. num = num*10+*s-'0';
  605. s++;
  606. }
  607. return s;
  608. }
  609. bool WsWuInfo::hasSubGraphTimings()
  610. {
  611. StatisticsFilter filter;
  612. filter.setScopeType(SSTsubgraph);
  613. filter.setKind(StTimeElapsed);
  614. Owned<IConstWUStatisticIterator> times = &cw->getStatistics(&filter);
  615. return times->first();
  616. }
  617. bool WsWuInfo::legacyHasSubGraphTimings()
  618. {
  619. StatisticsFilter filter;
  620. filter.setScopeDepth(1); // only "global" timers.
  621. filter.setMeasure(SMeasureTimeNs);
  622. Owned<IConstWUStatisticIterator> times = &cw->getStatistics(&filter);
  623. ForEach(*times)
  624. {
  625. IConstWUStatistic & cur = times->query();
  626. SCMStringBuffer name;
  627. cur.getDescription(name, false);
  628. StringAttr graphName;
  629. unsigned graphNum;
  630. unsigned subGraphNum;
  631. unsigned subId;
  632. if (parseGraphTimerLabel(name.str(), graphName, graphNum, subGraphNum, subId))
  633. return true;
  634. }
  635. return false;
  636. }
  637. void WsWuInfo::getGraphInfo(IEspECLWorkunit &info, unsigned flags)
  638. {
  639. if (version > 1.01)
  640. {
  641. info.setHaveSubGraphTimings(false);
  642. if (hasSubGraphTimings() || legacyHasSubGraphTimings())
  643. info.setHaveSubGraphTimings(true);
  644. }
  645. if (!(flags & WUINFO_IncludeGraphs))
  646. return;
  647. try
  648. {
  649. SCMStringBuffer runningGraph;
  650. WUGraphIDType id;
  651. WUState st = cw->getState();
  652. bool running = (!(st==WUStateFailed || st==WUStateAborted || st==WUStateCompleted) && cw->getRunningGraph(runningGraph,id));
  653. IArrayOf<IEspECLGraph> graphs;
  654. Owned<IConstWUGraphMetaIterator> it = &cw->getGraphsMeta(GraphTypeAny);
  655. ForEach(*it)
  656. {
  657. IConstWUGraphMeta &graph = it->query();
  658. SCMStringBuffer name, label, type;
  659. graph.getName(name);
  660. graph.getLabel(label);
  661. graph.getTypeName(type);
  662. WUGraphState graphState = graph.getState();
  663. Owned<IEspECLGraph> g= createECLGraph("","");
  664. g->setName(name.str());
  665. g->setLabel(label.str());
  666. g->setType(type.str());
  667. if (WUGraphComplete == graphState)
  668. g->setComplete(true);
  669. else if (running && (WUGraphRunning == graphState))
  670. {
  671. g->setRunning(true);
  672. g->setRunningId(id);
  673. }
  674. else if (version > 1.13 && (WUGraphFailed == graphState))
  675. g->setFailed(true);
  676. if (version >= 1.53)
  677. {
  678. SCMStringBuffer s;
  679. Owned<IConstWUStatistic> whenGraphStarted = cw->getStatistic(NULL, name.str(), StWhenGraphStarted);
  680. Owned<IConstWUStatistic> whenGraphFinished = cw->getStatistic(NULL, name.str(), StWhenGraphFinished);
  681. if (whenGraphStarted)
  682. g->setWhenStarted(whenGraphStarted->getFormattedValue(s).str());
  683. if (whenGraphFinished)
  684. g->setWhenFinished(whenGraphFinished->getFormattedValue(s).str());
  685. }
  686. Owned<IConstWUGraphProgress> progress = cw->getGraphProgress(name.str());
  687. if (progress)
  688. {
  689. WUGraphState graphstate= progress->queryGraphState();
  690. if (graphstate == WUGraphComplete)
  691. g->setComplete(true);
  692. if (version > 1.13 && graphstate == WUGraphFailed)
  693. {
  694. g->setFailed(true);
  695. }
  696. }
  697. graphs.append(*g.getLink());
  698. }
  699. info.setGraphs(graphs);
  700. }
  701. catch(IException* e)
  702. {
  703. StringBuffer eMsg;
  704. ERRLOG("%s", e->errorMessage(eMsg).str());
  705. info.setGraphsDesc(eMsg.str());
  706. e->Release();
  707. }
  708. }
  709. void WsWuInfo::getGraphTimingData(IArrayOf<IConstECLTimingData> &timingData, unsigned flags)
  710. {
  711. StatisticsFilter filter(SCTall, SSTsubgraph, SMeasureTimeNs, StTimeElapsed);
  712. Owned<IConstWUStatisticIterator> times = &cw->getStatistics(&filter);
  713. bool matched = false;
  714. ForEach(*times)
  715. {
  716. IConstWUStatistic & cur = times->query();
  717. SCMStringBuffer scope;
  718. cur.getScope(scope);
  719. StringAttr graphName;
  720. unsigned graphNum;
  721. unsigned subGraphId;
  722. if (parseGraphScope(scope.str(), graphName, graphNum, subGraphId))
  723. {
  724. unsigned time = (unsigned)nanoToMilli(cur.getValue());
  725. SCMStringBuffer name;
  726. cur.getDescription(name, true);
  727. Owned<IEspECLTimingData> g = createECLTimingData();
  728. g->setName(name.str());
  729. g->setGraphNum(graphNum);
  730. g->setSubGraphNum(subGraphId); // Use the Id - the number is not known
  731. g->setMS(time);
  732. g->setMin(time/60000);
  733. timingData.append(*g.getClear());
  734. matched = true;
  735. }
  736. }
  737. if (!matched)
  738. legacyGetGraphTimingData(timingData, flags);
  739. }
  740. void WsWuInfo::legacyGetGraphTimingData(IArrayOf<IConstECLTimingData> &timingData, unsigned flags)
  741. {
  742. StatisticsFilter filter;
  743. filter.setScopeDepth(1);
  744. filter.setMeasure(SMeasureTimeNs);
  745. Owned<IConstWUStatisticIterator> times = &cw->getStatistics(&filter);
  746. ForEach(*times)
  747. {
  748. IConstWUStatistic & cur = times->query();
  749. SCMStringBuffer name;
  750. cur.getDescription(name, false); // was previously always filled in.
  751. StringAttr graphName;
  752. unsigned graphNum;
  753. unsigned subGraphNum;
  754. unsigned subId;
  755. if (parseGraphTimerLabel(name.str(), graphName, graphNum, subGraphNum, subId))
  756. {
  757. unsigned time = (unsigned)nanoToMilli(cur.getValue());
  758. Owned<IEspECLTimingData> g = createECLTimingData();
  759. g->setName(name.str());
  760. g->setGraphNum(graphNum);
  761. g->setSubGraphNum(subGraphNum);
  762. g->setGID(subId);
  763. g->setMS(time);
  764. g->setMin(time/60000);
  765. timingData.append(*g.getClear());
  766. }
  767. }
  768. }
  769. void WsWuInfo::getRoxieCluster(IEspECLWorkunit &info, unsigned flags)
  770. {
  771. if (version > 1.06)
  772. {
  773. Owned<IConstWURoxieQueryInfo> roxieQueryInfo = cw->getRoxieQueryInfo();
  774. if (roxieQueryInfo)
  775. {
  776. SCMStringBuffer roxieClusterName;
  777. roxieQueryInfo->getRoxieClusterName(roxieClusterName);
  778. info.setRoxieCluster(roxieClusterName.str());
  779. }
  780. }
  781. }
  782. void WsWuInfo::getEventScheduleFlag(IEspECLWorkunit &info)
  783. {
  784. info.setEventSchedule(0);
  785. if (info.getState() && !stricmp(info.getState(), "wait"))
  786. {
  787. info.setEventSchedule(2); //Can deschedule
  788. }
  789. else
  790. {
  791. Owned<IConstWorkflowItemIterator> it = cw->getWorkflowItems();
  792. if (it)
  793. {
  794. ForEach(*it)
  795. {
  796. IConstWorkflowItem *r = it->query();
  797. if (!r)
  798. continue;
  799. Owned<IWorkflowEvent> wfevent = r->getScheduleEvent();
  800. if (!wfevent)
  801. continue;
  802. if (!r->hasScheduleCount() || (r->queryScheduleCountRemaining() > 0))
  803. {
  804. info.setEventSchedule(1); //Can reschedule
  805. break;
  806. }
  807. }
  808. }
  809. }
  810. }
  811. unsigned WsWuInfo::getTotalThorTime()
  812. {
  813. StatisticsFilter filter;
  814. filter.setCreatorType(SCTsummary);
  815. filter.setScope(GLOBAL_SCOPE);
  816. filter.setKind(StTimeElapsed);
  817. //Should only be a single value
  818. unsigned totalThorTimeMS = 0;
  819. Owned<IConstWUStatisticIterator> times = &cw->getStatistics(&filter);
  820. ForEach(*times)
  821. {
  822. totalThorTimeMS += (unsigned)nanoToMilli(times->query().getValue());
  823. }
  824. return totalThorTimeMS;
  825. }
  826. unsigned WsWuInfo::getLegacyTotalThorTime()
  827. {
  828. //4.2.x backward compatibility - only scope depth and measure filters work
  829. StatisticsFilter filter;
  830. filter.setScopeDepth(1); // only global
  831. filter.setMeasure(SMeasureTimeNs);
  832. Owned<IConstWUStatisticIterator> times = &cw->getStatistics(&filter);
  833. SCMStringBuffer oldname;
  834. ForEach(*times)
  835. {
  836. times->query().getDescription(oldname, false); // description will be set up
  837. if (streq(oldname.str(), TOTALTHORTIME))
  838. return (unsigned)nanoToMilli(times->query().getValue());
  839. }
  840. return 0;
  841. }
  842. void WsWuInfo::getCommon(IEspECLWorkunit &info, unsigned flags)
  843. {
  844. SCMStringBuffer s;
  845. info.setWuid(cw->getWuid(s).str());
  846. info.setProtected(cw->isProtected() ? 1 : 0);
  847. info.setJobname(cw->getJobName(s).str());
  848. info.setOwner(cw->getUser(s).str());
  849. info.setCluster(cw->getClusterName(clusterName).str());
  850. info.setSnapshot(cw->getSnapshot(s).str());
  851. if ((cw->getState() == WUStateScheduled) && cw->aborting())
  852. {
  853. info.setStateID(WUStateAborting);
  854. info.setState("aborting");
  855. }
  856. else
  857. {
  858. info.setStateID(cw->getState());
  859. info.setState(cw->getStateDesc(s).str());
  860. }
  861. if (cw->isPausing())
  862. info.setIsPausing(true);
  863. getEventScheduleFlag(info);
  864. if (version > 1.27)
  865. {
  866. unsigned totalThorTimeMS = getTotalThorTime();
  867. if (totalThorTimeMS == 0)
  868. totalThorTimeMS = getLegacyTotalThorTime();
  869. if (totalThorTimeMS)
  870. {
  871. StringBuffer totalThorTimeStr;
  872. formatDuration(totalThorTimeStr, totalThorTimeMS);
  873. if (version > 1.52)
  874. info.setTotalClusterTime(totalThorTimeStr.str());
  875. else
  876. info.setTotalThorTime(totalThorTimeStr.str());
  877. }
  878. }
  879. WsWuDateTime dt;
  880. cw->getTimeScheduled(dt);
  881. if(dt.isValid())
  882. info.setDateTimeScheduled(dt.getString(s).str());
  883. getRoxieCluster(info, flags);
  884. }
  885. void WsWuInfo::getInfo(IEspECLWorkunit &info, unsigned flags)
  886. {
  887. getCommon(info, flags);
  888. SecAccessFlags accessFlag = getWsWorkunitAccess(context, *cw);
  889. info.setAccessFlag(accessFlag);
  890. SCMStringBuffer s;
  891. info.setStateEx(cw->getStateEx(s).str());
  892. info.setPriorityClass(cw->getPriority());
  893. info.setPriorityLevel(cw->getPriorityLevel());
  894. if (context.querySecManager())
  895. info.setScope(cw->getWuScope(s).str());
  896. info.setActionEx(cw->getActionEx(s).str());
  897. info.setDescription(cw->getDebugValue("description", s).str());
  898. if (version > 1.21)
  899. info.setXmlParams(cw->getXmlParams(s).str());
  900. info.setResultLimit(cw->getResultLimit());
  901. info.setArchived(false);
  902. info.setGraphCount(cw->getGraphCount());
  903. info.setSourceFileCount(cw->getSourceFileCount());
  904. info.setVariableCount(cw->getVariableCount());
  905. info.setTimerCount(getTimerCount());
  906. info.setSourceFileCount(cw->getSourceFileCount());
  907. info.setApplicationValueCount(cw->getApplicationValueCount());
  908. info.setHasDebugValue(cw->hasDebugValue("__calculated__complexity__"));
  909. getClusterInfo(info, flags);
  910. getExceptions(info, flags);
  911. getHelpers(info, flags);
  912. getGraphInfo(info, flags);
  913. getSourceFiles(info, flags);
  914. getResults(info, flags);
  915. getVariables(info, flags);
  916. getTimers(info, flags);
  917. getDebugValues(info, flags);
  918. getApplicationValues(info, flags);
  919. getWorkflow(info, flags);
  920. }
  921. unsigned WsWuInfo::getWorkunitThorLogInfo(IArrayOf<IEspECLHelpFile>& helpers, IEspECLWorkunit &info)
  922. {
  923. unsigned countThorLog = 0;
  924. IArrayOf<IConstThorLogInfo> thorLogList;
  925. if (cw->getWuidVersion() > 0)
  926. {
  927. SCMStringBuffer clusterName;
  928. cw->getClusterName(clusterName);
  929. if (!clusterName.length()) //Cluster name may not be set yet
  930. return countThorLog;
  931. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  932. if (!clusterInfo)
  933. {
  934. SCMStringBuffer wuid;
  935. WARNLOG("Cannot find TargetClusterInfo for workunit %s", cw->getWuid(wuid).str());
  936. return countThorLog;
  937. }
  938. unsigned numberOfSlaves = clusterInfo->getSize();
  939. BoolHash uniqueProcesses;
  940. Owned<IStringIterator> thorInstances = cw->getProcesses("Thor");
  941. ForEach (*thorInstances)
  942. {
  943. SCMStringBuffer processName;
  944. thorInstances->str(processName);
  945. if (processName.length() < 1)
  946. continue;
  947. bool* found = uniqueProcesses.getValue(processName.str());
  948. if (found && *found)
  949. continue;
  950. uniqueProcesses.setValue(processName.str(), true);
  951. StringBuffer groupName;
  952. getClusterThorGroupName(groupName, processName.str());
  953. Owned<IStringIterator> thorLogs = cw->getLogs("Thor", processName.str());
  954. ForEach (*thorLogs)
  955. {
  956. SCMStringBuffer logName;
  957. thorLogs->str(logName);
  958. if (logName.length() < 1)
  959. continue;
  960. countThorLog++;
  961. StringBuffer fileType;
  962. if (countThorLog < 2)
  963. fileType.append(File_ThorLog);
  964. else
  965. fileType.appendf("%s%d", File_ThorLog, countThorLog);
  966. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  967. h->setName(logName.str());
  968. h->setDescription(processName.str());
  969. h->setType(fileType.str());
  970. if (version >= 1.43)
  971. {
  972. offset_t fileSize;
  973. if (getFileSize(logName.str(), NULL, fileSize))
  974. h->setFileSize(fileSize);
  975. }
  976. helpers.append(*h.getLink());
  977. if (version < 1.38)
  978. continue;
  979. const char* pStr = logName.str();
  980. const char* ppStr = strstr(pStr, "/thormaster.");
  981. if (!ppStr)
  982. {
  983. WARNLOG("Invalid thorlog entry in workunit xml: %s", logName.str());
  984. continue;
  985. }
  986. ppStr += 12;
  987. StringBuffer logDate = ppStr;
  988. logDate.setLength(10);
  989. Owned<IEspThorLogInfo> thorLog = createThorLogInfo("","");
  990. thorLog->setProcessName(processName.str());
  991. thorLog->setClusterGroup(groupName.str());
  992. thorLog->setLogDate(logDate.str());
  993. thorLog->setNumberSlaves(numberOfSlaves);
  994. thorLogList.append(*thorLog.getLink());
  995. }
  996. }
  997. }
  998. else //legacy wuid
  999. {
  1000. Owned<IStringIterator> thorLogs = cw->getLogs("Thor");
  1001. ForEach (*thorLogs)
  1002. {
  1003. SCMStringBuffer name;
  1004. thorLogs->str(name);
  1005. if (name.length() < 1)
  1006. continue;
  1007. countThorLog++;
  1008. StringBuffer fileType;
  1009. if (countThorLog < 2)
  1010. fileType.append(File_ThorLog);
  1011. else
  1012. fileType.appendf("%s%d", File_ThorLog, countThorLog);
  1013. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  1014. h->setName(name.str());
  1015. h->setType(fileType.str());
  1016. if (version >= 1.43)
  1017. {
  1018. offset_t fileSize;
  1019. if (getFileSize(name.str(), NULL, fileSize))
  1020. h->setFileSize(fileSize);
  1021. }
  1022. helpers.append(*h.getLink());
  1023. }
  1024. StringBuffer logDir;
  1025. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  1026. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  1027. Owned<IPropertyTree> logTree = &constEnv->getPTree();
  1028. if (logTree)
  1029. logTree->getProp("EnvSettings/log", logDir);
  1030. if (logDir.length() > 0)
  1031. {
  1032. Owned<IStringIterator> debugs = cw->getLogs("Thor");
  1033. ForEach(*debugs)
  1034. {
  1035. SCMStringBuffer val;
  1036. debugs->str(val);
  1037. if (val.length() < 1)
  1038. continue;
  1039. const char* pStr = val.str();
  1040. const char* ppStr = strstr(pStr, logDir.str());
  1041. if (!ppStr)
  1042. {
  1043. WARNLOG("Invalid thorlog entry in workunit xml: %s", val.str());
  1044. continue;
  1045. }
  1046. const char* pProcessName = ppStr + logDir.length();
  1047. char sep = pProcessName[0];
  1048. StringBuffer processName = pProcessName + 1;
  1049. ppStr = strchr(pProcessName + 1, sep);
  1050. if (!ppStr)
  1051. {
  1052. WARNLOG("Invalid thorlog entry in workunit xml: %s", val.str());
  1053. continue;
  1054. }
  1055. processName.setLength(ppStr - pProcessName - 1);
  1056. StringBuffer groupName;
  1057. getClusterThorGroupName(groupName, processName.str());
  1058. StringBuffer logDate = ppStr + 12;
  1059. logDate.setLength(10);
  1060. Owned<IEspThorLogInfo> thorLog = createThorLogInfo("","");
  1061. thorLog->setProcessName(processName.str());
  1062. thorLog->setClusterGroup(groupName.str());
  1063. thorLog->setLogDate(logDate.str());
  1064. //for legacy wuid, the log name does not contain slaveNum. So, a user may not specify
  1065. //a slaveNum and we only display the first slave log if > 1 per IP.
  1066. thorLog->setNumberSlaves(0);
  1067. thorLogList.append(*thorLog.getLink());
  1068. }
  1069. }
  1070. }
  1071. if (thorLogList.length() > 0)
  1072. info.setThorLogList(thorLogList);
  1073. thorLogList.kill();
  1074. return countThorLog;
  1075. }
  1076. bool WsWuInfo::getClusterInfo(IEspECLWorkunit &info, unsigned flags)
  1077. {
  1078. if (version > 1.04)
  1079. {
  1080. StringArray allowedClusters;
  1081. SCMStringBuffer val;
  1082. cw->getAllowedClusters(val);
  1083. if (val.length() > 0)
  1084. {
  1085. const char* ptr = val.str();
  1086. while(*ptr != '\0')
  1087. {
  1088. StringBuffer onesub;
  1089. while(*ptr != '\0' && *ptr != ',')
  1090. {
  1091. onesub.append((char)(*ptr));
  1092. ptr++;
  1093. }
  1094. if(onesub.length() > 0)
  1095. allowedClusters.append(onesub.str());
  1096. if(*ptr != '\0')
  1097. ptr++;
  1098. }
  1099. }
  1100. if (allowedClusters.length() > 0)
  1101. info.setAllowedClusters(allowedClusters);
  1102. }
  1103. if (version > 1.23 && clusterName.length())
  1104. {
  1105. int clusterTypeFlag = 0;
  1106. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  1107. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  1108. Owned<IPropertyTree> root = &constEnv->getPTree();
  1109. if (!root)
  1110. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_DALI,"Cannot connect to DALI server.");
  1111. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  1112. if (clusterInfo.get())
  1113. {//Set thor flag or roxie flag in order to display some options for thor or roxie
  1114. ClusterType platform = clusterInfo->getPlatform();
  1115. if (isThorCluster(platform))
  1116. {
  1117. clusterTypeFlag=1;
  1118. if (version > 1.29)
  1119. info.setThorLCR(ThorLCRCluster == platform);
  1120. }
  1121. else if (RoxieCluster == platform)
  1122. clusterTypeFlag=2;
  1123. }
  1124. info.setClusterFlag(clusterTypeFlag);
  1125. }
  1126. return true;
  1127. }
  1128. void WsWuInfo::getWorkflow(IEspECLWorkunit &info, unsigned flags)
  1129. {
  1130. bool eventCountRemaining = false;
  1131. bool eventCountUnlimited = false;
  1132. try
  1133. {
  1134. info.setEventSchedule(0);
  1135. unsigned workflowsCount = 0;
  1136. IArrayOf<IConstECLWorkflow> workflows;
  1137. Owned<IConstWorkflowItemIterator> it = cw->getWorkflowItems();
  1138. if (it)
  1139. {
  1140. ForEach(*it)
  1141. {
  1142. IConstWorkflowItem *r = it->query();
  1143. if (r)
  1144. {
  1145. IWorkflowEvent *wfevent = r->getScheduleEvent();
  1146. if (wfevent)
  1147. {
  1148. Owned<IEspECLWorkflow> g;
  1149. if (flags & WUINFO_IncludeWorkflows)
  1150. {
  1151. StringBuffer id;
  1152. g.setown(createECLWorkflow("",""));
  1153. g->setWFID(id.appendf("%d", r->queryWfid()).str());
  1154. g->setEventName(wfevent->queryName());
  1155. g->setEventText(wfevent->queryText());
  1156. }
  1157. if (r->hasScheduleCount())
  1158. {
  1159. if (r->queryScheduleCountRemaining() > 0)
  1160. eventCountRemaining = true;
  1161. if (flags & WUINFO_IncludeWorkflows)
  1162. {
  1163. g->setCount(r->queryScheduleCount());
  1164. g->setCountRemaining(r->queryScheduleCountRemaining());
  1165. }
  1166. }
  1167. else
  1168. {
  1169. eventCountUnlimited = true;
  1170. }
  1171. workflowsCount++;
  1172. if (flags & WUINFO_IncludeWorkflows)
  1173. workflows.append(*g.getLink());
  1174. }
  1175. }
  1176. }
  1177. if (workflows.length() > 0)
  1178. info.setWorkflows(workflows);
  1179. workflows.kill();
  1180. }
  1181. if (version >= 1.50)
  1182. info.setWorkflowCount(workflowsCount);
  1183. }
  1184. catch(IException* e)
  1185. {
  1186. StringBuffer eMsg;
  1187. ERRLOG("%s", e->errorMessage(eMsg).str());
  1188. info.setWorkflowsDesc(eMsg.str());
  1189. e->Release();
  1190. }
  1191. if (info.getState() && !stricmp(info.getState(), "wait"))
  1192. info.setEventSchedule(2); //Can deschedule
  1193. else if (eventCountUnlimited || eventCountRemaining)
  1194. info.setEventSchedule(1); //Can reschedule
  1195. }
  1196. IDistributedFile* WsWuInfo::getLogicalFileData(IEspContext& context, const char* logicalName, bool& showFileContent)
  1197. {
  1198. StringBuffer username;
  1199. context.getUserID(username);
  1200. Owned<IUserDescriptor> userdesc(createUserDescriptor());
  1201. userdesc->set(username.str(), context.queryPassword());
  1202. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(logicalName, userdesc);
  1203. if (!df)
  1204. return NULL;
  1205. bool blocked;
  1206. if (df->isCompressed(&blocked) && !blocked)
  1207. return df.getClear();
  1208. IPropertyTree& properties = df->queryAttributes();
  1209. const char * format = properties.queryProp("@format");
  1210. if (format && (stricmp(format,"csv")==0 || memicmp(format, "utf", 3) == 0))
  1211. {
  1212. showFileContent = true;
  1213. return df.getClear();
  1214. }
  1215. const char * recordEcl = properties.queryProp("ECL");
  1216. if (!recordEcl)
  1217. return df.getClear();
  1218. MultiErrorReceiver errs;
  1219. Owned<IHqlExpression> ret = ::parseQuery(recordEcl, &errs);
  1220. showFileContent = errs.errCount() == 0;
  1221. return df.getClear();
  1222. }
  1223. void WsWuInfo::getEclSchemaChildFields(IArrayOf<IEspECLSchemaItem>& schemas, IHqlExpression * expr, bool isConditional)
  1224. {
  1225. if(!expr)
  1226. return;
  1227. ForEachChild(idx, expr)
  1228. getEclSchemaFields(schemas, expr->queryChild(idx), isConditional);
  1229. }
  1230. void WsWuInfo::getEclSchemaFields(IArrayOf<IEspECLSchemaItem>& schemas, IHqlExpression * expr, bool isConditional)
  1231. {
  1232. if(!expr)
  1233. return;
  1234. int ret = expr->getOperator();
  1235. switch (ret)
  1236. {
  1237. case no_record:
  1238. getEclSchemaChildFields(schemas, expr, isConditional);
  1239. break;
  1240. case no_ifblock:
  1241. {
  1242. getEclSchemaChildFields(schemas, expr->queryChild(1), true);
  1243. break;
  1244. }
  1245. case no_field:
  1246. {
  1247. if (expr->hasAttribute(__ifblockAtom))
  1248. break;
  1249. ITypeInfo * type = expr->queryType();
  1250. IAtom * name = expr->queryName();
  1251. IHqlExpression * nameAttr = expr->queryAttribute(namedAtom);
  1252. StringBuffer outname;
  1253. if (nameAttr && nameAttr->queryChild(0) && nameAttr->queryChild(0)->queryValue())
  1254. nameAttr->queryChild(0)->queryValue()->getStringValue(outname);
  1255. else
  1256. outname.append(name).toLowerCase();
  1257. if(type)
  1258. {
  1259. type_t tc = type->getTypeCode();
  1260. if (tc == type_row)
  1261. {
  1262. getEclSchemaChildFields(schemas, expr->queryRecord(), isConditional);
  1263. }
  1264. else
  1265. {
  1266. if (type->getTypeCode() == type_alien)
  1267. {
  1268. IHqlAlienTypeInfo * alien = queryAlienType(type);
  1269. type = alien->queryPhysicalType();
  1270. }
  1271. Owned<IEspECLSchemaItem> schema = createECLSchemaItem("","");
  1272. StringBuffer eclType;
  1273. type->getECLType(eclType);
  1274. schema->setColumnName(outname);
  1275. schema->setColumnType(eclType.str());
  1276. schema->setColumnTypeCode(tc);
  1277. schema->setIsConditional(isConditional);
  1278. schemas.append(*schema.getClear());
  1279. }
  1280. }
  1281. break;
  1282. }
  1283. }
  1284. }
  1285. bool WsWuInfo::getResultEclSchemas(IConstWUResult &r, IArrayOf<IEspECLSchemaItem>& schemas)
  1286. {
  1287. SCMStringBuffer schema;
  1288. r.getResultEclSchema(schema);
  1289. if (!schema.length())
  1290. return false;
  1291. MultiErrorReceiver errs;
  1292. Owned<IHqlExpression> expr = ::parseQuery(schema.str(), &errs);
  1293. if (errs.errCount() != 0)
  1294. return false;
  1295. getEclSchemaFields(schemas, expr, false);
  1296. return true;
  1297. }
  1298. void WsWuInfo::getResult(IConstWUResult &r, IArrayOf<IEspECLResult>& results, unsigned flags)
  1299. {
  1300. SCMStringBuffer name;
  1301. r.getResultName(name);
  1302. SCMStringBuffer filename;
  1303. r.getResultLogicalName(filename);
  1304. bool showFileContent = false;
  1305. Owned<IDistributedFile> df = NULL;
  1306. if (filename.length())
  1307. df.setown(getLogicalFileData(context, filename.str(), showFileContent));
  1308. StringBuffer value, link;
  1309. if (r.getResultStatus() == ResultStatusUndefined)
  1310. value.set("[undefined]");
  1311. else if (r.isResultScalar())
  1312. {
  1313. try
  1314. {
  1315. SCMStringBuffer xml;
  1316. r.getResultXml(xml);
  1317. Owned<IPropertyTree> props = createPTreeFromXMLString(xml.str(), ipt_caseInsensitive);
  1318. IPropertyTree *val = props->queryPropTree("Row/*");
  1319. if(val)
  1320. value.set(val->queryProp(NULL));
  1321. else
  1322. {
  1323. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  1324. Owned<INewResultSet> result;
  1325. result.setown(resultSetFactory->createNewResultSet(&r, wuid.str()));
  1326. Owned<IResultSetCursor> cursor(result->createCursor());
  1327. cursor->first();
  1328. if (cursor->getIsAll(0))
  1329. {
  1330. value.set("<All/>");
  1331. }
  1332. else
  1333. {
  1334. Owned<IResultSetCursor> childCursor = cursor->getChildren(0);
  1335. if (childCursor)
  1336. {
  1337. ForEach(*childCursor)
  1338. {
  1339. StringBuffer out;
  1340. StringBufferAdaptor adaptor(out);
  1341. childCursor->getDisplayText(adaptor, 0);
  1342. if (!value.length())
  1343. value.append('[');
  1344. else
  1345. value.append(", ");
  1346. value.append('\'').append(out.str()).append('\'');
  1347. }
  1348. if (value.length())
  1349. value.append(']');
  1350. }
  1351. }
  1352. }
  1353. }
  1354. catch(...)
  1355. {
  1356. value.append("[value not available]");
  1357. }
  1358. }
  1359. else
  1360. {
  1361. value.append('[').append(r.getResultTotalRowCount()).append(" rows]");
  1362. if((r.getResultSequence()>=0) && (!filename.length() || (df && df->queryAttributes().hasProp("ECL"))))
  1363. link.append(r.getResultSequence());
  1364. }
  1365. Owned<IEspECLResult> result= createECLResult("","");
  1366. if (flags & WUINFO_IncludeEclSchemas)
  1367. {
  1368. IArrayOf<IEspECLSchemaItem> schemas;
  1369. if (getResultEclSchemas(r, schemas))
  1370. result->setECLSchemas(schemas);
  1371. }
  1372. if (flags & WUINFO_IncludeXmlSchema)
  1373. {
  1374. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  1375. Owned<INewResultSet> rs = resultSetFactory->createNewResultSet(&r, wuid.str());
  1376. Owned<IResultSetCursor> cursor(rs->createCursor());
  1377. SCMStringBuffer xsd;
  1378. const IResultSetMetaData & meta = cursor->queryResultSet()->getMetaData();
  1379. meta.getXmlXPathSchema(xsd, false);
  1380. result->setXmlSchema(xsd.str());
  1381. }
  1382. if (filename.length())
  1383. result->setShowFileContent(showFileContent);
  1384. result->setName(name.str());
  1385. result->setLink(link.str());
  1386. result->setSequence(r.getResultSequence());
  1387. result->setValue(value.str());
  1388. result->setFileName(filename.str());
  1389. result->setIsSupplied(r.getResultStatus() == ResultStatusSupplied);
  1390. result->setTotal(r.getResultTotalRowCount());
  1391. results.append(*result.getLink());
  1392. }
  1393. void WsWuInfo::getResults(IEspECLWorkunit &info, unsigned flags)
  1394. {
  1395. try
  1396. {
  1397. unsigned count = 0;
  1398. IArrayOf<IEspECLResult> results;
  1399. Owned<IConstWUResultIterator> it = &(cw->getResults());
  1400. ForEach(*it)
  1401. {
  1402. IConstWUResult &r = it->query();
  1403. if(r.getResultSequence()>=0)
  1404. {
  1405. if (flags & WUINFO_IncludeResults)
  1406. getResult(r, results, flags);
  1407. count++;
  1408. }
  1409. }
  1410. if (version >= 1.17)
  1411. info.setResultCount(count);
  1412. if ((flags & WUINFO_IncludeResults) && results.length() > 0)
  1413. info.setResults(results);
  1414. results.kill();
  1415. }
  1416. catch(IException* e)
  1417. {
  1418. StringBuffer eMsg;
  1419. ERRLOG("%s", e->errorMessage(eMsg).str());
  1420. info.setResultsDesc(eMsg.str());
  1421. e->Release();
  1422. }
  1423. }
  1424. void WsWuInfo::getStats(StatisticsFilter& filter, bool createDescriptions, IArrayOf<IEspWUStatisticItem>& statistics)
  1425. {
  1426. Owned<IConstWUStatisticIterator> stats = &cw->getStatistics(&filter);
  1427. ForEach(*stats)
  1428. {
  1429. IConstWUStatistic & cur = stats->query();
  1430. StringBuffer xmlBuf, tsValue;
  1431. SCMStringBuffer curCreator, curScope, curDescription, curFormattedValue;
  1432. StatisticCreatorType curCreatorType = cur.getCreatorType();
  1433. StatisticScopeType curScopeType = cur.getScopeType();
  1434. StatisticMeasure curMeasure = cur.getMeasure();
  1435. StatisticKind curKind = cur.getKind();
  1436. unsigned __int64 value = cur.getValue();
  1437. unsigned __int64 count = cur.getCount();
  1438. unsigned __int64 max = cur.getMax();
  1439. unsigned __int64 ts = cur.getTimestamp();
  1440. cur.getCreator(curCreator);
  1441. cur.getScope(curScope);
  1442. cur.getDescription(curDescription, createDescriptions);
  1443. cur.getFormattedValue(curFormattedValue);
  1444. Owned<IEspWUStatisticItem> wuStatistic = createWUStatisticItem();
  1445. if (curCreatorType != SCTnone)
  1446. wuStatistic->setCreatorType(queryCreatorTypeName(curCreatorType));
  1447. if (curCreator.length())
  1448. wuStatistic->setCreator(curCreator.str());
  1449. if (curScopeType != SSTnone)
  1450. wuStatistic->setScopeType(queryScopeTypeName(curScopeType));
  1451. if (curScope.length())
  1452. wuStatistic->setScope(curScope.str());
  1453. if (curMeasure != SMeasureNone)
  1454. wuStatistic->setMeasure(queryMeasureName(curMeasure));
  1455. if (curKind != StKindNone)
  1456. wuStatistic->setKind(queryStatisticName(curKind));
  1457. wuStatistic->setRawValue(value);
  1458. wuStatistic->setValue(curFormattedValue.str());
  1459. if (count != 1)
  1460. wuStatistic->setCount(count);
  1461. if (max)
  1462. wuStatistic->setMax(max);
  1463. if (ts)
  1464. {
  1465. formatStatistic(tsValue, ts, SMeasureTimestampUs);
  1466. wuStatistic->setTimeStamp(tsValue.str());
  1467. }
  1468. if (curDescription.length())
  1469. wuStatistic->setDescription(curDescription.str());
  1470. statistics.append(*wuStatistic.getClear());
  1471. }
  1472. }
  1473. bool WsWuInfo::getFileSize(const char* fileName, const char* IPAddress, offset_t& fileSize)
  1474. {
  1475. if (!fileName || !*fileName)
  1476. return false;
  1477. Owned<IFile> aFile;
  1478. if (!IPAddress || !*IPAddress)
  1479. {
  1480. aFile.setown(createIFile(fileName));
  1481. }
  1482. else
  1483. {
  1484. RemoteFilename rfn;
  1485. rfn.setRemotePath(fileName);
  1486. SocketEndpoint ep(IPAddress);
  1487. rfn.setIp(ep);
  1488. aFile.setown(createIFile(rfn));
  1489. }
  1490. if (!aFile)
  1491. return false;
  1492. bool isDir;
  1493. CDateTime modtime;
  1494. if (!aFile->getInfo(isDir, fileSize, modtime) || isDir)
  1495. return false;
  1496. return true;
  1497. }
  1498. void WsWuInfo::getHelpFiles(IConstWUQuery* query, WUFileType type, IArrayOf<IEspECLHelpFile>& helpers)
  1499. {
  1500. if (!query)
  1501. return;
  1502. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  1503. ForEach(*iter)
  1504. {
  1505. SCMStringBuffer name, Ip, description;
  1506. IConstWUAssociatedFile & cur = iter->query();
  1507. if (cur.getType() != type)
  1508. continue;
  1509. cur.getName(name);
  1510. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  1511. h->setName(name.str());
  1512. h->setType(getEnumText(type, queryFileTypes));
  1513. if (version > 1.31)
  1514. {
  1515. cur.getIp(Ip);
  1516. h->setIPAddress(Ip.str());
  1517. cur.getDescription(description);
  1518. if ((description.length() < 1) && (name.length() > 0))
  1519. {
  1520. const char* desc = pathTail(name.str());
  1521. if (desc && *desc)
  1522. description.set(desc);
  1523. }
  1524. if (description.length() < 1)
  1525. description.set("Help File");
  1526. h->setDescription(description.str());
  1527. if (version >= 1.43)
  1528. {
  1529. offset_t fileSize;
  1530. if (getFileSize(name.str(), Ip.str(), fileSize))
  1531. h->setFileSize(fileSize);
  1532. }
  1533. }
  1534. helpers.append(*h.getLink());
  1535. }
  1536. }
  1537. void WsWuInfo::getSubFiles(IPropertyTreeIterator* f, IEspECLSourceFile* eclSuperFile, StringArray& fileNames)
  1538. {
  1539. IArrayOf<IEspECLSourceFile> files;
  1540. ForEach(*f)
  1541. {
  1542. IPropertyTree &query = f->query();
  1543. const char *clusterName = query.queryProp("@cluster");
  1544. const char *fileName = query.queryProp("@name");
  1545. int fileCount = query.getPropInt("@useCount");
  1546. bool bFound = false;
  1547. if (fileName && *fileName && (fileNames.length() > 0))
  1548. {
  1549. for (unsigned i = 0; i < fileNames.length(); i++ )
  1550. {
  1551. const char *fileName0 = fileNames.item(i);
  1552. if (!stricmp(fileName, fileName0))
  1553. {
  1554. bFound = true;
  1555. break;
  1556. }
  1557. }
  1558. }
  1559. if (bFound)
  1560. continue;
  1561. Owned<IEspECLSourceFile> file= createECLSourceFile("","");
  1562. if(clusterName && *clusterName)
  1563. {
  1564. file->setFileCluster(clusterName);
  1565. }
  1566. if (fileName && *fileName)
  1567. {
  1568. file->setName(fileName);
  1569. fileNames.append(fileName);
  1570. }
  1571. file->setCount(fileCount);
  1572. Owned<IPropertyTreeIterator> filetrees= query.getElements("Subfile");
  1573. if (filetrees->first())
  1574. {
  1575. file->setIsSuperFile(true);
  1576. getSubFiles(filetrees, file, fileNames);
  1577. }
  1578. files.append(*file.getLink());
  1579. }
  1580. eclSuperFile->setECLSourceFiles(files);
  1581. return;
  1582. }
  1583. bool WsWuInfo::getResourceInfo(StringArray &viewnames, StringArray &urls, unsigned flags)
  1584. {
  1585. if (!(flags & (WUINFO_IncludeResultsViewNames | WUINFO_IncludeResourceURLs)))
  1586. return true;
  1587. try
  1588. {
  1589. Owned<IWuWebView> wv = createWuWebView(*cw, NULL, NULL, NULL, false);
  1590. if (wv)
  1591. {
  1592. if (flags & WUINFO_IncludeResultsViewNames)
  1593. wv->getResultViewNames(viewnames);
  1594. if (flags & WUINFO_IncludeResourceURLs)
  1595. wv->getResourceURLs(urls, NULL);
  1596. }
  1597. return true;
  1598. }
  1599. catch(IException* e)
  1600. {
  1601. StringBuffer eMsg;
  1602. ERRLOG("%s", e->errorMessage(eMsg).str());
  1603. e->Release();
  1604. }
  1605. return false;
  1606. }
  1607. unsigned WsWuInfo::getResourceURLCount()
  1608. {
  1609. try
  1610. {
  1611. Owned<IWuWebView> wv = createWuWebView(*cw, NULL, NULL, NULL, false);
  1612. if (wv)
  1613. return wv->getResourceURLCount();
  1614. }
  1615. catch(IException* e)
  1616. {
  1617. StringBuffer eMsg;
  1618. ERRLOG("%s", e->errorMessage(eMsg).str());
  1619. e->Release();
  1620. }
  1621. return 0;
  1622. }
  1623. void appendIOStreamContent(MemoryBuffer &mb, IFileIOStream *ios, bool forDownload)
  1624. {
  1625. StringBuffer line;
  1626. bool eof = false;
  1627. while (!eof)
  1628. {
  1629. line.clear();
  1630. loop
  1631. {
  1632. char c;
  1633. size32_t numRead = ios->read(1, &c);
  1634. if (!numRead)
  1635. {
  1636. eof = true;
  1637. break;
  1638. }
  1639. line.append(c);
  1640. if (c=='\n')
  1641. break;
  1642. }
  1643. mb.append(line.length(), line.str());
  1644. if (!forDownload && (mb.length() > 640000))
  1645. break;
  1646. }
  1647. }
  1648. void WsWuInfo::getWorkunitEclAgentLog(const char* fileName, const char* agentPid, MemoryBuffer& buf)
  1649. {
  1650. if(!fileName || !*fileName)
  1651. throw MakeStringException(ECLWATCH_ECLAGENT_LOG_NOT_FOUND,"Log file not specified");
  1652. Owned<IFile> rFile = createIFile(fileName);
  1653. if(!rFile)
  1654. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open file %s.", fileName);
  1655. OwnedIFileIO rIO = rFile->openShared(IFOread,IFSHfull);
  1656. if(!rIO)
  1657. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE, "Cannot read file %s.", fileName);
  1658. OwnedIFileIOStream ios = createBufferedIOStream(rIO);
  1659. StringBuffer line;
  1660. bool eof = false;
  1661. bool wuidFound = false;
  1662. StringBuffer pidstr;
  1663. if (agentPid && *agentPid)
  1664. pidstr.appendf(" %s ", agentPid);
  1665. else
  1666. pidstr.appendf(" %5d ", cw->getAgentPID());
  1667. char const * pidchars = pidstr.str();
  1668. while(!eof)
  1669. {
  1670. line.clear();
  1671. loop
  1672. {
  1673. char c;
  1674. size32_t numRead = ios->read(1, &c);
  1675. if (!numRead)
  1676. {
  1677. eof = true;
  1678. break;
  1679. }
  1680. line.append(c);
  1681. if (c=='\n')
  1682. break;
  1683. }
  1684. //Retain all rows that match a unique program instance - by retaining all rows that match a pid
  1685. if(strstr(line.str(), pidchars))
  1686. {
  1687. //Check if this is a new instance using line sequence number
  1688. if (strncmp(line.str(), "00000000", 8) == 0)
  1689. {
  1690. if (wuidFound) //If the correct instance has been found, return that instance before the next instance.
  1691. break;
  1692. //The last instance is not a correct instance. Clean the buf in order to start a new instance.
  1693. buf.clear();
  1694. }
  1695. //If we spot the workunit id anywhere in the tacing for this pid then assume it is the correct instance.
  1696. if(!wuidFound && strstr(line.str(), wuid.str()))
  1697. wuidFound = true;
  1698. buf.append(line.length(), line.str());
  1699. }
  1700. }
  1701. if (buf.length() < 1)
  1702. buf.append(47, "(Not found a log line related to this workunit)");
  1703. }
  1704. void WsWuInfo::getWorkunitThorLog(const char* fileName, MemoryBuffer& buf)
  1705. {
  1706. if(!fileName || !*fileName)
  1707. throw MakeStringException(ECLWATCH_ECLAGENT_LOG_NOT_FOUND,"Log file not specified");
  1708. Owned<IFile> rFile = createIFile(fileName);
  1709. if (!rFile)
  1710. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE,"Cannot open file %s.",fileName);
  1711. OwnedIFileIO rIO = rFile->openShared(IFOread,IFSHfull);
  1712. if (!rIO)
  1713. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read file %s.",fileName);
  1714. OwnedIFileIOStream ios = createBufferedIOStream(rIO);
  1715. StringBuffer line;
  1716. bool eof = false;
  1717. bool include = false;
  1718. VStringBuffer startwuid("Started wuid=%s", wuid.str());
  1719. VStringBuffer endwuid("Finished wuid=%s", wuid.str());
  1720. const char *sw = startwuid.str();
  1721. const char *ew = endwuid.str();
  1722. while (!eof)
  1723. {
  1724. line.clear();
  1725. loop
  1726. {
  1727. char c;
  1728. size32_t numRead = ios->read(1, &c);
  1729. if (!numRead)
  1730. {
  1731. eof = true;
  1732. break;
  1733. }
  1734. line.append(c);
  1735. if (c=='\n')
  1736. break;
  1737. }
  1738. if (strstr(line.str(), sw))
  1739. include = true;
  1740. if (include)
  1741. buf.append(line.length(), line.str());
  1742. if (strstr(line.str(), ew))
  1743. include = false;
  1744. }
  1745. }
  1746. void WsWuInfo::getWorkunitThorSlaveLog(const char *groupName, const char *ipAddress, const char* logDate, const char* logDir, int slaveNum, MemoryBuffer& buf, bool forDownload)
  1747. {
  1748. if (isEmpty(logDir))
  1749. throw MakeStringException(ECLWATCH_INVALID_INPUT,"ThorSlave log path not specified.");
  1750. if (isEmpty(logDate))
  1751. throw MakeStringException(ECLWATCH_INVALID_INPUT,"ThorSlave log date not specified.");
  1752. StringBuffer slaveIPAddress, logName;
  1753. if (slaveNum > 0)
  1754. {
  1755. if (isEmpty(groupName))
  1756. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Thor group not specified.");
  1757. Owned<IGroup> nodeGroup = queryNamedGroupStore().lookup(groupName);
  1758. if (!nodeGroup || (nodeGroup->ordinality() == 0))
  1759. {
  1760. WARNLOG("Node group %s not found", groupName);
  1761. return;
  1762. }
  1763. nodeGroup->queryNode(slaveNum-1).endpoint().getIpText(slaveIPAddress);
  1764. if (slaveIPAddress.length() < 1)
  1765. throw MakeStringException(ECLWATCH_INVALID_INPUT,"ThorSlave log network address not found.");
  1766. logName.appendf("thorslave.%d.%s.log", slaveNum, logDate);
  1767. }
  1768. else
  1769. {//legacy wuid: a user types in an IP address for a thor slave
  1770. if (isEmpty(ipAddress))
  1771. throw MakeStringException(ECLWATCH_INVALID_INPUT,"ThorSlave address not specified.");
  1772. //thorslave.10.239.219.6_20100.2012_05_23.log
  1773. logName.appendf("thorslave.%s*.%s.log", ipAddress, logDate);
  1774. const char* portPtr = strchr(ipAddress, '_');
  1775. if (!portPtr)
  1776. slaveIPAddress.append(ipAddress);
  1777. else
  1778. {
  1779. StringBuffer ipAddressStr = ipAddress;
  1780. ipAddressStr.setLength(portPtr - ipAddress);
  1781. slaveIPAddress.append(ipAddressStr.str());
  1782. }
  1783. }
  1784. RemoteFilename rfn;
  1785. rfn.setRemotePath(logDir);
  1786. SocketEndpoint ep(slaveIPAddress.str());
  1787. rfn.setIp(ep);
  1788. Owned<IFile> dir = createIFile(rfn);
  1789. Owned<IDirectoryIterator> diriter = dir->directoryFiles(logName.str());
  1790. if (!diriter->first())
  1791. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find Thor slave log file %s.", logName.str());
  1792. Linked<IFile> logfile = &diriter->query();
  1793. diriter.clear();
  1794. dir.clear();
  1795. // logfile is now the file to load
  1796. OwnedIFileIO rIO = logfile->openShared(IFOread,IFSHfull);
  1797. if (!rIO)
  1798. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read file %s.",logName.str());
  1799. OwnedIFileIOStream ios = createBufferedIOStream(rIO);
  1800. if (slaveNum > 0)
  1801. {
  1802. StringBuffer line;
  1803. bool eof = false;
  1804. bool include = false;
  1805. VStringBuffer startwuid("Started wuid=%s", wuid.str());
  1806. VStringBuffer endwuid("Finished wuid=%s", wuid.str());
  1807. const char *sw = startwuid.str();
  1808. const char *ew = endwuid.str();
  1809. while (!eof)
  1810. {
  1811. line.clear();
  1812. loop
  1813. {
  1814. char c;
  1815. size32_t numRead = ios->read(1, &c);
  1816. if (!numRead)
  1817. {
  1818. eof = true;
  1819. break;
  1820. }
  1821. line.append(c);
  1822. if (c=='\n')
  1823. break;
  1824. }
  1825. if (strstr(line.str(), sw))
  1826. include = true;
  1827. if (include)
  1828. buf.append(line.length(), line.str());
  1829. if (strstr(line.str(), ew))
  1830. include = false;
  1831. }
  1832. }
  1833. else
  1834. {//legacy wuid
  1835. appendIOStreamContent(buf, ios.get(), forDownload);
  1836. }
  1837. }
  1838. void WsWuInfo::getWorkunitResTxt(MemoryBuffer& buf)
  1839. {
  1840. Owned<IConstWUQuery> query = cw->getQuery();
  1841. if(!query)
  1842. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  1843. SCMStringBuffer resname;
  1844. queryDllServer().getDll(query->getQueryResTxtName(resname).str(), buf);
  1845. }
  1846. void WsWuInfo::getWorkunitArchiveQuery(MemoryBuffer& buf)
  1847. {
  1848. Owned<IConstWUQuery> query = cw->getQuery();
  1849. if(!query)
  1850. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  1851. SCMStringBuffer queryText;
  1852. query->getQueryText(queryText);
  1853. if ((queryText.length() < 1) || !isArchiveQuery(queryText.str()))
  1854. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Archive Query not found for workunit %s.", wuid.str());
  1855. buf.append(queryText.length(), queryText.str());
  1856. }
  1857. void WsWuInfo::getWorkunitQueryShortText(MemoryBuffer& buf)
  1858. {
  1859. Owned<IConstWUQuery> query = cw->getQuery();
  1860. if(!query)
  1861. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  1862. SCMStringBuffer queryText;
  1863. query->getQueryShortText(queryText);
  1864. if (queryText.length() < 1)
  1865. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU, "No query for workunit %s.",wuid.str());
  1866. buf.append(queryText.length(), queryText.str());
  1867. }
  1868. void WsWuInfo::getWorkunitDll(StringBuffer &dllname, MemoryBuffer& buf)
  1869. {
  1870. Owned<IConstWUQuery> query = cw->getQuery();
  1871. if(!query)
  1872. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  1873. StringBufferAdaptor isvName(dllname);
  1874. query->getQueryDllName(isvName);
  1875. queryDllServer().getDll(dllname.str(), buf);
  1876. }
  1877. void WsWuInfo::getWorkunitXml(const char* plainText, MemoryBuffer& buf)
  1878. {
  1879. const char* header;
  1880. if (plainText && (!stricmp(plainText, "yes")))
  1881. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  1882. else
  1883. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet href=\"../esp/xslt/xmlformatter.xsl\" type=\"text/xsl\"?>";
  1884. SCMStringBuffer xml;
  1885. exportWorkUnitToXML(cw, xml, true, false);
  1886. buf.append(strlen(header), header);
  1887. buf.append(xml.length(), xml.str());
  1888. }
  1889. void WsWuInfo::getWorkunitCpp(const char *cppname, const char* description, const char* ipAddress, MemoryBuffer& buf, bool forDownload)
  1890. {
  1891. if (isEmpty(description))
  1892. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File not specified.");
  1893. if (isEmpty(ipAddress))
  1894. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File location not specified.");
  1895. if (isEmpty(cppname))
  1896. throw MakeStringException(ECLWATCH_INVALID_FILE_NAME, "File path not specified.");
  1897. RemoteFilename rfn;
  1898. rfn.setRemotePath(cppname);
  1899. SocketEndpoint ep(ipAddress);
  1900. rfn.setIp(ep);
  1901. Owned<IFile> cppfile = createIFile(rfn);
  1902. if (!cppfile)
  1903. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open %s.", description);
  1904. OwnedIFileIO rIO = cppfile->openShared(IFOread,IFSHfull);
  1905. if (!rIO)
  1906. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read %s.", description);
  1907. OwnedIFileIOStream ios = createBufferedIOStream(rIO);
  1908. if (!ios)
  1909. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read %s.", description);
  1910. appendIOStreamContent(buf, ios.get(), forDownload);
  1911. }
  1912. void WsWuInfo::getWorkunitAssociatedXml(const char* name, const char* ipAddress, const char* plainText,
  1913. const char* description, bool forDownload, MemoryBuffer& buf)
  1914. {
  1915. if (isEmpty(description)) //'File Name' as shown in WU Details page
  1916. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File not specified.");
  1917. if (isEmpty(ipAddress))
  1918. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File location not specified.");
  1919. if (isEmpty(name)) //file name with full path
  1920. throw MakeStringException(ECLWATCH_INVALID_FILE_NAME, "File path not specified.");
  1921. RemoteFilename rfn;
  1922. rfn.setRemotePath(name);
  1923. SocketEndpoint ep(ipAddress);
  1924. rfn.setIp(ep);
  1925. Owned<IFile> rFile = createIFile(rfn);
  1926. if (!rFile)
  1927. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open %s.", description);
  1928. OwnedIFileIO rIO = rFile->openShared(IFOread,IFSHfull);
  1929. if (!rIO)
  1930. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read %s.", description);
  1931. OwnedIFileIOStream ios = createBufferedIOStream(rIO);
  1932. if (!ios)
  1933. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read %s.", description);
  1934. const char* header;
  1935. if (plainText && (!stricmp(plainText, "yes")))
  1936. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  1937. else
  1938. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet href=\"../esp/xslt/xmlformatter.xsl\" type=\"text/xsl\"?>";
  1939. buf.append(strlen(header), header);
  1940. appendIOStreamContent(buf, ios.get(), forDownload);
  1941. }
  1942. WsWuSearch::WsWuSearch(IEspContext& context,const char* owner,const char* state,const char* cluster,const char* startDate,const char* endDate,const char* ecl,const char* jobname,const char* appname,const char* appkey,const char* appvalue)
  1943. {
  1944. SecAccessFlags accessOwn;
  1945. SecAccessFlags accessOthers;
  1946. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1947. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1948. StringBuffer xpath("*");
  1949. if(ecl && *ecl)
  1950. xpath.append("[Query/Text=?~\"*").append(ecl).append("*\"]");
  1951. if(state && *state)
  1952. xpath.append("[@state=\"").append(state).append("\"]");
  1953. if(cluster && *cluster)
  1954. xpath.append("[@clusterName=\"").append(cluster).append("\"]");
  1955. if(owner && *owner)
  1956. xpath.append("[@submitID=?~\"").append(owner).append("\"]");
  1957. if(jobname && *jobname)
  1958. xpath.append("[@jobName=?~\"*").append(jobname).append("*\"]");
  1959. if((appname && *appname) || (appkey && *appkey) || (appvalue && *appvalue))
  1960. {
  1961. xpath.append("[Application/").append(appname && *appname ? appname : "*");
  1962. xpath.append("/").append(appkey && *appkey ? appkey : "*");
  1963. if(appvalue && *appvalue)
  1964. xpath.append("=?~\"").append(appvalue).append("\"");
  1965. xpath.append("]");
  1966. }
  1967. Owned<IConstWorkUnitIterator> it(factory->getWorkUnitsByXPath(xpath.str()));
  1968. StringBuffer wuFrom, wuTo;
  1969. if(startDate && *startDate)
  1970. createWuidFromDate(startDate, wuFrom);
  1971. if(endDate && *endDate)
  1972. createWuidFromDate(endDate, wuTo);
  1973. ForEach(*it)
  1974. {
  1975. IConstWorkUnit &cw = it->query();
  1976. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1977. continue;
  1978. SCMStringBuffer wuid;
  1979. cw.getWuid(wuid);
  1980. if (wuFrom.length() && strcmp(wuid.str(),wuFrom.str())<0)
  1981. continue;
  1982. if (wuTo.length() && strcmp(wuid.str(),wuTo.str())>0)
  1983. continue;
  1984. if (state && *state)
  1985. {
  1986. SCMStringBuffer descr;
  1987. if(!strieq(cw.getStateDesc(descr).str(),state))
  1988. continue;
  1989. }
  1990. wuids.push_back(wuid.str());
  1991. }
  1992. std::sort(wuids.begin(),wuids.end(),std::greater<std::string>());
  1993. }
  1994. StringBuffer& WsWuSearch::createWuidFromDate(const char* timestamp,StringBuffer& s)
  1995. {
  1996. CDateTime wuTime;
  1997. wuTime.setString(timestamp,NULL,true);
  1998. unsigned year, month, day, hour, minute, second, nano;
  1999. wuTime.getDate(year, month, day, true);
  2000. wuTime.getTime(hour, minute, second, nano, true);
  2001. s.appendf("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
  2002. return s;
  2003. }
  2004. struct CompareData
  2005. {
  2006. CompareData(const char* _filter): filter(_filter) {}
  2007. bool operator()(const Linked<DataCacheElement>& e) const
  2008. {
  2009. return stricmp(e->m_filter.c_str(),filter)==0;
  2010. }
  2011. const char* filter;
  2012. };
  2013. DataCacheElement* DataCache::lookup(IEspContext &context, const char* filter, unsigned timeOutMin)
  2014. {
  2015. CriticalBlock block(crit);
  2016. if (cache.size() < 1)
  2017. return NULL;
  2018. //erase data if it should be
  2019. CDateTime timeNow;
  2020. int timeout = timeOutMin;
  2021. timeNow.setNow();
  2022. timeNow.adjustTime(-timeout);
  2023. while (true)
  2024. {
  2025. std::list<Linked<DataCacheElement> >::iterator list_iter = cache.begin();
  2026. if (list_iter == cache.end())
  2027. break;
  2028. DataCacheElement* awu = list_iter->get();
  2029. if (!awu || (awu->m_timeCached > timeNow))
  2030. break;
  2031. cache.pop_front();
  2032. }
  2033. if (cache.size() < 1)
  2034. return NULL;
  2035. //Check whether we have the data cache for this cluster. If yes, get the version
  2036. std::list<Linked<DataCacheElement> >::iterator it = std::find_if(cache.begin(),cache.end(),CompareData(filter));
  2037. if(it!=cache.end())
  2038. {
  2039. return it->getLink();
  2040. }
  2041. return NULL;
  2042. }
  2043. void DataCache::add(const char* filter, const char* data, const char* name, const char* localName, const char* wuid,
  2044. const char* resultName, unsigned seq, __int64 start, unsigned count, __int64 requested, __int64 total)
  2045. {
  2046. CriticalBlock block(crit);
  2047. //Save new data
  2048. Owned<DataCacheElement> e=new DataCacheElement(filter, data, name, localName, wuid, resultName, seq, start, count, requested, total);
  2049. if (cacheSize > 0)
  2050. {
  2051. if (cache.size() >= cacheSize)
  2052. cache.pop_front();
  2053. cache.push_back(e.get());
  2054. }
  2055. return;
  2056. }
  2057. struct CompareArchivedWUs
  2058. {
  2059. CompareArchivedWUs(const char* _filter): filter(_filter) {}
  2060. bool operator()(const Linked<ArchivedWuCacheElement>& e) const
  2061. {
  2062. return stricmp(e->m_filter.c_str(),filter)==0;
  2063. }
  2064. const char* filter;
  2065. };
  2066. ArchivedWuCacheElement* ArchivedWuCache::lookup(IEspContext &context, const char* filter, const char* sashaUpdatedWhen, unsigned timeOutMin)
  2067. {
  2068. CriticalBlock block(crit);
  2069. if (cache.size() < 1)
  2070. return NULL;
  2071. //erase data if it should be
  2072. CDateTime timeNow;
  2073. int timeout = timeOutMin;
  2074. timeNow.setNow();
  2075. timeNow.adjustTime(-timeout);
  2076. while (true)
  2077. {
  2078. std::list<Linked<ArchivedWuCacheElement> >::iterator list_iter = cache.begin();
  2079. if (list_iter == cache.end())
  2080. break;
  2081. ArchivedWuCacheElement* awu = list_iter->get();
  2082. if (awu && !stricmp(sashaUpdatedWhen, awu->m_sashaUpdatedWhen.c_str()) && (awu->m_timeCached > timeNow))
  2083. break;
  2084. cache.pop_front();
  2085. }
  2086. if (cache.size() < 1)
  2087. return NULL;
  2088. //Check whether we have the data cache for this cluster. If yes, get the version
  2089. std::list<Linked<ArchivedWuCacheElement> >::iterator it = std::find_if(cache.begin(),cache.end(),CompareArchivedWUs(filter));
  2090. if(it!=cache.end())
  2091. return it->getLink();
  2092. return NULL;
  2093. }
  2094. void ArchivedWuCache::add(const char* filter, const char* sashaUpdatedWhen, bool hasNextPage, unsigned numWUsReturned, IArrayOf<IEspECLWorkunit>& wus)
  2095. {
  2096. CriticalBlock block(crit);
  2097. //Save new data
  2098. Owned<ArchivedWuCacheElement> e=new ArchivedWuCacheElement(filter, sashaUpdatedWhen, hasNextPage, numWUsReturned, wus);
  2099. if (cacheSize > 0)
  2100. {
  2101. if (cache.size() >= cacheSize)
  2102. cache.pop_front();
  2103. cache.push_back(e.get());
  2104. }
  2105. return;
  2106. }
  2107. WsWuJobQueueAuditInfo::WsWuJobQueueAuditInfo(IEspContext &context, const char *cluster, const char *from , const char *to, CHttpResponse* response, const char *xls)
  2108. {
  2109. if(!response)
  2110. return;
  2111. unsigned maxDisplay = 125;
  2112. IArrayOf<IEspThorQueue> items;
  2113. CDateTime fromTime;
  2114. CDateTime toTime;
  2115. StringBuffer fromstr;
  2116. StringBuffer tostr;
  2117. if(from && *from)
  2118. {
  2119. fromTime.setString(from,NULL,false);
  2120. fromTime.getString(fromstr, false);
  2121. }
  2122. if(to && *to)
  2123. {
  2124. toTime.setString(to,NULL,false);
  2125. toTime.getString(tostr, false);
  2126. }
  2127. StringBuffer filter("ThorQueueMonitor");
  2128. if(notEmpty(cluster))
  2129. filter.appendf(",%s", cluster);
  2130. StringAttrArray lines;
  2131. queryAuditLogs(fromTime, toTime, filter.str(), lines);
  2132. unsigned countLines = 0;
  2133. unsigned maxConnected = 0;
  2134. unsigned longestQueue = 0;
  2135. ForEachItemIn(idx, lines)
  2136. {
  2137. const char* line = lines.item(idx).text;
  2138. if(!line || !*line)
  2139. continue;
  2140. if (idx < (lines.length() - 1))
  2141. getAuditLineInfo(line, longestQueue, maxConnected, maxDisplay, 1, items);
  2142. else
  2143. getAuditLineInfo(line, longestQueue, maxConnected, maxDisplay, 2, items);
  2144. countLines++;
  2145. }
  2146. StringBuffer responsebuf;
  2147. if (items.length() < 1)
  2148. {
  2149. responsebuf.append("<script language=\"javascript\">\r\nparent.displayQEnd(\'No data found\')</script>\r\n");
  2150. response->sendChunk(responsebuf.str());
  2151. return;
  2152. }
  2153. unsigned itemCount = items.length();
  2154. if (itemCount > maxDisplay)
  2155. itemCount = maxDisplay;
  2156. responsebuf.append("<script language=\"javascript\">parent.displayQLegend()</script>\r\n");
  2157. response->sendChunk(responsebuf.str());
  2158. responsebuf.clear();
  2159. responsebuf.append("<script language=\"javascript\">parent.displayQBegin(").append(longestQueue).append(",").append(maxConnected).append(",").append(itemCount).append(")</script>\r\n");
  2160. response->sendChunk(responsebuf.str());
  2161. responsebuf.clear();
  2162. responsebuf.append("<script language=\"javascript\">\r\n");
  2163. //bool displayDT = false;
  2164. unsigned count = 0;
  2165. unsigned jobpending=0;
  2166. ForEachItemIn(i,items)
  2167. {
  2168. IEspThorQueue& tq = items.item(i);
  2169. //displayDT = !displayDT;
  2170. count++;
  2171. if (count > maxDisplay)
  2172. break;
  2173. StringBuffer countStr, dtStr;
  2174. countStr.appendulong(count);
  2175. //if (displayDT)
  2176. dtStr = tq.getDT();
  2177. responsebuf.append("parent.displayQueue(\'").append(count).append("\',\'").append(dtStr.str()).append("\',\'").append(tq.getRunningWUs()).append("\',");
  2178. responsebuf.append("\'").append(tq.getQueuedWUs()).append("\',\'").append(tq.getWaitingThors()).append("\',");
  2179. responsebuf.append("\'").append(tq.getConnectedThors()).append("\',\'").append(tq.getIdledThors()).append("\',");
  2180. responsebuf.append("\'").append(tq.getRunningWU1()).append("\',\'").append(tq.getRunningWU2()).append("\')\r\n");
  2181. if(++jobpending>=50)
  2182. {
  2183. responsebuf.append("</script>\r\n");
  2184. response->sendChunk(responsebuf.str());
  2185. responsebuf.clear();
  2186. responsebuf.append("<script language=\"javascript\">\r\n");
  2187. jobpending=0;
  2188. }
  2189. }
  2190. StringBuffer countStr;
  2191. countStr.appendulong(count);
  2192. StringBuffer msg("<table><tr><td>");
  2193. msg.append("Total Records in the Time Period: ").append(items.length()).append(" (<a href=\"/WsWorkunits/WUClusterJobQueueLOG?").append(xls).append("\">txt</a>...<a href=\"/WsWorkunits/WUClusterJobQueueXLS?").append(xls).append("\">xls</a>).");
  2194. msg.append("</td></tr><tr><td>");
  2195. if (count > maxDisplay)
  2196. msg.append("Displayed: First ").append(maxDisplay).append(". ");
  2197. msg.append("Max. Queue Length: ").append(longestQueue).append(".");
  2198. msg.append("</td></tr></table>");
  2199. responsebuf.append("parent.displayQEnd(\'").append(msg).append("\')</script>\r\n");
  2200. response->sendChunk(responsebuf.str());
  2201. }
  2202. void WsWuJobQueueAuditInfo::getAuditLineInfo(const char* line, unsigned& longestQueue, unsigned& maxConnected, unsigned maxDisplay, unsigned showAll, IArrayOf<IEspThorQueue>& items)
  2203. {
  2204. //2009-08-12 02:44:12 ,ThorQueueMonitor,thor400_88_dev,0,0,1,1,114,---,---
  2205. if(!line || !*line)
  2206. return;
  2207. Owned<IEspThorQueue> tq = createThorQueue();
  2208. StringBuffer dt, runningWUs, queuedWUs, waitingThors, connectedThors, idledThors, runningWU1, runningWU2;
  2209. // date/time
  2210. const char* bptr = line;
  2211. const char* eptr = strchr(bptr, ',');
  2212. if(eptr)
  2213. dt.append(eptr - bptr, bptr);
  2214. else
  2215. dt.append(bptr);
  2216. tq->setDT(dt.str());
  2217. if(!eptr)
  2218. {
  2219. if (checkNewThorQueueItem(tq, showAll, items))
  2220. items.append(*tq.getClear());
  2221. return;
  2222. }
  2223. //skip title
  2224. bptr = eptr + 1;
  2225. eptr = strchr(bptr, ',');
  2226. if(!eptr)
  2227. {
  2228. if (checkNewThorQueueItem(tq, showAll, items))
  2229. items.append(*tq.getClear());
  2230. return;
  2231. }
  2232. //skip queue name
  2233. bptr = eptr + 1;
  2234. eptr = strchr(bptr, ',');
  2235. if(!eptr)
  2236. {
  2237. if (checkNewThorQueueItem(tq, showAll, items))
  2238. items.append(*tq.getClear());
  2239. return;
  2240. }
  2241. //running
  2242. bptr = eptr + 1;
  2243. eptr = strchr(bptr, ',');
  2244. if(eptr)
  2245. runningWUs.append(eptr - bptr, bptr);
  2246. else
  2247. runningWUs.append(bptr);
  2248. tq->setRunningWUs(runningWUs.str());
  2249. if(!eptr)
  2250. {
  2251. if (checkNewThorQueueItem(tq, showAll, items))
  2252. items.append(*tq.getClear());
  2253. return;
  2254. }
  2255. //queued
  2256. bptr = eptr + 1;
  2257. eptr = strchr(bptr, ',');
  2258. if(eptr)
  2259. queuedWUs.append(eptr - bptr, bptr);
  2260. else
  2261. queuedWUs.append(bptr);
  2262. if (maxDisplay > items.length())
  2263. {
  2264. unsigned queueLen = atoi(queuedWUs.str());
  2265. if (queueLen > longestQueue)
  2266. longestQueue = queueLen;
  2267. }
  2268. tq->setQueuedWUs(queuedWUs.str());
  2269. if(!eptr)
  2270. {
  2271. if (checkNewThorQueueItem(tq, showAll, items))
  2272. items.append(*tq.getClear());
  2273. return;
  2274. }
  2275. //waiting
  2276. bptr = eptr + 1;
  2277. eptr = strchr(bptr, ',');
  2278. if(eptr)
  2279. waitingThors.append(eptr - bptr, bptr);
  2280. else
  2281. waitingThors.append(bptr);
  2282. tq->setWaitingThors(waitingThors.str());
  2283. if(!eptr)
  2284. {
  2285. if (checkNewThorQueueItem(tq, showAll, items))
  2286. items.append(*tq.getClear());
  2287. return;
  2288. }
  2289. //connected
  2290. bptr = eptr + 1;
  2291. eptr = strchr(bptr, ',');
  2292. if(eptr)
  2293. connectedThors.append(eptr - bptr, bptr);
  2294. else
  2295. connectedThors.append(bptr);
  2296. if (maxDisplay > items.length())
  2297. {
  2298. unsigned connnectedLen = atoi(connectedThors.str());
  2299. if (connnectedLen > maxConnected)
  2300. maxConnected = connnectedLen;
  2301. }
  2302. tq->setConnectedThors(connectedThors.str());
  2303. if(!eptr)
  2304. {
  2305. if (checkNewThorQueueItem(tq, showAll, items))
  2306. items.append(*tq.getClear());
  2307. return;
  2308. }
  2309. //idled
  2310. bptr = eptr + 1;
  2311. eptr = strchr(bptr, ',');
  2312. if(eptr)
  2313. idledThors.append(eptr - bptr, bptr);
  2314. else
  2315. idledThors.append(bptr);
  2316. tq->setIdledThors(idledThors.str());
  2317. if(!eptr)
  2318. {
  2319. items.append(*tq.getClear());
  2320. return;
  2321. }
  2322. //runningWU1
  2323. bptr = eptr + 1;
  2324. eptr = strchr(bptr, ',');
  2325. if(eptr)
  2326. runningWU1.append(eptr - bptr, bptr);
  2327. else
  2328. {
  2329. runningWU1.append(bptr);
  2330. }
  2331. if (!strcmp(runningWU1.str(), "---"))
  2332. runningWU1.clear();
  2333. if (runningWU1.length() > 0)
  2334. tq->setRunningWU1(runningWU1.str());
  2335. if(!eptr)
  2336. {
  2337. if (checkNewThorQueueItem(tq, showAll, items))
  2338. items.append(*tq.getClear());
  2339. return;
  2340. }
  2341. //runningWU2
  2342. bptr = eptr + 1;
  2343. eptr = strchr(bptr, ',');
  2344. if(eptr)
  2345. runningWU2.append(eptr - bptr, bptr);
  2346. else
  2347. {
  2348. runningWU2.append(bptr);
  2349. }
  2350. if (!strcmp(runningWU2.str(), "---"))
  2351. runningWU2.clear();
  2352. if (runningWU2.length() > 0)
  2353. tq->setRunningWU2(runningWU2.str());
  2354. if (checkNewThorQueueItem(tq, showAll, items))
  2355. items.append(*tq.getClear());
  2356. }
  2357. bool WsWuJobQueueAuditInfo::checkSameStrings(const char* s1, const char* s2)
  2358. {
  2359. if (s1)
  2360. {
  2361. if (!s2)
  2362. return false;
  2363. if (strcmp(s1, s2))
  2364. return false;
  2365. }
  2366. else if (s2)
  2367. {
  2368. if (!s1)
  2369. return false;
  2370. }
  2371. return true;
  2372. }
  2373. bool WsWuJobQueueAuditInfo::checkNewThorQueueItem(IEspThorQueue* tq, unsigned showAll, IArrayOf<IEspThorQueue>& items)
  2374. {
  2375. bool bAdd = false;
  2376. if (showAll < 1) //show every lines
  2377. bAdd = true;
  2378. else if (items.length() < 1)
  2379. bAdd = true;
  2380. else if (showAll > 1) //last line now
  2381. {
  2382. IEspThorQueue& tq0 = items.item(items.length()-1);
  2383. if (!checkSameStrings(tq->getDT(), tq0.getDT()))
  2384. bAdd = true;
  2385. }
  2386. else
  2387. {
  2388. IEspThorQueue& tq0 = items.item(items.length()-1);
  2389. if (!checkSameStrings(tq->getRunningWUs(), tq0.getRunningWUs()))
  2390. bAdd = true;
  2391. if (!checkSameStrings(tq->getQueuedWUs(), tq0.getQueuedWUs()))
  2392. bAdd = true;
  2393. if (!checkSameStrings(tq->getConnectedThors(), tq0.getConnectedThors()))
  2394. bAdd = true;
  2395. if (!checkSameStrings(tq->getConnectedThors(), tq0.getConnectedThors()))
  2396. bAdd = true;
  2397. if (!checkSameStrings(tq->getRunningWU1(), tq0.getRunningWU1()))
  2398. bAdd = true;
  2399. if (!checkSameStrings(tq->getRunningWU2(), tq0.getRunningWU2()))
  2400. bAdd = true;
  2401. }
  2402. return bAdd;
  2403. }
  2404. void xsltTransform(const char* xml, const char* sheet, IProperties *params, StringBuffer& ret)
  2405. {
  2406. StringBuffer xsl;
  2407. if(!checkFileExists(sheet))
  2408. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST, "Could not find stylesheet %s.",sheet);
  2409. Owned<IXslProcessor> proc = getXslProcessor();
  2410. Owned<IXslTransform> trans = proc->createXslTransform();
  2411. trans->setXmlSource(xml, strlen(xml));
  2412. trans->loadXslFromFile(sheet);
  2413. trans->copyParameters(params);
  2414. trans->transform(ret);
  2415. }
  2416. bool addToQueryString(StringBuffer &queryString, const char *name, const char *value, const char delim)
  2417. {
  2418. if (isEmpty(name) || isEmpty(value))
  2419. return false;
  2420. if (queryString.length() > 0)
  2421. queryString.append(delim);
  2422. queryString.append(name).append("=").append(value);
  2423. return true;
  2424. }
  2425. int WUSchedule::run()
  2426. {
  2427. try
  2428. {
  2429. while(!stopping)
  2430. {
  2431. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  2432. Owned<IConstWorkUnitIterator> itr = factory->getWorkUnitsByState(WUStateScheduled);
  2433. if (itr)
  2434. {
  2435. ForEach(*itr)
  2436. {
  2437. try
  2438. {
  2439. IConstWorkUnit & cw = itr->query();
  2440. if (cw.aborting())
  2441. {
  2442. WorkunitUpdate wu(&cw.lock());
  2443. wu->setState(WUStateAborted);
  2444. continue;
  2445. }
  2446. WsWuDateTime dt, now;
  2447. now.setNow();
  2448. cw.getTimeScheduled(dt);
  2449. if (now.compare(dt)>=0)
  2450. {
  2451. SCMStringBuffer wuid;
  2452. runWorkUnit(cw.getWuid(wuid).str());
  2453. }
  2454. }
  2455. catch(IException *e)
  2456. {
  2457. StringBuffer msg;
  2458. ERRLOG("Exception %d:%s in WsWorkunits Schedule::run", e->errorCode(), e->errorMessage(msg).str());
  2459. e->Release();
  2460. }
  2461. }
  2462. }
  2463. semSchedule.wait(1000*60);
  2464. }
  2465. }
  2466. catch(IException *e)
  2467. {
  2468. StringBuffer msg;
  2469. ERRLOG("Exception %d:%s in WsWorkunits Schedule::run", e->errorCode(), e->errorMessage(msg).str());
  2470. e->Release();
  2471. }
  2472. catch(...)
  2473. {
  2474. ERRLOG("Unknown exception in WsWorkunits Schedule::run");
  2475. }
  2476. if (m_container)
  2477. m_container->exitESP();
  2478. return 0;
  2479. }
  2480. void WsWuHelpers::setXmlParameters(IWorkUnit *wu, const char *xml, bool setJobname)
  2481. {
  2482. if (!xml || !*xml)
  2483. return;
  2484. Owned<IPropertyTree> tree = createPTreeFromXMLString(xml, ipt_none, (PTreeReaderOptions)(ptr_ignoreWhiteSpace | ptr_ignoreNameSpaces));
  2485. IPropertyTree *root = tree.get();
  2486. if (strieq(root->queryName(), "Envelope"))
  2487. root = root->queryPropTree("Body/*[1]");
  2488. if (!root)
  2489. return;
  2490. if (setJobname)
  2491. {
  2492. SCMStringBuffer name;
  2493. wu->getJobName(name);
  2494. if (!name.length())
  2495. wu->setJobName(root->queryName());
  2496. }
  2497. wu->setXmlParams(LINK(root));
  2498. }
  2499. void WsWuHelpers::setXmlParameters(IWorkUnit *wu, const char *xml, IArrayOf<IConstNamedValue> *variables, bool setJobname)
  2500. {
  2501. StringBuffer extParamXml;
  2502. if (variables && variables->length())
  2503. {
  2504. Owned<IPropertyTree> paramTree = (xml && *xml) ? createPTreeFromXMLString(xml) : createPTree("input");
  2505. ForEachItemIn(i, *variables)
  2506. {
  2507. IConstNamedValue &item = variables->item(i);
  2508. const char *name = item.getName();
  2509. const char *value = item.getValue();
  2510. if (!name || !*name)
  2511. continue;
  2512. if (!value)
  2513. {
  2514. size_t len = strlen(name);
  2515. char last = name[len-1];
  2516. if (last == '-' || last == '+')
  2517. {
  2518. StringAttr s(name, len-1);
  2519. paramTree->setPropInt(s.get(), last == '+' ? 1 : 0);
  2520. }
  2521. else
  2522. paramTree->setPropInt(name, 1);
  2523. continue;
  2524. }
  2525. paramTree->setProp(name, value);
  2526. }
  2527. toXML(paramTree, extParamXml);
  2528. xml=extParamXml.str();
  2529. }
  2530. setXmlParameters(wu, xml, setJobname);
  2531. }
  2532. void WsWuHelpers::submitWsWorkunit(IEspContext& context, IConstWorkUnit* cw, const char* cluster, const char* snapshot, int maxruntime, bool compile, bool resetWorkflow, bool resetVariables,
  2533. const char *paramXml, IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs)
  2534. {
  2535. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  2536. switch(cw->getState())
  2537. {
  2538. case WUStateRunning:
  2539. case WUStateDebugPaused:
  2540. case WUStateDebugRunning:
  2541. case WUStateCompiling:
  2542. case WUStateAborting:
  2543. case WUStateBlocked:
  2544. {
  2545. SCMStringBuffer descr;
  2546. throw MakeStringException(ECLWATCH_CANNOT_SUBMIT_WORKUNIT, "Cannot submit the workunit. Workunit state is '%s'.", cw->getStateDesc(descr).str());
  2547. }
  2548. }
  2549. SCMStringBuffer wuid;
  2550. cw->getWuid(wuid);
  2551. WorkunitUpdate wu(&cw->lock());
  2552. if(!wu.get())
  2553. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Cannot update workunit %s.", wuid.str());
  2554. wu->clearExceptions();
  2555. if(notEmpty(cluster))
  2556. wu->setClusterName(cluster);
  2557. if(notEmpty(snapshot))
  2558. wu->setSnapshot(snapshot);
  2559. wu->setState(WUStateSubmitted);
  2560. if (maxruntime)
  2561. wu->setDebugValueInt("maxRunTime",maxruntime,true);
  2562. if (debugs && debugs->length())
  2563. {
  2564. ForEachItemIn(i, *debugs)
  2565. {
  2566. IConstNamedValue &item = debugs->item(i);
  2567. const char *name = item.getName();
  2568. const char *value = item.getValue();
  2569. if (!name || !*name)
  2570. continue;
  2571. if (!value)
  2572. {
  2573. size_t len = strlen(name);
  2574. char last = name[len-1];
  2575. if (last == '-' || last == '+')
  2576. {
  2577. StringAttr s(name, len-1);
  2578. wu->setDebugValueInt(s.get(), last == '+' ? 1 : 0, true);
  2579. }
  2580. else
  2581. wu->setDebugValueInt(name, 1, true);
  2582. continue;
  2583. }
  2584. wu->setDebugValue(name, value, true);
  2585. }
  2586. }
  2587. if (resetWorkflow)
  2588. wu->resetWorkflow();
  2589. if (!compile)
  2590. wu->schedule();
  2591. if (resetVariables)
  2592. {
  2593. SCMStringBuffer varname;
  2594. Owned<IConstWUResultIterator> vars = &wu->getVariables();
  2595. ForEach (*vars)
  2596. {
  2597. vars->query().getResultName(varname);
  2598. Owned<IWUResult> v = wu->updateVariableByName(varname.str());
  2599. if (v)
  2600. v->setResultStatus(ResultStatusUndefined);
  2601. }
  2602. }
  2603. setXmlParameters(wu, paramXml, variables, (wu->getAction()==WUActionExecuteExisting));
  2604. wu->commit();
  2605. wu.clear();
  2606. if (!compile)
  2607. runWorkUnit(wuid.str());
  2608. else if (context.querySecManager())
  2609. secSubmitWorkUnit(wuid.str(), *context.querySecManager(), *context.queryUser());
  2610. else
  2611. submitWorkUnit(wuid.str(), context.queryUserId(), context.queryPassword());
  2612. AuditSystemAccess(context.queryUserId(), true, "Submitted %s", wuid.str());
  2613. }
  2614. void WsWuHelpers::submitWsWorkunit(IEspContext& context, const char *wuid, const char* cluster, const char* snapshot, int maxruntime, bool compile, bool resetWorkflow, bool resetVariables,
  2615. const char *paramXml, IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs)
  2616. {
  2617. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2618. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  2619. if(!cw)
  2620. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  2621. return submitWsWorkunit(context, cw, cluster, snapshot, maxruntime, compile, resetWorkflow, resetVariables, paramXml, variables, debugs);
  2622. }
  2623. void WsWuHelpers::copyWsWorkunit(IEspContext &context, IWorkUnit &wu, const char *srcWuid)
  2624. {
  2625. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2626. Owned<IConstWorkUnit> src(factory->openWorkUnit(srcWuid, false));
  2627. SCMStringBuffer wuid;
  2628. wu.getWuid(wuid);
  2629. queryExtendedWU(&wu)->copyWorkUnit(src, false);
  2630. SCMStringBuffer token;
  2631. wu.setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
  2632. wu.commit();
  2633. }
  2634. void WsWuHelpers::runWsWorkunit(IEspContext &context, StringBuffer &wuid, const char *srcWuid, const char *cluster, const char *paramXml,
  2635. IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs)
  2636. {
  2637. StringBufferAdaptor isvWuid(wuid);
  2638. NewWsWorkunit wu(context);
  2639. wu->getWuid(isvWuid);
  2640. copyWsWorkunit(context, *wu, srcWuid);
  2641. wu.clear();
  2642. submitWsWorkunit(context, wuid.str(), cluster, NULL, 0, false, true, true, paramXml, variables, debugs);
  2643. }
  2644. void WsWuHelpers::runWsWorkunit(IEspContext &context, IConstWorkUnit *cw, const char *srcWuid, const char *cluster, const char *paramXml,
  2645. IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs)
  2646. {
  2647. WorkunitUpdate wu(&cw->lock());
  2648. copyWsWorkunit(context, *wu, srcWuid);
  2649. wu.clear();
  2650. submitWsWorkunit(context, cw, cluster, NULL, 0, false, true, true, paramXml, variables, debugs);
  2651. }
  2652. IException * WsWuHelpers::noteException(IWorkUnit *wu, IException *e, ErrorSeverity level)
  2653. {
  2654. if (wu)
  2655. {
  2656. Owned<IWUException> we = wu->createException();
  2657. StringBuffer s;
  2658. we->setExceptionMessage(e->errorMessage(s).str());
  2659. we->setExceptionSource("WsWorkunits");
  2660. we->setSeverity(level);
  2661. if (level==SeverityError)
  2662. wu->setState(WUStateFailed);
  2663. }
  2664. return e;
  2665. }
  2666. StringBuffer & WsWuHelpers::resolveQueryWuid(StringBuffer &wuid, const char *queryset, const char *query, bool notSuspended, IWorkUnit *wu)
  2667. {
  2668. Owned<IPropertyTree> qs = getQueryRegistry(queryset, true);
  2669. if (!qs)
  2670. throw noteException(wu, MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "QuerySet '%s' not found", queryset));
  2671. Owned<IPropertyTree> q = resolveQueryAlias(qs, query);
  2672. if (!q)
  2673. throw noteException(wu, MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query '%s/%s' not found", queryset, query));
  2674. if (notSuspended && q->getPropBool("@suspended"))
  2675. throw noteException(wu, MakeStringException(ECLWATCH_QUERY_SUSPENDED, "Query '%s/%s' is suspended", queryset, query));
  2676. return wuid.append(q->queryProp("@wuid"));
  2677. }
  2678. void WsWuHelpers::runWsWuQuery(IEspContext &context, IConstWorkUnit *cw, const char *queryset, const char *query, const char *cluster, const char *paramXml)
  2679. {
  2680. StringBuffer srcWuid;
  2681. WorkunitUpdate wu(&cw->lock());
  2682. resolveQueryWuid(srcWuid, queryset, query, true, wu);
  2683. copyWsWorkunit(context, *wu, srcWuid);
  2684. wu.clear();
  2685. submitWsWorkunit(context, cw, cluster, NULL, 0, false, true, true, paramXml);
  2686. }
  2687. void WsWuHelpers::runWsWuQuery(IEspContext &context, StringBuffer &wuid, const char *queryset, const char *query, const char *cluster, const char *paramXml)
  2688. {
  2689. StringBuffer srcWuid;
  2690. StringBufferAdaptor isvWuid(wuid);
  2691. NewWsWorkunit wu(context);
  2692. wu->getWuid(isvWuid);
  2693. resolveQueryWuid(srcWuid, queryset, query, true, wu);
  2694. copyWsWorkunit(context, *wu, srcWuid);
  2695. wu.clear();
  2696. submitWsWorkunit(context, wuid.str(), cluster, NULL, 0, false, true, true, paramXml);
  2697. }
  2698. void WsWuHelpers::checkAndTrimWorkunit(const char* methodName, StringBuffer& input)
  2699. {
  2700. const char* trimmedInput = input.trim().str();
  2701. if (isEmpty(trimmedInput))
  2702. throw MakeStringException(ECLWATCH_INVALID_INPUT, "%s: Workunit ID not set", methodName);
  2703. if (!looksLikeAWuid(trimmedInput))
  2704. throw MakeStringException(ECLWATCH_INVALID_INPUT, "%s: Invalid Workunit ID: %s", methodName, trimmedInput);
  2705. return;
  2706. }
  2707. }