ws_workunitsHelpers.cpp 140 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129
  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. #include "rmtsmtp.hpp"
  27. #include "LogicFileWrapper.hpp"
  28. #ifndef _NO_LDAP
  29. #include "ldapsecurity.ipp"
  30. #endif
  31. #ifdef _USE_ZLIB
  32. #include "zcrypt.hpp"
  33. #endif
  34. namespace ws_workunits {
  35. const char * const timerFilterText = "measure[time],source[global],depth[1,]"; // Does not include hthor subgraph timings
  36. const char* zipFolder = "tempzipfiles" PATHSEPSTR;
  37. SecAccessFlags chooseWuAccessFlagsByOwnership(const char *user, const char *owner, SecAccessFlags accessOwn, SecAccessFlags accessOthers)
  38. {
  39. return (isEmpty(owner) || (user && streq(user, owner))) ? accessOwn : accessOthers;
  40. }
  41. SecAccessFlags chooseWuAccessFlagsByOwnership(const char *user, IConstWorkUnitInfo& cw, SecAccessFlags accessOwn, SecAccessFlags accessOthers)
  42. {
  43. return chooseWuAccessFlagsByOwnership(user, cw.queryUser(), accessOwn, accessOthers);
  44. }
  45. const char *getWuAccessType(const char *owner, const char *user)
  46. {
  47. return (isEmpty(owner) || (user && streq(user, owner))) ? OWN_WU_ACCESS : OTHERS_WU_ACCESS;
  48. }
  49. const char *getWuAccessType(IConstWorkUnit& cw, const char *user)
  50. {
  51. return getWuAccessType(cw.queryUser(), user);
  52. }
  53. void getUserWuAccessFlags(IEspContext& context, SecAccessFlags& accessOwn, SecAccessFlags& accessOthers, bool except)
  54. {
  55. if (!context.authorizeFeature(OWN_WU_ACCESS, accessOwn))
  56. accessOwn = SecAccess_None;
  57. if (!context.authorizeFeature(OTHERS_WU_ACCESS, accessOthers))
  58. accessOthers = SecAccess_None;
  59. if (except && (accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  60. {
  61. context.setAuthStatus(AUTH_STATUS_NOACCESS);
  62. AuditSystemAccess(context.queryUserId(), false, "Access Denied: User can't view any workunits");
  63. VStringBuffer msg("Access Denied: User %s does not have rights to access workunits.", context.queryUserId());
  64. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "%s", msg.str());
  65. }
  66. }
  67. SecAccessFlags getWsWorkunitAccess(IEspContext& ctx, IConstWorkUnit& cw)
  68. {
  69. SecAccessFlags accessFlag = SecAccess_None;
  70. ctx.authorizeFeature(getWuAccessType(cw, ctx.queryUserId()), accessFlag);
  71. return accessFlag;
  72. }
  73. bool validateWsWorkunitAccess(IEspContext& ctx, const char* wuid, SecAccessFlags minAccess)
  74. {
  75. Owned<IWorkUnitFactory> wf = getWorkUnitFactory(ctx.querySecManager(), ctx.queryUser());
  76. Owned<IConstWorkUnit> cw = wf->openWorkUnit(wuid);
  77. if (!cw)
  78. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Failed to open workunit %s when validating workunit access", wuid);
  79. return ctx.validateFeatureAccess(getWuAccessType(*cw, ctx.queryUserId()), minAccess, false);
  80. }
  81. void ensureWsWorkunitAccessByOwnerId(IEspContext& ctx, const char* owner, SecAccessFlags minAccess)
  82. {
  83. if (!ctx.validateFeatureAccess(getWuAccessType(owner, ctx.queryUserId()), minAccess, false))
  84. {
  85. ctx.setAuthStatus(AUTH_STATUS_NOACCESS);
  86. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to access workunit. Permission denied.");
  87. }
  88. }
  89. void ensureWsWorkunitAccess(IEspContext& ctx, IConstWorkUnit& cw, SecAccessFlags minAccess)
  90. {
  91. if (!ctx.validateFeatureAccess(getWuAccessType(cw, ctx.queryUserId()), minAccess, false))
  92. {
  93. ctx.setAuthStatus(AUTH_STATUS_NOACCESS);
  94. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to access workunit. Permission denied.");
  95. }
  96. }
  97. void ensureWsWorkunitAccess(IEspContext& context, const char* wuid, SecAccessFlags minAccess)
  98. {
  99. Owned<IWorkUnitFactory> wf = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  100. Owned<IConstWorkUnit> cw = wf->openWorkUnit(wuid);
  101. if (!cw)
  102. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Failed to open workunit %s when ensuring workunit access", wuid);
  103. ensureWsWorkunitAccess(context, *cw, minAccess);
  104. }
  105. void ensureWsCreateWorkunitAccess(IEspContext& ctx)
  106. {
  107. if (!ctx.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  108. {
  109. ctx.setAuthStatus(AUTH_STATUS_NOACCESS);
  110. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  111. }
  112. }
  113. StringBuffer &getWuidFromLogicalFileName(IEspContext &context, const char *logicalName, StringBuffer &wuid)
  114. {
  115. Owned<IDistributedFile> df = lookupLogicalName(context, logicalName, false, false, false, nullptr, defaultPrivilegedUser);
  116. if (!df)
  117. throw makeStringExceptionV(ECLWATCH_FILE_NOT_EXIST, "Cannot find file %s.", logicalName);
  118. return wuid.append(df->queryAttributes().queryProp("@workunit"));
  119. }
  120. void formatDuration(StringBuffer &s, unsigned ms)
  121. {
  122. unsigned days = ms / (1000*60*60*24);
  123. ms %= (1000*60*60*24);
  124. unsigned hours = ms / (1000*60*60);
  125. ms %= (1000*60*60);
  126. unsigned mins = ms / (1000*60);
  127. ms %= (1000*60);
  128. unsigned secs = ms / 1000;
  129. ms %= 1000;
  130. if (days)
  131. s.appendf("%d days ", days);
  132. if (hours || s.length())
  133. s.appendf("%d:", hours);
  134. if (mins || s.length())
  135. s.appendf("%d:", mins);
  136. if (s.length())
  137. s.appendf("%02d.%03d", secs, ms);
  138. else
  139. s.appendf("%d.%03d", secs, ms);
  140. }
  141. WsWUExceptions::WsWUExceptions(IConstWorkUnit& wu): numerr(0), numwrn(0), numinf(0), numalert(0)
  142. {
  143. Owned<IConstWUExceptionIterator> it = &wu.getExceptions();
  144. ForEach(*it)
  145. {
  146. IConstWUException & cur = it->query();
  147. SCMStringBuffer src, msg, file;
  148. Owned<IEspECLException> e= createECLException("","");
  149. e->setCode(cur.getExceptionCode());
  150. e->setSource(cur.getExceptionSource(src).str());
  151. e->setMessage(cur.getExceptionMessage(msg).str());
  152. e->setFileName(cur.getExceptionFileName(file).str());
  153. e->setLineNo(cur.getExceptionLineNo());
  154. e->setColumn(cur.getExceptionColumn());
  155. if (cur.getActivityId())
  156. e->setActivity(cur.getActivityId());
  157. if (cur.getPriority())
  158. e->setPriority(cur.getPriority());
  159. e->setScope(cur.queryScope());
  160. const char * label = "";
  161. switch (cur.getSeverity())
  162. {
  163. default:
  164. case SeverityError: label = "Error"; numerr++; break;
  165. case SeverityWarning: label = "Warning"; numwrn++; break;
  166. case SeverityInformation: label = "Info"; numinf++; break;
  167. case SeverityAlert: label = "Alert"; numalert++; break;
  168. }
  169. e->setSeverity(label);
  170. errors.append(*e.getLink());
  171. }
  172. }
  173. #define SDS_LOCK_TIMEOUT 30000
  174. void getSashaNode(SocketEndpoint &ep)
  175. {
  176. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  177. Owned<IConstEnvironment> env = factory->openEnvironment();
  178. Owned<IPropertyTree> root = &env->getPTree();
  179. IPropertyTree *pt = root->queryPropTree("Software/SashaServerProcess[1]/Instance[1]");
  180. if (!pt)
  181. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND, "Archive Server not found.");
  182. ep.set(pt->queryProp("@netAddress"), pt->getPropInt("@port",DEFAULT_SASHA_PORT));
  183. }
  184. void WsWuInfo::getSourceFiles(IEspECLWorkunit &info, unsigned long flags)
  185. {
  186. if (!(flags & WUINFO_IncludeSourceFiles))
  187. return;
  188. try
  189. {
  190. Owned<IUserDescriptor> userdesc;
  191. StringBuffer username;
  192. context.getUserID(username);
  193. const char* passwd = context.queryPassword();
  194. userdesc.setown(createUserDescriptor());
  195. userdesc->set(username.str(), passwd, context.querySignature());
  196. IArrayOf<IEspECLSourceFile> files;
  197. if (version < 1.27)
  198. {
  199. Owned<IPropertyTreeIterator> f=&cw->getFilesReadIterator();
  200. ForEach(*f)
  201. {
  202. IPropertyTree &query = f->query();
  203. const char *clusterName = query.queryProp("@cluster");
  204. const char *fileName = query.queryProp("@name");
  205. int fileCount = query.getPropInt("@useCount");
  206. Owned<IEspECLSourceFile> file= createECLSourceFile("","");
  207. if(clusterName && *clusterName)
  208. {
  209. file->setFileCluster(clusterName);
  210. }
  211. if (version > 1.11)
  212. {
  213. Owned<IPropertyTreeIterator> filetrees= query.getElements("Subfile");
  214. if (filetrees->first())
  215. file->setIsSuperFile(true);
  216. }
  217. if (fileName && *fileName)
  218. {
  219. file->setName(fileName);
  220. }
  221. file->setCount(fileCount);
  222. files.append(*file.getLink());
  223. }
  224. }
  225. else
  226. {
  227. StringArray fileNames;
  228. Owned<IPropertyTreeIterator> f=&cw->getFilesReadIterator();
  229. ForEach(*f)
  230. {
  231. IPropertyTree &query = f->query();
  232. const char *clusterName = query.queryProp("@cluster");
  233. const char *fileName = query.queryProp("@name");
  234. int fileCount = query.getPropInt("@useCount");
  235. bool bFound = false;
  236. if (fileName && *fileName && (fileNames.length() > 0))
  237. {
  238. for (unsigned i = 0; i < fileNames.length(); i++ ) // MORE - unnecessary n^2 process
  239. {
  240. const char *fileName0 = fileNames.item(i);
  241. if (!stricmp(fileName, fileName0))
  242. {
  243. bFound = true;
  244. break;
  245. }
  246. }
  247. }
  248. if (bFound)
  249. continue;
  250. Owned<IEspECLSourceFile> file= createECLSourceFile("","");
  251. if(clusterName && *clusterName)
  252. {
  253. file->setFileCluster(clusterName);
  254. }
  255. if (fileName && *fileName)
  256. {
  257. file->setName(fileName);
  258. }
  259. file->setCount(fileCount);
  260. Owned<IPropertyTreeIterator> filetrees= query.getElements("Subfile");
  261. if (filetrees->first())
  262. {
  263. file->setIsSuperFile(true);
  264. getSubFiles(filetrees, file, fileNames);
  265. }
  266. files.append(*file.getLink());
  267. }
  268. }
  269. info.setSourceFiles(files);
  270. }
  271. catch(IException* e)
  272. {
  273. StringBuffer eMsg;
  274. IERRLOG("%s", e->errorMessage(eMsg).str());
  275. info.setSourceFilesDesc(eMsg.str());
  276. e->Release();
  277. }
  278. }
  279. void WsWuInfo::getExceptions(IEspECLWorkunit &info, unsigned long flags)
  280. {
  281. if ((flags & WUINFO_IncludeExceptions) || version > 1.16)
  282. {
  283. WsWUExceptions errors(*cw);
  284. if (version > 1.16)
  285. {
  286. info.setErrorCount(errors.ErrCount());
  287. info.setWarningCount(errors.WrnCount());
  288. info.setInfoCount(errors.InfCount());
  289. info.setAlertCount(errors.AlertCount());
  290. }
  291. if ((flags & WUINFO_IncludeExceptions))
  292. info.setExceptions(errors);
  293. }
  294. }
  295. void WsWuInfo::getVariables(IEspECLWorkunit &info, unsigned long flags)
  296. {
  297. if (!(flags & WUINFO_IncludeVariables))
  298. return;
  299. try
  300. {
  301. IArrayOf<IEspECLResult> results;
  302. Owned<IConstWUResultIterator> vars = &cw->getVariables();
  303. ForEach(*vars)
  304. getResult(vars->query(), results, flags);
  305. info.setVariables(results);
  306. results.kill();
  307. }
  308. catch(IException* e)
  309. {
  310. StringBuffer eMsg;
  311. IERRLOG("%s", e->errorMessage(eMsg).str());
  312. info.setVariablesDesc(eMsg.str());
  313. e->Release();
  314. }
  315. }
  316. void WsWuInfo::addTimerToList(SCMStringBuffer& name, const char * scope, IConstWUStatistic & stat, IArrayOf<IEspECLTimer>& timers)
  317. {
  318. StringBuffer fd;
  319. formatStatistic(fd, stat.getValue(), stat.getMeasure());
  320. Owned<IEspECLTimer> t= createECLTimer("","");
  321. name.s.replace('_', ' '); // yuk!
  322. t->setName(name.str());
  323. t->setValue(fd.str());
  324. //Theoretically this could overflow, in practice it is unlikely - fix in the new stats interface when implemented
  325. t->setCount((unsigned)stat.getCount());
  326. if (version > 1.19)
  327. {
  328. StringAttr graphName;
  329. unsigned graphNum;
  330. unsigned subGraphNum = 0;
  331. unsigned subId = 0;
  332. if (parseGraphScope(scope, graphName, graphNum, subId) ||
  333. parseGraphTimerLabel(name.str(), graphName, graphNum, subGraphNum, subId)) // leacy
  334. {
  335. if (graphName.length() > 0)
  336. t->setGraphName(graphName);
  337. if (subId > 0)
  338. t->setSubGraphId((int)subId);
  339. }
  340. }
  341. if (version >= 1.72)
  342. {
  343. StringBuffer tsText;
  344. unsigned __int64 ts = stat.getTimestamp();
  345. formatStatistic(tsText, ts, SMeasureTimestampUs);
  346. t->setTimestamp(ts);
  347. t->setWhen(tsText.str());
  348. }
  349. timers.append(*t.getLink());
  350. }
  351. void WsWuInfo::doGetTimers(IArrayOf<IEspECLTimer>& timers)
  352. {
  353. class TimingVisitor : public WuScopeVisitorBase
  354. {
  355. public:
  356. TimingVisitor(WsWuInfo & _wuInfo, IArrayOf<IEspECLTimer>& _timers) : wuInfo(_wuInfo), timers(_timers) {}
  357. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  358. {
  359. SCMStringBuffer name;
  360. extra.getDescription(name, true);
  361. const char * scope = extra.queryScope();
  362. wuInfo.addTimerToList(name, scope, extra, timers);
  363. //Aggregate all the times spent executing graphs
  364. if ((kind == StTimeElapsed) && (extra.getScopeType() == SSTgraph))
  365. totalGraphTime.noteValue(value);
  366. }
  367. void addSummary()
  368. {
  369. if (totalGraphTime.getCount())
  370. {
  371. StringBuffer totalThorTimeText;
  372. formatStatistic(totalThorTimeText, totalGraphTime.getSum(), SMeasureTimeNs);
  373. Owned<IEspECLTimer> t= createECLTimer("","");
  374. if (wuInfo.version > 1.52)
  375. t->setName(TOTALCLUSTERTIME);
  376. else
  377. t->setName(TOTALTHORTIME);
  378. t->setValue(totalThorTimeText.str());
  379. t->setCount((unsigned)totalGraphTime.getCount());
  380. timers.append(*t.getClear());
  381. }
  382. }
  383. protected:
  384. WsWuInfo & wuInfo;
  385. IArrayOf<IEspECLTimer>& timers;
  386. StatsAggregation totalGraphTime;
  387. } visitor(*this, timers);
  388. WuScopeFilter filter(timerFilterText);
  389. Owned<IConstWUScopeIterator> it = &cw->getScopeIterator(filter);
  390. ForEach(*it)
  391. it->playProperties(visitor);
  392. visitor.addSummary();
  393. }
  394. void WsWuInfo::getTimers(IEspECLWorkunit &info, unsigned long flags)
  395. {
  396. if (!(flags & WUINFO_IncludeTimers))
  397. return;
  398. try
  399. {
  400. IArrayOf<IEspECLTimer> timers;
  401. doGetTimers(timers);
  402. info.setTimers(timers);
  403. }
  404. catch(IException* e)
  405. {
  406. StringBuffer eMsg;
  407. IERRLOG("%s", e->errorMessage(eMsg).str());
  408. info.setTimersDesc(eMsg.str());
  409. e->Release();
  410. }
  411. }
  412. class TimingCounter : public WuScopeVisitorBase
  413. {
  414. public:
  415. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  416. {
  417. numTimers++;
  418. if ((kind == StTimeElapsed) && (extra.getScopeType() == SSTgraph))
  419. hasGraphTiming = true;
  420. }
  421. unsigned getNumTimers() const
  422. {
  423. return numTimers + (hasGraphTiming ? 1 : 0);
  424. }
  425. protected:
  426. bool hasGraphTiming = false;
  427. unsigned numTimers = 0;
  428. };
  429. unsigned WsWuInfo::getTimerCount()
  430. {
  431. TimingCounter visitor;
  432. try
  433. {
  434. WuScopeFilter filter(timerFilterText);
  435. Owned<IConstWUScopeIterator> it = &cw->getScopeIterator(filter);
  436. ForEach(*it)
  437. it->playProperties(visitor);
  438. }
  439. catch(IException* e)
  440. {
  441. StringBuffer eMsg;
  442. IERRLOG("%s", e->errorMessage(eMsg).str());
  443. e->Release();
  444. }
  445. return visitor.getNumTimers();
  446. }
  447. EnumMapping queryFileTypes[] = {
  448. { FileTypeCpp, "cpp" },
  449. { FileTypeDll, "dll" },
  450. { FileTypeResText, "res" },
  451. { FileTypeHintXml, "hint" },
  452. { FileTypeXml, "xml" },
  453. { FileTypeLog, "log" },
  454. { FileTypeSize, NULL },
  455. };
  456. void WsWuInfo::getHelpers(IEspECLWorkunit &info, unsigned long flags)
  457. {
  458. try
  459. {
  460. IArrayOf<IEspECLHelpFile> helpers;
  461. unsigned helpersCount = 2; // ECL + Workunit XML are also helpers...
  462. Owned <IConstWUQuery> query = cw->getQuery();
  463. if(!query)
  464. {
  465. IERRLOG("Cannot get Query for this workunit.");
  466. info.setHelpersDesc("Cannot get Query for this workunit.");
  467. }
  468. else
  469. {
  470. if (flags & WUINFO_IncludeECL)
  471. {
  472. SCMStringBuffer queryText;
  473. query->getQueryShortText(queryText);
  474. if (queryText.length())
  475. {
  476. if((flags & WUINFO_TruncateEclTo64k) && (queryText.length() > 64000))
  477. queryText.setLen(queryText.str(), 64000);
  478. IEspECLQuery* q=&info.updateQuery();
  479. q->setText(queryText.str());
  480. }
  481. }
  482. if (version > 1.34)
  483. {
  484. SCMStringBuffer mainDefinition;
  485. query->getQueryMainDefinition(mainDefinition);
  486. if(mainDefinition.length())
  487. {
  488. IEspECLQuery* q=&info.updateQuery();
  489. q->setQueryMainDefinition(mainDefinition.str());
  490. }
  491. }
  492. if (version > 1.30)
  493. {
  494. info.setHasArchiveQuery(query->hasArchive());
  495. }
  496. for (unsigned i = 0; i < FileTypeSize; i++)
  497. getHelpFiles(query, (WUFileType) i, helpers, flags, helpersCount);
  498. }
  499. getWorkunitThorLogInfo(helpers, info, flags, helpersCount);
  500. if (cw->getWuidVersion() > 0)
  501. {
  502. Owned<IPropertyTreeIterator> eclAgents = cw->getProcesses("EclAgent", NULL);
  503. ForEach (*eclAgents)
  504. {
  505. StringBuffer logName;
  506. IPropertyTree& eclAgent = eclAgents->query();
  507. eclAgent.getProp("@log",logName);
  508. if (!logName.length())
  509. continue;
  510. helpersCount++;
  511. if (!(flags & WUINFO_IncludeHelpers))
  512. continue;
  513. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  514. h->setName(logName.str());
  515. h->setType(File_EclAgentLog);
  516. if (version >= 1.43)
  517. {
  518. offset_t fileSize;
  519. if (getFileSize(logName.str(), NULL, fileSize))
  520. h->setFileSize(fileSize);
  521. if (version >= 1.44)
  522. {
  523. if (eclAgent.hasProp("@pid"))
  524. h->setPID(eclAgent.getPropInt("@pid"));
  525. else
  526. h->setPID(cw->getAgentPID());
  527. }
  528. }
  529. helpers.append(*h.getLink());
  530. }
  531. }
  532. else // legacy wuid
  533. {
  534. Owned<IStringIterator> eclAgentLogs = cw->getLogs("EclAgent");
  535. ForEach (*eclAgentLogs)
  536. {
  537. SCMStringBuffer name;
  538. eclAgentLogs->str(name);
  539. if (name.length() < 1)
  540. continue;
  541. helpersCount++;
  542. if (!(flags & WUINFO_IncludeHelpers))
  543. break;
  544. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  545. h->setName(name.str());
  546. h->setType(File_EclAgentLog);
  547. if (version >= 1.43)
  548. {
  549. offset_t fileSize;
  550. if (getFileSize(name.str(), NULL, fileSize))
  551. h->setFileSize(fileSize);
  552. }
  553. helpers.append(*h.getLink());
  554. break;
  555. }
  556. }
  557. info.setHelpers(helpers);
  558. info.setHelpersCount(helpersCount);
  559. }
  560. catch(IException* e)
  561. {
  562. StringBuffer eMsg;
  563. IERRLOG("%s", e->errorMessage(eMsg).str());
  564. info.setHelpersDesc(eMsg.str());
  565. e->Release();
  566. }
  567. }
  568. void WsWuInfo::getApplicationValues(IEspECLWorkunit &info, unsigned long flags)
  569. {
  570. if (!(flags & WUINFO_IncludeApplicationValues))
  571. return;
  572. try
  573. {
  574. IArrayOf<IEspApplicationValue> av;
  575. Owned<IConstWUAppValueIterator> app(&cw->getApplicationValues());
  576. ForEach(*app)
  577. {
  578. IConstWUAppValue& val=app->query();
  579. Owned<IEspApplicationValue> t= createApplicationValue("","");
  580. t->setApplication(val.queryApplication());
  581. t->setName(val.queryName());
  582. t->setValue(val.queryValue());
  583. av.append(*t.getLink());
  584. }
  585. info.setApplicationValues(av);
  586. }
  587. catch(IException* e)
  588. {
  589. StringBuffer eMsg;
  590. IERRLOG("%s", e->errorMessage(eMsg).str());
  591. info.setApplicationValuesDesc(eMsg.str());
  592. e->Release();
  593. }
  594. }
  595. void WsWuInfo::getDebugValues(IEspECLWorkunit &info, unsigned long flags)
  596. {
  597. if (!(flags & WUINFO_IncludeDebugValues))
  598. {
  599. if (version >= 1.50)
  600. {
  601. unsigned debugValueCount = 0;
  602. Owned<IStringIterator> debugs(&cw->getDebugValues());
  603. ForEach(*debugs)
  604. debugValueCount++;
  605. info.setDebugValueCount(debugValueCount);
  606. }
  607. return;
  608. }
  609. try
  610. {
  611. IArrayOf<IEspDebugValue> dv;
  612. Owned<IStringIterator> debugs(&cw->getDebugValues());
  613. ForEach(*debugs)
  614. {
  615. SCMStringBuffer name, val;
  616. debugs->str(name);
  617. cw->getDebugValue(name.str(),val);
  618. Owned<IEspDebugValue> t= createDebugValue("","");
  619. t->setName(name.str());
  620. t->setValue(val.str());
  621. dv.append(*t.getLink());
  622. }
  623. if (version >= 1.50)
  624. info.setDebugValueCount(dv.length());
  625. info.setDebugValues(dv);
  626. }
  627. catch(IException* e)
  628. {
  629. StringBuffer eMsg;
  630. IERRLOG("%s", e->errorMessage(eMsg).str());
  631. info.setDebugValuesDesc(eMsg.str());
  632. e->Release();
  633. }
  634. }
  635. const char *getGraphNum(const char *s,unsigned &num)
  636. {
  637. while (*s && !isdigit(*s))
  638. s++;
  639. num = 0;
  640. while (isdigit(*s))
  641. {
  642. num = num*10+*s-'0';
  643. s++;
  644. }
  645. return s;
  646. }
  647. bool WsWuInfo::hasSubGraphTimings()
  648. {
  649. try
  650. {
  651. WuScopeFilter filter("depth[3],stype[subgraph],stat[TimeElapsed],nested[0]");
  652. Owned<IConstWUScopeIterator> it = &cw->getScopeIterator(filter);
  653. ForEach(*it)
  654. {
  655. stat_type value;
  656. if (it->getStat(StTimeElapsed, value))
  657. return true;
  658. }
  659. }
  660. catch(IException* e)
  661. {
  662. StringBuffer eMsg;
  663. IERRLOG("%s", e->errorMessage(eMsg).str());
  664. e->Release();
  665. }
  666. return false;
  667. }
  668. void WsWuInfo::doGetGraphs(IArrayOf<IEspECLGraph>& graphs)
  669. {
  670. SCMStringBuffer runningGraph;
  671. WUGraphIDType id;
  672. WUState st = cw->getState();
  673. bool running = (!(st==WUStateFailed || st==WUStateAborted || st==WUStateCompleted) && cw->getRunningGraph(runningGraph,id));
  674. Owned<IConstWUGraphMetaIterator> it = &cw->getGraphsMeta(GraphTypeAny);
  675. ForEach(*it)
  676. {
  677. IConstWUGraphMeta &graph = it->query();
  678. SCMStringBuffer name, label, type;
  679. graph.getName(name);
  680. graph.getLabel(label);
  681. graph.getTypeName(type);
  682. WUGraphState graphState = graph.getState();
  683. Owned<IEspECLGraph> g= createECLGraph();
  684. g->setName(name.str());
  685. g->setLabel(label.str());
  686. g->setType(type.str());
  687. if (WUGraphComplete == graphState)
  688. g->setComplete(true);
  689. else if (running && (WUGraphRunning == graphState))
  690. {
  691. g->setRunning(true);
  692. g->setRunningId(id);
  693. }
  694. else if (WUGraphFailed == graphState)
  695. g->setFailed(true);
  696. if (version >= 1.53)
  697. {
  698. //MORE: Will need to be prefixed with the wfid
  699. StringBuffer scope;
  700. scope.append(name);
  701. StringBuffer s;
  702. stat_type timeStamp;
  703. if (cw->getStatistic(timeStamp, scope.str(), StWhenStarted) ||
  704. cw->getStatistic(timeStamp, name.str(), StWhenGraphStarted))
  705. {
  706. g->setWhenStarted(formatStatistic(s.clear(), timeStamp, SMeasureTimestampUs));
  707. }
  708. if (cw->getStatistic(timeStamp, scope.str(), StWhenFinished) ||
  709. cw->getStatistic(timeStamp, name.str(), StWhenGraphFinished))
  710. {
  711. g->setWhenFinished(formatStatistic(s.clear(), timeStamp, SMeasureTimestampUs));
  712. }
  713. }
  714. graphs.append(*g.getLink());
  715. }
  716. }
  717. void WsWuInfo::getGraphInfo(IEspECLWorkunit &info, unsigned long flags)
  718. {
  719. if ((version > 1.01) && (version < 1.71))
  720. {
  721. info.setHaveSubGraphTimings(false);
  722. if (hasSubGraphTimings())
  723. info.setHaveSubGraphTimings(true);
  724. }
  725. if (!(flags & WUINFO_IncludeGraphs))
  726. return;
  727. try
  728. {
  729. IArrayOf<IEspECLGraph> graphs;
  730. doGetGraphs(graphs);
  731. info.setGraphs(graphs);
  732. }
  733. catch(IException* e)
  734. {
  735. StringBuffer eMsg;
  736. IERRLOG("%s", e->errorMessage(eMsg).str());
  737. info.setGraphsDesc(eMsg.str());
  738. e->Release();
  739. }
  740. }
  741. void WsWuInfo::getWUGraphNameAndTypes(WUGraphType graphType, IArrayOf<IEspNameAndType>& graphNameAndTypes)
  742. {
  743. Owned<IConstWUGraphMetaIterator> it = &cw->getGraphsMeta(graphType);
  744. ForEach(*it)
  745. {
  746. SCMStringBuffer name, type;
  747. IConstWUGraphMeta &graph = it->query();
  748. Owned<IEspNameAndType> nameAndType = createNameAndType();
  749. nameAndType->setName(graph.getName(name).str());
  750. nameAndType->setType(graph.getTypeName(type).str());
  751. graphNameAndTypes.append(*nameAndType.getLink());
  752. }
  753. }
  754. void WsWuInfo::getGraphTimingData(IArrayOf<IConstECLTimingData> &timingData)
  755. {
  756. class TimingVisitor : public WuScopeVisitorBase
  757. {
  758. public:
  759. TimingVisitor(WsWuInfo & _wuInfo, IArrayOf<IConstECLTimingData> & _timingData) : wuInfo(_wuInfo), timingData(_timingData) {}
  760. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & cur) override
  761. {
  762. const char * scope = cur.queryScope();
  763. StringAttr graphName;
  764. unsigned graphNum;
  765. unsigned subGraphId;
  766. if (parseGraphScope(scope, graphName, graphNum, subGraphId))
  767. {
  768. unsigned time = (unsigned)nanoToMilli(value);
  769. SCMStringBuffer name;
  770. cur.getDescription(name, true);
  771. Owned<IEspECLTimingData> g = createECLTimingData();
  772. g->setName(name.str());
  773. g->setGraphNum(graphNum);
  774. g->setSubGraphNum(subGraphId); // Use the Id - the number is not known
  775. g->setGID(subGraphId);
  776. g->setMS(time);
  777. g->setMin(time/60000);
  778. timingData.append(*g.getClear());
  779. }
  780. }
  781. protected:
  782. WsWuInfo & wuInfo;
  783. IArrayOf<IConstECLTimingData> & timingData;
  784. } visitor(*this, timingData);
  785. WuScopeFilter filter("stype[subgraph],stat[TimeElapsed],nested[0]");
  786. Owned<IConstWUScopeIterator> it = &cw->getScopeIterator(filter);
  787. ForEach(*it)
  788. it->playProperties(visitor);
  789. }
  790. void WsWuInfo::getServiceNames(IEspECLWorkunit &info, unsigned long flags)
  791. {
  792. if (!(flags & WUINFO_IncludeServiceNames))
  793. return;
  794. StringArray serviceNames;
  795. WuScopeFilter filter;
  796. filter.addScopeType("activity");
  797. filter.addOutputAttribute(WaServiceName);
  798. filter.addRequiredAttr(WaServiceName);
  799. filter.finishedFilter();
  800. Owned<IConstWUScopeIterator> it = &cw->getScopeIterator(filter);
  801. ForEach(*it)
  802. {
  803. StringBuffer serviceName;
  804. const char *value = it->queryAttribute(WaServiceName, serviceName);
  805. if (!isEmptyString(value))
  806. serviceNames.append(value);
  807. }
  808. info.setServiceNames(serviceNames);
  809. }
  810. void WsWuInfo::getEventScheduleFlag(IEspECLWorkunit &info)
  811. {
  812. info.setEventSchedule(0);
  813. if (info.getState() && !stricmp(info.getState(), "wait"))
  814. {
  815. info.setEventSchedule(2); //Can deschedule
  816. }
  817. else
  818. {
  819. Owned<IConstWorkflowItemIterator> it = cw->getWorkflowItems();
  820. if (it)
  821. {
  822. ForEach(*it)
  823. {
  824. IConstWorkflowItem *r = it->query();
  825. if (!r)
  826. continue;
  827. Owned<IWorkflowEvent> wfevent = r->getScheduleEvent();
  828. if (!wfevent)
  829. continue;
  830. if ((!r->hasScheduleCount() || (r->queryScheduleCountRemaining() > 0))
  831. && info.getState() && !strieq(info.getState(), "scheduled")
  832. && !strieq(info.getState(), "aborting") && !strieq(info.getState(), "aborted")
  833. && !strieq(info.getState(), "failed") && !strieq(info.getState(), "archived"))
  834. {
  835. info.setEventSchedule(1); //Can reschedule
  836. break;
  837. }
  838. }
  839. }
  840. }
  841. }
  842. void WsWuInfo::getCommon(IEspECLWorkunit &info, unsigned long flags)
  843. {
  844. info.setWuid(cw->queryWuid());
  845. info.setProtected(cw->isProtected() ? 1 : 0);
  846. info.setJobname(cw->queryJobName());
  847. info.setOwner(cw->queryUser());
  848. clusterName.set(cw->queryClusterName());
  849. info.setCluster(clusterName.str());
  850. SCMStringBuffer s;
  851. info.setSnapshot(cw->getSnapshot(s).str());
  852. if ((cw->getState() == WUStateScheduled) && cw->aborting())
  853. {
  854. info.setStateID(WUStateAborting);
  855. info.setState("aborting");
  856. }
  857. else
  858. {
  859. info.setStateID(cw->getState());
  860. info.setState(cw->queryStateDesc());
  861. }
  862. if (cw->isPausing())
  863. info.setIsPausing(true);
  864. getEventScheduleFlag(info);
  865. //The TotalClusterTime should always be returned between versions 1.27 and 1.73.
  866. //After version 1.73, it should be returned only if IncludeTotalClusterTime is true.
  867. if ((version > 1.27) && ((version < 1.73) || (flags & WUINFO_IncludeTotalClusterTime)))
  868. {
  869. unsigned totalThorTimeMS = cw->getTotalThorTime();
  870. if (totalThorTimeMS)
  871. {
  872. StringBuffer totalThorTimeStr;
  873. formatDuration(totalThorTimeStr, totalThorTimeMS);
  874. if (version > 1.52)
  875. info.setTotalClusterTime(totalThorTimeStr.str());
  876. else
  877. info.setTotalThorTime(totalThorTimeStr.str());
  878. }
  879. }
  880. WsWuDateTime dt;
  881. cw->getTimeScheduled(dt);
  882. if(dt.isValid())
  883. info.setDateTimeScheduled(dt.getString(s).str());
  884. }
  885. void WsWuInfo::setWUAbortTime(IEspECLWorkunit &info, unsigned __int64 abortTS)
  886. {
  887. StringBuffer abortTimeStr;
  888. formatStatistic(abortTimeStr, abortTS, SMeasureTimestampUs);
  889. if ((abortTimeStr.length() > 19) && (abortTimeStr.charAt(10) == 'T') && (abortTimeStr.charAt(19) == '.'))
  890. {
  891. abortTimeStr.setCharAt(10, ' ');
  892. abortTimeStr.setLength(19);
  893. }
  894. info.setAbortTime(abortTimeStr.str());
  895. }
  896. void WsWuInfo::getInfo(IEspECLWorkunit &info, unsigned long flags)
  897. {
  898. getCommon(info, flags);
  899. SecAccessFlags accessFlag = getWsWorkunitAccess(context, *cw);
  900. info.setAccessFlag(accessFlag);
  901. SCMStringBuffer s;
  902. info.setStateEx(cw->getStateEx(s).str());
  903. WUState state = cw->getState();
  904. if ((state == WUStateAborting) || (state == WUStateAborted))
  905. {
  906. unsigned __int64 abortTS = cw->getAbortTimeStamp();
  907. if (abortTS > 0) //AbortTimeStamp may not be set in old wu
  908. {
  909. setWUAbortTime(info, abortTS);
  910. cw->getAbortBy(s);
  911. if (s.length())
  912. info.setAbortBy(s.str());
  913. }
  914. }
  915. info.setPriorityClass(cw->getPriority());
  916. info.setPriorityLevel(cw->getPriorityLevel());
  917. if (context.querySecManager())
  918. info.setScope(cw->queryWuScope());
  919. info.setActionEx(cw->queryActionDesc());
  920. info.setDescription(cw->getDebugValue("description", s).str());
  921. if (version > 1.21)
  922. info.setXmlParams(cw->getXmlParams(s, true).str());
  923. info.setResultLimit(cw->getResultLimit());
  924. info.setArchived(false);
  925. info.setGraphCount(cw->getGraphCount());
  926. info.setSourceFileCount(cw->getSourceFileCount());
  927. info.setResultCount(cw->getResultCount());
  928. info.setWorkflowCount(cw->queryEventScheduledCount());
  929. info.setVariableCount(cw->getVariableCount());
  930. info.setTimerCount(getTimerCount());
  931. info.setSourceFileCount(cw->getSourceFileCount());
  932. info.setApplicationValueCount(cw->getApplicationValueCount());
  933. info.setHasDebugValue(cw->hasDebugValue("__calculated__complexity__"));
  934. getClusterInfo(info, flags);
  935. getExceptions(info, flags);
  936. getHelpers(info, flags);
  937. getGraphInfo(info, flags);
  938. getSourceFiles(info, flags);
  939. getResults(info, flags);
  940. getVariables(info, flags);
  941. getTimers(info, flags);
  942. getDebugValues(info, flags);
  943. getApplicationValues(info, flags);
  944. getWorkflow(info, flags);
  945. getServiceNames(info, flags);
  946. }
  947. unsigned WsWuInfo::getWorkunitThorLogInfo(IArrayOf<IEspECLHelpFile>& helpers, IEspECLWorkunit &info, unsigned long flags, unsigned& helpersCount)
  948. {
  949. unsigned countThorLog = 0;
  950. IArrayOf<IConstThorLogInfo> thorLogList;
  951. if (cw->getWuidVersion() > 0)
  952. {
  953. StringAttr clusterName(cw->queryClusterName());
  954. if (!clusterName.length()) //Cluster name may not be set yet
  955. return countThorLog;
  956. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  957. if (!clusterInfo)
  958. {
  959. IWARNLOG("Cannot find TargetClusterInfo for workunit %s", cw->queryWuid());
  960. return countThorLog;
  961. }
  962. unsigned numberOfSlaveLogs = clusterInfo->getNumberOfSlaveLogs();
  963. BoolHash uniqueProcesses;
  964. Owned<IStringIterator> thorInstances = cw->getProcesses("Thor");
  965. ForEach (*thorInstances)
  966. {
  967. SCMStringBuffer processName;
  968. thorInstances->str(processName);
  969. if (processName.length() < 1)
  970. continue;
  971. bool* found = uniqueProcesses.getValue(processName.str());
  972. if (found && *found)
  973. continue;
  974. uniqueProcesses.setValue(processName.str(), true);
  975. StringBuffer groupName;
  976. getClusterThorGroupName(groupName, processName.str());
  977. Owned<IStringIterator> thorLogs = cw->getLogs("Thor", processName.str());
  978. ForEach (*thorLogs)
  979. {
  980. SCMStringBuffer logName;
  981. thorLogs->str(logName);
  982. if (logName.length() < 1)
  983. continue;
  984. countThorLog++;
  985. StringBuffer fileType;
  986. if (countThorLog < 2)
  987. fileType.append(File_ThorLog);
  988. else
  989. fileType.appendf("%s%d", File_ThorLog, countThorLog);
  990. helpersCount++;
  991. if (flags & WUINFO_IncludeHelpers)
  992. {
  993. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  994. h->setName(logName.str());
  995. h->setDescription(processName.str());
  996. h->setType(fileType.str());
  997. if (version >= 1.43)
  998. {
  999. offset_t fileSize;
  1000. if (getFileSize(logName.str(), NULL, fileSize))
  1001. h->setFileSize(fileSize);
  1002. }
  1003. helpers.append(*h.getLink());
  1004. }
  1005. if (version < 1.38)
  1006. continue;
  1007. const char* pStr = logName.str();
  1008. const char* ppStr = strstr(pStr, "/thormaster.");
  1009. if (!ppStr)
  1010. {
  1011. IWARNLOG("Invalid thorlog entry in workunit xml: %s", logName.str());
  1012. continue;
  1013. }
  1014. ppStr += 12;
  1015. StringBuffer logDate(ppStr);
  1016. logDate.setLength(10);
  1017. Owned<IEspThorLogInfo> thorLog = createThorLogInfo("","");
  1018. thorLog->setProcessName(processName.str());
  1019. thorLog->setClusterGroup(groupName.str());
  1020. thorLog->setLogDate(logDate.str());
  1021. thorLog->setNumberSlaves(numberOfSlaveLogs);
  1022. thorLogList.append(*thorLog.getLink());
  1023. }
  1024. }
  1025. }
  1026. else //legacy wuid
  1027. {
  1028. Owned<IStringIterator> thorLogs = cw->getLogs("Thor");
  1029. ForEach (*thorLogs)
  1030. {
  1031. SCMStringBuffer name;
  1032. thorLogs->str(name);
  1033. if (name.length() < 1)
  1034. continue;
  1035. countThorLog++;
  1036. StringBuffer fileType;
  1037. if (countThorLog < 2)
  1038. fileType.append(File_ThorLog);
  1039. else
  1040. fileType.appendf("%s%d", File_ThorLog, countThorLog);
  1041. helpersCount++;
  1042. if (flags & WUINFO_IncludeHelpers)
  1043. {
  1044. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  1045. h->setName(name.str());
  1046. h->setType(fileType.str());
  1047. if (version >= 1.43)
  1048. {
  1049. offset_t fileSize;
  1050. if (getFileSize(name.str(), NULL, fileSize))
  1051. h->setFileSize(fileSize);
  1052. }
  1053. helpers.append(*h.getLink());
  1054. }
  1055. }
  1056. StringBuffer logDir;
  1057. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  1058. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  1059. Owned<IPropertyTree> logTree = &constEnv->getPTree();
  1060. if (logTree)
  1061. logTree->getProp("EnvSettings/log", logDir);
  1062. if (logDir.length() > 0)
  1063. {
  1064. Owned<IStringIterator> debugs = cw->getLogs("Thor");
  1065. ForEach(*debugs)
  1066. {
  1067. SCMStringBuffer val;
  1068. debugs->str(val);
  1069. if (val.length() < 1)
  1070. continue;
  1071. const char* pStr = val.str();
  1072. const char* ppStr = strstr(pStr, logDir.str());
  1073. if (!ppStr)
  1074. {
  1075. IWARNLOG("Invalid thorlog entry in workunit xml: %s", val.str());
  1076. continue;
  1077. }
  1078. const char* pProcessName = ppStr + logDir.length();
  1079. char sep = pProcessName[0];
  1080. StringBuffer processName(pProcessName + 1);
  1081. ppStr = strchr(pProcessName + 1, sep);
  1082. if (!ppStr)
  1083. {
  1084. IWARNLOG("Invalid thorlog entry in workunit xml: %s", val.str());
  1085. continue;
  1086. }
  1087. processName.setLength(ppStr - pProcessName - 1);
  1088. StringBuffer groupName;
  1089. getClusterThorGroupName(groupName, processName.str());
  1090. StringBuffer logDate(ppStr + 12);
  1091. logDate.setLength(10);
  1092. Owned<IEspThorLogInfo> thorLog = createThorLogInfo("","");
  1093. thorLog->setProcessName(processName.str());
  1094. thorLog->setClusterGroup(groupName.str());
  1095. thorLog->setLogDate(logDate.str());
  1096. //for legacy wuid, the log name does not contain slaveNum. So, a user may not specify
  1097. //a slaveNum and we only display the first slave log if > 1 per IP.
  1098. thorLog->setNumberSlaves(0);
  1099. thorLogList.append(*thorLog.getLink());
  1100. }
  1101. }
  1102. }
  1103. if (thorLogList.length() > 0)
  1104. info.setThorLogList(thorLogList);
  1105. thorLogList.kill();
  1106. return countThorLog;
  1107. }
  1108. bool WsWuInfo::getClusterInfo(IEspECLWorkunit &info, unsigned long flags)
  1109. {
  1110. if ((flags & WUINFO_IncludeAllowedClusters) && (version > 1.04))
  1111. {
  1112. StringArray allowedClusters;
  1113. SCMStringBuffer val;
  1114. cw->getAllowedClusters(val);
  1115. if (val.length() > 0)
  1116. {
  1117. const char* ptr = val.str();
  1118. while(*ptr != '\0')
  1119. {
  1120. StringBuffer onesub;
  1121. while(*ptr != '\0' && *ptr != ',')
  1122. {
  1123. onesub.append((char)(*ptr));
  1124. ptr++;
  1125. }
  1126. if(onesub.length() > 0)
  1127. allowedClusters.append(onesub.str());
  1128. if(*ptr != '\0')
  1129. ptr++;
  1130. }
  1131. }
  1132. if (allowedClusters.length() > 0)
  1133. info.setAllowedClusters(allowedClusters);
  1134. }
  1135. if (version > 1.23 && clusterName.length())
  1136. {
  1137. int clusterTypeFlag = 0;
  1138. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  1139. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  1140. Owned<IPropertyTree> root = &constEnv->getPTree();
  1141. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  1142. if (clusterInfo.get())
  1143. {//Set thor flag or roxie flag in order to display some options for thor or roxie
  1144. ClusterType platform = clusterInfo->getPlatform();
  1145. if (isThorCluster(platform))
  1146. {
  1147. clusterTypeFlag=1;
  1148. if (version > 1.29)
  1149. info.setThorLCR(ThorLCRCluster == platform);
  1150. }
  1151. else if (RoxieCluster == platform)
  1152. clusterTypeFlag=2;
  1153. }
  1154. info.setClusterFlag(clusterTypeFlag);
  1155. }
  1156. return true;
  1157. }
  1158. void WsWuInfo::getWorkflow(IEspECLWorkunit &info, unsigned long flags)
  1159. {
  1160. if (!(flags & WUINFO_IncludeWorkflows))
  1161. return;
  1162. try
  1163. {
  1164. Owned<IConstWorkflowItemIterator> it = cw->getWorkflowItems();
  1165. if (!it)
  1166. return;
  1167. IArrayOf<IConstECLWorkflow> workflows;
  1168. ForEach(*it)
  1169. {
  1170. IConstWorkflowItem* r = it->query();
  1171. if (!r)
  1172. continue;
  1173. IWorkflowEvent* wfevent = r->getScheduleEvent();
  1174. if (!wfevent)
  1175. continue;
  1176. StringBuffer id;
  1177. Owned<IEspECLWorkflow> g = createECLWorkflow();
  1178. g->setWFID(id.appendf("%d", r->queryWfid()).str());
  1179. g->setEventName(wfevent->queryName());
  1180. g->setEventText(wfevent->queryText());
  1181. if (r->hasScheduleCount())
  1182. {
  1183. g->setCount(r->queryScheduleCount());
  1184. g->setCountRemaining(r->queryScheduleCountRemaining());
  1185. }
  1186. workflows.append(*g.getLink());
  1187. }
  1188. if (workflows.length() > 0)
  1189. info.setWorkflows(workflows);
  1190. }
  1191. catch(IException* e)
  1192. {
  1193. StringBuffer eMsg;
  1194. IERRLOG("%s", e->errorMessage(eMsg).str());
  1195. info.setWorkflowsDesc(eMsg.str());
  1196. e->Release();
  1197. }
  1198. }
  1199. IDistributedFile* WsWuInfo::getLogicalFileData(IEspContext& context, const char* logicalName, bool& showFileContent)
  1200. {
  1201. Owned<IDistributedFile> df = lookupLogicalName(context, logicalName, false, false, false, nullptr, defaultPrivilegedUser);
  1202. if (!df)
  1203. return nullptr;
  1204. bool blocked;
  1205. if (df->isCompressed(&blocked) && !blocked)
  1206. return df.getClear();
  1207. IPropertyTree& properties = df->queryAttributes();
  1208. const char * format = properties.queryProp("@format");
  1209. if (format && (stricmp(format,"csv")==0 || memicmp(format, "utf", 3) == 0))
  1210. {
  1211. showFileContent = true;
  1212. return df.getClear();
  1213. }
  1214. const char * recordEcl = properties.queryProp("ECL");
  1215. if (!recordEcl)
  1216. return df.getClear();
  1217. MultiErrorReceiver errs;
  1218. Owned<IHqlExpression> ret = ::parseQuery(recordEcl, &errs);
  1219. showFileContent = errs.errCount() == 0;
  1220. return df.getClear();
  1221. }
  1222. void WsWuInfo::getEclSchemaChildFields(IArrayOf<IEspECLSchemaItem>& schemas, IHqlExpression * expr, bool isConditional)
  1223. {
  1224. if(!expr)
  1225. return;
  1226. ForEachChild(idx, expr)
  1227. getEclSchemaFields(schemas, expr->queryChild(idx), isConditional);
  1228. }
  1229. void WsWuInfo::getEclSchemaFields(IArrayOf<IEspECLSchemaItem>& schemas, IHqlExpression * expr, bool isConditional)
  1230. {
  1231. if(!expr)
  1232. return;
  1233. int ret = expr->getOperator();
  1234. switch (ret)
  1235. {
  1236. case no_record:
  1237. getEclSchemaChildFields(schemas, expr, isConditional);
  1238. break;
  1239. case no_ifblock:
  1240. {
  1241. getEclSchemaChildFields(schemas, expr->queryChild(1), true);
  1242. break;
  1243. }
  1244. case no_field:
  1245. {
  1246. if (expr->hasAttribute(__ifblockAtom))
  1247. break;
  1248. ITypeInfo * type = expr->queryType();
  1249. IAtom * name = expr->queryName();
  1250. IHqlExpression * nameAttr = expr->queryAttribute(namedAtom);
  1251. StringBuffer outname;
  1252. if (nameAttr && nameAttr->queryChild(0) && nameAttr->queryChild(0)->queryValue())
  1253. nameAttr->queryChild(0)->queryValue()->getStringValue(outname);
  1254. else
  1255. outname.append(name).toLowerCase();
  1256. if(type)
  1257. {
  1258. type_t tc = type->getTypeCode();
  1259. if (tc == type_row)
  1260. {
  1261. getEclSchemaChildFields(schemas, expr->queryRecord(), isConditional);
  1262. }
  1263. else
  1264. {
  1265. if (type->getTypeCode() == type_alien)
  1266. {
  1267. IHqlAlienTypeInfo * alien = queryAlienType(type);
  1268. type = alien->queryPhysicalType();
  1269. }
  1270. Owned<IEspECLSchemaItem> schema = createECLSchemaItem("","");
  1271. StringBuffer eclType;
  1272. type->getECLType(eclType);
  1273. schema->setColumnName(outname);
  1274. schema->setColumnType(eclType.str());
  1275. schema->setColumnTypeCode(tc);
  1276. schema->setIsConditional(isConditional);
  1277. schemas.append(*schema.getClear());
  1278. }
  1279. }
  1280. break;
  1281. }
  1282. }
  1283. }
  1284. bool WsWuInfo::getResultEclSchemas(IConstWUResult &r, IArrayOf<IEspECLSchemaItem>& schemas)
  1285. {
  1286. SCMStringBuffer schema;
  1287. r.getResultEclSchema(schema);
  1288. if (!schema.length())
  1289. return false;
  1290. MultiErrorReceiver errs;
  1291. Owned<IHqlExpression> expr = ::parseQuery(schema.str(), &errs);
  1292. if (errs.errCount() != 0)
  1293. return false;
  1294. getEclSchemaFields(schemas, expr, false);
  1295. return true;
  1296. }
  1297. void WsWuInfo::getResult(IConstWUResult &r, IArrayOf<IEspECLResult>& results, unsigned long flags)
  1298. {
  1299. SCMStringBuffer name;
  1300. r.getResultName(name);
  1301. SCMStringBuffer filename;
  1302. r.getResultLogicalName(filename);
  1303. bool showFileContent = false;
  1304. Owned<IDistributedFile> df = NULL;
  1305. if (filename.length())
  1306. df.setown(getLogicalFileData(context, filename.str(), showFileContent));
  1307. StringBuffer value, link;
  1308. if (r.getResultStatus() == ResultStatusUndefined)
  1309. value.set("[undefined]");
  1310. else if (r.isResultScalar())
  1311. {
  1312. try
  1313. {
  1314. SCMStringBuffer xml;
  1315. r.getResultXml(xml, true);
  1316. Owned<IPropertyTree> props = createPTreeFromXMLString(xml.str(), ipt_caseInsensitive);
  1317. IPropertyTree *val = props->queryPropTree("Row/*");
  1318. if(val)
  1319. value.set(val->queryProp(NULL));
  1320. else
  1321. {
  1322. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  1323. Owned<INewResultSet> result;
  1324. result.setown(resultSetFactory->createNewResultSet(&r, wuid.str()));
  1325. Owned<IResultSetCursor> cursor(result->createCursor());
  1326. cursor->first();
  1327. if (r.getResultIsAll())
  1328. {
  1329. value.set("<All/>");
  1330. }
  1331. else
  1332. {
  1333. Owned<IResultSetCursor> childCursor = cursor->getChildren(0);
  1334. if (childCursor)
  1335. {
  1336. ForEach(*childCursor)
  1337. {
  1338. StringBuffer out;
  1339. StringBufferAdaptor adaptor(out);
  1340. childCursor->getDisplayText(adaptor, 0);
  1341. if (!value.length())
  1342. value.append('[');
  1343. else
  1344. value.append(", ");
  1345. value.append('\'').append(out.str()).append('\'');
  1346. }
  1347. if (value.length())
  1348. value.append(']');
  1349. }
  1350. }
  1351. }
  1352. }
  1353. catch(...)
  1354. {
  1355. value.append("[value not available]");
  1356. }
  1357. }
  1358. else
  1359. {
  1360. value.append('[').append(r.getResultTotalRowCount()).append(" rows]");
  1361. if((r.getResultSequence()>=0) && (!filename.length() || (df && df->queryAttributes().hasProp("ECL"))))
  1362. link.append(r.getResultSequence());
  1363. }
  1364. Owned<IEspECLResult> result= createECLResult("","");
  1365. if (flags & WUINFO_IncludeEclSchemas)
  1366. {
  1367. IArrayOf<IEspECLSchemaItem> schemas;
  1368. if (getResultEclSchemas(r, schemas))
  1369. result->setECLSchemas(schemas);
  1370. }
  1371. if (flags & WUINFO_IncludeXmlSchema)
  1372. {
  1373. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  1374. Owned<INewResultSet> rs = resultSetFactory->createNewResultSet(&r, wuid.str());
  1375. Owned<IResultSetCursor> cursor(rs->createCursor());
  1376. SCMStringBuffer xsd;
  1377. const IResultSetMetaData & meta = cursor->queryResultSet()->getMetaData();
  1378. meta.getXmlXPathSchema(xsd, false);
  1379. result->setXmlSchema(xsd.str());
  1380. }
  1381. if (filename.length())
  1382. result->setShowFileContent(showFileContent);
  1383. result->setName(name.str());
  1384. result->setLink(link.str());
  1385. result->setSequence(r.getResultSequence());
  1386. result->setValue(value.str());
  1387. result->setFileName(filename.str());
  1388. result->setIsSupplied(r.getResultStatus() == ResultStatusSupplied);
  1389. result->setTotal(r.getResultTotalRowCount());
  1390. results.append(*result.getLink());
  1391. }
  1392. void WsWuInfo::getResults(IEspECLWorkunit &info, unsigned long flags)
  1393. {
  1394. if (!(flags & WUINFO_IncludeResults))
  1395. return;
  1396. try
  1397. {
  1398. IArrayOf<IEspECLResult> results;
  1399. Owned<IConstWUResultIterator> it = &(cw->getResults());
  1400. ForEach(*it)
  1401. {
  1402. IConstWUResult &r = it->query();
  1403. if(r.getResultSequence()>=0)
  1404. getResult(r, results, flags);
  1405. }
  1406. if (results.length())
  1407. info.setResults(results);
  1408. results.kill();
  1409. }
  1410. catch(IException* e)
  1411. {
  1412. StringBuffer eMsg;
  1413. IERRLOG("%s", e->errorMessage(eMsg).str());
  1414. info.setResultsDesc(eMsg.str());
  1415. e->Release();
  1416. }
  1417. }
  1418. class FilteredStatisticsVisitor : public WuScopeVisitorBase
  1419. {
  1420. public:
  1421. FilteredStatisticsVisitor(WsWuInfo & _wuInfo, bool _createDescriptions, IArrayOf<IEspWUStatisticItem>& _statistics, const StatisticsFilter& _statsFilter)
  1422. : wuInfo(_wuInfo), statistics(_statistics), statsFilter(_statsFilter), createDescriptions(_createDescriptions) {}
  1423. virtual void noteStatistic(StatisticKind curKind, unsigned __int64 value, IConstWUStatistic & cur) override
  1424. {
  1425. StringBuffer xmlBuf, tsValue;
  1426. SCMStringBuffer curCreator, curDescription, curFormattedValue;
  1427. StatisticCreatorType curCreatorType = cur.getCreatorType();
  1428. StatisticScopeType curScopeType = cur.getScopeType();
  1429. StatisticMeasure curMeasure = cur.getMeasure();
  1430. unsigned __int64 count = cur.getCount();
  1431. unsigned __int64 max = cur.getMax();
  1432. unsigned __int64 ts = cur.getTimestamp();
  1433. const char * curScope = cur.queryScope();
  1434. cur.getCreator(curCreator);
  1435. cur.getDescription(curDescription, createDescriptions);
  1436. cur.getFormattedValue(curFormattedValue);
  1437. Owned<IEspWUStatisticItem> wuStatistic = createWUStatisticItem();
  1438. if (!statsFilter.matches(curCreatorType, curCreator.str(), curScopeType, curScope, curMeasure, curKind, value))
  1439. return;
  1440. if (wuInfo.version > 1.61)
  1441. wuStatistic->setWuid(wuInfo.wuid);
  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 (!isEmpty(curScope))
  1449. wuStatistic->setScope(curScope);
  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. protected:
  1470. WsWuInfo & wuInfo;
  1471. const StatisticsFilter& statsFilter;
  1472. IArrayOf<IEspWUStatisticItem>& statistics;
  1473. bool createDescriptions;
  1474. };
  1475. void WsWuInfo::getStats(const WuScopeFilter & filter, const StatisticsFilter& statsFilter, bool createDescriptions, IArrayOf<IEspWUStatisticItem>& statistics)
  1476. {
  1477. FilteredStatisticsVisitor visitor(*this, createDescriptions, statistics, statsFilter);
  1478. Owned<IConstWUScopeIterator> it = &cw->getScopeIterator(filter);
  1479. ForEach(*it)
  1480. it->playProperties(visitor);
  1481. }
  1482. bool WsWuInfo::getFileSize(const char* fileName, const char* IPAddress, offset_t& fileSize)
  1483. {
  1484. if (!fileName || !*fileName)
  1485. return false;
  1486. Owned<IFile> aFile;
  1487. if (!IPAddress || !*IPAddress)
  1488. {
  1489. aFile.setown(createIFile(fileName));
  1490. }
  1491. else
  1492. {
  1493. RemoteFilename rfn;
  1494. rfn.setRemotePath(fileName);
  1495. SocketEndpoint ep(IPAddress);
  1496. rfn.setIp(ep);
  1497. aFile.setown(createIFile(rfn));
  1498. }
  1499. if (!aFile)
  1500. return false;
  1501. bool isDir;
  1502. CDateTime modtime;
  1503. if (!aFile->getInfo(isDir, fileSize, modtime) || isDir)
  1504. return false;
  1505. return true;
  1506. }
  1507. void WsWuInfo::getHelpFiles(IConstWUQuery* query, WUFileType type, IArrayOf<IEspECLHelpFile>& helpers, unsigned long flags, unsigned& helpersCount)
  1508. {
  1509. if (!query)
  1510. return;
  1511. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  1512. ForEach(*iter)
  1513. {
  1514. SCMStringBuffer name, Ip, description;
  1515. IConstWUAssociatedFile & cur = iter->query();
  1516. if (cur.getType() != type)
  1517. continue;
  1518. helpersCount++;
  1519. if (!(flags & WUINFO_IncludeHelpers))
  1520. continue;
  1521. cur.getName(name);
  1522. Owned<IEspECLHelpFile> h= createECLHelpFile("","");
  1523. h->setName(name.str());
  1524. h->setType(getEnumText(type, queryFileTypes));
  1525. if (version > 1.31)
  1526. {
  1527. cur.getIp(Ip);
  1528. h->setIPAddress(Ip.str());
  1529. cur.getDescription(description);
  1530. if ((description.length() < 1) && (name.length() > 0))
  1531. {
  1532. const char* desc = pathTail(name.str());
  1533. if (desc && *desc)
  1534. description.set(desc);
  1535. }
  1536. if (description.length() < 1)
  1537. description.set("Help File");
  1538. h->setDescription(description.str());
  1539. if (version >= 1.43)
  1540. {
  1541. offset_t fileSize;
  1542. if (getFileSize(name.str(), Ip.str(), fileSize))
  1543. h->setFileSize(fileSize);
  1544. }
  1545. if (version >= 1.58)
  1546. {
  1547. h->setMinActivityId(cur.getMinActivityId());
  1548. h->setMaxActivityId(cur.getMaxActivityId());
  1549. }
  1550. }
  1551. helpers.append(*h.getLink());
  1552. }
  1553. }
  1554. void WsWuInfo::getSubFiles(IPropertyTreeIterator* f, IEspECLSourceFile* eclSuperFile, StringArray& fileNames)
  1555. {
  1556. IArrayOf<IEspECLSourceFile> files;
  1557. ForEach(*f)
  1558. {
  1559. IPropertyTree &query = f->query();
  1560. const char *clusterName = query.queryProp("@cluster");
  1561. const char *fileName = query.queryProp("@name");
  1562. int fileCount = query.getPropInt("@useCount");
  1563. bool bFound = false;
  1564. if (fileName && *fileName && (fileNames.length() > 0)) // MORE - this is an n^2 process and as far as I can tell unnecessary as there will be no dups
  1565. {
  1566. for (unsigned i = 0; i < fileNames.length(); i++ )
  1567. {
  1568. const char *fileName0 = fileNames.item(i);
  1569. if (!stricmp(fileName, fileName0))
  1570. {
  1571. bFound = true;
  1572. break;
  1573. }
  1574. }
  1575. }
  1576. if (bFound)
  1577. continue;
  1578. Owned<IEspECLSourceFile> file= createECLSourceFile("","");
  1579. if(clusterName && *clusterName)
  1580. {
  1581. file->setFileCluster(clusterName);
  1582. }
  1583. if (fileName && *fileName)
  1584. {
  1585. file->setName(fileName);
  1586. fileNames.append(fileName);
  1587. }
  1588. file->setCount(fileCount);
  1589. Owned<IPropertyTreeIterator> filetrees= query.getElements("Subfile"); // We do not store subfiles of subfiles like this - so this code will never be triggered
  1590. if (filetrees->first())
  1591. {
  1592. file->setIsSuperFile(true);
  1593. getSubFiles(filetrees, file, fileNames);
  1594. }
  1595. files.append(*file.getLink());
  1596. }
  1597. eclSuperFile->setECLSourceFiles(files);
  1598. return;
  1599. }
  1600. bool WsWuInfo::getResourceInfo(StringArray &viewnames, StringArray &urls, unsigned long flags)
  1601. {
  1602. if (!(flags & (WUINFO_IncludeResultsViewNames | WUINFO_IncludeResourceURLs)))
  1603. return true;
  1604. try
  1605. {
  1606. Owned<IWuWebView> wv = createWuWebView(*cw, NULL, NULL, NULL, false, nullptr);
  1607. if (wv)
  1608. {
  1609. if (flags & WUINFO_IncludeResultsViewNames)
  1610. wv->getResultViewNames(viewnames);
  1611. if (flags & WUINFO_IncludeResourceURLs)
  1612. wv->getResourceURLs(urls, NULL);
  1613. }
  1614. return true;
  1615. }
  1616. catch(IException* e)
  1617. {
  1618. StringBuffer eMsg;
  1619. IERRLOG("%s", e->errorMessage(eMsg).str());
  1620. e->Release();
  1621. }
  1622. return false;
  1623. }
  1624. unsigned WsWuInfo::getResourceURLCount()
  1625. {
  1626. try
  1627. {
  1628. Owned<IWuWebView> wv = createWuWebView(*cw, NULL, NULL, NULL, false, nullptr);
  1629. if (wv)
  1630. return wv->getResourceURLCount();
  1631. }
  1632. catch(IException* e)
  1633. {
  1634. StringBuffer eMsg;
  1635. IERRLOG("%s", e->errorMessage(eMsg).str());
  1636. e->Release();
  1637. }
  1638. return 0;
  1639. }
  1640. void WsWuInfo::copyContentFromRemoteFile(const char* sourceFileName, const char* sourceIPAddress,
  1641. const char* sourceAlias, const char *outFileName)
  1642. {
  1643. RemoteFilename rfn;
  1644. rfn.setRemotePath(sourceFileName);
  1645. SocketEndpoint ep(sourceIPAddress);
  1646. rfn.setIp(ep);
  1647. OwnedIFile source = createIFile(rfn);
  1648. if (!source)
  1649. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open %s.", sourceAlias);
  1650. OwnedIFile target = createIFile(outFileName);
  1651. if (!target)
  1652. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open %s.", outFileName);
  1653. copyFile(target, source);
  1654. }
  1655. void WsWuInfo::readFileContent(const char* sourceFileName, const char* sourceIPAddress,
  1656. const char* sourceAlias, MemoryBuffer &mb, bool forDownload)
  1657. {
  1658. RemoteFilename rfn;
  1659. rfn.setRemotePath(sourceFileName);
  1660. SocketEndpoint ep(sourceIPAddress);
  1661. rfn.setIp(ep);
  1662. OwnedIFile source = createIFile(rfn);
  1663. if (!source)
  1664. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open %s.", sourceAlias);
  1665. OwnedIFileIO sourceIO = source->openShared(IFOread,IFSHfull);
  1666. if (!sourceIO)
  1667. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE, "Cannot open %s.", sourceAlias);
  1668. offset_t len = source->size();
  1669. if (!forDownload && (len > 640000))
  1670. len = 640000;
  1671. if (read(sourceIO, 0, len, mb) != len)
  1672. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE, "Cannot read %s.", sourceAlias);
  1673. }
  1674. void WsWuInfo::getWorkunitEclAgentLog(const char* processName, const char* fileName, const char* agentPid, MemoryBuffer& buf, const char* outFile)
  1675. {
  1676. if (isEmptyString(processName) && isEmptyString(fileName))
  1677. throw makeStringException(ECLWATCH_ECLAGENT_LOG_NOT_FOUND, "Log file or process name has to be specified");
  1678. Owned<IFileIOStream> outIOS;
  1679. if (!isEmptyString(outFile))
  1680. {
  1681. CWsWuFileHelper helper(nullptr);
  1682. outIOS.setown(helper.createIOStreamWithFileName(outFile, IFOcreate));
  1683. }
  1684. StringBuffer line;
  1685. bool wuidFound = false;
  1686. bool wuFinish = false;
  1687. StringBuffer pidstr;
  1688. if (agentPid && *agentPid)
  1689. pidstr.appendf(" %s ", agentPid);
  1690. else
  1691. pidstr.appendf(" %5d ", cw->getAgentPID());
  1692. char const* pidchars = pidstr.str();
  1693. size32_t pidLen = pidstr.length();
  1694. unsigned pidOffset = 0;//offset of PID in logfile entry
  1695. //If a WU runs into another day, the WU information is stored in multiple log files.
  1696. //Find out the logSpec for each log file based on the given processName or fileName.
  1697. StringArray logSpecs;
  1698. getWUProcessLogSpecs(processName, fileName, nullptr, true, logSpecs);
  1699. ForEachItemIn(i, logSpecs)
  1700. {
  1701. if (wuFinish)
  1702. break;
  1703. Owned<IFile> rFile = createIFile(logSpecs.item(i));
  1704. if (!rFile)
  1705. throw makeStringExceptionV(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open file %s.", logSpecs.item(i));
  1706. OwnedIFileIO rIO = rFile->openShared(IFOread,IFSHfull);
  1707. if (!rIO)
  1708. throw makeStringExceptionV(ECLWATCH_CANNOT_READ_FILE, "Cannot read file %s.", logSpecs.item(i));
  1709. OwnedIFileIOStream ios = createIOStream(rIO);
  1710. Owned<IStreamLineReader> lineReader = createLineReader(ios, true);
  1711. /*
  1712. Scan the master daily logfile for given PID/WUID. We make the following assumptions
  1713. Column ordering (time, date, pid) is unknown, but we must assume it is constant throughout the logfile.
  1714. It is assumed that the first column is the 8 digit workunit logfile line number.
  1715. Rows from concurrent workunits are intermixed.
  1716. Logfiles are searched via PID and WUID. You are not assured of a match until you have both.
  1717. PIDS and TIDS can and are reused. Beware that a TID could match the search PID.
  1718. Once you have both, you know the offset of the PID column. It is assumed this offset remains constant.
  1719. Search stops at EOF, or early exit if the search PID reappears on different WUID.
  1720. */
  1721. while (!lineReader->readLine(line.clear()))
  1722. {
  1723. if (pidOffset > line.length())
  1724. continue;
  1725. //Retain all rows that match a unique program instance - by retaining all rows that match a pid
  1726. const char* pPid = strstr(line.str() + pidOffset, pidchars);
  1727. if (isEmptyString(pPid))
  1728. continue;
  1729. //Check if this is a new instance using line sequence number (PIDs are often reused)
  1730. if (strncmp(line.str(), "00000000", 8) == 0)
  1731. {
  1732. if (wuidFound) //If the correct instance has been found, return that instance before the next instance.
  1733. {
  1734. wuFinish = true;
  1735. break;
  1736. }
  1737. //The last instance is not a correct instance. Clean the buf in order to start a new instance.
  1738. if (isEmptyString(outFile))
  1739. buf.clear();
  1740. }
  1741. //If we spot the workunit id anywhere in the tracing for this pid then assume it is the correct instance.
  1742. if(!wuidFound && strstr(line.str(), wuid.str()))
  1743. {
  1744. pidOffset = pPid - line.str();//remember offset of PID within line
  1745. wuidFound = true;
  1746. }
  1747. if (pidOffset && 0 == strncmp(line.str() + pidOffset, pidchars, pidLen))//this makes sure the match was the PID and not the TID or something else
  1748. outputALine(line.length(), line.str(), buf, outIOS);
  1749. }
  1750. }
  1751. if (!wuidFound)
  1752. {
  1753. const char * msg = "(No logfile entries found for this workunit)";
  1754. outputALine(strlen(msg), msg, buf, outIOS);
  1755. }
  1756. }
  1757. void WsWuInfo::getWorkunitThorMasterLog(const char* processName, const char* fileName, MemoryBuffer& buf, const char* outFile)
  1758. {
  1759. readWorkunitThorLog(processName, fileName, nullptr, 0, buf, outFile);
  1760. }
  1761. void WsWuInfo::getWorkunitThorSlaveLog(IGroup *nodeGroup, const char *ipAddress, const char* processName, const char* logDate,
  1762. const char* logDir, int slaveNum, MemoryBuffer& buf, const char* outFile, bool forDownload)
  1763. {
  1764. if (isEmpty(logDir))
  1765. throw MakeStringException(ECLWATCH_INVALID_INPUT,"ThorSlave log path not specified.");
  1766. StringBuffer slaveIPAddress;
  1767. if (slaveNum > 0)
  1768. {
  1769. nodeGroup->queryNode(slaveNum-1).endpoint().getIpText(slaveIPAddress);
  1770. if (slaveIPAddress.length() < 1)
  1771. throw makeStringException(ECLWATCH_INVALID_INPUT, "ThorSlave log network address not found.");
  1772. readWorkunitThorLog(processName, logDir, slaveIPAddress, slaveNum, buf, outFile);
  1773. }
  1774. else
  1775. {//legacy wuid: a user types in an IP address for a thor slave
  1776. if (isEmpty(logDate))
  1777. throw makeStringException(ECLWATCH_INVALID_INPUT,"ThorSlave log date not specified.");
  1778. if (isEmpty(ipAddress))
  1779. throw MakeStringException(ECLWATCH_INVALID_INPUT,"ThorSlave address not specified.");
  1780. StringBuffer logName(logDir);
  1781. addPathSepChar(logName);
  1782. //thorslave.10.239.219.6_20100.2012_05_23.log
  1783. logName.appendf("thorslave.%s*.%s.log", ipAddress, logDate);
  1784. const char* portPtr = strchr(ipAddress, '_');
  1785. if (!portPtr)
  1786. slaveIPAddress.append(ipAddress);
  1787. else
  1788. {
  1789. StringBuffer ipAddressStr(ipAddress);
  1790. ipAddressStr.setLength(portPtr - ipAddress);
  1791. slaveIPAddress.append(ipAddressStr.str());
  1792. }
  1793. readFileContent(logName, slaveIPAddress.str(), logName, buf, forDownload);
  1794. }
  1795. }
  1796. void WsWuInfo::getWorkunitThorSlaveLog(IPropertyTree* directories, const char *process,
  1797. const char* instanceName, const char *ipAddress, const char* logDate, int slaveNum,
  1798. MemoryBuffer& buf, const char* outFile, bool forDownload)
  1799. {
  1800. StringBuffer logDir, groupName;
  1801. getConfigurationDirectory(directories, "log", "thor", process, logDir);
  1802. getClusterThorGroupName(groupName, instanceName);
  1803. if (groupName.isEmpty())
  1804. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed to get Thor Group Name for %s", instanceName);
  1805. Owned<IGroup> nodeGroup = queryNamedGroupStore().lookup(groupName);
  1806. if (!nodeGroup || (nodeGroup->ordinality() == 0))
  1807. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Node group %s not found", groupName.str());
  1808. getWorkunitThorSlaveLog(nodeGroup, ipAddress, process, logDate, logDir.str(), slaveNum, buf, outFile, forDownload);
  1809. }
  1810. void WsWuInfo::readWorkunitThorLog(const char* processName, const char* log, const char* slaveIPAddress, unsigned slaveNum, MemoryBuffer& buf, const char* outFile)
  1811. {
  1812. Owned<IFileIOStream> outIOS;
  1813. if (!isEmptyString(outFile))
  1814. {
  1815. CWsWuFileHelper helper(nullptr);
  1816. outIOS.setown(helper.createIOStreamWithFileName(outFile, IFOcreate));
  1817. }
  1818. StringArray logSpecs;
  1819. if (slaveIPAddress) //thor slave
  1820. getWUProcessLogSpecs(processName, nullptr, log, false, logSpecs); //log: logDir
  1821. else
  1822. getWUProcessLogSpecs(processName, log, nullptr, false, logSpecs); //log: logSpec
  1823. unsigned processID = 0; //The processID is unknown at the begining of the first day.
  1824. ForEachItemIn(i, logSpecs)
  1825. {
  1826. const char* logSpec = logSpecs.item(i);
  1827. Owned<IFile> rFile;
  1828. if (slaveIPAddress)
  1829. {
  1830. StringBuffer thorMasterLog, ext;
  1831. splitFilename(logSpec, nullptr, nullptr, &thorMasterLog, &ext);
  1832. StringBuffer logSpecStr(log);
  1833. addPathSepChar(logSpecStr);
  1834. //Append the file name of the slave log to logSpecStr.
  1835. //The pattern of the file name is: thorslave.SLAVENUM.LOGDATE.log.
  1836. //ex. thorslave.2.2020_09_16.log
  1837. //The LOGDATE is parsed from the thorMasterLog (ex. thormaster.2020_09_16).
  1838. logSpecStr.appendf("thorslave.%u%s%s", slaveNum, thorMasterLog.str() + strlen("thormaster"), ext.str());
  1839. RemoteFilename rfn;
  1840. rfn.setRemotePath(logSpecStr);
  1841. SocketEndpoint ep(slaveIPAddress);
  1842. rfn.setIp(ep);
  1843. rFile.setown(createIFile(rfn));
  1844. if (!rFile)
  1845. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open file %s on %s.", logSpecStr.str(), slaveIPAddress);
  1846. }
  1847. else
  1848. {
  1849. rFile.setown(createIFile(logSpec));
  1850. if (!rFile)
  1851. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Cannot open file %s.", logSpec);
  1852. }
  1853. readWorkunitThorLogOneDay(rFile, processID, buf, outIOS);
  1854. }
  1855. }
  1856. void WsWuInfo::readWorkunitThorLogOneDay(IFile* sourceFile, unsigned& processID, MemoryBuffer& buf, IFileIOStream* outIOS)
  1857. {
  1858. OwnedIFileIO sourceIO = sourceFile->openShared(IFOread,IFSHfull);
  1859. if (!sourceIO)
  1860. throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read file %s.", sourceFile->queryFilename());
  1861. Owned<IFileIOStream> ios = createIOStream(sourceIO);
  1862. VStringBuffer startwuid("Started wuid=%s", wuid.str());
  1863. VStringBuffer endwuid("Finished wuid=%s", wuid.str());
  1864. StringBuffer line;
  1865. Owned<IStreamLineReader> lineReader = createLineReader(ios, true);
  1866. bool eof = lineReader->readLine(line.clear());
  1867. if (eof)
  1868. return;
  1869. // Process header for log file format
  1870. unsigned logfields = getMessageFieldsFromHeader(line);
  1871. if (logfields==0) // No header line, so must be in legacy format
  1872. logfields = MSGFIELD_LEGACY;
  1873. else
  1874. eof = lineReader->readLine(line.clear());
  1875. const unsigned columnNumPID = getPositionOfField(logfields, MSGFIELD_process);
  1876. bool outputThisLine = false;
  1877. if (processID > 0) //after the 1st page of the log
  1878. outputThisLine = true;
  1879. bool foundEndWUID = false;
  1880. while (!eof)
  1881. {
  1882. if (outputThisLine)
  1883. {
  1884. //If the slave is restarted before WU is finished, we cannot find out the "Finished wuid=...".
  1885. //So, we should check whether the slave is restarting or not.
  1886. unsigned pID = 0;
  1887. foundEndWUID = parseLogLine(line.str(), endwuid, pID, columnNumPID);
  1888. if ((pID > 0) && (pID != processID))
  1889. break;
  1890. outputALine(line.length(), line.str(), buf, outIOS);
  1891. if (foundEndWUID)
  1892. outputThisLine = false;
  1893. }
  1894. else if (strstr(line.str(), startwuid))
  1895. {
  1896. outputThisLine = true;
  1897. foundEndWUID = false;
  1898. outputALine(line.length(), line.str(), buf, outIOS);
  1899. if (processID == 0)
  1900. parseLogLine(line.str(), nullptr, processID, columnNumPID);
  1901. }
  1902. eof = lineReader->readLine(line.clear());
  1903. }
  1904. }
  1905. bool WsWuInfo::parseLogLine(const char* line, const char* endWUID, unsigned& processID, const unsigned columnNumPID)
  1906. {
  1907. const char* bptr = line;
  1908. for (unsigned cur=0; cur < columnNumPID && *bptr; ++cur)
  1909. {
  1910. while(*bptr && *bptr!=' ') ++bptr; // Skip field
  1911. while(*bptr && *bptr==' ') ++bptr; // Skip spaces
  1912. }
  1913. if (!*bptr) return false;
  1914. const char* eptr = bptr + 1;
  1915. while (*eptr && isdigit(*eptr)) //Read ProcessID
  1916. eptr++;
  1917. if (*eptr != ' ')
  1918. return false;
  1919. processID = (unsigned) atoi_l(bptr, eptr - bptr);
  1920. return (endWUID && strstr(eptr+1, endWUID));
  1921. }
  1922. void WsWuInfo::getWUProcessLogSpecs(const char* processName, const char* logSpec, const char* logDir, bool eclAgent, StringArray& logSpecs)
  1923. {
  1924. Owned<IStringIterator> logs;
  1925. if (eclAgent)
  1926. logs.setown(cw->getLogs("EclAgent"));
  1927. else
  1928. { //Thor
  1929. if (!isEmptyString(processName))
  1930. logs.setown(cw->getLogs("Thor", processName));
  1931. else
  1932. {
  1933. //Parse the process name from the logSpec or logDir.
  1934. if (isEmptyString(logSpec) && isEmptyString(logDir))
  1935. throw makeStringException(ECLWATCH_ECLAGENT_LOG_NOT_FOUND, "Process name and log file not specified");
  1936. StringBuffer path, process;
  1937. if (!isEmptyString(logDir))
  1938. path.set(logDir);
  1939. else
  1940. {
  1941. //Parse the path from the logSpec (ex.: //10.173.123.208/mnt/disk1/var/log/HPCCSystems/mythor/thormaster.2020_01_16.log)
  1942. splitFilename(logSpec, nullptr, &path, nullptr, nullptr);
  1943. }
  1944. //Parse the process name (ex. mythor) from the path (ex.: //10.173.123.208/mnt/disk1/var/log/HPCCSystems/mythor/)
  1945. removeTrailingPathSepChar(path);
  1946. splitFilename(path, nullptr, nullptr, &process, nullptr);
  1947. logs.setown(cw->getLogs("Thor", process));
  1948. }
  1949. }
  1950. ForEach (*logs)
  1951. {
  1952. SCMStringBuffer logStr;
  1953. logs->str(logStr);
  1954. if (logStr.length() < 1)
  1955. continue;
  1956. logSpecs.append(logStr.str());
  1957. }
  1958. if (logSpecs.length() > 1)
  1959. logSpecs.sortAscii(false); //Sort the logSpecs from old to new
  1960. }
  1961. void WsWuInfo::getWorkunitResTxt(MemoryBuffer& buf)
  1962. {
  1963. Owned<IConstWUQuery> query = cw->getQuery();
  1964. if(!query)
  1965. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  1966. SCMStringBuffer resname;
  1967. queryDllServer().getDll(query->getQueryResTxtName(resname).str(), buf);
  1968. }
  1969. IConstWUQuery* WsWuInfo::getEmbeddedQuery()
  1970. {
  1971. Owned<IWuWebView> wv = createWuWebView(*cw, NULL, NULL, NULL, false, nullptr);
  1972. if (wv)
  1973. return wv->getEmbeddedQuery();
  1974. return NULL;
  1975. }
  1976. void WsWuInfo::getWorkunitArchiveQuery(IStringVal& str)
  1977. {
  1978. Owned<IConstWUQuery> query = cw->getQuery();
  1979. if(!query)
  1980. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  1981. query->getQueryText(str);
  1982. if ((str.length() < 1) || !isArchiveQuery(str.str()))
  1983. {
  1984. if (!query->hasArchive())
  1985. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Archive query not found for workunit %s.", wuid.str());
  1986. Owned<IConstWUQuery> embeddedQuery = getEmbeddedQuery();
  1987. if (!embeddedQuery)
  1988. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Embedded query not found for workunit %s.", wuid.str());
  1989. embeddedQuery->getQueryText(str);
  1990. if ((str.length() < 1) || !isArchiveQuery(str.str()))
  1991. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Archive query not found for workunit %s.", wuid.str());
  1992. }
  1993. }
  1994. void WsWuInfo::getWorkunitArchiveQuery(StringBuffer& buf)
  1995. {
  1996. StringBufferAdaptor queryText(buf);
  1997. getWorkunitArchiveQuery(queryText);
  1998. }
  1999. void WsWuInfo::getWorkunitArchiveQuery(MemoryBuffer& buf)
  2000. {
  2001. SCMStringBuffer queryText;
  2002. getWorkunitArchiveQuery(queryText);
  2003. buf.append(queryText.length(), queryText.str());
  2004. }
  2005. void WsWuInfo::getWorkunitQueryShortText(MemoryBuffer& buf, const char* outFile)
  2006. {
  2007. Owned<IConstWUQuery> query = cw->getQuery();
  2008. if(!query)
  2009. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  2010. SCMStringBuffer queryText;
  2011. query->getQueryShortText(queryText);
  2012. if (queryText.length() < 1)
  2013. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU, "No query for workunit %s.",wuid.str());
  2014. if (isEmptyString(outFile))
  2015. buf.append(queryText.length(), queryText.str());
  2016. else
  2017. {
  2018. CWsWuFileHelper helper(nullptr);
  2019. Owned<IFileIOStream> outIOS = helper.createIOStreamWithFileName(outFile, IFOcreate);
  2020. outIOS->write(queryText.length(), queryText.str());
  2021. }
  2022. }
  2023. void WsWuInfo::getWorkunitDll(StringBuffer &dllname, MemoryBuffer& buf)
  2024. {
  2025. Owned<IConstWUQuery> query = cw->getQuery();
  2026. if(!query)
  2027. throw MakeStringException(ECLWATCH_QUERY_NOT_FOUND_FOR_WU,"No query for workunit %s.",wuid.str());
  2028. StringBufferAdaptor isvName(dllname);
  2029. query->getQueryDllName(isvName);
  2030. queryDllServer().getDll(dllname.str(), buf);
  2031. }
  2032. void WsWuInfo::getWorkunitXml(const char* plainText, MemoryBuffer& buf)
  2033. {
  2034. const char* header;
  2035. if (plainText && (!stricmp(plainText, "yes")))
  2036. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  2037. else
  2038. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet href=\"../esp/xslt/xmlformatter.xsl\" type=\"text/xsl\"?>";
  2039. StringBuffer xml;
  2040. exportWorkUnitToXML(cw, xml, true, false, true);
  2041. buf.append(strlen(header), header);
  2042. buf.append(xml.length(), xml.str());
  2043. }
  2044. void WsWuInfo::getWorkunitCpp(const char* cppname, const char* description, const char* ipAddress, MemoryBuffer& buf, bool forDownload, const char* outFile)
  2045. {
  2046. if (isEmpty(description))
  2047. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File not specified.");
  2048. if (isEmpty(ipAddress))
  2049. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File location not specified.");
  2050. if (isEmpty(cppname))
  2051. throw MakeStringException(ECLWATCH_INVALID_FILE_NAME, "File path not specified.");
  2052. if (isEmpty(outFile))
  2053. readFileContent(cppname, ipAddress, description, buf, forDownload);
  2054. else
  2055. copyContentFromRemoteFile(cppname, ipAddress, description, outFile);
  2056. }
  2057. void WsWuInfo::getWorkunitAssociatedXml(const char* name, const char* ipAddress, const char* plainText,
  2058. const char* description, bool forDownload, bool addXMLDeclaration, MemoryBuffer& buf, const char* outFile)
  2059. {
  2060. if (isEmpty(description)) //'File Name' as shown in WU Details page
  2061. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File not specified.");
  2062. if (isEmpty(ipAddress))
  2063. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File location not specified.");
  2064. if (isEmpty(name)) //file name with full path
  2065. throw MakeStringException(ECLWATCH_INVALID_FILE_NAME, "File path not specified.");
  2066. if (addXMLDeclaration)
  2067. {
  2068. const char* header;
  2069. if (plainText && (!stricmp(plainText, "yes")))
  2070. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  2071. else
  2072. header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet href=\"../esp/xslt/xmlformatter.xsl\" type=\"text/xsl\"?>";
  2073. buf.append(strlen(header), header);
  2074. }
  2075. if (isEmpty(outFile))
  2076. readFileContent(name, ipAddress, description, buf, forDownload);
  2077. else
  2078. copyContentFromRemoteFile(name, ipAddress, description, outFile);
  2079. }
  2080. IPropertyTree* WsWuInfo::getWorkunitArchive()
  2081. {
  2082. Owned <IConstWUQuery> query = cw->getQuery();
  2083. if(!query)
  2084. return NULL;
  2085. SCMStringBuffer name, ip;
  2086. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  2087. ForEach(*iter)
  2088. {
  2089. IConstWUAssociatedFile& cur = iter->query();
  2090. if (cur.getType() != FileTypeXml)
  2091. continue;
  2092. cur.getName(name);
  2093. if (name.length() < 15)
  2094. continue;
  2095. const char* pStr = name.str() + name.length() - 15;
  2096. if (strieq(pStr, ".archive.eclxml"))
  2097. {
  2098. cur.getIp(ip);
  2099. break;
  2100. }
  2101. }
  2102. if (!ip.length())
  2103. return NULL;
  2104. MemoryBuffer content;
  2105. getWorkunitAssociatedXml(name.str(), ip.str(), "", "WU archive eclxml", true, false, content, nullptr);
  2106. if (!content.length())
  2107. return NULL;
  2108. return createPTreeFromXMLString(content.length(), content.toByteArray());
  2109. }
  2110. IEspWUArchiveFile* WsWuInfo::readArchiveFileAttr(IPropertyTree& fileTree, const char* path)
  2111. {
  2112. const char* fileName = fileTree.queryProp("@name");
  2113. if (isEmpty(fileName))
  2114. return NULL;
  2115. Owned<IEspWUArchiveFile> file= createWUArchiveFile();
  2116. file->setName(fileName);
  2117. if (!isEmpty(path))
  2118. file->setPath(path);
  2119. if (fileTree.hasProp("@key"))
  2120. file->setKey(fileTree.queryProp("@key"));
  2121. if (fileTree.hasProp("@sourcePath"))
  2122. file->setSourcePath(fileTree.queryProp("@sourcePath"));
  2123. return file.getClear();
  2124. }
  2125. IEspWUArchiveModule* WsWuInfo::readArchiveModuleAttr(IPropertyTree& moduleTree, const char* path)
  2126. {
  2127. const char* moduleName = moduleTree.queryProp("@name");
  2128. if (isEmpty(moduleName))
  2129. return NULL;
  2130. Owned<IEspWUArchiveModule> module= createWUArchiveModule();
  2131. module->setName(moduleName);
  2132. if (!isEmpty(path))
  2133. module->setPath(path);
  2134. if (moduleTree.hasProp("@fullName"))
  2135. module->setFullName(moduleTree.queryProp("@fullName"));
  2136. if (moduleTree.hasProp("@key"))
  2137. module->setKey(moduleTree.queryProp("@key"));
  2138. if (moduleTree.hasProp("@plugin"))
  2139. module->setPlugin(moduleTree.queryProp("@plugin"));
  2140. if (moduleTree.hasProp("@version"))
  2141. module->setVersion(moduleTree.queryProp("@version"));
  2142. if (moduleTree.hasProp("@sourcePath"))
  2143. module->setSourcePath(moduleTree.queryProp("@sourcePath"));
  2144. if (moduleTree.hasProp("@flags"))
  2145. module->setFlags(moduleTree.getPropInt("@flags", 0));
  2146. return module.getClear();
  2147. }
  2148. void WsWuInfo::readArchiveFiles(IPropertyTree* archiveTree, const char* path, IArrayOf<IEspWUArchiveFile>& files)
  2149. {
  2150. Owned<IPropertyTreeIterator> iter = archiveTree->getElements("Attribute");
  2151. ForEach(*iter)
  2152. {
  2153. IPropertyTree& item = iter->query();
  2154. Owned<IEspWUArchiveFile> file = readArchiveFileAttr(item, path);
  2155. if (file)
  2156. files.append(*file.getClear());
  2157. }
  2158. }
  2159. void WsWuInfo::listArchiveFiles(IPropertyTree* archiveTree, const char* path, IArrayOf<IEspWUArchiveModule>& modules, IArrayOf<IEspWUArchiveFile>& files)
  2160. {
  2161. if (!archiveTree)
  2162. return;
  2163. Owned<IPropertyTreeIterator> iter = archiveTree->getElements("Module");
  2164. ForEach(*iter)
  2165. {
  2166. IPropertyTree& item = iter->query();
  2167. Owned<IEspWUArchiveModule> module = readArchiveModuleAttr(item, path);
  2168. if (!module)
  2169. continue;
  2170. StringBuffer newPath;
  2171. if (isEmpty(path))
  2172. newPath.set(module->getName());
  2173. else
  2174. newPath.setf("%s/%s", path, module->getName());
  2175. IArrayOf<IEspWUArchiveModule> modulesInModule;
  2176. IArrayOf<IEspWUArchiveFile> filesInModule;
  2177. listArchiveFiles(&item, newPath.str(), modulesInModule, filesInModule);
  2178. if (modulesInModule.length())
  2179. module->setArchiveModules(modulesInModule);
  2180. if (filesInModule.length())
  2181. module->setFiles(filesInModule);
  2182. modules.append(*module.getClear());
  2183. }
  2184. readArchiveFiles(archiveTree, path, files);
  2185. }
  2186. void WsWuInfo::getArchiveFile(IPropertyTree* archive, const char* moduleName, const char* attrName, const char* path, StringBuffer& file)
  2187. {
  2188. StringBuffer xPath;
  2189. if (!isEmpty(path))
  2190. {
  2191. StringArray list;
  2192. list.appendListUniq(path, "/");
  2193. ForEachItemIn(m, list)
  2194. {
  2195. const char* module = list.item(m);
  2196. if (!isEmpty(module))
  2197. xPath.appendf("Module[@name=\"%s\"]/", module);
  2198. }
  2199. }
  2200. if (isEmpty(moduleName))
  2201. xPath.appendf("Attribute[@name=\"%s\"]", attrName);
  2202. else
  2203. xPath.appendf("Module[@name=\"%s\"]/Text", moduleName);
  2204. file.set(archive->queryProp(xPath.str()));
  2205. }
  2206. void WsWuInfo::outputALine(size32_t length, const char* content, MemoryBuffer& outputBuf, IFileIOStream* outIOS)
  2207. {
  2208. if (outIOS)
  2209. outIOS->write(length, content);
  2210. else
  2211. outputBuf.append(length, content);
  2212. }
  2213. WsWuSearch::WsWuSearch(IEspContext& context,const char* owner,const char* state,const char* cluster,const char* startDate,const char* endDate,const char* jobname)
  2214. {
  2215. SecAccessFlags accessOwn;
  2216. SecAccessFlags accessOthers;
  2217. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  2218. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2219. Owned<IConstWorkUnitIterator> it(factory->getWorkUnitsByOwner(owner)); // null owner means fetch all
  2220. StringBuffer wuFrom, wuTo, jobPattern;
  2221. if (startDate && *startDate)
  2222. createWuidFromDate(startDate, wuFrom);
  2223. if (endDate && *endDate)
  2224. createWuidFromDate(endDate, wuTo);
  2225. if (jobname && *jobname)
  2226. jobPattern.appendf("*%s*", jobname);
  2227. ForEach(*it)
  2228. {
  2229. IConstWorkUnitInfo &cw = it->query();
  2230. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  2231. continue;
  2232. if (state && *state && !strieq(cw.queryStateDesc(), state))
  2233. continue;
  2234. if (cluster && *cluster && !strieq(cw.queryClusterName(), cluster))
  2235. continue;
  2236. if (jobPattern.length() && !WildMatch(cw.queryJobName(), jobPattern, true))
  2237. continue;
  2238. const char *wuid = cw.queryWuid();
  2239. if (wuFrom.length() && strcmp(wuid,wuFrom.str())<0)
  2240. continue;
  2241. if (wuTo.length() && strcmp(wuid, wuTo.str())>0)
  2242. continue;
  2243. wuids.push_back(wuid);
  2244. }
  2245. std::sort(wuids.begin(), wuids.end(),std::greater<std::string>());
  2246. }
  2247. StringBuffer& WsWuSearch::createWuidFromDate(const char* timestamp,StringBuffer& s)
  2248. {
  2249. CDateTime wuTime;
  2250. wuTime.setString(timestamp,NULL,true);
  2251. unsigned year, month, day, hour, minute, second, nano;
  2252. wuTime.getDate(year, month, day, true);
  2253. wuTime.getTime(hour, minute, second, nano, true);
  2254. s.appendf("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
  2255. return s;
  2256. }
  2257. struct CompareData
  2258. {
  2259. CompareData(const char* _filter): filter(_filter) {}
  2260. bool operator()(const Linked<DataCacheElement>& e) const
  2261. {
  2262. return stricmp(e->m_filter.c_str(),filter)==0;
  2263. }
  2264. const char* filter;
  2265. };
  2266. DataCacheElement* DataCache::lookup(IEspContext &context, const char* filter, unsigned timeOutMin)
  2267. {
  2268. CriticalBlock block(crit);
  2269. if (cache.size() < 1)
  2270. return NULL;
  2271. //erase data if it should be
  2272. CDateTime timeNow;
  2273. int timeout = timeOutMin;
  2274. timeNow.setNow();
  2275. timeNow.adjustTime(-timeout);
  2276. while (true)
  2277. {
  2278. std::list<Linked<DataCacheElement> >::iterator list_iter = cache.begin();
  2279. if (list_iter == cache.end())
  2280. break;
  2281. DataCacheElement* awu = list_iter->get();
  2282. if (!awu || (awu->m_timeCached > timeNow))
  2283. break;
  2284. cache.pop_front();
  2285. }
  2286. if (cache.size() < 1)
  2287. return NULL;
  2288. //Check whether we have the data cache for this cluster. If yes, get the version
  2289. std::list<Linked<DataCacheElement> >::iterator it = std::find_if(cache.begin(),cache.end(),CompareData(filter));
  2290. if(it!=cache.end())
  2291. {
  2292. return it->getLink();
  2293. }
  2294. return NULL;
  2295. }
  2296. void DataCache::add(const char* filter, const char* data, const char* name, const char* localName, const char* wuid,
  2297. const char* resultName, unsigned seq, __int64 start, unsigned count, __int64 requested, __int64 total)
  2298. {
  2299. CriticalBlock block(crit);
  2300. //Save new data
  2301. Owned<DataCacheElement> e=new DataCacheElement(filter, data, name, localName, wuid, resultName, seq, start, count, requested, total);
  2302. if (cacheSize > 0)
  2303. {
  2304. if (cache.size() >= cacheSize)
  2305. cache.pop_front();
  2306. cache.push_back(e.get());
  2307. }
  2308. return;
  2309. }
  2310. struct CompareArchivedWUs
  2311. {
  2312. CompareArchivedWUs(const char* _filter): filter(_filter) {}
  2313. bool operator()(const Linked<ArchivedWuCacheElement>& e) const
  2314. {
  2315. return stricmp(e->m_filter.c_str(),filter)==0;
  2316. }
  2317. const char* filter;
  2318. };
  2319. ArchivedWuCacheElement* ArchivedWuCache::lookup(IEspContext &context, const char* filter, const char* sashaUpdatedWhen, unsigned timeOutMin)
  2320. {
  2321. CriticalBlock block(crit);
  2322. if (cache.size() < 1)
  2323. return NULL;
  2324. //erase data if it should be
  2325. CDateTime timeNow;
  2326. int timeout = timeOutMin;
  2327. timeNow.setNow();
  2328. timeNow.adjustTime(-timeout);
  2329. while (true)
  2330. {
  2331. std::list<Linked<ArchivedWuCacheElement> >::iterator list_iter = cache.begin();
  2332. if (list_iter == cache.end())
  2333. break;
  2334. ArchivedWuCacheElement* awu = list_iter->get();
  2335. if (awu && !stricmp(sashaUpdatedWhen, awu->m_sashaUpdatedWhen.c_str()) && (awu->m_timeCached > timeNow))
  2336. break;
  2337. cache.pop_front();
  2338. }
  2339. if (cache.size() < 1)
  2340. return NULL;
  2341. //Check whether we have the data cache for this cluster. If yes, get the version
  2342. std::list<Linked<ArchivedWuCacheElement> >::iterator it = std::find_if(cache.begin(),cache.end(),CompareArchivedWUs(filter));
  2343. if(it!=cache.end())
  2344. return it->getLink();
  2345. return NULL;
  2346. }
  2347. void ArchivedWuCache::add(const char* filter, const char* sashaUpdatedWhen, bool hasNextPage, unsigned numWUsReturned, IArrayOf<IEspECLWorkunit>& wus, IArrayOf<IEspECLWorkunitLW>& lwwus)
  2348. {
  2349. CriticalBlock block(crit);
  2350. //Save new data
  2351. Owned<ArchivedWuCacheElement> e=new ArchivedWuCacheElement(filter, sashaUpdatedWhen, hasNextPage, numWUsReturned, wus, lwwus);
  2352. if (cacheSize > 0)
  2353. {
  2354. if (cache.size() >= cacheSize)
  2355. cache.pop_front();
  2356. cache.push_back(e.get());
  2357. }
  2358. return;
  2359. }
  2360. WsWuJobQueueAuditInfo::WsWuJobQueueAuditInfo(IEspContext &context, const char *cluster, const char *from , const char *to, CHttpResponse* response, const char *xls)
  2361. {
  2362. if(!response)
  2363. return;
  2364. unsigned maxDisplay = 125;
  2365. IArrayOf<IEspThorQueue> items;
  2366. CDateTime fromTime;
  2367. CDateTime toTime;
  2368. StringBuffer fromstr;
  2369. StringBuffer tostr;
  2370. if(from && *from)
  2371. {
  2372. fromTime.setString(from,NULL,false);
  2373. fromTime.getString(fromstr, false);
  2374. }
  2375. if(to && *to)
  2376. {
  2377. toTime.setString(to,NULL,false);
  2378. toTime.getString(tostr, false);
  2379. }
  2380. StringBuffer filter("ThorQueueMonitor");
  2381. if(notEmpty(cluster))
  2382. filter.appendf(",%s", cluster);
  2383. StringAttrArray lines;
  2384. queryAuditLogs(fromTime, toTime, filter.str(), lines);
  2385. unsigned countLines = 0;
  2386. unsigned maxConnected = 0;
  2387. unsigned longestQueue = 0;
  2388. ForEachItemIn(idx, lines)
  2389. {
  2390. const char* line = lines.item(idx).text;
  2391. if(!line || !*line)
  2392. continue;
  2393. if (idx < (lines.length() - 1))
  2394. getAuditLineInfo(line, longestQueue, maxConnected, maxDisplay, 1, items);
  2395. else
  2396. getAuditLineInfo(line, longestQueue, maxConnected, maxDisplay, 2, items);
  2397. countLines++;
  2398. }
  2399. StringBuffer responsebuf;
  2400. if (items.length() < 1)
  2401. {
  2402. responsebuf.append("<script language=\"javascript\">\r\nparent.displayQEnd(\'No data found\')</script>\r\n");
  2403. response->sendChunk(responsebuf.str());
  2404. return;
  2405. }
  2406. unsigned itemCount = items.length();
  2407. if (itemCount > maxDisplay)
  2408. itemCount = maxDisplay;
  2409. responsebuf.append("<script language=\"javascript\">parent.displayQLegend()</script>\r\n");
  2410. response->sendChunk(responsebuf.str());
  2411. responsebuf.clear();
  2412. responsebuf.append("<script language=\"javascript\">parent.displayQBegin(").append(longestQueue).append(",").append(maxConnected).append(",").append(itemCount).append(")</script>\r\n");
  2413. response->sendChunk(responsebuf.str());
  2414. responsebuf.clear();
  2415. responsebuf.append("<script language=\"javascript\">\r\n");
  2416. //bool displayDT = false;
  2417. unsigned count = 0;
  2418. unsigned jobpending=0;
  2419. ForEachItemIn(i,items)
  2420. {
  2421. IEspThorQueue& tq = items.item(i);
  2422. //displayDT = !displayDT;
  2423. count++;
  2424. if (count > maxDisplay)
  2425. break;
  2426. StringBuffer countStr, dtStr;
  2427. countStr.appendulong(count);
  2428. //if (displayDT)
  2429. dtStr = tq.getDT();
  2430. responsebuf.append("parent.displayQueue(\'").append(count).append("\',\'").append(dtStr.str()).append("\',\'").append(tq.getRunningWUs()).append("\',");
  2431. responsebuf.append("\'").append(tq.getQueuedWUs()).append("\',\'").append(tq.getWaitingThors()).append("\',");
  2432. responsebuf.append("\'").append(tq.getConnectedThors()).append("\',\'").append(tq.getIdledThors()).append("\',");
  2433. responsebuf.append("\'").append(tq.getRunningWU1()).append("\',\'").append(tq.getRunningWU2()).append("\')\r\n");
  2434. if(++jobpending>=50)
  2435. {
  2436. responsebuf.append("</script>\r\n");
  2437. response->sendChunk(responsebuf.str());
  2438. responsebuf.clear();
  2439. responsebuf.append("<script language=\"javascript\">\r\n");
  2440. jobpending=0;
  2441. }
  2442. }
  2443. StringBuffer countStr;
  2444. countStr.appendulong(count);
  2445. StringBuffer msg("<table><tr><td>");
  2446. 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>).");
  2447. msg.append("</td></tr><tr><td>");
  2448. if (count > maxDisplay)
  2449. msg.append("Displayed: First ").append(maxDisplay).append(". ");
  2450. msg.append("Max. Queue Length: ").append(longestQueue).append(".");
  2451. msg.append("</td></tr></table>");
  2452. responsebuf.append("parent.displayQEnd(\'").append(msg).append("\')</script>\r\n");
  2453. response->sendChunk(responsebuf.str());
  2454. }
  2455. void WsWuJobQueueAuditInfo::getAuditLineInfo(const char* line, unsigned& longestQueue, unsigned& maxConnected, unsigned maxDisplay, unsigned showAll, IArrayOf<IEspThorQueue>& items)
  2456. {
  2457. //2009-08-12 02:44:12 ,ThorQueueMonitor,thor400_88_dev,0,0,1,1,114,---,---
  2458. if(!line || !*line)
  2459. return;
  2460. Owned<IEspThorQueue> tq = createThorQueue();
  2461. StringBuffer dt, runningWUs, queuedWUs, waitingThors, connectedThors, idledThors, runningWU1, runningWU2;
  2462. // date/time
  2463. const char* bptr = line;
  2464. const char* eptr = strchr(bptr, ',');
  2465. if(eptr)
  2466. dt.append(eptr - bptr, bptr);
  2467. else
  2468. dt.append(bptr);
  2469. tq->setDT(dt.str());
  2470. if(!eptr)
  2471. {
  2472. if (checkNewThorQueueItem(tq, showAll, items))
  2473. items.append(*tq.getClear());
  2474. return;
  2475. }
  2476. //skip title
  2477. bptr = eptr + 1;
  2478. eptr = strchr(bptr, ',');
  2479. if(!eptr)
  2480. {
  2481. if (checkNewThorQueueItem(tq, showAll, items))
  2482. items.append(*tq.getClear());
  2483. return;
  2484. }
  2485. //skip queue name
  2486. bptr = eptr + 1;
  2487. eptr = strchr(bptr, ',');
  2488. if(!eptr)
  2489. {
  2490. if (checkNewThorQueueItem(tq, showAll, items))
  2491. items.append(*tq.getClear());
  2492. return;
  2493. }
  2494. //running
  2495. bptr = eptr + 1;
  2496. eptr = strchr(bptr, ',');
  2497. if(eptr)
  2498. runningWUs.append(eptr - bptr, bptr);
  2499. else
  2500. runningWUs.append(bptr);
  2501. tq->setRunningWUs(runningWUs.str());
  2502. if(!eptr)
  2503. {
  2504. if (checkNewThorQueueItem(tq, showAll, items))
  2505. items.append(*tq.getClear());
  2506. return;
  2507. }
  2508. //queued
  2509. bptr = eptr + 1;
  2510. eptr = strchr(bptr, ',');
  2511. if(eptr)
  2512. queuedWUs.append(eptr - bptr, bptr);
  2513. else
  2514. queuedWUs.append(bptr);
  2515. if (maxDisplay > items.length())
  2516. {
  2517. unsigned queueLen = atoi(queuedWUs.str());
  2518. if (queueLen > longestQueue)
  2519. longestQueue = queueLen;
  2520. }
  2521. tq->setQueuedWUs(queuedWUs.str());
  2522. if(!eptr)
  2523. {
  2524. if (checkNewThorQueueItem(tq, showAll, items))
  2525. items.append(*tq.getClear());
  2526. return;
  2527. }
  2528. //waiting
  2529. bptr = eptr + 1;
  2530. eptr = strchr(bptr, ',');
  2531. if(eptr)
  2532. waitingThors.append(eptr - bptr, bptr);
  2533. else
  2534. waitingThors.append(bptr);
  2535. tq->setWaitingThors(waitingThors.str());
  2536. if(!eptr)
  2537. {
  2538. if (checkNewThorQueueItem(tq, showAll, items))
  2539. items.append(*tq.getClear());
  2540. return;
  2541. }
  2542. //connected
  2543. bptr = eptr + 1;
  2544. eptr = strchr(bptr, ',');
  2545. if(eptr)
  2546. connectedThors.append(eptr - bptr, bptr);
  2547. else
  2548. connectedThors.append(bptr);
  2549. if (maxDisplay > items.length())
  2550. {
  2551. unsigned connnectedLen = atoi(connectedThors.str());
  2552. if (connnectedLen > maxConnected)
  2553. maxConnected = connnectedLen;
  2554. }
  2555. tq->setConnectedThors(connectedThors.str());
  2556. if(!eptr)
  2557. {
  2558. if (checkNewThorQueueItem(tq, showAll, items))
  2559. items.append(*tq.getClear());
  2560. return;
  2561. }
  2562. //idled
  2563. bptr = eptr + 1;
  2564. eptr = strchr(bptr, ',');
  2565. if(eptr)
  2566. idledThors.append(eptr - bptr, bptr);
  2567. else
  2568. idledThors.append(bptr);
  2569. tq->setIdledThors(idledThors.str());
  2570. if(!eptr)
  2571. {
  2572. items.append(*tq.getClear());
  2573. return;
  2574. }
  2575. //runningWU1
  2576. bptr = eptr + 1;
  2577. eptr = strchr(bptr, ',');
  2578. if(eptr)
  2579. runningWU1.append(eptr - bptr, bptr);
  2580. else
  2581. {
  2582. runningWU1.append(bptr);
  2583. }
  2584. if (!strcmp(runningWU1.str(), "---"))
  2585. runningWU1.clear();
  2586. if (runningWU1.length() > 0)
  2587. tq->setRunningWU1(runningWU1.str());
  2588. if(!eptr)
  2589. {
  2590. if (checkNewThorQueueItem(tq, showAll, items))
  2591. items.append(*tq.getClear());
  2592. return;
  2593. }
  2594. //runningWU2
  2595. bptr = eptr + 1;
  2596. eptr = strchr(bptr, ',');
  2597. if(eptr)
  2598. runningWU2.append(eptr - bptr, bptr);
  2599. else
  2600. {
  2601. runningWU2.append(bptr);
  2602. }
  2603. if (!strcmp(runningWU2.str(), "---"))
  2604. runningWU2.clear();
  2605. if (runningWU2.length() > 0)
  2606. tq->setRunningWU2(runningWU2.str());
  2607. if (checkNewThorQueueItem(tq, showAll, items))
  2608. items.append(*tq.getClear());
  2609. }
  2610. bool WsWuJobQueueAuditInfo::checkSameStrings(const char* s1, const char* s2)
  2611. {
  2612. if (s1)
  2613. {
  2614. if (!s2)
  2615. return false;
  2616. if (strcmp(s1, s2))
  2617. return false;
  2618. }
  2619. else if (s2)
  2620. {
  2621. if (!s1)
  2622. return false;
  2623. }
  2624. return true;
  2625. }
  2626. bool WsWuJobQueueAuditInfo::checkNewThorQueueItem(IEspThorQueue* tq, unsigned showAll, IArrayOf<IEspThorQueue>& items)
  2627. {
  2628. bool bAdd = false;
  2629. if (showAll < 1) //show every lines
  2630. bAdd = true;
  2631. else if (items.length() < 1)
  2632. bAdd = true;
  2633. else if (showAll > 1) //last line now
  2634. {
  2635. IEspThorQueue& tq0 = items.item(items.length()-1);
  2636. if (!checkSameStrings(tq->getDT(), tq0.getDT()))
  2637. bAdd = true;
  2638. }
  2639. else
  2640. {
  2641. IEspThorQueue& tq0 = items.item(items.length()-1);
  2642. if (!checkSameStrings(tq->getRunningWUs(), tq0.getRunningWUs()))
  2643. bAdd = true;
  2644. if (!checkSameStrings(tq->getQueuedWUs(), tq0.getQueuedWUs()))
  2645. bAdd = true;
  2646. if (!checkSameStrings(tq->getConnectedThors(), tq0.getConnectedThors()))
  2647. bAdd = true;
  2648. if (!checkSameStrings(tq->getWaitingThors(), tq0.getWaitingThors()))
  2649. bAdd = true;
  2650. if (!checkSameStrings(tq->getRunningWU1(), tq0.getRunningWU1()))
  2651. bAdd = true;
  2652. if (!checkSameStrings(tq->getRunningWU2(), tq0.getRunningWU2()))
  2653. bAdd = true;
  2654. }
  2655. return bAdd;
  2656. }
  2657. void xsltTransform(const char* xml, const char* sheet, IProperties *params, StringBuffer& ret)
  2658. {
  2659. StringBuffer xsl;
  2660. if(!checkFileExists(sheet))
  2661. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST, "Could not find stylesheet %s.",sheet);
  2662. Owned<IXslProcessor> proc = getXslProcessor();
  2663. Owned<IXslTransform> trans = proc->createXslTransform();
  2664. trans->setXmlSource(xml, strlen(xml));
  2665. trans->loadXslFromFile(sheet);
  2666. trans->copyParameters(params);
  2667. trans->transform(ret);
  2668. }
  2669. bool addToQueryString(StringBuffer &queryString, const char *name, const char *value, const char delim)
  2670. {
  2671. if (isEmpty(name) || isEmpty(value))
  2672. return false;
  2673. if (queryString.length() > 0)
  2674. queryString.append(delim);
  2675. queryString.append(name).append("=").append(value);
  2676. return true;
  2677. }
  2678. int WUSchedule::run()
  2679. {
  2680. PROGLOG("ECLWorkunit WUSchedule Thread started.");
  2681. unsigned int waitTimeMillies = 1000*60;
  2682. while(!stopping)
  2683. {
  2684. if (!m_container)
  2685. {
  2686. DBGLOG("ECLWorkunit WUSchedule Thread is waiting for container to be set.");
  2687. }
  2688. else if (!detached)
  2689. {
  2690. try
  2691. {
  2692. if (waitTimeMillies == (unsigned)-1)
  2693. {
  2694. PROGLOG("ECLWorkunit WUSchedule Thread Re-started.");
  2695. waitTimeMillies = 1000*60;
  2696. }
  2697. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  2698. Owned<IConstWorkUnitIterator> itr = factory->getScheduledWorkUnits();
  2699. if (itr)
  2700. {
  2701. ForEach(*itr)
  2702. {
  2703. try
  2704. {
  2705. IConstWorkUnitInfo & cw = itr->query();
  2706. if (factory->isAborting(cw.queryWuid()))
  2707. {
  2708. WorkunitUpdate wu(factory->updateWorkUnit(cw.queryWuid()));
  2709. wu->setState(WUStateAborted);
  2710. continue;
  2711. }
  2712. WsWuDateTime dt, now;
  2713. now.setNow();
  2714. cw.getTimeScheduled(dt);
  2715. if (now.compare(dt)>=0)
  2716. {
  2717. runWorkUnit(cw.queryWuid(), cw.queryClusterName());
  2718. if (m_container->hasCacheClient())
  2719. {
  2720. StringArray errorMsgs;
  2721. m_container->clearCacheByGroupID("ESPWsWUs", errorMsgs);
  2722. if (errorMsgs.length() > 0)
  2723. {
  2724. ForEachItemIn(i, errorMsgs)
  2725. DBGLOG("%s", errorMsgs.item(i));
  2726. }
  2727. }
  2728. }
  2729. }
  2730. catch(IException *e)
  2731. {
  2732. StringBuffer msg;
  2733. IERRLOG("Exception %d:%s in WsWorkunits Schedule::run while processing WU", e->errorCode(), e->errorMessage(msg).str());
  2734. e->Release();
  2735. }
  2736. }
  2737. }
  2738. }
  2739. catch(IException *e)
  2740. {
  2741. StringBuffer msg;
  2742. IERRLOG("Exception %d:%s in WsWorkunits Schedule::run while fetching scheduled WUs from DALI", e->errorCode(), e->errorMessage(msg).str());
  2743. e->Release();
  2744. }
  2745. catch(...)
  2746. {
  2747. IERRLOG("Unknown exception in WsWorkunits Schedule::run while fetching scheduled WUs from DALI");
  2748. }
  2749. }
  2750. else
  2751. {
  2752. OWARNLOG("Detached from DALI, WSWorkunits schedule interrupted");
  2753. waitTimeMillies = (unsigned)-1;
  2754. }
  2755. semSchedule.wait(waitTimeMillies);
  2756. }
  2757. return 0;
  2758. }
  2759. void WsWuHelpers::setXmlParameters(IWorkUnit *wu, const char *xml, bool setJobname)
  2760. {
  2761. if (!xml || !*xml)
  2762. return;
  2763. Owned<IPropertyTree> tree = createPTreeFromXMLString(xml, ipt_none, (PTreeReaderOptions)(ptr_ignoreWhiteSpace | ptr_ignoreNameSpaces));
  2764. IPropertyTree *root = tree.get();
  2765. if (strieq(root->queryName(), "Envelope"))
  2766. root = root->queryPropTree("Body/*[1]");
  2767. if (!root)
  2768. return;
  2769. if (setJobname)
  2770. {
  2771. const char *name = wu->queryJobName();
  2772. if (!name || !*name)
  2773. wu->setJobName(root->queryName());
  2774. }
  2775. wu->setXmlParams(LINK(root));
  2776. }
  2777. void WsWuHelpers::setXmlParameters(IWorkUnit *wu, const char *xml, IArrayOf<IConstNamedValue> *variables, bool setJobname)
  2778. {
  2779. StringBuffer extParamXml;
  2780. if (variables && variables->length())
  2781. {
  2782. Owned<IPropertyTree> paramTree = (xml && *xml) ? createPTreeFromXMLString(xml) : createPTree("input");
  2783. ForEachItemIn(i, *variables)
  2784. {
  2785. IConstNamedValue &item = variables->item(i);
  2786. const char *name = item.getName();
  2787. const char *value = item.getValue();
  2788. if (!name || !*name)
  2789. continue;
  2790. if (!value)
  2791. {
  2792. size_t len = strlen(name);
  2793. char last = name[len-1];
  2794. if (last == '-' || last == '+')
  2795. {
  2796. StringAttr s(name, len-1);
  2797. paramTree->setPropInt(s.get(), last == '+' ? 1 : 0);
  2798. }
  2799. else
  2800. paramTree->setPropInt(name, 1);
  2801. continue;
  2802. }
  2803. paramTree->setProp(name, value);
  2804. }
  2805. toXML(paramTree, extParamXml);
  2806. xml=extParamXml.str();
  2807. }
  2808. setXmlParameters(wu, xml, setJobname);
  2809. }
  2810. void WsWuHelpers::submitWsWorkunit(IEspContext& context, IConstWorkUnit* cw, const char* cluster, const char* snapshot, int maxruntime, bool compile, bool resetWorkflow, bool resetVariables,
  2811. const char *paramXml, IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs, IArrayOf<IConstApplicationValue> *applications)
  2812. {
  2813. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  2814. #ifndef _NO_LDAP
  2815. CLdapSecManager* secmgr = dynamic_cast<CLdapSecManager*>(context.querySecManager());
  2816. // View Scope is checked only when LDAP secmgr is available AND checkViewPermissions config is also enabled.
  2817. // Otherwise, the view permission check is skipped, and WU is submitted as normal.
  2818. if (secmgr && secmgr->getCheckViewPermissions())
  2819. {
  2820. StringArray filenames, columnnames;
  2821. if (cw->getFieldUsageArray(filenames, columnnames, cluster)) // check view permission only for a query with fieldUsage information
  2822. {
  2823. if (!secmgr->authorizeViewScope(*context.queryUser(), filenames, columnnames))
  2824. throw MakeStringException(ECLWATCH_VIEW_ACCESS_DENIED, "View Access denied for a WU: %s", cw->queryWuid());
  2825. }
  2826. }
  2827. #endif
  2828. switch(cw->getState())
  2829. {
  2830. case WUStateRunning:
  2831. case WUStateDebugPaused:
  2832. case WUStateDebugRunning:
  2833. case WUStateCompiling:
  2834. case WUStateAborting:
  2835. case WUStateBlocked:
  2836. throw MakeStringException(ECLWATCH_CANNOT_SUBMIT_WORKUNIT, "Cannot submit the workunit. Workunit state is '%s'.", cw->queryStateDesc());
  2837. }
  2838. StringAttr wuid(cw->queryWuid());
  2839. WorkunitUpdate wu(&cw->lock());
  2840. if(!wu.get())
  2841. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Cannot update workunit %s.", wuid.str());
  2842. wu->clearExceptions();
  2843. if(notEmpty(cluster))
  2844. wu->setClusterName(cluster);
  2845. if(notEmpty(snapshot))
  2846. wu->setSnapshot(snapshot);
  2847. wu->setState(WUStateSubmitted);
  2848. if (maxruntime)
  2849. wu->setDebugValueInt("maxRunTime",maxruntime,true);
  2850. if (debugs && debugs->length())
  2851. {
  2852. ForEachItemIn(i, *debugs)
  2853. {
  2854. IConstNamedValue &item = debugs->item(i);
  2855. const char *name = item.getName();
  2856. const char *value = item.getValue();
  2857. if (!name || !*name)
  2858. continue;
  2859. StringBuffer expanded;
  2860. if (*name=='-')
  2861. name=expanded.append("eclcc").append(name).str();
  2862. if (!value)
  2863. {
  2864. size_t len = strlen(name);
  2865. char last = name[len-1];
  2866. if (last == '-' || last == '+')
  2867. {
  2868. StringAttr s(name, len-1);
  2869. wu->setDebugValueInt(s.get(), last == '+' ? 1 : 0, true);
  2870. }
  2871. else
  2872. wu->setDebugValueInt(name, 1, true);
  2873. continue;
  2874. }
  2875. wu->setDebugValue(name, value, true);
  2876. }
  2877. }
  2878. if (applications)
  2879. {
  2880. ForEachItemIn(ii, *applications)
  2881. {
  2882. IConstApplicationValue& item = applications->item(ii);
  2883. if(notEmpty(item.getApplication()) && notEmpty(item.getName()))
  2884. wu->setApplicationValue(item.getApplication(), item.getName(), item.getValue(), true);
  2885. }
  2886. }
  2887. if (resetWorkflow)
  2888. wu->resetWorkflow();
  2889. if (!compile)
  2890. wu->schedule();
  2891. if (resetVariables)
  2892. {
  2893. SCMStringBuffer varname;
  2894. Owned<IConstWUResultIterator> vars = &wu->getVariables();
  2895. ForEach (*vars)
  2896. {
  2897. vars->query().getResultName(varname);
  2898. Owned<IWUResult> v = wu->updateVariableByName(varname.str());
  2899. if (v)
  2900. v->setResultStatus(ResultStatusUndefined);
  2901. }
  2902. }
  2903. setXmlParameters(wu, paramXml, variables, (wu->getAction()==WUActionExecuteExisting));
  2904. wu->commit();
  2905. wu.clear();
  2906. if (!compile)
  2907. runWorkUnit(wuid.str());
  2908. else if (context.querySecManager())
  2909. secSubmitWorkUnit(wuid.str(), *context.querySecManager(), *context.queryUser());
  2910. else
  2911. submitWorkUnit(wuid.str(), context.queryUserId(), context.queryPassword());
  2912. AuditSystemAccess(context.queryUserId(), true, "Submitted %s", wuid.str());
  2913. }
  2914. void WsWuHelpers::submitWsWorkunit(IEspContext& context, const char *wuid, const char* cluster, const char* snapshot, int maxruntime, bool compile, bool resetWorkflow, bool resetVariables,
  2915. const char *paramXml, IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs, IArrayOf<IConstApplicationValue> *applications)
  2916. {
  2917. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2918. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  2919. if(!cw)
  2920. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  2921. submitWsWorkunit(context, cw, cluster, snapshot, maxruntime, compile, resetWorkflow, resetVariables, paramXml, variables, debugs, applications);
  2922. }
  2923. void WsWuHelpers::copyWsWorkunit(IEspContext &context, IWorkUnit &wu, const char *srcWuid)
  2924. {
  2925. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2926. Owned<IConstWorkUnit> src(factory->openWorkUnit(srcWuid));
  2927. queryExtendedWU(&wu)->copyWorkUnit(src, false, false);
  2928. wu.commit();
  2929. }
  2930. void WsWuHelpers::runWsWorkunit(IEspContext &context, StringBuffer &wuid, const char *srcWuid, const char *cluster, const char *paramXml,
  2931. IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs, IArrayOf<IConstApplicationValue> *applications)
  2932. {
  2933. NewWsWorkunit wu(context);
  2934. wuid.set(wu->queryWuid());
  2935. copyWsWorkunit(context, *wu, srcWuid);
  2936. wu.clear();
  2937. submitWsWorkunit(context, wuid.str(), cluster, NULL, 0, false, true, true, paramXml, variables, debugs, applications);
  2938. }
  2939. void WsWuHelpers::runWsWorkunit(IEspContext &context, IConstWorkUnit *cw, const char *srcWuid, const char *cluster, const char *paramXml,
  2940. IArrayOf<IConstNamedValue> *variables, IArrayOf<IConstNamedValue> *debugs, IArrayOf<IConstApplicationValue> *applications)
  2941. {
  2942. WorkunitUpdate wu(&cw->lock());
  2943. copyWsWorkunit(context, *wu, srcWuid);
  2944. wu.clear();
  2945. submitWsWorkunit(context, cw, cluster, NULL, 0, false, true, true, paramXml, variables, debugs, applications);
  2946. }
  2947. IException * WsWuHelpers::noteException(IWorkUnit *wu, IException *e, ErrorSeverity level)
  2948. {
  2949. if (wu)
  2950. {
  2951. Owned<IWUException> we = wu->createException();
  2952. StringBuffer s;
  2953. we->setExceptionMessage(e->errorMessage(s).str());
  2954. we->setExceptionSource("WsWorkunits");
  2955. we->setSeverity(level);
  2956. if (level==SeverityError)
  2957. wu->setState(WUStateFailed);
  2958. }
  2959. return e;
  2960. }
  2961. StringBuffer & WsWuHelpers::resolveQueryWuid(StringBuffer &wuid, const char *queryset, const char *query, bool notSuspended, IWorkUnit *wu)
  2962. {
  2963. Owned<IPropertyTree> qs = getQueryRegistry(queryset, true);
  2964. if (!qs)
  2965. throw noteException(wu, MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "QuerySet '%s' not found", queryset));
  2966. Owned<IPropertyTree> q = resolveQueryAlias(qs, query);
  2967. if (!q)
  2968. throw noteException(wu, MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query '%s/%s' not found", queryset, query));
  2969. if (notSuspended && q->getPropBool("@suspended"))
  2970. throw noteException(wu, MakeStringException(ECLWATCH_QUERY_SUSPENDED, "Query '%s/%s' is suspended", queryset, query));
  2971. return wuid.append(q->queryProp("@wuid"));
  2972. }
  2973. void WsWuHelpers::runWsWuQuery(IEspContext &context, IConstWorkUnit *cw, const char *queryset, const char *query,
  2974. const char *cluster, const char *paramXml, IArrayOf<IConstApplicationValue> *applications)
  2975. {
  2976. StringBuffer srcWuid;
  2977. WorkunitUpdate wu(&cw->lock());
  2978. resolveQueryWuid(srcWuid, queryset, query, true, wu);
  2979. copyWsWorkunit(context, *wu, srcWuid);
  2980. wu.clear();
  2981. submitWsWorkunit(context, cw, cluster, NULL, 0, false, true, true, paramXml, NULL, NULL, applications);
  2982. }
  2983. void WsWuHelpers::runWsWuQuery(IEspContext &context, StringBuffer &wuid, const char *queryset, const char *query,
  2984. const char *cluster, const char *paramXml, IArrayOf<IConstApplicationValue> *applications)
  2985. {
  2986. StringBuffer srcWuid;
  2987. NewWsWorkunit wu(context);
  2988. wuid.set(wu->queryWuid());
  2989. resolveQueryWuid(srcWuid, queryset, query, true, wu);
  2990. copyWsWorkunit(context, *wu, srcWuid);
  2991. wu.clear();
  2992. submitWsWorkunit(context, wuid.str(), cluster, NULL, 0, false, true, true, paramXml, NULL, NULL, applications);
  2993. }
  2994. void WsWuHelpers::checkAndTrimWorkunit(const char* methodName, StringBuffer& input)
  2995. {
  2996. const char* trimmedInput = input.trim().str();
  2997. if (isEmpty(trimmedInput))
  2998. throw MakeStringException(ECLWATCH_INVALID_INPUT, "%s: Workunit ID not set", methodName);
  2999. if (!looksLikeAWuid(trimmedInput, 'W'))
  3000. throw MakeStringException(ECLWATCH_INVALID_INPUT, "%s: Invalid Workunit ID: %s", methodName, trimmedInput);
  3001. return;
  3002. }
  3003. IFileIOStream* CWsWuFileHelper::createIOStreamWithFileName(const char* fileNameWithPath, IFOmode mode)
  3004. {
  3005. if (isEmptyString(fileNameWithPath))
  3006. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "File name not specified.");
  3007. Owned<IFile> wuInfoIFile = createIFile(fileNameWithPath);
  3008. Owned<IFileIO> wuInfoIO = wuInfoIFile->open(mode);
  3009. if (!wuInfoIO)
  3010. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE, "Failed to open %s.", fileNameWithPath);
  3011. return createIOStream(wuInfoIO);
  3012. }
  3013. void CWsWuFileHelper::writeToFile(const char* fileName, size32_t contentLength, const void* content)
  3014. {
  3015. if (isEmptyString(fileName))
  3016. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "File name not specified.");
  3017. Owned<IFile> wuInfoIFile = createIFile(fileName);
  3018. Owned<IFileIO> wuInfoIO = wuInfoIFile->open(IFOcreate);
  3019. if (wuInfoIO)
  3020. wuInfoIO->write(0, contentLength, content);
  3021. else
  3022. PROGLOG("Failed to open %s.", fileName);
  3023. }
  3024. void CWsWuFileHelper::writeToFileIOStream(const char* folder, const char* file, MemoryBuffer& mb)
  3025. {
  3026. if (isEmptyString(folder))
  3027. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty folder name is not allowed to create FileIOStream.");
  3028. if (isEmptyString(file))
  3029. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty file name is not allowed to create FileIOStream.");
  3030. VStringBuffer fileNameWithPath("%s%c%s", folder, PATHSEPCHAR, file);
  3031. CWsWuFileHelper helper(nullptr);
  3032. Owned<IFileIOStream> outIOS = helper.createIOStreamWithFileName(fileNameWithPath.str(), IFOcreate);
  3033. if (outIOS)
  3034. outIOS->write(mb.length(), mb.toByteArray());
  3035. else
  3036. PROGLOG("Failed to open FileIOStream for %s.", fileNameWithPath.str());
  3037. }
  3038. void CWsWuFileHelper::cleanFolder(IFile* folder, bool removeFolder)
  3039. {
  3040. if (!folder)
  3041. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Invalid file interface for the zip folder.");
  3042. Owned<IDirectoryIterator> iter = folder->directoryFiles(NULL,false,false);
  3043. ForEach(*iter)
  3044. {
  3045. OwnedIFile thisFile = createIFile(iter->query().queryFilename());
  3046. if (thisFile->isFile() == fileBool::foundYes)
  3047. thisFile->remove();
  3048. }
  3049. if (removeFolder)
  3050. folder->remove();
  3051. }
  3052. void CWsWuFileHelper::createProcessLogfile(IConstWorkUnit* cwu, WsWuInfo& winfo, const char* process, const char* path)
  3053. {
  3054. BoolHash uniqueProcesses;
  3055. Owned<IPropertyTreeIterator> procs = cwu->getProcesses(process, NULL);
  3056. ForEach (*procs)
  3057. {
  3058. StringBuffer logSpec;
  3059. IPropertyTree& proc = procs->query();
  3060. const char* processName = proc.queryName();
  3061. if (isEmpty(processName))
  3062. continue;
  3063. //If a WU runs into another day, the procs contains >1 entries for the same process.
  3064. //Only one entry is needed to find out the process data for creating the new process
  3065. //log file which stores the WU information for multiple days.
  3066. bool* found = uniqueProcesses.getValue(processName);
  3067. if (found && *found)
  3068. continue;
  3069. uniqueProcesses.setValue(processName, true);
  3070. MemoryBuffer mb;
  3071. VStringBuffer fileName("%s%c%s", path, PATHSEPCHAR, processName);
  3072. try
  3073. {
  3074. if (strieq(process, "EclAgent"))
  3075. {
  3076. StringBuffer pid;
  3077. pid.appendf("%d", proc.getPropInt("@pid"));
  3078. fileName.append("_eclagent.log");
  3079. winfo.getWorkunitEclAgentLog(processName, nullptr, pid.str(), mb, fileName.str());
  3080. }
  3081. else if (strieq(process, "Thor"))
  3082. {
  3083. fileName.append("_thormaster.log");
  3084. winfo.getWorkunitThorMasterLog(processName, nullptr, mb, fileName.str());
  3085. }
  3086. }
  3087. catch(IException* e)
  3088. {
  3089. StringBuffer s;
  3090. e->errorMessage(s);
  3091. IERRLOG("Error accessing Process Log file %s: %s", logSpec.str(), s.str());
  3092. writeToFile(fileName.str(), s.length(), s.str());
  3093. e->Release();
  3094. }
  3095. }
  3096. }
  3097. void CWsWuFileHelper::createThorSlaveLogfile(IConstWorkUnit* cwu, WsWuInfo& winfo, const char* path)
  3098. {
  3099. if (cwu->getWuidVersion() == 0)
  3100. return;
  3101. const char* clusterName = cwu->queryClusterName();
  3102. if (isEmptyString(clusterName)) //Cluster name may not be set yet
  3103. return;
  3104. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName);
  3105. if (!clusterInfo)
  3106. {
  3107. OWARNLOG("Cannot find TargetClusterInfo for workunit %s", cwu->queryWuid());
  3108. return;
  3109. }
  3110. Owned<IThreadFactory> threadFactory = new CGetThorSlaveLogToFileThreadFactory();
  3111. Owned<IThreadPool> threadPool = createThreadPool("WsWuFileHelper GetThorSlaveLogToFile Thread Pool",
  3112. threadFactory, NULL, thorSlaveLogThreadPoolSize, INFINITE);
  3113. unsigned numberOfSlaveLogs = clusterInfo->getNumberOfSlaveLogs();
  3114. BoolHash uniqueProcesses;
  3115. Owned<IStringIterator> thorInstances = cwu->getProcesses("Thor");
  3116. ForEach (*thorInstances)
  3117. {
  3118. SCMStringBuffer processName;
  3119. thorInstances->str(processName);
  3120. if (processName.length() == 0)
  3121. continue;
  3122. bool* found = uniqueProcesses.getValue(processName.str());
  3123. if (found && *found)
  3124. continue;
  3125. uniqueProcesses.setValue(processName.str(), true);
  3126. StringBuffer groupName, logDir;
  3127. getClusterThorGroupName(groupName, processName.str());
  3128. if (groupName.isEmpty())
  3129. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed to get Thor Group Name for %s", processName.str());
  3130. Owned<IGroup> nodeGroup = queryNamedGroupStore().lookup(groupName);
  3131. if (!nodeGroup || (nodeGroup->ordinality() == 0))
  3132. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Node group %s not found", groupName.str());
  3133. getConfigurationDirectory(directories, "log", "thor", processName.str(), logDir);
  3134. for (unsigned i = 0; i < numberOfSlaveLogs; i++)
  3135. {
  3136. VStringBuffer fileName("%s%c%s_thorslave.%u.log", path, PATHSEPCHAR, processName.str(), i+1);
  3137. Owned<CGetThorSlaveLogToFileThreadParam> threadParam = new CGetThorSlaveLogToFileThreadParam(
  3138. &winfo, nodeGroup, processName.str(), logDir, i+1, fileName);
  3139. threadPool->start(threadParam.getClear());
  3140. }
  3141. }
  3142. threadPool->joinAll();
  3143. }
  3144. void CWsWuFileHelper::createZAPInfoFile(const char* url, const char* espIP, const char* thorIP, const char* problemDesc,
  3145. const char* whatChanged, const char* timing, IConstWorkUnit* cwu, const char* pathNameStr)
  3146. {
  3147. VStringBuffer fileName("%s.txt", pathNameStr);
  3148. Owned<IFileIOStream> outFile = createIOStreamWithFileName(fileName.str(), IFOcreate);
  3149. StringBuffer sb;
  3150. sb.set("Workunit: ").append(cwu->queryWuid()).append("\r\n");
  3151. sb.append("User: ").append(cwu->queryUser()).append("\r\n");
  3152. sb.append("Build Version:").append(getBuildVersion()).append("\r\n");
  3153. sb.append("Cluster: ").append(cwu->queryClusterName()).append("\r\n");
  3154. if (!isEmptyString(espIP))
  3155. sb.append("ESP: ").append(espIP).append("\r\n");
  3156. else
  3157. {
  3158. StringBuffer espIPAddr;
  3159. IpAddress ipaddr = queryHostIP();
  3160. ipaddr.getIpText(espIPAddr);
  3161. sb.append("ESP: ").append(espIPAddr.str()).append("\r\n");
  3162. }
  3163. if (!isEmptyString(url))
  3164. sb.append("URL: ").append(url).append("\r\n");
  3165. if (!isEmptyString(thorIP))
  3166. sb.append("Thor: ").append(thorIP).append("\r\n");
  3167. outFile->write(sb.length(), sb.str());
  3168. //Exceptions/Warnings/Info
  3169. Owned<IConstWUExceptionIterator> exceptions = &cwu->getExceptions();
  3170. StringBuffer info, warn, err, alert;
  3171. ForEach(*exceptions)
  3172. {
  3173. const char* severityString = nullptr;
  3174. switch (exceptions->query().getSeverity())
  3175. {
  3176. case SeverityInformation:
  3177. severityString = "Information: ";
  3178. break;
  3179. case SeverityWarning:
  3180. severityString = "Warnings: ";
  3181. break;
  3182. case SeverityError:
  3183. severityString = "Exceptions: ";
  3184. break;
  3185. case SeverityAlert:
  3186. severityString = "Alert: ";
  3187. break;
  3188. }
  3189. if (!severityString)
  3190. continue;
  3191. SCMStringBuffer temp;
  3192. exceptions->query().getExceptionMessage(temp);
  3193. writeZAPWUInfoToIOStream(outFile, severityString, temp);
  3194. }
  3195. //User provided Information
  3196. writeZAPWUInfoToIOStream(outFile, "Problem: ", problemDesc);
  3197. writeZAPWUInfoToIOStream(outFile, "What Changed: ", whatChanged);
  3198. writeZAPWUInfoToIOStream(outFile, "Timing: ", timing);
  3199. }
  3200. void CWsWuFileHelper::writeZAPWUInfoToIOStream(IFileIOStream* outFile, const char* name, SCMStringBuffer& value)
  3201. {
  3202. outFile->write(strlen(name), name);
  3203. outFile->write(3, "\r\n\t");
  3204. outFile->write(value.length(), value.str());
  3205. outFile->write(4, "\r\n\r\n");
  3206. }
  3207. void CWsWuFileHelper::writeZAPWUInfoToIOStream(IFileIOStream* outFile, const char* name, const char* value)
  3208. {
  3209. outFile->write(strlen(name), name);
  3210. outFile->write(strlen(value), value);
  3211. outFile->write(4, "\r\n\r\n");
  3212. }
  3213. void CWsWuFileHelper::createZAPWUXMLFile(WsWuInfo& winfo, const char* pathNameStr)
  3214. {
  3215. MemoryBuffer mb;
  3216. winfo.getWorkunitXml(NULL, mb);
  3217. VStringBuffer fileName("%s.xml", pathNameStr);
  3218. writeToFile(fileName.str(), mb.length(), mb.bufferBase());
  3219. }
  3220. void CWsWuFileHelper::createZAPECLQueryArchiveFiles(IConstWorkUnit* cwu, const char* pathNameStr)
  3221. {
  3222. Owned<IConstWUQuery> query = cwu->getQuery();
  3223. if(!query)
  3224. return;
  3225. //Add archive if present
  3226. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  3227. ForEach(*iter)
  3228. {
  3229. IConstWUAssociatedFile& cur = iter->query();
  3230. SCMStringBuffer ssb, ip;
  3231. cur.getDescription(ssb);
  3232. if (!strieq(ssb.str(), "archive"))
  3233. continue;
  3234. cur.getName(ssb);
  3235. cur.getIp(ip);
  3236. if (!ssb.length() || !ip.length())
  3237. continue;
  3238. StringBuffer fileName, archiveContents;
  3239. try
  3240. {
  3241. SocketEndpoint ep(ip.str());
  3242. RemoteFilename rfn;
  3243. rfn.setRemotePath(ssb.str());
  3244. rfn.setIp(ep);
  3245. Owned<IFile> rFile = createIFile(rfn);
  3246. if (!rFile)
  3247. {
  3248. OERRLOG("Cannot open %s on %s", ssb.str(), ip.str());
  3249. continue;
  3250. }
  3251. archiveContents.loadFile(rFile);
  3252. }
  3253. catch (IException *e)
  3254. {
  3255. StringBuffer s;
  3256. e->errorMessage(s);
  3257. OERRLOG("Error accessing archive file %s: %s", ssb.str(), s.str());
  3258. archiveContents.insert(0, "Error accessing archive file ").appendf("%s: %s\r\n\r\n", ssb.str(), s.str());
  3259. e->Release();
  3260. }
  3261. fileName.setf("%s.archive", pathNameStr);
  3262. writeToFile(fileName.str(), archiveContents.length(), archiveContents.str());
  3263. break;
  3264. }
  3265. //Add Query
  3266. SCMStringBuffer temp;
  3267. query->getQueryText(temp);
  3268. if (temp.length())
  3269. {
  3270. VStringBuffer fileName("%s.ecl", pathNameStr);
  3271. writeToFile(fileName.str(), temp.length(), temp.str());
  3272. }
  3273. }
  3274. void CWsWuFileHelper::createZAPWUGraphProgressFile(const char* wuid, const char* pathNameStr)
  3275. {
  3276. Owned<IPropertyTree> graphProgress = getWUGraphProgress(wuid, true);
  3277. if (!graphProgress)
  3278. return;
  3279. StringBuffer graphProgressXML;
  3280. toXML(graphProgress, graphProgressXML, 1, XML_Format);
  3281. VStringBuffer fileName("%s.graphprogress", pathNameStr);
  3282. writeToFile(fileName.str(), graphProgressXML.length(), graphProgressXML.str());
  3283. }
  3284. int CWsWuFileHelper::zipAFolder(const char* folder, const char* passwordReq, const char* zipFileNameWithPath)
  3285. {
  3286. VStringBuffer archiveInPath("%s%c*", folder, PATHSEPCHAR);
  3287. StringBuffer zipCommand;
  3288. if (!isEmptyString(passwordReq))
  3289. zipCommand.setf("zip -j --password %s %s %s", passwordReq, zipFileNameWithPath, archiveInPath.str());
  3290. else
  3291. zipCommand.setf("zip -j %s %s", zipFileNameWithPath, archiveInPath.str());
  3292. return (system(zipCommand.str()));
  3293. }
  3294. int CWsWuFileHelper::zipAFolder(const char* folder, bool gzip, const char* zipFileNameWithPath)
  3295. {
  3296. StringBuffer zipCommand;
  3297. VStringBuffer archiveInPath("%s%c*", folder, PATHSEPCHAR);
  3298. if (!gzip)
  3299. zipCommand.appendf("zip -j %s %s", zipFileNameWithPath, archiveInPath.str());
  3300. else
  3301. zipCommand.appendf("tar -czf %s %s", zipFileNameWithPath, archiveInPath.str());
  3302. return (system(zipCommand.str()));
  3303. }
  3304. void CWsWuFileHelper::createWUZAPFile(IEspContext& context, IConstWorkUnit* cwu, CWsWuZAPInfoReq& request,
  3305. StringBuffer& zipFileName, StringBuffer& zipFileNameWithPath, unsigned _thorSlaveLogThreadPoolSize)
  3306. {
  3307. StringBuffer zapReportNameStr, folderToZIP, inFileNamePrefixWithPath;
  3308. Owned<IFile> zipDir = createWorkingFolder(context, request.wuid.str(), "ZAPReport_", zapReportNameStr, folderToZIP);
  3309. setZAPFile(request.zapFileName.str(), zapReportNameStr.str(), zipFileName, zipFileNameWithPath);
  3310. thorSlaveLogThreadPoolSize = _thorSlaveLogThreadPoolSize;
  3311. //create WU ZAP files
  3312. inFileNamePrefixWithPath.set(folderToZIP.str()).append(PATHSEPCHAR).append(zapReportNameStr.str());
  3313. createZAPInfoFile(request.url.str(), request.espIP.str(), request.thorIP.str(), request.problemDesc.str(), request.whatChanged.str(),
  3314. request.whereSlow.str(), cwu, inFileNamePrefixWithPath.str());
  3315. createZAPECLQueryArchiveFiles(cwu, inFileNamePrefixWithPath.str());
  3316. WsWuInfo winfo(context, cwu);
  3317. createZAPWUXMLFile(winfo, inFileNamePrefixWithPath.str());
  3318. createZAPWUGraphProgressFile(request.wuid.str(), inFileNamePrefixWithPath.str());
  3319. createZAPWUQueryAssociatedFiles(cwu, folderToZIP);
  3320. createProcessLogfile(cwu, winfo, "EclAgent", folderToZIP.str());
  3321. createProcessLogfile(cwu, winfo, "Thor", folderToZIP.str());
  3322. if (request.includeThorSlaveLog.isEmpty() || strieq(request.includeThorSlaveLog.str(), "on"))
  3323. createThorSlaveLogfile(cwu, winfo, folderToZIP.str());
  3324. //Write out to ZIP file
  3325. int zipRet = zipAFolder(folderToZIP.str(), request.password.str(), zipFileNameWithPath);
  3326. //Remove the temporary files and the folder
  3327. cleanFolder(zipDir, true);
  3328. if (zipRet != 0)
  3329. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Failed to execute system command 'zip'. Please make sure that zip utility is installed.");
  3330. }
  3331. void CWsWuFileHelper::createZAPWUQueryAssociatedFiles(IConstWorkUnit* cwu, const char* pathToCreate)
  3332. {
  3333. Owned<IConstWUQuery> query = cwu->getQuery();
  3334. if (!query)
  3335. {
  3336. IERRLOG("Cannot get Query for workunit %s.", cwu->queryWuid());
  3337. return;
  3338. }
  3339. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  3340. ForEach(*iter)
  3341. {
  3342. SCMStringBuffer name, ip;
  3343. IConstWUAssociatedFile& cur = iter->query();
  3344. cur.getName(name);
  3345. cur.getIp(ip);
  3346. RemoteFilename rfn;
  3347. SocketEndpoint ep(ip.str());
  3348. rfn.setPath(ep, name.str());
  3349. OwnedIFile sourceFile = createIFile(rfn);
  3350. if (!sourceFile)
  3351. {
  3352. IERRLOG("Cannot open %s on %s.", name.str(), ip.str());
  3353. continue;
  3354. }
  3355. StringBuffer fileName(name.str());
  3356. getFileNameOnly(fileName, false);
  3357. StringBuffer outFileName(pathToCreate);
  3358. outFileName.append(PATHSEPCHAR).append(fileName);
  3359. OwnedIFile outFile = createIFile(outFileName);
  3360. if (!outFile)
  3361. {
  3362. IERRLOG("Cannot create %s.", outFileName.str());
  3363. continue;
  3364. }
  3365. copyFile(outFile, sourceFile);
  3366. }
  3367. }
  3368. void CWsWuFileHelper::setZAPFile(const char* zipFileNameReq, const char* zipFileNamePrefix,
  3369. StringBuffer& zipFileName, StringBuffer& zipFileNameWithPath)
  3370. {
  3371. StringBuffer outFileNameReq(zipFileNameReq);
  3372. //Clean zipFileNameReq. The zipFileNameReq should not end with PATHSEPCHAR.
  3373. while (!outFileNameReq.isEmpty() && (outFileNameReq.charAt(outFileNameReq.length() - 1) == PATHSEPCHAR))
  3374. outFileNameReq.setLength(outFileNameReq.length() - 1);
  3375. if (outFileNameReq.isEmpty())
  3376. zipFileName.set(zipFileNamePrefix).append(".zip");
  3377. else
  3378. {
  3379. zipFileName.set(outFileNameReq.str());
  3380. const char* ext = pathExtension(zipFileName.str());
  3381. if (!ext || !strieq(ext, ".zip"))
  3382. zipFileName.append(".zip");
  3383. }
  3384. zipFileNameWithPath.set(zipFolder);
  3385. Owned<IFile> workingDir = createIFile(zipFileNameWithPath.str());
  3386. if (!workingDir->exists())
  3387. workingDir->createDirectory();
  3388. zipFileNameWithPath.append(PATHSEPCHAR).append(zipFileName);
  3389. OwnedIFile thisFile = createIFile(zipFileNameWithPath.str());
  3390. if (thisFile->isFile() == fileBool::foundYes)
  3391. thisFile->remove();
  3392. }
  3393. IFile* CWsWuFileHelper::createWorkingFolder(IEspContext& context, const char* wuid, const char* namePrefix,
  3394. StringBuffer& namePrefixStr, StringBuffer& folderName)
  3395. {
  3396. StringBuffer userName;
  3397. if (context.queryUser())
  3398. userName.append(context.queryUser()->getName());
  3399. namePrefixStr.set(namePrefix).append(wuid).append('_').append(userName.str());
  3400. folderName.append(zipFolder).append(namePrefixStr.str());
  3401. Owned<IFile> workingDir = createIFile(folderName.str());
  3402. if (!workingDir->exists())
  3403. workingDir->createDirectory();
  3404. else
  3405. cleanFolder(workingDir, false);
  3406. return workingDir.getClear();
  3407. }
  3408. IFileIOStream* CWsWuFileHelper::createWUZAPFileIOStream(IEspContext& context, IConstWorkUnit* cwu,
  3409. CWsWuZAPInfoReq& request, unsigned thorSlaveLogThreadPoolSize)
  3410. {
  3411. StringBuffer zapFileName, zapFileNameWithPath;
  3412. createWUZAPFile(context, cwu, request, zapFileName, zapFileNameWithPath, thorSlaveLogThreadPoolSize);
  3413. if (request.sendEmail)
  3414. {
  3415. CWsWuEmailHelper emailHelper(request.emailFrom.str(), request.emailTo.str(), request.emailServer.str(), request.port);
  3416. StringBuffer subject(request.emailSubject.str());
  3417. if (subject.isEmpty())
  3418. subject.append(request.wuid.str()).append(" ZAP Report");
  3419. emailHelper.setSubject(subject.str());
  3420. PROGLOG("Sending WU ZAP email (%s): from %s to %s", request.emailServer.str(), request.emailFrom.str(), request.emailTo.str());
  3421. StringArray warnings;
  3422. if (!request.attachZAPReportToEmail)
  3423. emailHelper.send(request.emailBody.str(), "", 0, warnings);
  3424. else
  3425. {
  3426. Owned<IFile> f = createIFile(zapFileNameWithPath.str());
  3427. Owned<IFileIO> io = f->open(IFOread);
  3428. unsigned zapFileSize = (unsigned) io->size();
  3429. if (zapFileSize > request.maxAttachmentSize)
  3430. {
  3431. request.emailBody.appendf("\n\n(Failed to attach the ZAP report. The size limit is %u bytes.)", request.maxAttachmentSize);
  3432. emailHelper.send(request.emailBody.str(), "", 0, warnings);
  3433. }
  3434. else
  3435. {
  3436. MemoryBuffer mb;
  3437. void * data = mb.reserve(zapFileSize);
  3438. size32_t read = io->read(0, zapFileSize, data);
  3439. mb.setLength(read);
  3440. emailHelper.setAttachmentName(zapFileName.str());
  3441. emailHelper.setMimeType("application/zip, application/octet-stream");
  3442. emailHelper.send(request.emailBody.str(), mb.toByteArray(), mb.length(), warnings);
  3443. }
  3444. }
  3445. }
  3446. VStringBuffer headerStr("attachment;filename=%s", zapFileName.str());
  3447. context.addCustomerHeader("Content-disposition", headerStr.str());
  3448. return createIOStreamWithFileName(zapFileNameWithPath.str(), IFOread);
  3449. }
  3450. IFileIOStream* CWsWuFileHelper::createWUFileIOStream(IEspContext& context, const char* wuid, IArrayOf<IConstWUFileOption>& wuFileOptions,
  3451. CWUFileDownloadOption& downloadOptions, StringBuffer& contentType)
  3452. {
  3453. StringBuffer fileName, fileNameStr, workingFolder, zipFileNameWithPath;
  3454. Owned<IFile> zipDir;
  3455. bool doZIP = (downloadOptions == CWUFileDownloadOption_ZIP) || (downloadOptions == CWUFileDownloadOption_GZIP);
  3456. if (doZIP)
  3457. {
  3458. zipDir.setown(createWorkingFolder(context, wuid, "WUFiles_", fileNameStr, workingFolder));
  3459. }
  3460. else
  3461. {
  3462. StringBuffer userName;
  3463. if (context.queryUser())
  3464. userName.append(context.queryUser()->getName());
  3465. fileName.set("WUFiles_").append(wuid).append('_').append(userName.str());
  3466. }
  3467. WsWuInfo winfo(context, wuid);
  3468. ForEachItemIn(i, wuFileOptions)
  3469. {
  3470. if (!doZIP)
  3471. {//If no zip, only return one file. If > 1 files, the caller throws exception.
  3472. readWUFile(wuid, zipFolder, winfo, wuFileOptions.item(i), fileName, contentType);
  3473. break;
  3474. }
  3475. StringBuffer aFileName, aFileMimeType;//Not used
  3476. readWUFile(wuid, workingFolder.str(), winfo, wuFileOptions.item(i), aFileName, aFileMimeType);
  3477. }
  3478. if (!doZIP)
  3479. {
  3480. if (downloadOptions != CWUFileDownloadOption_OriginalText)
  3481. {
  3482. VStringBuffer headerStr("attachment;filename=%s", fileName.str());
  3483. context.addCustomerHeader("Content-disposition", headerStr.str());
  3484. }
  3485. zipFileNameWithPath.set(zipFolder).append(fileName.str());
  3486. return createIOStreamWithFileName(zipFileNameWithPath.str(), IFOread);
  3487. }
  3488. if (downloadOptions == CWUFileDownloadOption_ZIP)
  3489. fileName.set(fileNameStr).append(".zip");
  3490. else
  3491. fileName.set(fileNameStr).append(".gzip");
  3492. zipFileNameWithPath.set(zipFolder).append(fileName.str());
  3493. {
  3494. OwnedIFile oldFile = createIFile(zipFileNameWithPath.str());
  3495. if (oldFile->isFile() == fileBool::foundYes)
  3496. oldFile->remove();
  3497. }
  3498. int zipRet = zipAFolder(workingFolder.str(), downloadOptions == CWUFileDownloadOption_GZIP, zipFileNameWithPath);
  3499. //Remove the temporary files and the folder
  3500. cleanFolder(zipDir, true);
  3501. if (zipRet != 0)
  3502. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "Failed to execute system command 'zip'. Please make sure that zip utility is installed.");
  3503. contentType.set(HTTP_TYPE_OCTET_STREAM);
  3504. VStringBuffer headerStr("attachment;filename=%s", fileName.str());
  3505. context.addCustomerHeader("Content-disposition", headerStr.str());
  3506. return createIOStreamWithFileName(zipFileNameWithPath.str(), IFOread);
  3507. }
  3508. void CWsWuFileHelper::readWUFile(const char* wuid, const char* workingFolder, WsWuInfo& winfo, IConstWUFileOption& item,
  3509. StringBuffer& fileName, StringBuffer& fileMimeType)
  3510. {
  3511. MemoryBuffer mb;
  3512. StringBuffer fileNameWithPath;
  3513. CWUFileType fileType = item.getFileType();
  3514. switch (fileType)
  3515. {
  3516. case CWUFileType_ArchiveQuery:
  3517. winfo.getWorkunitArchiveQuery(mb);
  3518. fileName.set("ArchiveQuery.xml");
  3519. fileMimeType.set(HTTP_TYPE_APPLICATION_XML);
  3520. writeToFileIOStream(workingFolder, "ArchiveQuery.xml", mb);
  3521. break;
  3522. case CWUFileType_CPP:
  3523. case CWUFileType_LOG:
  3524. {
  3525. const char *tail=pathTail(item.getName());
  3526. fileName.set(tail ? tail : item.getName());
  3527. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  3528. fileNameWithPath.set(workingFolder).append(PATHSEPCHAR).append(fileName.str());
  3529. winfo.getWorkunitCpp(item.getName(), item.getDescription(), item.getIPAddress(), mb, true, fileNameWithPath.str());
  3530. break;
  3531. }
  3532. case CWUFileType_DLL:
  3533. {
  3534. const char *tail=pathTail(item.getName());
  3535. fileName.set(tail ? tail : item.getName());
  3536. fileMimeType.set(HTTP_TYPE_OCTET_STREAM);
  3537. StringBuffer name;
  3538. winfo.getWorkunitDll(name, mb);
  3539. writeToFileIOStream(workingFolder, fileName.str(), mb);
  3540. break;
  3541. }
  3542. case CWUFileType_Res:
  3543. fileName.set("res.txt");
  3544. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  3545. winfo.getWorkunitResTxt(mb);
  3546. writeToFileIOStream(workingFolder, fileName.str(), mb);
  3547. break;
  3548. case CWUFileType_ThorLog:
  3549. fileName.set("thormaster.log");
  3550. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  3551. fileNameWithPath.set(workingFolder).append(PATHSEPCHAR).append(fileName.str());
  3552. winfo.getWorkunitThorMasterLog(nullptr, item.getName(), mb, fileNameWithPath.str());
  3553. break;
  3554. case CWUFileType_ThorSlaveLog:
  3555. {
  3556. fileName.set("ThorSlave.log");
  3557. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  3558. fileNameWithPath.set(workingFolder).append(PATHSEPCHAR).append(fileName.str());
  3559. winfo.getWorkunitThorSlaveLog(directories, item.getProcess(), item.getClusterGroup(), item.getIPAddress(),
  3560. item.getLogDate(), item.getSlaveNumber(), mb, fileNameWithPath.str(), false);
  3561. break;
  3562. }
  3563. case CWUFileType_EclAgentLog:
  3564. fileName.set("eclagent.log");
  3565. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  3566. fileNameWithPath.set(workingFolder).append(PATHSEPCHAR).append(fileName.str());
  3567. winfo.getWorkunitEclAgentLog(nullptr, item.getName(), item.getProcess(), mb, fileNameWithPath.str());
  3568. break;
  3569. case CWUFileType_XML:
  3570. {
  3571. StringBuffer name(item.getName());
  3572. if (!name.isEmpty())
  3573. {
  3574. const char *tail=pathTail(name.str());
  3575. fileName.set(tail ? tail : name.str());
  3576. fileNameWithPath.set(workingFolder).append(PATHSEPCHAR).append(fileName.str());
  3577. winfo.getWorkunitAssociatedXml(fileName.str(), item.getIPAddress(), item.getPlainText(), item.getDescription(), true, true, mb, fileNameWithPath.str());
  3578. }
  3579. else
  3580. {
  3581. fileName.setf("%s.xml", wuid);
  3582. winfo.getWorkunitXml(item.getPlainText(), mb);
  3583. writeToFileIOStream(workingFolder, fileName.str(), mb);
  3584. }
  3585. const char* plainText = item.getPlainText();
  3586. if (plainText && strieq(plainText, "yes"))
  3587. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  3588. else
  3589. fileMimeType.set(HTTP_TYPE_APPLICATION_XML);
  3590. break;
  3591. }
  3592. case CWUFileType_WUECL:
  3593. fileName.setf("%s.ecl", wuid);
  3594. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  3595. fileNameWithPath.set(workingFolder).append(PATHSEPCHAR).append(fileName.str());
  3596. winfo.getWorkunitQueryShortText(mb, fileNameWithPath.str());
  3597. break;
  3598. default:
  3599. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Unsupported file type %d.", fileType);
  3600. }
  3601. }
  3602. void CWsWuEmailHelper::send(const char* body, const void* attachment, size32_t lenAttachment, StringArray& warnings)
  3603. {
  3604. if (lenAttachment == 0)
  3605. sendEmail(to.get(), subject.get(), body, mailServer.get(), port, sender.get(), &warnings);
  3606. else
  3607. sendEmailAttachData(to.get(), subject.get(), body, lenAttachment, attachment, mimeType.get(),
  3608. attachmentName.get(), mailServer.get(), port, sender.get(), &warnings);
  3609. }
  3610. }