ws_workunitsHelpers.cpp 135 KB

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