ws_workunitsHelpers.cpp 104 KB

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