ws_workunitsHelpers.cpp 102 KB

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