ws_workunitsHelpers.cpp 98 KB

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