ws_workunitsHelpers.cpp 83 KB

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