ws_workunitsHelpers.cpp 132 KB

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