ws_workunitsHelpers.cpp 102 KB

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