ws_workunitsService.cpp 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149
  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 "ws_workunitsService.hpp"
  14. #include "ws_fs.hpp"
  15. #include "jlib.hpp"
  16. #include "jflz.hpp"
  17. #include "daclient.hpp"
  18. #include "dalienv.hpp"
  19. #include "dadfs.hpp"
  20. #include "daaudit.hpp"
  21. #include "exception_util.hpp"
  22. #include "wujobq.hpp"
  23. #include "eventqueue.hpp"
  24. #include "fileview.hpp"
  25. #include "hqlerror.hpp"
  26. #include "sacmd.hpp"
  27. #include "wuwebview.hpp"
  28. #include "portlist.h"
  29. #include "dllserver.hpp"
  30. #include "schedulectrl.hpp"
  31. #include "scheduleread.hpp"
  32. #include "dadfs.hpp"
  33. #include "dfuwu.hpp"
  34. #include "thorplugin.hpp"
  35. #include "roxiecontrol.hpp"
  36. #include "package.h"
  37. #ifdef _USE_ZLIB
  38. #include "zcrypt.hpp"
  39. #endif
  40. #define ESP_WORKUNIT_DIR "workunits/"
  41. #define SDS_LOCK_TIMEOUT (5*60*1000) // 5 mins
  42. class ExecuteExistingQueryInfo
  43. {
  44. public:
  45. ExecuteExistingQueryInfo(IConstWorkUnit *cw)
  46. {
  47. SCMStringBuffer isv;
  48. cw->getJobName(isv);
  49. const char *name = isv.str();
  50. const char *div = strchr(name, '.');
  51. if (div)
  52. {
  53. queryset.set(name, div-name);
  54. query.set(div+1);
  55. }
  56. }
  57. public:
  58. StringAttr queryset;
  59. StringAttr query;
  60. };
  61. typedef enum _WuActionType
  62. {
  63. ActionDelete=0,
  64. ActionProtect,
  65. ActionAbort,
  66. ActionRestore,
  67. ActionEventSchedule,
  68. ActionEventDeschedule,
  69. ActionChangeState,
  70. ActionPause,
  71. ActionPauseNow,
  72. ActionResume,
  73. ActionUnknown
  74. } WsWuActionType;
  75. void setActionResult(const char* wuid, int action, const char* result, StringBuffer& strAction, IArrayOf<IConstWUActionResult>* results)
  76. {
  77. if (!results || !wuid || !*wuid || !result || !*result)
  78. return;
  79. switch(action)
  80. {
  81. case ActionDelete:
  82. {
  83. strAction = "Delete";
  84. break;
  85. }
  86. case ActionProtect:
  87. {
  88. strAction = "Protect";
  89. break;
  90. }
  91. case ActionAbort:
  92. {
  93. strAction = "Abort";
  94. break;
  95. }
  96. case ActionRestore:
  97. {
  98. strAction = "Restore";
  99. break;
  100. }
  101. case ActionEventSchedule:
  102. {
  103. strAction = "EventSchedule";
  104. break;
  105. }
  106. case ActionEventDeschedule:
  107. {
  108. strAction = "EventDeschedule";
  109. break;
  110. }
  111. case ActionChangeState:
  112. {
  113. strAction = "ChangeState";
  114. break;
  115. }
  116. case ActionPause:
  117. {
  118. strAction = "Pause";
  119. break;
  120. }
  121. case ActionPauseNow:
  122. {
  123. strAction = "PauseNow";
  124. break;
  125. }
  126. case ActionResume:
  127. {
  128. strAction = "Resume";
  129. break;
  130. }
  131. default:
  132. {
  133. strAction = "Unknown";
  134. }
  135. }
  136. Owned<IEspWUActionResult> res = createWUActionResult("", "");
  137. res->setWuid(wuid);
  138. res->setAction(strAction.str());
  139. res->setResult(result);
  140. results->append(*res.getClear());
  141. }
  142. bool doAction(IEspContext& context, StringArray& wuids, int action, IProperties* params, IArrayOf<IConstWUActionResult>* results)
  143. {
  144. if (!wuids.length())
  145. return true;
  146. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  147. bool bAllSuccess = true;
  148. for(aindex_t i=0; i<wuids.length();i++)
  149. {
  150. StringBuffer strAction;
  151. StringBuffer wuidStr = wuids.item(i);
  152. const char* wuid = wuidStr.trim().str();
  153. if (isEmpty(wuid))
  154. {
  155. WARNLOG("Empty Workunit ID");
  156. continue;
  157. }
  158. try
  159. {
  160. if (!looksLikeAWuid(wuid))
  161. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  162. if ((action == ActionRestore) || (action == ActionEventDeschedule))
  163. {
  164. switch(action)
  165. {
  166. case ActionRestore:
  167. {
  168. SocketEndpoint ep;
  169. if (params->hasProp("sashaServerIP"))
  170. ep.set(params->queryProp("sashaServerIP"), params->getPropInt("sashaServerPort"));
  171. else
  172. getSashaNode(ep);
  173. Owned<ISashaCommand> cmd = createSashaCommand();
  174. cmd->setAction(SCA_RESTORE);
  175. cmd->addId(wuid);
  176. Owned<INode> node = createINode(ep);
  177. if (!node)
  178. throw MakeStringException(ECLWATCH_INODE_NOT_FOUND,"INode not found.");
  179. StringBuffer s;
  180. if (!cmd->send(node, 1*60*1000))
  181. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to Archive server at %s.", ep.getUrlStr(s).str());
  182. if (cmd->numIds()==0)
  183. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Could not Archive/restore %s",wuid);
  184. StringBuffer reply;
  185. cmd->getId(0,reply);
  186. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  187. ensureWsWorkunitAccess(context, wuid, SecAccess_Write);
  188. break;
  189. }
  190. case ActionEventDeschedule:
  191. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Full, false)
  192. || !context.validateFeatureAccess(OTHERS_WU_ACCESS, SecAccess_Full, false))
  193. ensureWsWorkunitAccess(context, wuid, SecAccess_Full);
  194. descheduleWorkunit(wuid);
  195. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  196. break;
  197. }
  198. }
  199. else
  200. {
  201. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  202. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  203. if(!cw)
  204. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  205. if ((action == ActionDelete) && (cw->getState() == WUStateWait))
  206. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,"Cannot delete a workunit which is in a 'Wait' status.");
  207. switch(action)
  208. {
  209. case ActionPause:
  210. {
  211. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  212. WorkunitUpdate wu(&cw->lock());
  213. wu->setAction(WUActionPause);
  214. break;
  215. }
  216. case ActionPauseNow:
  217. {
  218. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  219. WorkunitUpdate wu(&cw->lock());
  220. wu->setAction(WUActionPauseNow);
  221. break;
  222. }
  223. case ActionResume:
  224. {
  225. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  226. WorkunitUpdate wu(&cw->lock());
  227. wu->setAction(WUActionResume);
  228. break;
  229. }
  230. case ActionDelete:
  231. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  232. {
  233. int state = cw->getState();
  234. switch (state)
  235. {
  236. case WUStateWait:
  237. case WUStateAborted:
  238. case WUStateCompleted:
  239. case WUStateFailed:
  240. case WUStateArchived:
  241. case WUStateCompiled:
  242. case WUStateUploadingFiles:
  243. break;
  244. default:
  245. {
  246. WorkunitUpdate wu(&cw->lock());
  247. wu->setState(WUStateFailed);
  248. }
  249. }
  250. cw.clear();
  251. factory->deleteWorkUnit(wuid);
  252. AuditSystemAccess(context.queryUserId(), true, "Deleted %s", wuid);
  253. }
  254. break;
  255. case ActionAbort:
  256. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  257. {
  258. if (cw->getState() == WUStateWait)
  259. {
  260. WorkunitUpdate wu(&cw->lock());
  261. wu->deschedule();
  262. wu->setState(WUStateAborted);
  263. }
  264. else
  265. secAbortWorkUnit(wuid, *context.querySecManager(), *context.queryUser());
  266. AuditSystemAccess(context.queryUserId(), true, "Aborted %s", wuid);
  267. }
  268. break;
  269. case ActionProtect:
  270. cw->protect(!params || params->getPropBool("Protect",true));
  271. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  272. break;
  273. case ActionChangeState:
  274. {
  275. if (params)
  276. {
  277. WUState state = (WUState) params->getPropInt("State");
  278. if (state > WUStateUnknown && state < WUStateSize)
  279. {
  280. WorkunitUpdate wu(&cw->lock());
  281. wu->setState(state);
  282. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  283. }
  284. }
  285. }
  286. break;
  287. case ActionEventSchedule:
  288. {
  289. WorkunitUpdate wu(&cw->lock());
  290. wu->schedule();
  291. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  292. }
  293. break;
  294. }
  295. }
  296. setActionResult(wuid, action, "Success", strAction, results);
  297. }
  298. catch (IException *e)
  299. {
  300. bAllSuccess = false;
  301. StringBuffer eMsg;
  302. StringBuffer failedMsg("Failed: ");
  303. setActionResult(wuid, action, failedMsg.append(e->errorMessage(eMsg)).str(), strAction, results);
  304. WARNLOG("Failed to %s for workunit: %s, %s", strAction.str(), wuid, eMsg.str());
  305. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction.str(), wuid);
  306. e->Release();
  307. continue;
  308. }
  309. catch (...)
  310. {
  311. bAllSuccess = false;
  312. StringBuffer failedMsg;
  313. failedMsg.appendf("Unknown exception");
  314. setActionResult(wuid, action, failedMsg.str(), strAction, results);
  315. WARNLOG("Failed to %s for workunit: %s, %s", strAction.str(), wuid, failedMsg.str());
  316. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction.str(), wuid);
  317. continue;
  318. }
  319. }
  320. int timeToWait = 0;
  321. if (params)
  322. timeToWait = params->getPropInt("BlockTillFinishTimer");
  323. if (timeToWait != 0)
  324. {
  325. for(aindex_t i=0; i<wuids.length();i++)
  326. {
  327. const char* wuid=wuids.item(i);
  328. if (isEmpty(wuid))
  329. continue;
  330. waitForWorkUnitToComplete(wuid, timeToWait);
  331. }
  332. }
  333. return bAllSuccess;
  334. }
  335. static void checkUpdateQuerysetLibraries()
  336. {
  337. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  338. if (!globalLock)
  339. return;
  340. IPropertyTree *root = globalLock->queryRoot();
  341. if (!root)
  342. return;
  343. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  344. Owned<IPropertyTreeIterator> querySets = root->getElements("QuerySet");
  345. ForEach(*querySets)
  346. {
  347. IPropertyTree &querySet = querySets->query();
  348. if (querySet.hasProp("@updatedLibraries")) //only need to do this once, then publish and copy will keep up to date
  349. continue;
  350. Owned<IPropertyTreeIterator> queries = querySet.getElements("Query");
  351. ForEach(*queries)
  352. {
  353. IPropertyTree &query = queries->query();
  354. if (query.hasProp("@libCount"))
  355. continue;
  356. const char *wuid = query.queryProp("@wuid");
  357. if (!wuid || !*wuid)
  358. continue;
  359. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  360. if (!cw)
  361. continue;
  362. checkAddLibrariesToQueryEntry(&query, cw);
  363. }
  364. querySet.setPropBool("@updatedLibraries", true);
  365. }
  366. }
  367. MapStringTo<int> wuActionTable;
  368. void CWsWorkunitsEx::init(IPropertyTree *cfg, const char *process, const char *service)
  369. {
  370. if (!daliClientActive())
  371. {
  372. ERRLOG("No Dali Connection Active.");
  373. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  374. }
  375. setPasswordsFromSDS();
  376. DBGLOG("Initializing %s service [process = %s]", service, process);
  377. checkUpdateQuerysetLibraries();
  378. refreshValidClusters();
  379. daliServers.set(cfg->queryProp("Software/EspProcess/@daliServers"));
  380. wuActionTable.setValue("delete", ActionDelete);
  381. wuActionTable.setValue("abort", ActionAbort);
  382. wuActionTable.setValue("pausenow", ActionPauseNow);
  383. wuActionTable.setValue("pause", ActionPause);
  384. wuActionTable.setValue("resume", ActionResume);
  385. wuActionTable.setValue("protect", ActionProtect);
  386. wuActionTable.setValue("unprotect", ActionProtect);
  387. wuActionTable.setValue("restore", ActionRestore);
  388. wuActionTable.setValue("reschedule", ActionEventSchedule);
  389. wuActionTable.setValue("deschedule", ActionEventDeschedule);
  390. wuActionTable.setValue("settofailed", ActionChangeState);
  391. awusCacheMinutes = AWUS_CACHE_MIN_DEFAULT;
  392. VStringBuffer xpath("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/AWUsCacheMinutes", process, service);
  393. cfg->getPropInt(xpath.str(), awusCacheMinutes);
  394. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@netAddress", process, service);
  395. if (cfg->hasProp(xpath.str()))
  396. {
  397. sashaServerIp.set(cfg->queryProp(xpath.str()));
  398. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@port", process, service);
  399. sashaServerPort = cfg->getPropInt(xpath.str(), DEFAULT_SASHA_PORT);
  400. }
  401. maxRequestEntityLength = cfg->getPropInt("Software[1]/EspProcess[1]/EspProtocol[@type='http_protocol'][1]/@maxRequestEntityLength");
  402. directories.set(cfg->queryPropTree("Software/Directories"));
  403. const char *name = cfg->queryProp("Software/EspProcess/@name");
  404. getConfigurationDirectory(directories, "query", "esp", name ? name : "esp", queryDirectory);
  405. recursiveCreateDirectory(queryDirectory.str());
  406. dataCache.setown(new DataCache(DATA_SIZE));
  407. archivedWuCache.setown(new ArchivedWuCache(AWUS_CACHE_SIZE));
  408. //Create a folder for temporarily holding gzip files by WUResultBin()
  409. Owned<IFile> tmpdir = createIFile(TEMPZIPDIR);
  410. if(!tmpdir->exists())
  411. tmpdir->createDirectory();
  412. recursiveCreateDirectory(ESP_WORKUNIT_DIR);
  413. m_sched.start();
  414. filesInUse.subscribe();
  415. }
  416. void CWsWorkunitsEx::refreshValidClusters()
  417. {
  418. validClusters.kill();
  419. Owned<IStringIterator> it = getTargetClusters(NULL, NULL);
  420. ForEach(*it)
  421. {
  422. SCMStringBuffer s;
  423. IStringVal &val = it->str(s);
  424. if (!validClusters.getValue(val.str()))
  425. validClusters.setValue(val.str(), true);
  426. }
  427. }
  428. bool CWsWorkunitsEx::isValidCluster(const char *cluster)
  429. {
  430. if (!cluster || !*cluster)
  431. return false;
  432. CriticalBlock block(crit);
  433. if (validClusters.getValue(cluster))
  434. return true;
  435. if (validateTargetClusterName(cluster))
  436. {
  437. refreshValidClusters();
  438. return true;
  439. }
  440. return false;
  441. }
  442. bool CWsWorkunitsEx::onWUCreate(IEspContext &context, IEspWUCreateRequest &req, IEspWUCreateResponse &resp)
  443. {
  444. try
  445. {
  446. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  447. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  448. NewWsWorkunit wu(context);
  449. SCMStringBuffer wuid;
  450. resp.updateWorkunit().setWuid(wu->getWuid(wuid).str());
  451. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  452. }
  453. catch(IException* e)
  454. {
  455. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  456. }
  457. return true;
  458. }
  459. static bool origValueChanged(const char *newValue, const char *origValue, StringBuffer &s, bool nillable=true)
  460. {
  461. if (!nillable && isEmpty(newValue))
  462. return false;
  463. if(newValue && origValue)
  464. {
  465. if (!streq(origValue, newValue))
  466. {
  467. s.append(newValue).trim();
  468. return true;
  469. }
  470. return false;
  471. }
  472. if (newValue)
  473. {
  474. s.append(newValue).trim();
  475. return true;
  476. }
  477. return (origValue!=NULL);
  478. }
  479. bool CWsWorkunitsEx::onWUUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  480. {
  481. try
  482. {
  483. StringBuffer wuid = req.getWuid();
  484. WsWuHelpers::checkAndTrimWorkunit("WUUpdate", wuid);
  485. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  486. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  487. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  488. if(!cw)
  489. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  490. if(req.getProtected() != req.getProtectedOrig())
  491. {
  492. cw->protect(req.getProtected());
  493. cw.clear();
  494. cw.setown(factory->openWorkUnit(wuid.str(), false));
  495. if(!cw)
  496. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  497. }
  498. if ((req.getState() == WUStateRunning)||(req.getState() == WUStateDebugPaused)||(req.getState() == WUStateDebugRunning))
  499. {
  500. WsWuInfo winfo(context, cw);
  501. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  502. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  503. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  504. return true;
  505. }
  506. WorkunitUpdate wu(&cw->lock());
  507. if(!req.getState_isNull() && (req.getStateOrig_isNull() || req.getState() != req.getStateOrig()))
  508. {
  509. if (!req.getStateOrig_isNull() && cw->getState() != (WUState) req.getStateOrig())
  510. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Cannot update workunit %s because its state has been changed internally. Please refresh the page and try again.", wuid.str());
  511. WUState state = (WUState) req.getState();
  512. if(state < WUStateSize)
  513. wu->setState(state);
  514. }
  515. StringBuffer s;
  516. if (origValueChanged(req.getJobname(), req.getJobnameOrig(), s))
  517. wu->setJobName(s.trim().str());
  518. if (origValueChanged(req.getDescription(), req.getDescriptionOrig(), s.clear()))
  519. wu->setDebugValue("description", (req.getDescription() && *req.getDescription()) ? s.trim().str() : NULL, true);
  520. double version = context.getClientVersion();
  521. if (version > 1.04)
  522. {
  523. if (origValueChanged(req.getClusterSelection(), req.getClusterOrig(), s.clear(), false))
  524. {
  525. if (!isValidCluster(s.str()))
  526. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", s.str());
  527. if (req.getState() == WUStateBlocked)
  528. switchWorkUnitQueue(wu.get(), s.str());
  529. else if ((req.getState() != WUStateSubmitted) && (req.getState() != WUStateRunning) && (req.getState() != WUStateDebugPaused) && (req.getState() != WUStateDebugRunning))
  530. wu->setClusterName(s.str());
  531. }
  532. }
  533. WsWuHelpers::setXmlParameters(wu, req.getXmlParams(), (req.getAction()==WUActionExecuteExisting));
  534. if (notEmpty(req.getQueryText()))
  535. {
  536. Owned<IWUQuery> query=wu->updateQuery();
  537. query->setQueryText(req.getQueryText());
  538. }
  539. if (version > 1.34 && notEmpty(req.getQueryMainDefinition()))
  540. {
  541. Owned<IWUQuery> query=wu->updateQuery();
  542. query->setQueryMainDefinition(req.getQueryMainDefinition());
  543. }
  544. if (!req.getResultLimit_isNull())
  545. wu->setResultLimit(req.getResultLimit());
  546. if (!req.getAction_isNull())
  547. {
  548. WUAction action = (WUAction) req.getAction();
  549. if(action < WUActionSize)
  550. wu->setAction(action);
  551. }
  552. if (!req.getPriorityClass_isNull())
  553. {
  554. WUPriorityClass priority = (WUPriorityClass) req.getPriorityClass();
  555. if(priority<PriorityClassSize)
  556. wu->setPriority(priority);
  557. }
  558. if (!req.getPriorityLevel_isNull())
  559. wu->setPriorityLevel(req.getPriorityLevel());
  560. if (origValueChanged(req.getScope(), req.getScopeOrig(), s.clear(), false))
  561. wu->setWuScope(s.str());
  562. ForEachItemIn(di, req.getDebugValues())
  563. {
  564. IConstDebugValue& item = req.getDebugValues().item(di);
  565. if (notEmpty(item.getName()))
  566. wu->setDebugValue(item.getName(), item.getValue(), true);
  567. }
  568. ForEachItemIn(ai, req.getApplicationValues())
  569. {
  570. IConstApplicationValue& item=req.getApplicationValues().item(ai);
  571. if(notEmpty(item.getApplication()) && notEmpty(item.getName()))
  572. wu->setApplicationValue(item.getApplication(), item.getName(), item.getValue(), true);
  573. }
  574. wu->commit();
  575. wu.clear();
  576. WsWuInfo winfo(context, cw);
  577. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  578. StringBuffer thorSlaveIP;
  579. if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
  580. thorSlaveIP = req.getThorSlaveIP();
  581. if (thorSlaveIP.length() > 0)
  582. {
  583. StringBuffer url;
  584. url.appendf("/WsWorkunits/WUInfo?Wuid=%s&ThorSlaveIP=%s", wuid.str(), thorSlaveIP.str());
  585. resp.setRedirectUrl(url.str());
  586. }
  587. else
  588. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  589. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  590. }
  591. catch(IException* e)
  592. {
  593. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  594. }
  595. return true;
  596. }
  597. bool CWsWorkunitsEx::onWUCreateAndUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  598. {
  599. try
  600. {
  601. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  602. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  603. NewWsWorkunit wu(context);
  604. SCMStringBuffer wuid;
  605. wu->getWuid(wuid);
  606. req.setWuid(wuid.str());
  607. }
  608. catch(IException* e)
  609. {
  610. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  611. }
  612. return onWUUpdate(context, req, resp);
  613. }
  614. static inline StringBuffer &appendUrlParameter(StringBuffer &url, const char *name, const char *value, bool &first)
  615. {
  616. if (notEmpty(value))
  617. {
  618. url.append(first ? '?' : '&').append(name).append('=').append(value);
  619. first=false;
  620. }
  621. return url;
  622. }
  623. bool CWsWorkunitsEx::onWUAction(IEspContext &context, IEspWUActionRequest &req, IEspWUActionResponse &resp)
  624. {
  625. try
  626. {
  627. StringBuffer sAction(req.getActionType());
  628. if (!sAction.length())
  629. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined.");
  630. int *action=wuActionTable.getValue(sAction.toLowerCase().str());
  631. if (!action)
  632. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Invalid Action '%s'.", sAction.str());
  633. Owned<IProperties> params = createProperties(true);
  634. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  635. if (*action==ActionProtect)
  636. params->setProp("Protect", streq(sAction.str(), "protect"));
  637. if (*action==ActionChangeState && streq(sAction.str(), "settofailed"))
  638. params->setProp("State",4);
  639. if ((*action==ActionRestore) && !sashaServerIp.isEmpty())
  640. {
  641. params->setProp("sashaServerIP", sashaServerIp.get());
  642. params->setProp("sashaServerPort", sashaServerPort);
  643. }
  644. IArrayOf<IConstWUActionResult> results;
  645. if (doAction(context, req.getWuids(), *action, params, &results) && *action!=ActionDelete && checkRedirect(context))
  646. {
  647. StringBuffer redirect;
  648. if(req.getPageFrom() && strieq(req.getPageFrom(), "wuid"))
  649. redirect.append("/WsWorkunits/WUInfo?Wuid=").append(req.getWuids().item(0));
  650. else if (req.getPageFrom() && strieq(req.getPageFrom(), "scheduler"))
  651. {
  652. redirect.set("/WsWorkunits/WUShowScheduled");
  653. bool first=true;
  654. appendUrlParameter(redirect, "Cluster", req.getEventServer(), first);
  655. appendUrlParameter(redirect, "EventName", req.getEventName(), first);
  656. }
  657. else
  658. {
  659. redirect.append("/WsWorkunits/WUQuery");
  660. bool first=true;
  661. appendUrlParameter(redirect, "PageSize", req.getPageSize(), first);
  662. appendUrlParameter(redirect, "PageStartFrom", req.getCurrentPage(), first);
  663. appendUrlParameter(redirect, "Sortby", req.getSortby(), first);
  664. appendUrlParameter(redirect, "Descending", req.getDescending() ? "1" : "0", first);
  665. appendUrlParameter(redirect, "State", req.getState(), first);
  666. appendUrlParameter(redirect, "Cluster", req.getCluster(), first);
  667. appendUrlParameter(redirect, "Owner", req.getOwner(), first);
  668. appendUrlParameter(redirect, "StartDate", req.getStartDate(), first);
  669. appendUrlParameter(redirect, "EndDate", req.getEndDate(), first);
  670. appendUrlParameter(redirect, "ECL", req.getECL(), first);
  671. appendUrlParameter(redirect, "Jobname", req.getJobname(), first);
  672. }
  673. resp.setRedirectUrl(redirect.str());
  674. }
  675. else
  676. resp.setActionResults(results);
  677. }
  678. catch(IException* e)
  679. {
  680. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  681. }
  682. return true;
  683. }
  684. bool CWsWorkunitsEx::onWUDelete(IEspContext &context, IEspWUDeleteRequest &req, IEspWUDeleteResponse &resp)
  685. {
  686. try
  687. {
  688. IArrayOf<IConstWUActionResult> results;
  689. Owned<IProperties> params = createProperties(true);
  690. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  691. if (!doAction(context,req.getWuids(), ActionDelete, params, &results))
  692. resp.setActionResults(results);
  693. }
  694. catch(IException* e)
  695. {
  696. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  697. }
  698. return true;
  699. }
  700. bool CWsWorkunitsEx::onWUAbort(IEspContext &context, IEspWUAbortRequest &req, IEspWUAbortResponse &resp)
  701. {
  702. try
  703. {
  704. IArrayOf<IConstWUActionResult> results;
  705. Owned<IProperties> params = createProperties(true);
  706. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  707. if (!doAction(context,req.getWuids(), ActionAbort, params, &results))
  708. resp.setActionResults(results);
  709. }
  710. catch(IException* e)
  711. {
  712. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  713. }
  714. return true;
  715. }
  716. bool CWsWorkunitsEx::onWUProtect(IEspContext &context, IEspWUProtectRequest &req, IEspWUProtectResponse &resp)\
  717. {
  718. try
  719. {
  720. IArrayOf<IConstWUActionResult> results;
  721. Owned<IProperties> params(createProperties(true));
  722. params->setProp("Protect", req.getProtect());
  723. params->setProp("BlockTillFinishTimer", 0);
  724. if (!doAction(context,req.getWuids(), ActionProtect, params, &results))
  725. resp.setActionResults(results);
  726. }
  727. catch(IException* e)
  728. {
  729. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  730. }
  731. return true;
  732. }
  733. bool CWsWorkunitsEx::onWUResubmit(IEspContext &context, IEspWUResubmitRequest &req, IEspWUResubmitResponse &resp)
  734. {
  735. try
  736. {
  737. Owned<IMultiException> me = MakeMultiException();
  738. SCMStringBuffer wuid;
  739. StringArray wuids;
  740. double version = context.getClientVersion();
  741. IArrayOf<IEspResubmittedWU> resubmittedWUs;
  742. for(aindex_t i=0; i<req.getWuids().length();i++)
  743. {
  744. StringBuffer requestWuid = req.getWuids().item(i);
  745. WsWuHelpers::checkAndTrimWorkunit("WUResubmit", requestWuid);
  746. ensureWsWorkunitAccess(context, requestWuid.str(), SecAccess_Write);
  747. wuid.set(requestWuid.str());
  748. try
  749. {
  750. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  751. if(req.getCloneWorkunit() || req.getRecompile())
  752. {
  753. Owned<IConstWorkUnit> src(factory->openWorkUnit(wuid.str(), false));
  754. NewWsWorkunit wu(factory, context);
  755. wu->getWuid(wuid);
  756. queryExtendedWU(wu)->copyWorkUnit(src, false);
  757. SCMStringBuffer token;
  758. wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
  759. }
  760. wuids.append(wuid.str());
  761. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str(), false));
  762. if(!cw)
  763. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  764. //Dont allow resubmit of someone else's workunit
  765. if (context.querySecManager())
  766. {
  767. IUserDescriptor * owner = cw->queryUserDescriptor();
  768. if (!owner)
  769. throw MakeStringException(ECLWATCH_CANNOT_SUBMIT_WORKUNIT,"Workunit User Descriptor missing on %s", wuid.str());
  770. StringBuffer ownerUserName;
  771. owner->getUserName(ownerUserName);
  772. if (strcmp(context.queryUser()->getName(), ownerUserName.str()))
  773. throw MakeStringException(ECLWATCH_CANNOT_SUBMIT_WORKUNIT,"Cannot resubmit another user's workunit %s.", wuid.str());
  774. }
  775. WsWuHelpers::submitWsWorkunit(context, cw, NULL, NULL, 0, req.getRecompile(), req.getResetWorkflow(), false);
  776. if (version < 1.40)
  777. continue;
  778. Owned<IEspResubmittedWU> resubmittedWU = createResubmittedWU();
  779. resubmittedWU->setWUID(wuid.str());
  780. if (!streq(requestWuid.str(), wuid.str()))
  781. resubmittedWU->setParentWUID(requestWuid.str());
  782. resubmittedWUs.append(*resubmittedWU.getClear());
  783. }
  784. catch (IException *E)
  785. {
  786. me->append(*E);
  787. }
  788. catch (...)
  789. {
  790. me->append(*MakeStringException(0,"Unknown exception submitting %s",wuid.str()));
  791. }
  792. }
  793. if(me->ordinality())
  794. throw me.getLink();
  795. int timeToWait = req.getBlockTillFinishTimer();
  796. if (timeToWait != 0)
  797. {
  798. for(aindex_t i=0; i<wuids.length(); i++)
  799. waitForWorkUnitToComplete(wuids.item(i), timeToWait);
  800. }
  801. if (version >= 1.40)
  802. resp.setWUs(resubmittedWUs);
  803. if(wuids.length()==1)
  804. {
  805. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuids.item(0)));
  806. }
  807. }
  808. catch(IException* e)
  809. {
  810. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  811. }
  812. return true;
  813. }
  814. bool CWsWorkunitsEx::onWUPushEvent(IEspContext &context, IEspWUPushEventRequest &req, IEspWUPushEventResponse &resp)
  815. {
  816. try
  817. {
  818. const char *name = req.getEventName();
  819. const char *text = req.getEventText();
  820. const char *target = NULL;
  821. if (notEmpty(name) && notEmpty(text))
  822. {
  823. Owned<IScheduleEventPusher> pusher(getScheduleEventPusher());
  824. pusher->push(name, text, target);
  825. StringBuffer redirect("/WsWorkunits/WUShowScheduled");
  826. bool first=true;
  827. appendUrlParameter(redirect, "PushEventName", name, first);
  828. appendUrlParameter(redirect, "PushEventText", text, first);
  829. resp.setRedirectUrl(redirect.str());
  830. return true;
  831. }
  832. }
  833. catch(IException* e)
  834. {
  835. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  836. }
  837. return false;
  838. }
  839. bool CWsWorkunitsEx::onWUSchedule(IEspContext &context, IEspWUScheduleRequest &req, IEspWUScheduleResponse &resp)
  840. {
  841. try
  842. {
  843. StringBuffer wuid = req.getWuid();
  844. WsWuHelpers::checkAndTrimWorkunit("WUSchedule", wuid);
  845. const char* cluster = req.getCluster();
  846. if (isEmpty(cluster))
  847. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  848. if (!isValidCluster(cluster))
  849. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  850. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  851. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  852. ensureWsWorkunitAccess(context, *wu.get(), SecAccess_Write);
  853. switch(wu->getState())
  854. {
  855. case WUStateDebugPaused:
  856. case WUStateDebugRunning:
  857. case WUStateRunning:
  858. case WUStateAborting:
  859. case WUStateBlocked:
  860. {
  861. SCMStringBuffer descr;
  862. throw MakeStringException(ECLWATCH_CANNOT_SCHEDULE_WORKUNIT, "Cannot schedule the workunit. Workunit state is '%s'.", wu->getStateDesc(descr).str());
  863. }
  864. }
  865. wu->clearExceptions();
  866. wu->setClusterName(cluster);
  867. if (notEmpty(req.getWhen()))
  868. {
  869. WsWuDateTime dt;
  870. dt.setString(req.getWhen());
  871. wu->setTimeScheduled(dt);
  872. }
  873. if(notEmpty(req.getSnapshot()))
  874. wu->setSnapshot(req.getSnapshot());
  875. wu->setState(WUStateScheduled);
  876. if (req.getMaxRunTime())
  877. wu->setDebugValueInt("maxRunTime", req.getMaxRunTime(), true);
  878. SCMStringBuffer token;
  879. wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
  880. AuditSystemAccess(context.queryUserId(), true, "Scheduled %s", wuid.str());
  881. }
  882. catch(IException* e)
  883. {
  884. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  885. }
  886. return true;
  887. }
  888. bool CWsWorkunitsEx::onWUSubmit(IEspContext &context, IEspWUSubmitRequest &req, IEspWUSubmitResponse &resp)
  889. {
  890. try
  891. {
  892. StringBuffer wuid = req.getWuid();
  893. WsWuHelpers::checkAndTrimWorkunit("WUSubmit", wuid);
  894. const char *cluster = req.getCluster();
  895. if (isEmpty(cluster))
  896. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  897. if (!isValidCluster(cluster))
  898. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  899. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  900. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  901. if(!cw)
  902. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  903. if (cw->getAction()==WUActionExecuteExisting)
  904. {
  905. ExecuteExistingQueryInfo info(cw);
  906. if (info.queryset.isEmpty() || info.query.isEmpty())
  907. {
  908. WorkunitUpdate wu(&cw->lock());
  909. throw WsWuHelpers::noteException(wu, MakeStringException(ECLWATCH_INVALID_INPUT,"Queryset and/or query not specified"));
  910. }
  911. WsWuHelpers::runWsWuQuery(context, cw, info.queryset.sget(), info.query.sget(), cluster, NULL);
  912. }
  913. else
  914. WsWuHelpers::submitWsWorkunit(context, cw, cluster, req.getSnapshot(), req.getMaxRunTime(), true, false, false);
  915. if (req.getBlockTillFinishTimer() != 0)
  916. waitForWorkUnitToComplete(wuid.str(), req.getBlockTillFinishTimer());
  917. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  918. }
  919. catch(IException* e)
  920. {
  921. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  922. }
  923. return true;
  924. }
  925. WUExceptionSeverity checkGetExceptionSeverity(CWUExceptionSeverity severity)
  926. {
  927. switch (severity)
  928. {
  929. case CWUExceptionSeverity_INFO:
  930. return ExceptionSeverityInformation;
  931. case CWUExceptionSeverity_WARNING:
  932. return ExceptionSeverityWarning;
  933. case CWUExceptionSeverity_ERROR:
  934. return ExceptionSeverityError;
  935. }
  936. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT,"invalid exception severity");
  937. }
  938. bool CWsWorkunitsEx::onWURun(IEspContext &context, IEspWURunRequest &req, IEspWURunResponse &resp)
  939. {
  940. try
  941. {
  942. const char *cluster = req.getCluster();
  943. if (notEmpty(cluster) && !isValidCluster(cluster))
  944. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  945. StringBuffer wuidStr = req.getWuid();
  946. const char* runWuid = wuidStr.trim().str();
  947. StringBuffer wuid;
  948. WUExceptionSeverity severity = checkGetExceptionSeverity(req.getExceptionSeverity());
  949. if (runWuid && *runWuid)
  950. {
  951. if (!looksLikeAWuid(runWuid))
  952. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", runWuid);
  953. if (req.getCloneWorkunit())
  954. WsWuHelpers::runWsWorkunit(context, wuid, runWuid, cluster, req.getInput(), &req.getVariables(), &req.getDebugValues());
  955. else
  956. {
  957. WsWuHelpers::submitWsWorkunit(context, runWuid, cluster, NULL, 0, false, true, true, req.getInput(), &req.getVariables(), &req.getDebugValues());
  958. wuid.set(runWuid);
  959. }
  960. }
  961. else if (notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  962. WsWuHelpers::runWsWuQuery(context, wuid, req.getQuerySet(), req.getQuery(), cluster, req.getInput());
  963. else
  964. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
  965. int timeToWait = req.getWait();
  966. if (timeToWait != 0)
  967. waitForWorkUnitToComplete(wuid.str(), timeToWait);
  968. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  969. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  970. if (!cw)
  971. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.", wuid.str());
  972. SCMStringBuffer stateDesc;
  973. resp.setState(cw->getStateDesc(stateDesc).str());
  974. resp.setWuid(wuid.str());
  975. switch (cw->getState())
  976. {
  977. case WUStateCompleted:
  978. case WUStateFailed:
  979. case WUStateUnknown:
  980. {
  981. SCMStringBuffer result;
  982. unsigned flags = WorkUnitXML_SeverityTags;
  983. if (req.getNoRootTag())
  984. flags |= WorkUnitXML_NoRoot;
  985. getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  986. resp.setResults(result.str());
  987. break;
  988. }
  989. default:
  990. break;
  991. }
  992. }
  993. catch(IException* e)
  994. {
  995. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  996. }
  997. return true;
  998. }
  999. bool CWsWorkunitsEx::onWUWaitCompiled(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  1000. {
  1001. try
  1002. {
  1003. StringBuffer wuid = req.getWuid();
  1004. WsWuHelpers::checkAndTrimWorkunit("WUWaitCompiled", wuid);
  1005. secWaitForWorkUnitToCompile(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait());
  1006. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1007. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  1008. if(!cw)
  1009. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  1010. resp.setStateID(cw->getState());
  1011. }
  1012. catch(IException* e)
  1013. {
  1014. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1015. }
  1016. return true;
  1017. }
  1018. bool CWsWorkunitsEx::onWUWaitComplete(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  1019. {
  1020. try
  1021. {
  1022. StringBuffer wuid = req.getWuid();
  1023. WsWuHelpers::checkAndTrimWorkunit("WUWaitComplete", wuid);
  1024. resp.setStateID(secWaitForWorkUnitToComplete(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait(), req.getReturnOnWait()));
  1025. }
  1026. catch(IException* e)
  1027. {
  1028. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1029. }
  1030. return true;
  1031. }
  1032. bool CWsWorkunitsEx::onWUCDebug(IEspContext &context, IEspWUDebugRequest &req, IEspWUDebugResponse &resp)
  1033. {
  1034. try
  1035. {
  1036. StringBuffer wuid = req.getWuid();
  1037. WsWuHelpers::checkAndTrimWorkunit("WUCDebug", wuid);
  1038. StringBuffer result;
  1039. secDebugWorkunit(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getCommand(), result);
  1040. resp.setResult(result);
  1041. }
  1042. catch(IException* e)
  1043. {
  1044. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1045. }
  1046. return true;
  1047. }
  1048. bool CWsWorkunitsEx::onWUSyntaxCheckECL(IEspContext &context, IEspWUSyntaxCheckRequest &req, IEspWUSyntaxCheckResponse &resp)
  1049. {
  1050. try
  1051. {
  1052. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1053. NewWsWorkunit wu(factory, context);
  1054. wu->setAction(WUActionCheck);
  1055. if(notEmpty(req.getModuleName()) && notEmpty(req.getAttributeName()))
  1056. {
  1057. wu->setApplicationValue("SyntaxCheck", "ModuleName", req.getModuleName(), true);
  1058. wu->setApplicationValue("SyntaxCheck", "AttributeName", req.getAttributeName(), true);
  1059. }
  1060. ForEachItemIn(di, req.getDebugValues())
  1061. {
  1062. IConstDebugValue& item=req.getDebugValues().item(di);
  1063. if(notEmpty(item.getName()))
  1064. wu->setDebugValue(item.getName(), item.getValue(), true);
  1065. }
  1066. wu.setQueryText(req.getECL());
  1067. SCMStringBuffer wuid;
  1068. wu->getWuid(wuid);
  1069. wu->commit();
  1070. wu.clear();
  1071. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1072. waitForWorkUnitToComplete(wuid.str(), req.getTimeToWait());
  1073. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str(), false));
  1074. WsWUExceptions errors(*cw);
  1075. resp.setErrors(errors);
  1076. cw.clear();
  1077. factory->deleteWorkUnit(wuid.str());
  1078. }
  1079. catch(IException* e)
  1080. {
  1081. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1082. }
  1083. return true;
  1084. }
  1085. bool CWsWorkunitsEx::onWUCompileECL(IEspContext &context, IEspWUCompileECLRequest &req, IEspWUCompileECLResponse &resp)
  1086. {
  1087. try
  1088. {
  1089. ensureWsCreateWorkunitAccess(context);
  1090. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1091. NewWsWorkunit wu(factory, context);
  1092. if(req.getIncludeComplexity())
  1093. {
  1094. wu->setAction(WUActionCompile);
  1095. wu->setDebugValueInt("calculateComplexity",1,true);
  1096. }
  1097. else
  1098. wu->setAction(WUActionCheck);
  1099. if(req.getModuleName() && req.getAttributeName())
  1100. {
  1101. wu->setApplicationValue("SyntaxCheck","ModuleName",req.getModuleName(),true);
  1102. wu->setApplicationValue("SyntaxCheck","AttributeName",req.getAttributeName(),true);
  1103. }
  1104. if(req.getIncludeDependencies())
  1105. wu->setApplicationValueInt("SyntaxCheck","IncludeDependencies",1,true);
  1106. wu.setQueryText(req.getECL());
  1107. SCMStringBuffer wuid;
  1108. wu->getWuid(wuid);
  1109. wu.clear();
  1110. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1111. waitForWorkUnitToComplete(wuid.str(),req.getTimeToWait());
  1112. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  1113. SCMStringBuffer s;
  1114. cw->getDebugValue("__Calculated__Complexity__",s);
  1115. if(s.length())
  1116. resp.setComplexity(s.str());
  1117. WsWUExceptions errors(*cw);
  1118. resp.setErrors(errors);
  1119. if(!errors.ErrCount())
  1120. {
  1121. IArrayOf<IEspWUECLAttribute> dependencies;
  1122. for(unsigned count=1;;count++)
  1123. {
  1124. SCMStringBuffer xml;
  1125. cw->getApplicationValue("SyntaxCheck",StringBuffer("Dependency").append(count).str(),xml);
  1126. if(!xml.length())
  1127. break;
  1128. Owned<IPropertyTree> dep=createPTreeFromXMLString(xml.str(), ipt_caseInsensitive);
  1129. if(!dep)
  1130. continue;
  1131. Owned<IEspWUECLAttribute> att = createWUECLAttribute("","");
  1132. att->setModuleName(dep->queryProp("@module"));
  1133. att->setAttributeName(dep->queryProp("@name"));
  1134. int flags = dep->getPropInt("@flags",0);
  1135. if(flags & ob_locked)
  1136. {
  1137. if(flags & ob_lockedself)
  1138. att->setIsCheckedOut(true);
  1139. else
  1140. att->setIsLocked(true);
  1141. }
  1142. if(flags & ob_sandbox)
  1143. att->setIsSandbox(true);
  1144. if(flags & ob_orphaned)
  1145. att->setIsOrphaned(true);
  1146. dependencies.append(*att.getLink());
  1147. }
  1148. resp.setDependencies(dependencies);
  1149. }
  1150. cw.clear();
  1151. factory->deleteWorkUnit(wuid.str());
  1152. }
  1153. catch(IException* e)
  1154. {
  1155. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1156. }
  1157. return true;
  1158. }
  1159. bool CWsWorkunitsEx::onWUGetDependancyTrees(IEspContext& context, IEspWUGetDependancyTreesRequest& req, IEspWUGetDependancyTreesResponse& resp)
  1160. {
  1161. try
  1162. {
  1163. DBGLOG("WUGetDependancyTrees");
  1164. unsigned int timeMilliSec = 500;
  1165. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1166. NewWsWorkunit wu(factory, context);
  1167. wu->setAction(WUActionCheck);
  1168. if (notEmpty(req.getCluster()))
  1169. wu->setClusterName(req.getCluster());
  1170. if (notEmpty(req.getSnapshot()))
  1171. wu->setSnapshot(req.getSnapshot());
  1172. wu->setDebugValue("gatherDependenciesSelection",notEmpty(req.getItems()) ? req.getItems() : NULL,true);
  1173. if (context.getClientVersion() > 1.12)
  1174. {
  1175. wu->setDebugValueInt("gatherDependencies", 1, true);
  1176. const char *timeout = req.getTimeoutMilliSec();
  1177. if (notEmpty(timeout))
  1178. {
  1179. const char *finger = timeout;
  1180. while (*finger)
  1181. {
  1182. if (!isdigit(*finger++))
  1183. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Incorrect timeout value");
  1184. }
  1185. timeMilliSec = atol(timeout);
  1186. }
  1187. }
  1188. SCMStringBuffer wuid;
  1189. wu->getWuid(wuid);
  1190. wu->commit();
  1191. wu.clear();
  1192. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1193. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1194. int state = waitForWorkUnitToComplete(wuid.str(), timeMilliSec);
  1195. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  1196. WsWUExceptions errors(*cw);
  1197. resp.setErrors(errors);
  1198. MemoryBuffer temp;
  1199. MemoryBuffer2IDataVal xmlresult(temp);
  1200. Owned<IConstWUResult> result = cw->getResultBySequence(0);
  1201. if (result)
  1202. {
  1203. result->getResultRaw(xmlresult, NULL, NULL);
  1204. resp.setDependancyTrees(temp);
  1205. }
  1206. wu.setown(&cw->lock());
  1207. wu->setState(WUStateAborted);
  1208. wu->commit();
  1209. wu.clear();
  1210. factory->deleteWorkUnit(wuid.str());
  1211. }
  1212. catch(IException* e)
  1213. {
  1214. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1215. }
  1216. return true;
  1217. }
  1218. bool getWsWuInfoFromSasha(IEspContext &context, SocketEndpoint &ep, const char* wuid, IEspECLWorkunit *info)
  1219. {
  1220. Owned<INode> node = createINode(ep);
  1221. Owned<ISashaCommand> cmd = createSashaCommand();
  1222. cmd->addId(wuid);
  1223. cmd->setAction(SCA_GET);
  1224. if (!cmd->send(node, 1*60*1000))
  1225. {
  1226. StringBuffer url;
  1227. DBGLOG("Could not connect to Sasha server at %s", ep.getUrlStr(url).str());
  1228. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.", url.str());
  1229. }
  1230. if (cmd->numIds()==0)
  1231. {
  1232. DBGLOG("Could not read archived workunit %s",wuid);
  1233. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
  1234. }
  1235. unsigned num = cmd->numResults();
  1236. if (num < 1)
  1237. return false;
  1238. StringBuffer res;
  1239. cmd->getResult(0, res);
  1240. if(res.length() < 1)
  1241. return false;
  1242. Owned<IPropertyTree> wpt = createPTreeFromXMLString(res.str());
  1243. if (!wpt)
  1244. return false;
  1245. const char * owner = wpt->queryProp("@submitID");
  1246. ensureWsWorkunitAccessByOwnerId(context, owner, SecAccess_Read);
  1247. info->setWuid(wuid);
  1248. info->setArchived(true);
  1249. if (notEmpty(owner))
  1250. info->setOwner(owner);
  1251. const char * state = wpt->queryProp("@state");
  1252. if (notEmpty(state))
  1253. info->setState(state);
  1254. const char * cluster = wpt->queryProp("@clusterName");
  1255. if (notEmpty(cluster))
  1256. info->setCluster(cluster);
  1257. const char * scope = wpt->queryProp("@scope");
  1258. if (notEmpty(scope))
  1259. info->setScope(scope);
  1260. const char * jobName = wpt->queryProp("@jobName");
  1261. if (notEmpty(jobName))
  1262. info->setJobname(jobName);
  1263. const char * description = wpt->queryProp("Debug/description");
  1264. if (notEmpty(description))
  1265. info->setDescription(description);
  1266. const char * queryText = wpt->queryProp("Query/Text");
  1267. if (notEmpty(queryText))
  1268. info->updateQuery().setText(queryText);
  1269. const char * protectedWU = wpt->queryProp("@protected");
  1270. info->setProtected((protectedWU && *protectedWU!='0'));
  1271. return true;
  1272. }
  1273. #define WUDETAILS_REFRESH_MINS 1
  1274. void getArchivedWUInfo(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort, const char *wuid, IEspWUInfoResponse &resp)
  1275. {
  1276. SocketEndpoint ep;
  1277. if (sashaServerIP && *sashaServerIP)
  1278. ep.set(sashaServerIP, sashaServerPort);
  1279. else
  1280. getSashaNode(ep);
  1281. if (getWsWuInfoFromSasha(context, ep, wuid, &resp.updateWorkunit()))
  1282. {
  1283. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1284. resp.setCanCompile(false);
  1285. return;
  1286. }
  1287. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Cannot find workunit %s.", wuid);
  1288. return;
  1289. }
  1290. #define WUDETAILS_REFRESH_MINS 1
  1291. bool CWsWorkunitsEx::onWUInfo(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1292. {
  1293. try
  1294. {
  1295. StringBuffer wuid = req.getWuid();
  1296. WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
  1297. double version = context.getClientVersion();
  1298. if (req.getType() && strieq(req.getType(), "archived workunits"))
  1299. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1300. else
  1301. {
  1302. try
  1303. {
  1304. //The access is checked here because getArchivedWUInfo() has its own access check.
  1305. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1306. unsigned flags=0;
  1307. if (req.getTruncateEclTo64k())
  1308. flags|=WUINFO_TruncateEclTo64k;
  1309. if (req.getIncludeExceptions())
  1310. flags|=WUINFO_IncludeExceptions;
  1311. if (req.getIncludeGraphs())
  1312. flags|=WUINFO_IncludeGraphs;
  1313. if (req.getIncludeSourceFiles())
  1314. flags|=WUINFO_IncludeSourceFiles;
  1315. if (req.getIncludeResults())
  1316. flags|=WUINFO_IncludeResults;
  1317. if (req.getIncludeVariables())
  1318. flags|=WUINFO_IncludeVariables;
  1319. if (req.getIncludeTimers())
  1320. flags|=WUINFO_IncludeTimers;
  1321. if (req.getIncludeDebugValues())
  1322. flags|=WUINFO_IncludeDebugValues;
  1323. if (req.getIncludeApplicationValues())
  1324. flags|=WUINFO_IncludeApplicationValues;
  1325. if (req.getIncludeWorkflows())
  1326. flags|=WUINFO_IncludeWorkflows;
  1327. if (!req.getSuppressResultSchemas())
  1328. flags|=WUINFO_IncludeEclSchemas;
  1329. if (req.getIncludeXmlSchemas())
  1330. flags|=WUINFO_IncludeXmlSchema;
  1331. if (req.getIncludeResultsViewNames())
  1332. flags|=WUINFO_IncludeResultsViewNames;
  1333. if (req.getIncludeResourceURLs())
  1334. flags|=WUINFO_IncludeResourceURLs;
  1335. WsWuInfo winfo(context, wuid.str());
  1336. winfo.getInfo(resp.updateWorkunit(), flags);
  1337. if (req.getIncludeResultsViewNames()||req.getIncludeResourceURLs()||(version >= 1.50))
  1338. {
  1339. StringArray views, urls;
  1340. winfo.getResourceInfo(views, urls, WUINFO_IncludeResultsViewNames|WUINFO_IncludeResourceURLs);
  1341. IEspECLWorkunit& eclWU = resp.updateWorkunit();
  1342. if (req.getIncludeResultsViewNames())
  1343. resp.setResultViews(views);
  1344. if (req.getIncludeResourceURLs())
  1345. eclWU.setResourceURLs(urls);
  1346. if (version >= 1.50)
  1347. {
  1348. eclWU.setResultViewCount(views.length());
  1349. eclWU.setResourceURLCount(urls.length());
  1350. }
  1351. }
  1352. }
  1353. catch (IException *e)
  1354. {
  1355. if (e->errorCode() != ECLWATCH_CANNOT_OPEN_WORKUNIT)
  1356. throw e;
  1357. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1358. e->Release();
  1359. }
  1360. switch (resp.getWorkunit().getStateID())
  1361. {
  1362. case WUStateCompiling:
  1363. case WUStateCompiled:
  1364. case WUStateScheduled:
  1365. case WUStateSubmitted:
  1366. case WUStateRunning:
  1367. case WUStateAborting:
  1368. case WUStateWait:
  1369. case WUStateUploadingFiles:
  1370. case WUStateDebugPaused:
  1371. case WUStateDebugRunning:
  1372. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1373. break;
  1374. case WUStateBlocked:
  1375. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS*5);
  1376. break;
  1377. }
  1378. resp.setCanCompile(notEmpty(context.queryUserId()));
  1379. if (context.getClientVersion() > 1.24 && notEmpty(req.getThorSlaveIP()))
  1380. resp.setThorSlaveIP(req.getThorSlaveIP());
  1381. }
  1382. }
  1383. catch(IException* e)
  1384. {
  1385. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1386. }
  1387. return true;
  1388. }
  1389. bool CWsWorkunitsEx::onWUInfoDetails(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1390. {
  1391. return onWUInfo(context, req, resp);
  1392. }
  1393. bool CWsWorkunitsEx::onWUResultView(IEspContext &context, IEspWUResultViewRequest &req, IEspWUResultViewResponse &resp)
  1394. {
  1395. StringBuffer wuid = req.getWuid();
  1396. WsWuHelpers::checkAndTrimWorkunit("WUResultView", wuid);
  1397. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1398. Owned<IWuWebView> wv = createWuWebView(wuid.str(), NULL, getCFD(), true);
  1399. StringBuffer html;
  1400. wv->renderSingleResult(req.getViewName(), req.getResultName(), html);
  1401. resp.setResult(html.str());
  1402. resp.setResult_mimetype("text/html");
  1403. return true;
  1404. }
  1405. void doWUQueryBySingleWuid(IEspContext &context, const char *wuid, IEspWUQueryResponse &resp)
  1406. {
  1407. Owned<IEspECLWorkunit> info= createECLWorkunit("","");
  1408. WsWuInfo winfo(context, wuid);
  1409. winfo.getCommon(*info, 0);
  1410. IArrayOf<IEspECLWorkunit> results;
  1411. results.append(*info.getClear());
  1412. resp.setWorkunits(results);
  1413. resp.setPageSize(1);
  1414. resp.setCount(1);
  1415. }
  1416. void doWUQueryByFile(IEspContext &context, const char *logicalFile, IEspWUQueryResponse &resp)
  1417. {
  1418. StringBuffer wuid;
  1419. getWuidFromLogicalFileName(context, logicalFile, wuid);
  1420. if (!wuid.length())
  1421. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1422. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1423. Owned<IConstWorkUnit> cw= factory->openWorkUnit(wuid.str(), false);
  1424. if (!cw)
  1425. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1426. if (getWsWorkunitAccess(context, *cw) < SecAccess_Read)
  1427. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED,"Cannot access the workunit for file %s.",logicalFile);
  1428. SCMStringBuffer parent;
  1429. if (!cw->getParentWuid(parent).length())
  1430. doWUQueryBySingleWuid(context, wuid.str(), resp);
  1431. resp.setFirst(false);
  1432. resp.setPageSize(1);
  1433. resp.setCount(1);
  1434. }
  1435. void doWUQueryByXPath(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1436. {
  1437. IArrayOf<IEspECLWorkunit> results;
  1438. WsWuSearch wlist(context,req.getOwner(),req.getState(),req.getCluster(),req.getStartDate(),req.getEndDate(),req.getECL(),req.getJobname(),req.getApplicationName(),req.getApplicationKey(),req.getApplicationData());
  1439. int count=(int)req.getPageSize();
  1440. if (!count)
  1441. count=100;
  1442. if (wlist.getSize() < 1)
  1443. {
  1444. resp.setNumWUs(0);
  1445. return;
  1446. }
  1447. if (wlist.getSize() < count)
  1448. count = (int) wlist.getSize() - 1;
  1449. WsWuSearch::iterator begin, end;
  1450. if(notEmpty(req.getAfter()))
  1451. {
  1452. begin=wlist.locate(req.getAfter());
  1453. end=min(begin+count,wlist.end());
  1454. }
  1455. else if (notEmpty(req.getBefore()))
  1456. {
  1457. end=wlist.locate(req.getBefore());
  1458. begin=max(end-count,wlist.begin());
  1459. }
  1460. else
  1461. {
  1462. begin=wlist.begin();
  1463. end=min(begin+count,wlist.end());
  1464. }
  1465. if(begin>wlist.begin() && begin<wlist.end())
  1466. resp.setCurrent(begin->c_str());
  1467. if (context.getClientVersion() > 1.02)
  1468. {
  1469. resp.setPageStartFrom(begin - wlist.begin() + 1);
  1470. resp.setNumWUs((int)wlist.getSize());
  1471. resp.setCount(end - begin);
  1472. }
  1473. if(end<wlist.end())
  1474. resp.setNext(end->c_str());
  1475. for(;begin!=end;begin++)
  1476. {
  1477. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1478. WsWuInfo winfo(context, begin->c_str());
  1479. winfo.getCommon(*info, 0);
  1480. results.append(*info.getClear());
  1481. }
  1482. resp.setPageSize(abs(count));
  1483. resp.setWorkunits(results);
  1484. return;
  1485. }
  1486. bool addWUQueryFilter(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *name, WUSortField value)
  1487. {
  1488. if (isEmpty(name))
  1489. return false;
  1490. filters[count++] = value;
  1491. buff.append(name);
  1492. return true;
  1493. }
  1494. bool addWUQueryFilterTime(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *stime, WUSortField value)
  1495. {
  1496. if (isEmpty(stime))
  1497. return false;
  1498. CDateTime dt;
  1499. dt.setString(stime, NULL, true);
  1500. unsigned year, month, day, hour, minute, second, nano;
  1501. dt.getDate(year, month, day, true);
  1502. dt.getTime(hour, minute, second, nano, true);
  1503. VStringBuffer wuid("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
  1504. filters[count++] = value;
  1505. buff.append(wuid.str());
  1506. return true;
  1507. }
  1508. bool addWUQueryFilterApplication(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *appname, const char *appkey, const char *appdata)
  1509. {
  1510. if (isEmpty(appname) && isEmpty(appkey) && isEmpty(appdata)) //no application filter
  1511. return false;
  1512. VStringBuffer path("Application/%s/%s", appname && *appname ? appname : "*", appkey && *appkey ? appkey : "*");
  1513. if(appdata && *appdata)
  1514. path.append("=?~\"").append(appdata).append("\"");
  1515. filters[count++] = WUSFcustom;
  1516. buff.append(path.str());
  1517. return true;
  1518. }
  1519. void doWUQueryWithSort(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1520. {
  1521. SecAccessFlags accessOwn;
  1522. SecAccessFlags accessOthers;
  1523. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1524. double version = context.getClientVersion();
  1525. IArrayOf<IEspECLWorkunit> results;
  1526. int begin = 0;
  1527. unsigned int count = 100;
  1528. int pagesize = 100;
  1529. if (version > 1.01)
  1530. {
  1531. pagesize = (int)req.getPageSize();
  1532. if (!req.getCount_isNull())
  1533. pagesize = req.getCount();
  1534. if(pagesize < 1)
  1535. pagesize = 100;
  1536. begin = (int)req.getPageStartFrom();
  1537. }
  1538. else
  1539. {
  1540. count=(unsigned)req.getCount();
  1541. if(!count)
  1542. count=100;
  1543. if (notEmpty(req.getAfter()))
  1544. begin=atoi(req.getAfter());
  1545. else if (notEmpty(req.getBefore()))
  1546. begin=atoi(req.getBefore())-count;
  1547. if (begin < 0)
  1548. begin = 0;
  1549. pagesize = count;
  1550. }
  1551. WUSortField sortorder[2] = {(WUSortField) (WUSFwuid | WUSFreverse), WUSFterm};
  1552. if(notEmpty(req.getSortby()))
  1553. {
  1554. const char *sortby = req.getSortby();
  1555. if (strieq(sortby, "Owner"))
  1556. sortorder[0] = WUSFuser;
  1557. else if (strieq(sortby, "JobName"))
  1558. sortorder[0] = WUSFjob;
  1559. else if (strieq(sortby, "Cluster"))
  1560. sortorder[0] = WUSFcluster;
  1561. else if (strieq(sortby, "RoxieCluster"))
  1562. sortorder[0] = WUSFroxiecluster;
  1563. else if (strieq(sortby, "Protected"))
  1564. sortorder[0] = WUSFprotected;
  1565. else if (strieq(sortby, "State"))
  1566. sortorder[0] = WUSFstate;
  1567. else if (strieq(sortby, "ThorTime"))
  1568. sortorder[0] = (WUSortField) (WUSFtotalthortime+WUSFnumeric);
  1569. else
  1570. sortorder[0] = WUSFwuid;
  1571. sortorder[0] = (WUSortField) (sortorder[0] | WUSFnocase);
  1572. bool descending = req.getDescending();
  1573. if (descending)
  1574. sortorder[0] = (WUSortField) (sortorder[0] | WUSFreverse);
  1575. }
  1576. WUSortField filters[10];
  1577. unsigned short filterCount = 0;
  1578. MemoryBuffer filterbuf;
  1579. bool bDoubleCheckState = false;
  1580. if(req.getState() && *req.getState())
  1581. {
  1582. filters[filterCount++] = WUSFstate;
  1583. if (!strieq(req.getState(), "unknown"))
  1584. filterbuf.append(req.getState());
  1585. else
  1586. filterbuf.append("");
  1587. if (strieq(req.getState(), "submitted"))
  1588. bDoubleCheckState = true;
  1589. }
  1590. addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
  1591. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1592. if(version > 1.07)
  1593. addWUQueryFilter(filters, filterCount, filterbuf, req.getRoxieCluster(), WUSFroxiecluster);
  1594. addWUQueryFilter(filters, filterCount, filterbuf, req.getLogicalFile(), WUSFfileread);
  1595. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1596. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobname(), (WUSortField) (WUSFjob | WUSFnocase));
  1597. addWUQueryFilter(filters, filterCount, filterbuf, req.getECL(), (WUSortField) (WUSFecl | WUSFwild));
  1598. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1599. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1600. addWUQueryFilterApplication(filters, filterCount, filterbuf, req.getApplicationName(), req.getApplicationKey(), req.getApplicationData());
  1601. filters[filterCount] = WUSFterm;
  1602. __int64 cacheHint = 0;
  1603. if (!req.getCacheHint_isNull())
  1604. cacheHint = req.getCacheHint();
  1605. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1606. unsigned numWUs;
  1607. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), begin, pagesize+1, "", &cacheHint, &numWUs);
  1608. if (version >= 1.41)
  1609. resp.setCacheHint(cacheHint);
  1610. unsigned actualCount = 0;
  1611. ForEach(*it)
  1612. {
  1613. IConstWorkUnit& cw = it->query();
  1614. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1615. {
  1616. numWUs--;
  1617. continue;
  1618. }
  1619. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1620. {
  1621. numWUs--;
  1622. continue;
  1623. }
  1624. SCMStringBuffer parent;
  1625. if (!cw.getParentWuid(parent).length())
  1626. {
  1627. const char* wuid = cw.getWuid(parent).str();
  1628. if (!looksLikeAWuid(wuid))
  1629. {
  1630. numWUs--;
  1631. continue;
  1632. }
  1633. actualCount++;
  1634. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1635. WsWuInfo winfo(context, wuid);
  1636. winfo.getCommon(*info, 0);
  1637. results.append(*info.getClear());
  1638. }
  1639. }
  1640. if (version > 1.02)
  1641. {
  1642. resp.setPageStartFrom(begin+1);
  1643. resp.setNumWUs(numWUs);
  1644. if (results.length() > (aindex_t)pagesize)
  1645. results.pop();
  1646. if(unsigned (begin + pagesize) < numWUs)
  1647. {
  1648. resp.setNextPage(begin + pagesize);
  1649. resp.setPageEndAt(begin + pagesize);
  1650. int last = begin + pagesize;
  1651. while (numWUs > (unsigned) last + pagesize)
  1652. last += pagesize;
  1653. resp.setLastPage(last);
  1654. }
  1655. else
  1656. {
  1657. resp.setNextPage(-1);
  1658. resp.setPageEndAt(numWUs);
  1659. }
  1660. if(begin > 0)
  1661. {
  1662. resp.setFirst(false);
  1663. if (begin - pagesize > 0)
  1664. resp.setPrevPage(begin - pagesize);
  1665. else
  1666. resp.setPrevPage(0);
  1667. }
  1668. resp.setPageSize(pagesize);
  1669. }
  1670. else
  1671. {
  1672. if(begin>0 && actualCount > 0)
  1673. {
  1674. char buf[10];
  1675. itoa(begin, buf, 10);
  1676. resp.setCurrent(buf);
  1677. }
  1678. if(count<actualCount)
  1679. {
  1680. char buf[10];
  1681. itoa(begin+count, buf, 10);
  1682. resp.setNext(buf);
  1683. resp.setNumWUs(numWUs);
  1684. if (results.length() > count)
  1685. results.pop();
  1686. }
  1687. if(begin == 0 && actualCount <= count)
  1688. resp.setFirst(false);
  1689. resp.setCount(count);
  1690. }
  1691. resp.setWorkunits(results);
  1692. return;
  1693. }
  1694. void doWUQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
  1695. ArchivedWuCache &archivedWuCache, unsigned cacheMinutes, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1696. {
  1697. class CArchivedWUsReader : public CInterface, implements IArchivedWUsReader
  1698. {
  1699. IEspContext& context;
  1700. IEspWUQueryRequest& req;
  1701. unsigned pageFrom, pageSize;
  1702. StringAttr sashaServerIP;
  1703. unsigned sashaServerPort;
  1704. unsigned cacheMinutes;
  1705. StringBuffer filterStr;
  1706. ArchivedWuCache& archivedWuCache;
  1707. unsigned numberOfWUsReturned;
  1708. bool hasMoreWU;
  1709. void readDateFilters(StringBuffer& from, StringBuffer& to)
  1710. {
  1711. CDateTime timeFrom, timeTo;
  1712. if(notEmpty(req.getEndDate()))
  1713. timeTo.setString(req.getEndDate(), NULL, true);
  1714. else
  1715. timeTo.setNow();
  1716. unsigned year, month, day, hour, minute, second, nano;
  1717. timeTo.getDate(year, month, day, true);
  1718. timeTo.getTime(hour, minute, second, nano, true);
  1719. to.setf("%4d%02d%02d%02d%02d", year, month, day, hour, minute);
  1720. if(!notEmpty(req.getStartDate()))
  1721. return;
  1722. timeFrom.setString(req.getStartDate(), NULL, true);
  1723. if (timeFrom >= timeTo)
  1724. return;
  1725. unsigned year0, month0, day0, hour0, minute0, second0, nano0;
  1726. timeFrom.getDate(year0, month0, day0, true);
  1727. timeFrom.getTime(hour0, minute0, second0, nano0, true);
  1728. from.setf("%4d%02d%02d%02d%02d", year0, month0, day0, hour0, minute0);
  1729. return;
  1730. }
  1731. bool addToFilterString(const char *name, const char *value)
  1732. {
  1733. if (isEmpty(name) || isEmpty(value))
  1734. return false;
  1735. if (filterStr.length())
  1736. filterStr.append(';');
  1737. filterStr.append(name).append("=").append(value);
  1738. return true;
  1739. }
  1740. bool addToFilterString(const char *name, unsigned value)
  1741. {
  1742. if (isEmpty(name))
  1743. return false;
  1744. if (filterStr.length())
  1745. filterStr.append(';');
  1746. filterStr.append(name).append("=").append(value);
  1747. return true;
  1748. }
  1749. void setFilterString()
  1750. {
  1751. addToFilterString("cluster", req.getCluster());
  1752. addToFilterString("owner", req.getOwner());
  1753. addToFilterString("jobName", req.getJobname());
  1754. addToFilterString("state", req.getState());
  1755. addToFilterString("timeFrom", req.getStartDate());
  1756. addToFilterString("timeTo", req.getEndDate());
  1757. addToFilterString("pageStart", pageFrom);
  1758. addToFilterString("pageSize", pageSize);
  1759. if (sashaServerIP && *sashaServerIP)
  1760. {
  1761. addToFilterString("sashaServerIP", sashaServerIP.get());
  1762. addToFilterString("sashaServerPort", sashaServerPort);
  1763. }
  1764. }
  1765. void setSashaCommand(INode* sashaserver, ISashaCommand* cmd)
  1766. {
  1767. cmd->setAction(SCA_LIST);
  1768. cmd->setOutputFormat("owner,jobname,cluster,state");
  1769. cmd->setOnline(false);
  1770. cmd->setArchived(true);
  1771. cmd->setStart(pageFrom);
  1772. cmd->setLimit(pageSize+1); //read an extra WU to check hasMoreWU
  1773. if (notEmpty(req.getCluster()))
  1774. cmd->setCluster(req.getCluster());
  1775. if (notEmpty(req.getOwner()))
  1776. cmd->setOwner(req.getOwner());
  1777. if (notEmpty(req.getJobname()))
  1778. cmd->setJobName(req.getJobname());
  1779. if (notEmpty(req.getState()))
  1780. cmd->setState(req.getState());
  1781. StringBuffer timeFrom, timeTo;
  1782. readDateFilters(timeFrom, timeTo);
  1783. if (timeFrom.length())
  1784. cmd->setAfter(timeFrom.str());
  1785. if (timeTo.length())
  1786. cmd->setBefore(timeTo.str());
  1787. return;
  1788. }
  1789. IEspECLWorkunit *createArchivedWUEntry(StringArray& wuDataArray, bool canAccess)
  1790. {
  1791. Owned<IEspECLWorkunit> info= createECLWorkunit("","");
  1792. const char* wuid = wuDataArray.item(0);
  1793. const char* owner = wuDataArray.item(1);
  1794. const char* jobName = wuDataArray.item(2);
  1795. const char* cluster = wuDataArray.item(3);
  1796. const char* state = wuDataArray.item(4);
  1797. info->setWuid(wuid);
  1798. if (!canAccess)
  1799. info->setState("<Hidden>");
  1800. else
  1801. {
  1802. if (notEmpty(owner))
  1803. info->setOwner(owner);
  1804. if (notEmpty(jobName))
  1805. info->setJobname(jobName);
  1806. if (notEmpty(cluster))
  1807. info->setCluster(cluster);
  1808. if (notEmpty(state))
  1809. info->setState(state);
  1810. }
  1811. return info.getClear();
  1812. }
  1813. static int compareWuids(IInterface **_a, IInterface **_b)
  1814. {
  1815. IEspECLWorkunit *a = *(IEspECLWorkunit **)_a;
  1816. IEspECLWorkunit *b = *(IEspECLWorkunit **)_b;
  1817. return strcmp(b->getWuid(), a->getWuid());
  1818. }
  1819. public:
  1820. IMPLEMENT_IINTERFACE_USING(CInterface);
  1821. CArchivedWUsReader(IEspContext& _context, const char* _sashaServerIP, unsigned _sashaServerPort, ArchivedWuCache& _archivedWuCache,
  1822. unsigned _cacheMinutes, unsigned _pageFrom, unsigned _pageSize, IEspWUQueryRequest& _req)
  1823. : context(_context), sashaServerIP(_sashaServerIP), sashaServerPort(_sashaServerPort),
  1824. archivedWuCache(_archivedWuCache), cacheMinutes(_cacheMinutes), pageFrom(_pageFrom), pageSize(_pageSize), req(_req)
  1825. {
  1826. hasMoreWU = false;
  1827. numberOfWUsReturned = 0;
  1828. }
  1829. void getArchivedWUs(IArrayOf<IEspECLWorkunit>& archivedWUs)
  1830. {
  1831. setFilterString();
  1832. Owned<ArchivedWuCacheElement> cachedResults = archivedWuCache.lookup(context, filterStr, "AddWhenAvailable", cacheMinutes);
  1833. if (cachedResults)
  1834. {
  1835. hasMoreWU = cachedResults->m_hasNextPage;
  1836. numberOfWUsReturned = cachedResults->numWUsReturned;
  1837. if (cachedResults->m_results.length())
  1838. {
  1839. ForEachItemIn(ai, cachedResults->m_results)
  1840. archivedWUs.append(*LINK(&cachedResults->m_results.item(ai)));
  1841. }
  1842. }
  1843. else
  1844. {
  1845. SocketEndpoint ep;
  1846. if (sashaServerIP && *sashaServerIP)
  1847. ep.set(sashaServerIP, sashaServerPort);
  1848. else
  1849. getSashaNode(ep);
  1850. Owned<INode> sashaserver = createINode(ep);
  1851. Owned<ISashaCommand> cmd = createSashaCommand();
  1852. setSashaCommand(sashaserver, cmd);
  1853. if (!cmd->send(sashaserver))
  1854. {
  1855. StringBuffer msg("Cannot connect to archive server at ");
  1856. sashaserver->endpoint().getUrlStr(msg);
  1857. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER, "%s", msg.str());
  1858. }
  1859. numberOfWUsReturned = cmd->numIds();
  1860. hasMoreWU = (numberOfWUsReturned > pageSize);
  1861. if (hasMoreWU)
  1862. numberOfWUsReturned--;
  1863. if (numberOfWUsReturned > 0)
  1864. {
  1865. SecAccessFlags accessOwn, accessOthers;
  1866. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1867. for (unsigned i=0; i<numberOfWUsReturned; i++)
  1868. {
  1869. const char *csline = cmd->queryId(i);
  1870. if (!csline || !*csline)
  1871. continue;
  1872. StringArray wuDataArray;
  1873. wuDataArray.appendList(csline, ",");
  1874. const char* wuid = wuDataArray.item(0);
  1875. if (isEmpty(wuid))
  1876. {
  1877. WARNLOG("Empty WUID in SCA_LIST response"); // JCS->KW - have u ever seen this happen?
  1878. continue;
  1879. }
  1880. const char* owner = wuDataArray.item(1);
  1881. bool canAccess = chooseWuAccessFlagsByOwnership(context.queryUserId(), owner, accessOwn, accessOthers) >= SecAccess_Read;
  1882. Owned<IEspECLWorkunit> info = createArchivedWUEntry(wuDataArray, canAccess);
  1883. archivedWUs.append(*info.getClear());
  1884. }
  1885. archivedWUs.sort(compareWuids);
  1886. archivedWuCache.add(filterStr, "AddWhenAvailable", hasMoreWU, numberOfWUsReturned, archivedWUs);
  1887. }
  1888. }
  1889. return;
  1890. };
  1891. bool getHasMoreWU() { return hasMoreWU; };
  1892. unsigned getNumberOfWUsReturned() { return numberOfWUsReturned; };
  1893. };
  1894. unsigned pageStart = (unsigned) req.getPageStartFrom();
  1895. unsigned pageSize = (unsigned) req.getPageSize();
  1896. if(pageSize < 1)
  1897. pageSize=500;
  1898. IArrayOf<IEspECLWorkunit> archivedWUs;
  1899. Owned<IArchivedWUsReader> archiveWUsReader = new CArchivedWUsReader(context, sashaServerIP, sashaServerPort, archivedWuCache,
  1900. cacheMinutes, pageStart, pageSize, req);
  1901. archiveWUsReader->getArchivedWUs(archivedWUs);
  1902. resp.setWorkunits(archivedWUs);
  1903. resp.setNumWUs(archiveWUsReader->getNumberOfWUsReturned());
  1904. resp.setType("archived only");
  1905. resp.setPageSize(pageSize);
  1906. resp.setPageStartFrom(pageStart+1);
  1907. resp.setPageEndAt(pageStart + archiveWUsReader->getNumberOfWUsReturned());
  1908. if(pageStart > 0)
  1909. { //This is not the first page;
  1910. resp.setFirst(false);
  1911. resp.setPrevPage((pageStart > pageSize) ? pageStart - pageSize: 0);
  1912. }
  1913. if (archiveWUsReader->getHasMoreWU())
  1914. resp.setNextPage(pageStart + pageSize);
  1915. return;
  1916. }
  1917. bool CWsWorkunitsEx::onWUQuery(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1918. {
  1919. try
  1920. {
  1921. StringBuffer wuidStr = req.getWuid();
  1922. const char* wuid = wuidStr.trim().str();
  1923. if (req.getType() && strieq(req.getType(), "archived workunits"))
  1924. doWUQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
  1925. else if(notEmpty(wuid) && looksLikeAWuid(wuid))
  1926. doWUQueryBySingleWuid(context, wuid, resp);
  1927. else if (notEmpty(req.getLogicalFile()) && req.getLogicalFileSearchType() && strieq(req.getLogicalFileSearchType(), "Created"))
  1928. doWUQueryByFile(context, req.getLogicalFile(), resp);
  1929. else
  1930. doWUQueryWithSort(context, req, resp);
  1931. resp.setState(req.getState());
  1932. resp.setCluster(req.getCluster());
  1933. resp.setRoxieCluster(req.getRoxieCluster());
  1934. resp.setOwner(req.getOwner());
  1935. resp.setStartDate(req.getStartDate());
  1936. resp.setEndDate(req.getEndDate());
  1937. double version = context.getClientVersion();
  1938. StringBuffer basicQuery;
  1939. addToQueryString(basicQuery, "State", req.getState());
  1940. addToQueryString(basicQuery, "Cluster", req.getCluster());
  1941. if (version > 1.07)
  1942. addToQueryString(basicQuery, "RoxieCluster", req.getRoxieCluster());
  1943. addToQueryString(basicQuery, "Owner", req.getOwner());
  1944. addToQueryString(basicQuery, "StartDate", req.getStartDate());
  1945. addToQueryString(basicQuery, "EndDate", req.getEndDate());
  1946. if (version > 1.25 && req.getLastNDays() > -1)
  1947. addToQueryString(basicQuery, "LastNDays", StringBuffer().append(req.getLastNDays()).str());
  1948. addToQueryString(basicQuery, "ECL", req.getECL());
  1949. addToQueryString(basicQuery, "Jobname", req.getJobname());
  1950. addToQueryString(basicQuery, "Type", req.getType());
  1951. if (addToQueryString(basicQuery, "LogicalFile", req.getLogicalFile()))
  1952. addToQueryString(basicQuery, "LogicalFileSearchType", req.getLogicalFileSearchType());
  1953. resp.setFilters(basicQuery.str());
  1954. if (notEmpty(req.getSortby()) && !strstr(basicQuery.str(), StringBuffer(req.getSortby()).append('=').str()))
  1955. {
  1956. resp.setSortby(req.getSortby());
  1957. addToQueryString(basicQuery, "Sortby", req.getSortby());
  1958. if (req.getDescending())
  1959. {
  1960. resp.setDescending(req.getDescending());
  1961. addToQueryString(basicQuery, "Descending", "1");
  1962. }
  1963. }
  1964. resp.setBasicQuery(basicQuery.str());
  1965. StringBuffer s;
  1966. if(notEmpty(req.getECL()))
  1967. resp.setECL(Utils::url_encode(req.getECL(), s).str());
  1968. if(notEmpty(req.getJobname()))
  1969. resp.setJobname(Utils::url_encode(req.getJobname(), s.clear()).str());
  1970. }
  1971. catch(IException* e)
  1972. {
  1973. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1974. }
  1975. return true;
  1976. }
  1977. void appendResultSet(MemoryBuffer& mb, INewResultSet* result, const char *name, __int64 start, unsigned& count, __int64& total, bool bin, bool xsd, ESPSerializationFormat fmt, const IProperties *xmlns)
  1978. {
  1979. if (!result)
  1980. return;
  1981. Owned<IResultSetCursor> cursor(result->createCursor());
  1982. total=result->getNumRows();
  1983. if(bin)
  1984. count = getResultBin(mb, result, (unsigned)start, count);
  1985. else
  1986. {
  1987. struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
  1988. {
  1989. MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
  1990. IMPLEMENT_IINTERFACE;
  1991. virtual const char * str() const { UNIMPLEMENTED; }
  1992. virtual void set(const char *val) { buffer.append(strlen(val),val); }
  1993. virtual void clear() { } // support appending only
  1994. virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
  1995. virtual unsigned length() const { return buffer.length(); };
  1996. MemoryBuffer & buffer;
  1997. } adaptor(mb);
  1998. if (fmt==ESPSerializationJSON)
  1999. count = getResultJSON(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL);
  2000. else
  2001. count = getResultXml(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL, xmlns);
  2002. }
  2003. }
  2004. INewResultSet* createFilteredResultSet(INewResultSet* result, IArrayOf<IConstNamedValue>* filterBy)
  2005. {
  2006. if (!result || !filterBy || !filterBy->length())
  2007. return NULL;
  2008. Owned<IFilteredResultSet> filter = result->createFiltered();
  2009. const IResultSetMetaData &meta = result->getMetaData();
  2010. unsigned columnCount = meta.getColumnCount();
  2011. ForEachItemIn(i, *filterBy)
  2012. {
  2013. IConstNamedValue &item = filterBy->item(i);
  2014. const char *name = item.getName();
  2015. const char *value = item.getValue();
  2016. if (!name || !*name || !value || !*value)
  2017. continue;
  2018. for(unsigned col = 0; col < columnCount; col++)
  2019. {
  2020. SCMStringBuffer scmbuf;
  2021. meta.getColumnLabel(scmbuf, col);
  2022. if (strieq(scmbuf.str(), name))
  2023. {
  2024. filter->addFilter(col, value);
  2025. break;
  2026. }
  2027. }
  2028. }
  2029. return filter->create();
  2030. }
  2031. void getWsWuResult(IEspContext &context, const char* wuid, const char *name, const char *logical, unsigned index, __int64 start,
  2032. unsigned& count, __int64& total, IStringVal& resname, bool bin, IArrayOf<IConstNamedValue>* filterBy, MemoryBuffer& mb, bool xsd=true)
  2033. {
  2034. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2035. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  2036. if(!cw)
  2037. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  2038. Owned<IConstWUResult> result;
  2039. if (notEmpty(name))
  2040. result.setown(cw->getResultByName(name));
  2041. else if (notEmpty(logical))
  2042. {
  2043. Owned<IConstWUResultIterator> it = &cw->getResults();
  2044. ForEach(*it)
  2045. {
  2046. IConstWUResult &r = it->query();
  2047. SCMStringBuffer filename;
  2048. if(strieq(r.getResultLogicalName(filename).str(), logical))
  2049. {
  2050. result.setown(LINK(&r));
  2051. break;
  2052. }
  2053. }
  2054. }
  2055. else
  2056. result.setown(cw->getResultBySequence(index));
  2057. if (!result)
  2058. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2059. if (!resname.length())
  2060. result->getResultName(resname);
  2061. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  2062. SCMStringBuffer logicalName;
  2063. result->getResultLogicalName(logicalName);
  2064. Owned<INewResultSet> rs;
  2065. if (logicalName.length())
  2066. {
  2067. SCMStringBuffer cluster; //MORE is this wrong cluster?
  2068. rs.setown(resultSetFactory->createNewFileResultSet(logicalName.str(), cw->getClusterName(cluster).str()));
  2069. }
  2070. else
  2071. rs.setown(resultSetFactory->createNewResultSet(result, wuid));
  2072. if (!filterBy || !filterBy->length())
  2073. appendResultSet(mb, rs, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryXmlns());
  2074. else
  2075. {
  2076. Owned<INewResultSet> filteredResult = createFilteredResultSet(rs, filterBy);
  2077. appendResultSet(mb, filteredResult, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryXmlns());
  2078. }
  2079. }
  2080. void openSaveFile(IEspContext &context, int opt, const char* filename, const char* origMimeType, MemoryBuffer& buf, IEspWULogFileResponse &resp)
  2081. {
  2082. if (opt < 1)
  2083. {
  2084. resp.setThefile(buf);
  2085. resp.setThefile_mimetype(origMimeType);
  2086. }
  2087. else if (opt < 2)
  2088. {
  2089. StringBuffer headerStr("attachment;");
  2090. if (filename && *filename)
  2091. {
  2092. const char* pFileName = strrchr(filename, PATHSEPCHAR);
  2093. if (pFileName)
  2094. headerStr.appendf("filename=%s", pFileName+1);
  2095. else
  2096. headerStr.appendf("filename=%s", filename);
  2097. }
  2098. MemoryBuffer buf0;
  2099. unsigned i = 0;
  2100. char* p = (char*) buf.toByteArray();
  2101. while (i < buf.length())
  2102. {
  2103. if (p[0] != 10)
  2104. buf0.append(p[0]);
  2105. else
  2106. buf0.append(0x0d);
  2107. p++;
  2108. i++;
  2109. }
  2110. resp.setThefile(buf);
  2111. resp.setThefile_mimetype(origMimeType);
  2112. context.addCustomerHeader("Content-disposition", headerStr.str());
  2113. }
  2114. else
  2115. {
  2116. #ifndef _USE_ZLIB
  2117. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2118. #else
  2119. StringBuffer fileNameStr, headerStr("attachment;");
  2120. if (notEmpty(filename))
  2121. {
  2122. fileNameStr.append(filename);
  2123. headerStr.append("filename=").append(filename).append((opt>2) ? ".gz" : ".zip");
  2124. }
  2125. else
  2126. fileNameStr.append("file");
  2127. StringBuffer ifname;
  2128. ifname.appendf("%s%sT%xAT%x", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick()).append((opt>2)? "" : ".zip");
  2129. IZZIPor* Zipor = createZZIPor();
  2130. int ret = 0;
  2131. if (opt > 2)
  2132. ret = Zipor->gzipToFile(buf.length(), (void*)buf.toByteArray(), ifname.str());
  2133. else
  2134. ret = Zipor->zipToFile(buf.length(), (void*)buf.toByteArray(), fileNameStr.str(), ifname.str());
  2135. releaseIZ(Zipor);
  2136. if (ret < 0)
  2137. {
  2138. Owned<IFile> rFile = createIFile(ifname.str());
  2139. if (rFile->exists())
  2140. rFile->remove();
  2141. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2142. }
  2143. Owned <IFile> rf = createIFile(ifname.str());
  2144. if (!rf->exists())
  2145. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2146. MemoryBuffer out;
  2147. Owned <IFileIO> fio = rf->open(IFOread);
  2148. read(fio, 0, (size32_t) rf->size(), out);
  2149. resp.setThefile(out);
  2150. fio.clear();
  2151. rf->remove();
  2152. resp.setThefile_mimetype((opt > 2) ? "application/x-gzip" : "application/zip");
  2153. context.addCustomerHeader("Content-disposition", headerStr.str());
  2154. #endif
  2155. }
  2156. }
  2157. bool CWsWorkunitsEx::onWUFile(IEspContext &context,IEspWULogFileRequest &req, IEspWULogFileResponse &resp)
  2158. {
  2159. try
  2160. {
  2161. StringBuffer wuidStr = req.getWuid();
  2162. const char* wuidIn = wuidStr.trim().str();
  2163. if (wuidIn && *wuidIn)
  2164. {
  2165. if (!looksLikeAWuid(wuidIn))
  2166. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID");
  2167. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2168. }
  2169. StringAttr wuid(wuidIn);
  2170. if (wuid.isEmpty() && notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  2171. {
  2172. Owned<IPropertyTree> registry = getQueryRegistry(req.getQuerySet(), false);
  2173. if (!registry)
  2174. throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", req.getQuerySet());
  2175. Owned<IPropertyTree> query = resolveQueryAlias(registry, req.getQuery());
  2176. if (!query)
  2177. throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", req.getQuery());
  2178. resp.setQuerySet(req.getQuerySet());
  2179. resp.setQueryName(query->queryProp("@name"));
  2180. resp.setQueryId(query->queryProp("@id"));
  2181. wuid.set(query->queryProp("@wuid"));
  2182. }
  2183. int opt = req.getOption();
  2184. if (!wuid.isEmpty())
  2185. {
  2186. resp.setWuid(wuid.get());
  2187. MemoryBuffer mb;
  2188. WsWuInfo winfo(context, wuid);
  2189. if (strieq(File_ArchiveQuery, req.getType()))
  2190. {
  2191. winfo.getWorkunitArchiveQuery(mb);
  2192. openSaveFile(context, opt, "ArchiveQuery.xml", HTTP_TYPE_APPLICATION_XML, mb, resp);
  2193. }
  2194. else if (strieq(File_Cpp,req.getType()) && notEmpty(req.getName()))
  2195. {
  2196. winfo.getWorkunitCpp(req.getName(), req.getDescription(), req.getIPAddress(),mb, opt > 0);
  2197. openSaveFile(context, opt, req.getName(), HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2198. }
  2199. else if (strieq(File_DLL,req.getType()))
  2200. {
  2201. StringBuffer name;
  2202. winfo.getWorkunitDll(name, mb);
  2203. resp.setFileName(name.str());
  2204. resp.setDaliServer(daliServers.get());
  2205. openSaveFile(context, opt, req.getName(), HTTP_TYPE_OCTET_STREAM, mb, resp);
  2206. }
  2207. else if (strieq(File_Res,req.getType()))
  2208. {
  2209. winfo.getWorkunitResTxt(mb);
  2210. openSaveFile(context, opt, "res.txt", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2211. }
  2212. else if (strncmp(req.getType(), File_ThorLog, 7) == 0)
  2213. {
  2214. winfo.getWorkunitThorLog(req.getName(), mb);
  2215. openSaveFile(context, opt, "thormaster.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2216. }
  2217. else if (strieq(File_ThorSlaveLog,req.getType()))
  2218. {
  2219. StringBuffer logDir;
  2220. getConfigurationDirectory(directories, "log", "thor", req.getProcess(), logDir);
  2221. winfo.getWorkunitThorSlaveLog(req.getClusterGroup(), req.getIPAddress(), req.getLogDate(), logDir.str(), req.getSlaveNumber(), mb, false);
  2222. openSaveFile(context, opt, "ThorSlave.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2223. }
  2224. else if (strieq(File_EclAgentLog,req.getType()))
  2225. {
  2226. winfo.getWorkunitEclAgentLog(req.getName(), req.getProcess(), mb);
  2227. openSaveFile(context, opt, "eclagent.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2228. }
  2229. else if (strieq(File_XML,req.getType()) && notEmpty(req.getName()))
  2230. {
  2231. const char* name = req.getName();
  2232. const char* ptr = strrchr(name, '/');
  2233. if (ptr)
  2234. ptr++;
  2235. else
  2236. ptr = name;
  2237. winfo.getWorkunitAssociatedXml(name, req.getIPAddress(), req.getPlainText(), req.getDescription(), opt > 0, mb);
  2238. openSaveFile(context, opt, ptr, HTTP_TYPE_APPLICATION_XML, mb, resp);
  2239. }
  2240. else if (strieq(File_XML,req.getType()) || strieq(File_WUECL,req.getType()))
  2241. {
  2242. StringBuffer mimeType, fileName;
  2243. if (strieq(File_WUECL,req.getType()))
  2244. {
  2245. fileName.setf("%s.ecl", wuid.get());
  2246. winfo.getWorkunitQueryShortText(mb);
  2247. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2248. }
  2249. else
  2250. {
  2251. fileName.setf("%s.xml", wuid.get());
  2252. winfo.getWorkunitXml(req.getPlainText(), mb);
  2253. if (opt < 2)
  2254. {
  2255. const char* plainText = req.getPlainText();
  2256. if (plainText && (!stricmp(plainText, "yes")))
  2257. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2258. else
  2259. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2260. }
  2261. else
  2262. {
  2263. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2264. }
  2265. }
  2266. openSaveFile(context, opt, fileName.str(), mimeType.str(), mb, resp);
  2267. }
  2268. }
  2269. }
  2270. catch(IException* e)
  2271. {
  2272. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2273. }
  2274. return true;
  2275. }
  2276. bool CWsWorkunitsEx::onWUResultBin(IEspContext &context,IEspWUResultBinRequest &req, IEspWUResultBinResponse &resp)
  2277. {
  2278. try
  2279. {
  2280. StringBuffer wuidStr = req.getWuid();
  2281. const char* wuidIn = wuidStr.trim().str();
  2282. if (wuidIn && *wuidIn)
  2283. {
  2284. if (!looksLikeAWuid(wuidIn))
  2285. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuidIn);
  2286. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2287. }
  2288. MemoryBuffer mb;
  2289. __int64 total=0;
  2290. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  2291. unsigned count = req.getCount(), requested=count;
  2292. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  2293. SCMStringBuffer name;
  2294. bool bin = (req.getFormat() && strieq(req.getFormat(),"raw"));
  2295. if (notEmpty(wuidIn) && notEmpty(req.getResultName()))
  2296. getWsWuResult(context, wuidIn, req.getResultName(), NULL, 0, start, count, total, name, bin, filterBy, mb);
  2297. else if (notEmpty(wuidIn) && (req.getSequence() >= 0))
  2298. getWsWuResult(context, wuidIn, NULL, NULL, req.getSequence(), start, count, total, name, bin,filterBy, mb);
  2299. else if (notEmpty(req.getLogicalName()))
  2300. {
  2301. const char* logicalName = req.getLogicalName();
  2302. StringBuffer wuid;
  2303. getWuidFromLogicalFileName(context, logicalName, wuid);
  2304. if (!wuid.length())
  2305. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.",logicalName);
  2306. getWsWuResult(context, wuid.str(), NULL, logicalName, 0, start, count, total, name, bin, filterBy, mb);
  2307. }
  2308. else
  2309. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2310. if(stricmp(req.getFormat(),"xls")==0)
  2311. {
  2312. Owned<IProperties> params(createProperties());
  2313. params->setProp("showCount",0);
  2314. StringBuffer xml;
  2315. xml.append("<WUResultExcel><Result>").append(mb.length(), mb.toByteArray()).append("</Result></WUResultExcel>");
  2316. if (xml.length() > MAXXLSTRANSFER)
  2317. throw MakeStringException(ECLWATCH_TOO_BIG_DATA_SET, "The data set is too big to be converted to an Excel file. Please use the gzip link to download a compressed XML data file.");
  2318. StringBuffer xls;
  2319. xsltTransform(xml.str(), StringBuffer(getCFD()).append("./smc_xslt/result.xslt").str(), params, xls);
  2320. MemoryBuffer out;
  2321. out.setBuffer(xls.length(), (void*)xls.str());
  2322. resp.setResult(out);
  2323. resp.setResult_mimetype("application/vnd.ms-excel");
  2324. }
  2325. #ifdef _USE_ZLIB
  2326. else if(strieq(req.getFormat(),"zip") || strieq(req.getFormat(),"gzip"))
  2327. {
  2328. bool gzip = strieq(req.getFormat(),"gzip");
  2329. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2330. xml.append("<Result>").append(mb.length(),mb.toByteArray()).append("</Result>");
  2331. VStringBuffer ifname("%s%sT%xAT%x%s", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick(), gzip ? "" : ".zip");
  2332. IZZIPor* Zipor = createZZIPor();
  2333. int ret = 0;
  2334. if (gzip)
  2335. ret = Zipor->gzipToFile(xml.length(), (void*)xml.str(), ifname.str());
  2336. else
  2337. ret = Zipor->zipToFile(xml.length(), (void*)xml.str(), "WUResult.xml", ifname.str());
  2338. releaseIZ(Zipor);
  2339. if (ret < 0)
  2340. {
  2341. Owned<IFile> rFile = createIFile(ifname.str());
  2342. if (rFile->exists())
  2343. rFile->remove();
  2344. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "The data cannot be compressed.");
  2345. }
  2346. MemoryBuffer out;
  2347. Owned <IFile> rf = createIFile(ifname.str());
  2348. if (rf->exists())
  2349. {
  2350. Owned <IFileIO> fio = rf->open(IFOread);
  2351. read(fio, 0, (size32_t) rf->size(), out);
  2352. resp.setResult(out);
  2353. }
  2354. if (gzip)
  2355. {
  2356. resp.setResult_mimetype("application/x-gzip");
  2357. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.gz");
  2358. }
  2359. else
  2360. {
  2361. resp.setResult_mimetype("application/zip");
  2362. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.zip");
  2363. }
  2364. Owned<IFile> rFile = createIFile(ifname.str());
  2365. if (rFile->exists())
  2366. rFile->remove();
  2367. }
  2368. #endif
  2369. else
  2370. {
  2371. resp.setResult(mb);
  2372. }
  2373. resp.setName(name.str());
  2374. resp.setWuid(wuidIn);
  2375. resp.setSequence(req.getSequence());
  2376. resp.setStart(start);
  2377. if (requested > total)
  2378. requested = (unsigned)total;
  2379. resp.setRequested(requested);
  2380. resp.setCount(count);
  2381. resp.setTotal(total);
  2382. resp.setFormat(req.getFormat());
  2383. }
  2384. catch(IException* e)
  2385. {
  2386. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2387. }
  2388. return true;
  2389. }
  2390. bool CWsWorkunitsEx::onWUResultSummary(IEspContext &context, IEspWUResultSummaryRequest &req, IEspWUResultSummaryResponse &resp)
  2391. {
  2392. try
  2393. {
  2394. StringBuffer wuid = req.getWuid();
  2395. WsWuHelpers::checkAndTrimWorkunit("WUResultSummary", wuid);
  2396. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2397. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  2398. if(!cw)
  2399. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  2400. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2401. resp.setWuid(wuid.str());
  2402. resp.setSequence(req.getSequence());
  2403. IArrayOf<IEspECLResult> results;
  2404. Owned<IConstWUResult> r = cw->getResultBySequence(req.getSequence());
  2405. if (r)
  2406. {
  2407. WsWuInfo winfo(context, cw);
  2408. winfo.getResult(*r, results, 0);
  2409. resp.setFormat(r->getResultFormat());
  2410. resp.setResult(results.item(0));
  2411. }
  2412. }
  2413. catch(IException* e)
  2414. {
  2415. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2416. }
  2417. return true;
  2418. }
  2419. void getFileResults(IEspContext &context, const char* logicalName, const char* cluster,__int64 start, unsigned& count,__int64& total,
  2420. IStringVal& resname,bool bin, IArrayOf<IConstNamedValue>* filterBy, MemoryBuffer& buf, bool xsd)
  2421. {
  2422. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  2423. Owned<INewResultSet> result(resultSetFactory->createNewFileResultSet(logicalName, cluster));
  2424. if (!filterBy || !filterBy->length())
  2425. appendResultSet(buf, result, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  2426. else
  2427. {
  2428. Owned<INewResultSet> filteredResult = createFilteredResultSet(result, filterBy);
  2429. appendResultSet(buf, filteredResult, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  2430. }
  2431. }
  2432. void getWorkunitCluster(IEspContext &context, const char* wuid, SCMStringBuffer& cluster, bool checkArchiveWUs)
  2433. {
  2434. if (isEmpty(wuid))
  2435. return;
  2436. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2437. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  2438. if (cw)
  2439. cw->getClusterName(cluster);
  2440. else if (checkArchiveWUs)
  2441. {
  2442. Owned<IPropertyTree> wuProps;// = getArchivedWorkUnitProperties(wuid);
  2443. if (wuProps)
  2444. cluster.set(wuProps->queryProp("@clusterName"));
  2445. }
  2446. }
  2447. bool CWsWorkunitsEx::onWUResult(IEspContext &context, IEspWUResultRequest &req, IEspWUResultResponse &resp)
  2448. {
  2449. try
  2450. {
  2451. StringBuffer wuidStr = req.getWuid();
  2452. const char* wuid = wuidStr.trim().str();
  2453. if (wuid && *wuid)
  2454. {
  2455. if (!looksLikeAWuid(wuid))
  2456. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  2457. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  2458. }
  2459. MemoryBuffer mb;
  2460. SCMStringBuffer name;
  2461. __int64 total=0;
  2462. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  2463. unsigned count=req.getCount() ? req.getCount() : 100, requested=count;
  2464. unsigned seq = req.getSequence();
  2465. bool inclXsd = !req.getSuppressXmlSchema();
  2466. VStringBuffer filter("start=%"I64F"d;count=%d", start, count);
  2467. addToQueryString(filter, "clusterName", req.getCluster(), ';');
  2468. addToQueryString(filter, "logicalName", req.getLogicalName(), ';');
  2469. if (wuid && *wuid)
  2470. addToQueryString(filter, "wuid", wuid, ';');
  2471. addToQueryString(filter, "resultName", req.getResultName(), ';');
  2472. filter.appendf(";seq=%d;", seq);
  2473. if (inclXsd)
  2474. filter.append("xsd;");
  2475. if (context.getResponseFormat()==ESPSerializationJSON)
  2476. filter.append("json;");
  2477. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  2478. ForEachItemIn(i, *filterBy)
  2479. {
  2480. IConstNamedValue &item = filterBy->item(i);
  2481. const char *name = item.getName();
  2482. const char *value = item.getValue();
  2483. if (name && *name && value && *value)
  2484. addToQueryString(filter, name, value, ';');
  2485. }
  2486. const char* logicalName = req.getLogicalName();
  2487. const char* clusterName = req.getCluster();
  2488. const char* resultName = req.getResultName();
  2489. Owned<DataCacheElement> data = dataCache->lookup(context, filter, awusCacheMinutes);
  2490. if (data)
  2491. {
  2492. mb.append(data->m_data.c_str());
  2493. name.set(data->m_name.c_str());
  2494. logicalName = data->m_logicalName.c_str();
  2495. wuid = data->m_wuid.c_str();
  2496. resultName = data->m_resultName.c_str();
  2497. seq = data->m_seq;
  2498. start = data->m_start;
  2499. count = data->m_rowcount;
  2500. requested = (unsigned)data->m_requested;
  2501. total = data->m_total;
  2502. if (notEmpty(logicalName))
  2503. resp.setLogicalName(logicalName);
  2504. else
  2505. {
  2506. if (notEmpty(wuid))
  2507. resp.setWuid(wuid);
  2508. resp.setSequence(seq);
  2509. }
  2510. }
  2511. else
  2512. {
  2513. if(logicalName && *logicalName)
  2514. {
  2515. StringBuffer lwuid;
  2516. getWuidFromLogicalFileName(context, logicalName, lwuid);
  2517. SCMStringBuffer cluster;
  2518. if (lwuid.length())
  2519. getWorkunitCluster(context, lwuid.str(), cluster, true);
  2520. if (cluster.length())
  2521. {
  2522. getFileResults(context, logicalName, cluster.str(), start, count, total, name, false, filterBy, mb, inclXsd);
  2523. resp.setLogicalName(logicalName);
  2524. }
  2525. else if (notEmpty(clusterName))
  2526. {
  2527. getFileResults(context, logicalName, clusterName, start, count, total, name, false, filterBy, mb, inclXsd);
  2528. resp.setLogicalName(logicalName);
  2529. }
  2530. else
  2531. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Need valid target cluster to browse file %s.",logicalName);
  2532. }
  2533. else if (notEmpty(wuid) && notEmpty(resultName))
  2534. {
  2535. name.set(resultName);
  2536. getWsWuResult(context, wuid, resultName, NULL, 0, start, count, total, name, false, filterBy, mb, inclXsd);
  2537. resp.setWuid(wuid);
  2538. resp.setSequence(seq);
  2539. }
  2540. else
  2541. {
  2542. getWsWuResult(context, wuid, NULL, NULL, seq, start, count, total, name, false, filterBy, mb, inclXsd);
  2543. resp.setWuid(wuid);
  2544. resp.setSequence(seq);
  2545. }
  2546. mb.append(0);
  2547. if (requested > total)
  2548. requested = (unsigned)total;
  2549. dataCache->add(filter, mb.toByteArray(), name.str(), logicalName, wuid, resultName, seq, start, count, requested, total);
  2550. }
  2551. resp.setName(name.str());
  2552. resp.setStart(start);
  2553. if (clusterName && *clusterName)
  2554. resp.setCluster(clusterName);
  2555. resp.setRequested(requested);
  2556. resp.setCount(count);
  2557. resp.setTotal(total);
  2558. resp.setResult(mb.toByteArray());
  2559. context.queryXslParameters()->setProp("escapeResults","1");
  2560. }
  2561. catch(IException* e)
  2562. {
  2563. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2564. }
  2565. return true;
  2566. }
  2567. void getScheduledWUs(IEspContext &context, const char *stateReq, const char *serverName, const char *eventName, IArrayOf<IEspScheduledWU> & results)
  2568. {
  2569. double version = context.getClientVersion();
  2570. if (notEmpty(serverName))
  2571. {
  2572. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2573. Owned<IScheduleReader> reader = getScheduleReader(serverName, eventName);
  2574. Owned<IScheduleReaderIterator> it(reader->getIterator());
  2575. while(it->isValidEventName())
  2576. {
  2577. StringBuffer ieventName;
  2578. it->getEventName(ieventName);
  2579. while(it->isValidEventText())
  2580. {
  2581. StringBuffer ieventText;
  2582. it->getEventText(ieventText);
  2583. while(it->isValidWuid())
  2584. {
  2585. StringBuffer wuid;
  2586. it->getWuid(wuid);
  2587. if (wuid.length())
  2588. {
  2589. bool match = false;
  2590. unsigned stateID = WUStateUnknown;
  2591. SCMStringBuffer jobName, owner, state;
  2592. try
  2593. {
  2594. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  2595. if (!cw && (!stateReq || !*stateReq))
  2596. match = true;
  2597. else if (cw)
  2598. {
  2599. if ((cw->getState() == WUStateScheduled) && cw->aborting())
  2600. {
  2601. stateID = WUStateAborting;
  2602. state.set("aborting");
  2603. }
  2604. else
  2605. {
  2606. stateID = cw->getState();
  2607. cw->getStateDesc(state);
  2608. }
  2609. if (!stateReq || !*stateReq || strieq(stateReq, state.str()))
  2610. {
  2611. match = true;
  2612. cw->getJobName(jobName);
  2613. cw->getUser(owner);
  2614. }
  2615. }
  2616. }
  2617. catch (IException *e)
  2618. {
  2619. EXCLOG(e, "Get scheduled WUs");
  2620. e->Release();
  2621. }
  2622. if (!match)
  2623. {
  2624. it->nextWuid();
  2625. continue;
  2626. }
  2627. Owned<IEspScheduledWU> scheduledWU = createScheduledWU("");
  2628. scheduledWU->setWuid(wuid.str());
  2629. scheduledWU->setCluster(serverName);
  2630. if (ieventName.length())
  2631. scheduledWU->setEventName(ieventName.str());
  2632. if (ieventText.str())
  2633. scheduledWU->setEventText(ieventText.str());
  2634. if (jobName.length())
  2635. scheduledWU->setJobName(jobName.str());
  2636. if (version >= 1.51)
  2637. {
  2638. if (owner.length())
  2639. scheduledWU->setOwner(owner.str());
  2640. if (state.length())
  2641. {
  2642. scheduledWU->setStateID(stateID);
  2643. scheduledWU->setState(state.str());
  2644. }
  2645. }
  2646. results.append(*scheduledWU.getLink());
  2647. }
  2648. it->nextWuid();
  2649. }
  2650. it->nextEventText();
  2651. }
  2652. it->nextEventName();
  2653. }
  2654. }
  2655. return;
  2656. }
  2657. bool CWsWorkunitsEx::onWUShowScheduled(IEspContext &context, IEspWUShowScheduledRequest & req, IEspWUShowScheduledResponse & resp)
  2658. {
  2659. try
  2660. {
  2661. DBGLOG("WUShowScheduled");
  2662. const char *clusterName = req.getCluster();
  2663. const char *eventName = req.getEventName();
  2664. const char *state = req.getState();
  2665. IArrayOf<IEspScheduledWU> results;
  2666. if(notEmpty(req.getPushEventName()))
  2667. resp.setPushEventName(req.getPushEventName());
  2668. if(notEmpty(req.getPushEventText()))
  2669. resp.setPushEventText(req.getPushEventText());
  2670. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2671. Owned<IConstEnvironment> environment = factory->openEnvironment();
  2672. Owned<IPropertyTree> root = &environment->getPTree();
  2673. if (!root)
  2674. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  2675. unsigned i = 0;
  2676. Owned<IPropertyTreeIterator> ic = root->getElements("Software/Topology/Cluster");
  2677. IArrayOf<IEspServerInfo> servers;
  2678. ForEach(*ic)
  2679. {
  2680. IPropertyTree &cluster = ic->query();
  2681. const char *iclusterName = cluster.queryProp("@name");
  2682. if (isEmpty(iclusterName))
  2683. continue;
  2684. if(isEmpty(clusterName))
  2685. getScheduledWUs(context, state, iclusterName, eventName, results);
  2686. else if (strieq(clusterName, iclusterName))
  2687. {
  2688. getScheduledWUs(context, state, clusterName, eventName, results);
  2689. resp.setClusterSelected(i+1);
  2690. }
  2691. Owned<IEspServerInfo> server = createServerInfo("");
  2692. server->setName(iclusterName);
  2693. servers.append(*server.getLink());
  2694. i++;
  2695. }
  2696. if (servers.length())
  2697. resp.setClusters(servers);
  2698. if (results.length())
  2699. resp.setWorkunits(results);
  2700. bool first=false;
  2701. StringBuffer Query("PageFrom=Scheduler");
  2702. appendUrlParameter(Query, "EventName", eventName, first);
  2703. appendUrlParameter(Query, "ECluster", clusterName, first);
  2704. resp.setQuery(Query.str());
  2705. }
  2706. catch(IException* e)
  2707. {
  2708. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2709. }
  2710. return true;
  2711. }
  2712. bool CWsWorkunitsEx::onWUExport(IEspContext &context, IEspWUExportRequest &req, IEspWUExportResponse &resp)
  2713. {
  2714. try
  2715. {
  2716. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2717. WsWuSearch ws(context, req.getOwner(), req.getState(), req.getCluster(), req.getStartDate(), req.getEndDate(), req.getECL(), req.getJobname());
  2718. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Workunits>");
  2719. for(WsWuSearch::iterator it=ws.begin(); it!=ws.end(); it++)
  2720. {
  2721. Owned<IConstWorkUnit> cw = factory->openWorkUnit(it->c_str(), false);
  2722. if (cw)
  2723. exportWorkUnitToXML(cw, xml, true, false);
  2724. }
  2725. xml.append("</Workunits>");
  2726. MemoryBuffer mb;
  2727. mb.setBuffer(xml.length(),(void*)xml.str());
  2728. resp.setExportData(mb);
  2729. resp.setExportData_mimetype(HTTP_TYPE_APPLICATION_XML);
  2730. }
  2731. catch(IException* e)
  2732. {
  2733. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2734. }
  2735. return true;
  2736. }
  2737. bool CWsWorkunitsEx::onWUListLocalFileRequired(IEspContext& context, IEspWUListLocalFileRequiredRequest& req, IEspWUListLocalFileRequiredResponse& resp)
  2738. {
  2739. try
  2740. {
  2741. StringBuffer wuid = req.getWuid();
  2742. WsWuHelpers::checkAndTrimWorkunit("WUListLocalFileRequired", wuid);
  2743. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  2744. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2745. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  2746. if (!cw)
  2747. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Workunit %s not found.", wuid.str());
  2748. IArrayOf<IEspLogicalFileUpload> localFiles;
  2749. Owned<IConstLocalFileUploadIterator> it = cw->getLocalFileUploads();
  2750. ForEach(*it)
  2751. {
  2752. Owned<IConstLocalFileUpload> file = it->get();
  2753. if(!file)
  2754. continue;
  2755. Owned<IEspLogicalFileUpload> up = createLogicalFileUpload();
  2756. SCMStringBuffer s;
  2757. up->setType(file->queryType());
  2758. up->setSource(file->getSource(s).str());
  2759. up->setDestination(file->getDestination(s).str());
  2760. up->setEventTag(file->getEventTag(s).str());
  2761. localFiles.append(*up.getLink());
  2762. }
  2763. resp.setLocalFileUploads(localFiles);
  2764. }
  2765. catch(IException* e)
  2766. {
  2767. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2768. }
  2769. return true;
  2770. }
  2771. typedef enum wsEclTypes_
  2772. {
  2773. wsEclTypeUnknown,
  2774. xsdString,
  2775. xsdBoolean,
  2776. xsdDecimal,
  2777. xsdFloat,
  2778. xsdDouble,
  2779. xsdDuration,
  2780. xsdDateTime,
  2781. xsdTime,
  2782. xsdDate,
  2783. xsdYearMonth,
  2784. xsdYear,
  2785. xsdMonthDay,
  2786. xsdDay,
  2787. xsdMonth,
  2788. xsdHexBinary,
  2789. xsdBase64Binary,
  2790. xsdAnyURI,
  2791. xsdQName,
  2792. xsdNOTATION,
  2793. xsdNormalizedString,
  2794. xsdToken,
  2795. xsdLanguage,
  2796. xsdNMTOKEN,
  2797. xsdNMTOKENS,
  2798. xsdName,
  2799. xsdNCName,
  2800. xsdID,
  2801. xsdIDREF,
  2802. xsdIDREFS,
  2803. xsdENTITY,
  2804. xsdENTITIES,
  2805. xsdInteger,
  2806. xsdNonPositiveInteger,
  2807. xsdNegativeInteger,
  2808. xsdLong,
  2809. xsdInt,
  2810. xsdShort,
  2811. xsdByte,
  2812. xsdNonNegativeInteger,
  2813. xsdUnsignedLong,
  2814. xsdUnsignedInt,
  2815. xsdUnsignedShort,
  2816. xsdUnsignedByte,
  2817. xsdPositiveInteger,
  2818. tnsRawDataFile,
  2819. tnsCsvDataFile,
  2820. tnsEspStringArray,
  2821. tnsEspIntArray,
  2822. tnsXmlDataSet,
  2823. maxWsEclType
  2824. } wsEclType;
  2825. bool CWsWorkunitsEx::onWUAddLocalFileToWorkunit(IEspContext& context, IEspWUAddLocalFileToWorkunitRequest& req, IEspWUAddLocalFileToWorkunitResponse& resp)
  2826. {
  2827. try
  2828. {
  2829. StringBuffer wuid = req.getWuid();
  2830. WsWuHelpers::checkAndTrimWorkunit("WUAddLocalFileToWorkunit", wuid);
  2831. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  2832. resp.setWuid(wuid.str());
  2833. const char* varname = req.getName();
  2834. if (isEmpty(varname))
  2835. {
  2836. resp.setResult("Name is not defined!");
  2837. return true;
  2838. }
  2839. resp.setName(varname);
  2840. wsEclType type = (wsEclType) req.getType();
  2841. const char *val = req.getVal();
  2842. unsigned len = req.getLength();
  2843. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2844. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  2845. if (!wu)
  2846. {
  2847. resp.setResult("Workunit not found!");
  2848. return true;
  2849. }
  2850. Owned<IWUResult> wuRslt = wu->updateResultByName(varname);
  2851. if (isEmpty(val))
  2852. val=req.getDefVal();
  2853. if (notEmpty(val))
  2854. {
  2855. switch (type)
  2856. {
  2857. case xsdBoolean:
  2858. wuRslt->setResultBool((strieq(val, "1") || strieq(val, "true") || strieq(val, "on")));
  2859. wuRslt->setResultStatus(ResultStatusSupplied);
  2860. break;
  2861. case xsdDecimal:
  2862. case xsdFloat:
  2863. case xsdDouble:
  2864. wuRslt->setResultReal(atof(val));
  2865. wuRslt->setResultStatus(ResultStatusSupplied);
  2866. break;
  2867. case xsdInteger:
  2868. case xsdNonPositiveInteger:
  2869. case xsdNegativeInteger:
  2870. case xsdLong:
  2871. case xsdInt:
  2872. case xsdShort:
  2873. case xsdByte:
  2874. case xsdNonNegativeInteger:
  2875. case xsdUnsignedLong:
  2876. case xsdUnsignedInt:
  2877. case xsdUnsignedShort:
  2878. case xsdUnsignedByte:
  2879. case xsdPositiveInteger:
  2880. wuRslt->setResultInt(_atoi64(val));
  2881. wuRslt->setResultStatus(ResultStatusSupplied);
  2882. break;
  2883. case tnsEspIntArray:
  2884. case tnsEspStringArray:
  2885. wuRslt->setResultRaw(len, val, ResultFormatXmlSet);
  2886. break;
  2887. case tnsRawDataFile:
  2888. wuRslt->setResultRaw(len, val, ResultFormatRaw);
  2889. break;
  2890. case tnsXmlDataSet:
  2891. wuRslt->setResultRaw(len, val, ResultFormatXml);
  2892. break;
  2893. case tnsCsvDataFile:
  2894. case xsdBase64Binary: //tbd
  2895. case xsdHexBinary:
  2896. break;
  2897. default:
  2898. wuRslt->setResultString(val, len);
  2899. wuRslt->setResultStatus(ResultStatusSupplied);
  2900. break;
  2901. }
  2902. }
  2903. resp.setResult("Result has been set as required!");
  2904. }
  2905. catch(IException* e)
  2906. {
  2907. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2908. }
  2909. return true;
  2910. }
  2911. void getClusterConfig(char const * clusterType, char const * clusterName, char const * processName, StringBuffer& netAddress)
  2912. {
  2913. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2914. Owned<IConstEnvironment> environment = factory->openEnvironment();
  2915. Owned<IPropertyTree> pRoot = &environment->getPTree();
  2916. VStringBuffer xpath("Software/%s[@name='%s']", clusterType, clusterName);
  2917. IPropertyTree* pCluster = pRoot->queryPropTree(xpath.str());
  2918. if (!pCluster)
  2919. throw MakeStringException(ECLWATCH_CLUSTER_NOT_IN_ENV_INFO, "'%s %s' is not defined.", clusterType, clusterName);
  2920. const char* port = pCluster->queryProp(xpath.set(processName).append("@port").str());
  2921. const char* computer = pCluster->queryProp(xpath.set(processName).append("@computer").str());
  2922. if (isEmpty(computer))
  2923. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_INFO, "'%s %s: %s' is not defined.", clusterType, clusterName, processName);
  2924. Owned<IConstMachineInfo> pMachine = environment->getMachine(computer);
  2925. if (pMachine)
  2926. {
  2927. StringBufferAdaptor s(netAddress);
  2928. pMachine->getNetAddress(s);
  2929. #ifdef MACHINE_IP
  2930. if (streq(netAddress.str(), "."))
  2931. netAddress = MACHINE_IP;
  2932. #endif
  2933. netAddress.append(':').append(port);
  2934. }
  2935. return;
  2936. }
  2937. bool CWsWorkunitsEx::onWUProcessGraph(IEspContext &context,IEspWUProcessGraphRequest &req, IEspWUProcessGraphResponse &resp)
  2938. {
  2939. try
  2940. {
  2941. StringBuffer wuid = req.getWuid();
  2942. WsWuHelpers::checkAndTrimWorkunit("WUProcessGraph", wuid);
  2943. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2944. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  2945. if(!cw)
  2946. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  2947. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2948. Owned <IConstWUGraph> graph = cw->getGraph(req.getName());
  2949. Owned <IPropertyTree> xgmml = graph->getXGMMLTree(true); // merge in graph progress information
  2950. StringBuffer xml;
  2951. resp.setTheGraph(toXML(xgmml.get(), xml).str());
  2952. }
  2953. catch(IException* e)
  2954. {
  2955. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2956. }
  2957. return true;
  2958. }
  2959. bool isRunning(IConstWorkUnit &cw)
  2960. {
  2961. // MORE - move into workunit interface
  2962. switch (cw.getState())
  2963. {
  2964. case WUStateFailed:
  2965. case WUStateAborted:
  2966. case WUStateCompleted:
  2967. return false;
  2968. default:
  2969. return true;
  2970. }
  2971. }
  2972. bool CWsWorkunitsEx::onWUGetGraph(IEspContext& context, IEspWUGetGraphRequest& req, IEspWUGetGraphResponse& resp)
  2973. {
  2974. try
  2975. {
  2976. StringBuffer wuid = req.getWuid();
  2977. WsWuHelpers::checkAndTrimWorkunit("WUGetGraph", wuid);
  2978. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2979. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  2980. if(!cw)
  2981. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  2982. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2983. WUGraphIDType id;
  2984. SCMStringBuffer runningGraph;
  2985. bool running= (isRunning(*cw) && cw->getRunningGraph(runningGraph,id));
  2986. IArrayOf<IEspECLGraphEx> graphs;
  2987. Owned<IConstWUGraphIterator> it = &cw->getGraphs(GraphTypeAny);
  2988. ForEach(*it)
  2989. {
  2990. IConstWUGraph &graph = it->query();
  2991. if(!graph.isValid())
  2992. continue;
  2993. SCMStringBuffer name, label, type;
  2994. graph.getName(name);
  2995. graph.getLabel(label);
  2996. graph.getTypeName(type);
  2997. if(isEmpty(req.getGraphName()) || strieq(name.str(), req.getGraphName()))
  2998. {
  2999. Owned<IEspECLGraphEx> g = createECLGraphEx("","");
  3000. g->setName(name.str());
  3001. g->setLabel(label.str());
  3002. g->setType(type.str());
  3003. if(running && streq(name.str(), runningGraph.str()))
  3004. {
  3005. g->setRunning(true);
  3006. g->setRunningId(id);
  3007. }
  3008. Owned<IPropertyTree> xgmml = graph.getXGMMLTree(true);
  3009. // New functionality, if a subgraph id is specified and we only want to load the xgmml for that subgraph
  3010. // then we need to conditionally pull a propertytree from the xgmml graph one and use that for the xgmml.
  3011. StringBuffer xml;
  3012. if (notEmpty(req.getSubGraphId()))
  3013. {
  3014. VStringBuffer xpath("//node[@id='%s']", req.getSubGraphId());
  3015. toXML(xgmml->queryPropTree(xpath.str()), xml);
  3016. }
  3017. else
  3018. toXML(xgmml, xml);
  3019. g->setGraph(xml.str());
  3020. if (context.getClientVersion() > 1.20)
  3021. {
  3022. Owned<IConstWUGraphProgress> progress = cw->getGraphProgress(name.str());
  3023. if (progress)
  3024. {
  3025. WUGraphState graphstate= progress->queryGraphState();
  3026. if (graphstate == WUGraphComplete)
  3027. g->setComplete(true);
  3028. else if (graphstate == WUGraphFailed)
  3029. g->setFailed(true);
  3030. }
  3031. }
  3032. graphs.append(*g.getClear());
  3033. }
  3034. }
  3035. resp.setGraphs(graphs);
  3036. }
  3037. catch(IException* e)
  3038. {
  3039. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3040. }
  3041. return true;
  3042. }
  3043. bool CWsWorkunitsEx::onGVCAjaxGraph(IEspContext &context, IEspGVCAjaxGraphRequest &req, IEspGVCAjaxGraphResponse &resp)
  3044. {
  3045. try
  3046. {
  3047. resp.setName(req.getName());
  3048. resp.setGraphName(req.getGraphName());
  3049. resp.setGraphType("eclwatch");
  3050. double version = context.getClientVersion();
  3051. if (version > 1.19)
  3052. resp.setSubGraphId(req.getSubGraphId());
  3053. if (version > 1.20)
  3054. resp.setSubGraphOnly(req.getSubGraphOnly());
  3055. }
  3056. catch(IException* e)
  3057. {
  3058. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3059. }
  3060. return true;
  3061. }
  3062. bool CWsWorkunitsEx::onWUGraphInfo(IEspContext &context,IEspWUGraphInfoRequest &req, IEspWUGraphInfoResponse &resp)
  3063. {
  3064. try
  3065. {
  3066. StringBuffer wuid = req.getWuid();
  3067. WsWuHelpers::checkAndTrimWorkunit("WUGraphInfo", wuid);
  3068. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3069. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  3070. if(!cw)
  3071. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3072. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  3073. resp.setWuid(wuid.str());
  3074. resp.setName(req.getName());
  3075. resp.setRunning(isRunning(*cw));
  3076. if (notEmpty(req.getGID()))
  3077. resp.setGID(req.getGID());
  3078. if(!req.getBatchWU_isNull())
  3079. resp.setBatchWU(req.getBatchWU());
  3080. }
  3081. catch(IException* e)
  3082. {
  3083. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3084. }
  3085. return true;
  3086. }
  3087. bool CWsWorkunitsEx::onWUGVCGraphInfo(IEspContext &context,IEspWUGVCGraphInfoRequest &req, IEspWUGVCGraphInfoResponse &resp)
  3088. {
  3089. try
  3090. {
  3091. StringBuffer wuid = req.getWuid();
  3092. WsWuHelpers::checkAndTrimWorkunit("WUGVCGraphInfo", wuid);
  3093. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3094. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  3095. if(!cw)
  3096. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3097. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3098. resp.setWuid(wuid.str());
  3099. resp.setName(req.getName());
  3100. resp.setRunning(isRunning(*cw));
  3101. if (notEmpty(req.getGID()))
  3102. resp.setGID(req.getGID());
  3103. if(!req.getBatchWU_isNull())
  3104. resp.setBatchWU(req.getBatchWU());
  3105. StringBuffer xml("<Control><Endpoint><Query id=\"Gordon.Extractor.0\">");
  3106. xml.appendf("<Graph id=\"%s\">", req.getName());
  3107. if (context.getClientVersion() > 1.17)
  3108. {
  3109. xml.append("<Subgraph>");
  3110. xml.append(req.getSubgraphId_isNull() ? 0 : req.getSubgraphId());
  3111. xml.append("</Subgraph>");
  3112. }
  3113. xml.append("</Graph></Query></Endpoint></Control>");
  3114. resp.setTheGraph(xml.str());
  3115. }
  3116. catch(IException* e)
  3117. {
  3118. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3119. }
  3120. return true;
  3121. }
  3122. bool CWsWorkunitsEx::onWUGraphTiming(IEspContext &context, IEspWUGraphTimingRequest &req, IEspWUGraphTimingResponse &resp)
  3123. {
  3124. try
  3125. {
  3126. StringBuffer wuid = req.getWuid();
  3127. WsWuHelpers::checkAndTrimWorkunit("WUGraphTiming", wuid);
  3128. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3129. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  3130. if(!cw)
  3131. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3132. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3133. resp.updateWorkunit().setWuid(wuid.str());
  3134. WsWuInfo winfo(context, cw);
  3135. IArrayOf<IConstECLTimingData> timingData;
  3136. winfo.getGraphTimingData(timingData, 0);
  3137. resp.updateWorkunit().setTimingData(timingData);
  3138. }
  3139. catch(IException* e)
  3140. {
  3141. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3142. }
  3143. return true;
  3144. }
  3145. int CWsWorkunitsSoapBindingEx::onGetForm(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
  3146. {
  3147. try
  3148. {
  3149. StringBuffer xml;
  3150. StringBuffer xslt;
  3151. if(strieq(method,"WUQuery") || strieq(method,"WUJobList"))
  3152. {
  3153. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  3154. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3155. Owned<IPropertyTree> root = &environment->getPTree();
  3156. if (!root)
  3157. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  3158. if(strieq(method,"WUQuery"))
  3159. {
  3160. SecAccessFlags accessOwn;
  3161. SecAccessFlags accessOthers;
  3162. getUserWuAccessFlags(context, accessOwn, accessOthers, false);
  3163. xml.append("<WUQuery>");
  3164. if ((accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  3165. xml.appendf("<ErrorMessage>Access to workunit is denied.</ErrorMessage>");
  3166. else
  3167. {
  3168. MapStringTo<bool> added;
  3169. Owned<IPropertyTreeIterator> it = root->getElements("Software/Topology/Cluster");
  3170. ForEach(*it)
  3171. {
  3172. const char *name = it->query().queryProp("@name");
  3173. if (notEmpty(name) && !added.getValue(name))
  3174. {
  3175. added.setValue(name, true);
  3176. appendXMLTag(xml, "Cluster", name);
  3177. }
  3178. }
  3179. }
  3180. xml.append("</WUQuery>");
  3181. xslt.append(getCFD()).append("./smc_xslt/wuid_search.xslt");
  3182. }
  3183. else if (strieq(method,"WUJobList"))
  3184. {
  3185. StringBuffer cluster, defaultProcess, range;
  3186. request->getParameter("Cluster", cluster);
  3187. request->getParameter("Process",defaultProcess);
  3188. request->getParameter("Range",range);
  3189. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(cluster);
  3190. xml.append("<WUJobList>");
  3191. if (range.length())
  3192. appendXMLTag(xml, "Range", range.str());
  3193. if (clusterInfo)
  3194. {
  3195. const StringArray &thorInstances = clusterInfo->getThorProcesses();
  3196. ForEachItemIn(i, thorInstances)
  3197. {
  3198. const char* instance = thorInstances.item(i);
  3199. if (defaultProcess.length() && strieq(instance, defaultProcess.str()))
  3200. xml.append("<Cluster selected=\"1\">").append(instance).append("</Cluster>");
  3201. else
  3202. xml.append("<Cluster>").append(instance).append("</Cluster>");
  3203. }
  3204. }
  3205. xml.append("<TargetCluster>").append(cluster).append("</TargetCluster>");
  3206. xml.append("</WUJobList>");
  3207. xslt.append(getCFD()).append("./smc_xslt/jobs_search.xslt");
  3208. response->addHeader("Expires", "0");
  3209. }
  3210. }
  3211. if (xslt.length() && xml.length())
  3212. {
  3213. StringBuffer html;
  3214. xsltTransform(xml.str(), xslt.str(), NULL, html);
  3215. response->setContent(html.str());
  3216. response->setContentType(HTTP_TYPE_TEXT_HTML_UTF8);
  3217. response->send();
  3218. return 0;
  3219. }
  3220. }
  3221. catch(IException* e)
  3222. {
  3223. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3224. }
  3225. return onGetNotFound(context, request, response, service);
  3226. }
  3227. bool isDeploymentTypeCompressed(const char *type)
  3228. {
  3229. if (type && *type)
  3230. return (0==strncmp(type, "compressed_", strlen("compressed_")));
  3231. return false;
  3232. }
  3233. const char *skipCompressedTypeQualifier(const char *type)
  3234. {
  3235. if (isDeploymentTypeCompressed(type))
  3236. type += strlen("compressed_");
  3237. return type;
  3238. }
  3239. void deployEclOrArchive(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  3240. {
  3241. NewWsWorkunit wu(context);
  3242. SCMStringBuffer wuid;
  3243. wu->getWuid(wuid);
  3244. wu->setAction(WUActionCompile);
  3245. StringBuffer name(req.getName());
  3246. if (!name.trim().length() && notEmpty(req.getFileName()))
  3247. splitFilename(req.getFileName(), NULL, NULL, &name, NULL);
  3248. if (name.length())
  3249. wu->setJobName(name.str());
  3250. if (req.getObject().length())
  3251. {
  3252. MemoryBuffer mb;
  3253. const MemoryBuffer *uncompressed = &req.getObject();
  3254. if (isDeploymentTypeCompressed(req.getObjType()))
  3255. {
  3256. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  3257. uncompressed = &mb;
  3258. }
  3259. StringBuffer text(uncompressed->length(), uncompressed->toByteArray());
  3260. wu.setQueryText(text.str());
  3261. }
  3262. if (req.getQueryMainDefinition())
  3263. wu.setQueryMain(req.getQueryMainDefinition());
  3264. if (req.getSnapshot())
  3265. wu->setSnapshot(req.getSnapshot());
  3266. if (!req.getResultLimit_isNull())
  3267. wu->setResultLimit(req.getResultLimit());
  3268. wu->commit();
  3269. wu.clear();
  3270. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), NULL, 0, true, false, false, NULL, NULL, &req.getDebugValues());
  3271. waitForWorkUnitToCompile(wuid.str(), req.getWait());
  3272. WsWuInfo winfo(context, wuid.str());
  3273. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  3274. winfo.getExceptions(resp.updateWorkunit(), WUINFO_All);
  3275. name.clear();
  3276. if (notEmpty(resp.updateWorkunit().getJobname()))
  3277. origValueChanged(req.getName(), resp.updateWorkunit().getJobname(), name, false);
  3278. if (name.length()) //non generated user specified name, so override #Workunit('name')
  3279. {
  3280. WorkunitUpdate wx(&winfo.cw->lock());
  3281. wx->setJobName(name.str());
  3282. resp.updateWorkunit().setJobname(name.str());
  3283. }
  3284. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  3285. }
  3286. StringBuffer &sharedObjectFileName(StringBuffer &filename, const char *name, const char *ext, unsigned copy)
  3287. {
  3288. filename.append((name && *name) ? name : "workunit");
  3289. if (copy)
  3290. filename.append('-').append(copy);
  3291. if (notEmpty(ext))
  3292. filename.append(ext);
  3293. return filename;
  3294. }
  3295. inline StringBuffer &buildFullDllPath(StringBuffer &dllpath, StringBuffer &dllname, const char *dir, const char *name, const char *ext, unsigned copy)
  3296. {
  3297. return addPathSepChar(dllpath.set(dir)).append(sharedObjectFileName(dllname, name, ext, copy));
  3298. }
  3299. void writeSharedObject(const char *srcpath, const MemoryBuffer &obj, const char *dir, StringBuffer &dllpath, StringBuffer &dllname)
  3300. {
  3301. StringBuffer name, ext;
  3302. if (srcpath && *srcpath)
  3303. splitFilename(srcpath, NULL, NULL, &name, &ext);
  3304. unsigned copy=0;
  3305. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), copy);
  3306. while (checkFileExists(dllpath.str()))
  3307. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), ++copy);
  3308. DBGLOG("Writing workunit dll: %s", dllpath.str());
  3309. Owned<IFile> f = createIFile(dllpath.str());
  3310. Owned<IFileIO> io = f->open(IFOcreate);
  3311. io->write(0, obj.length(), obj.toByteArray());
  3312. }
  3313. void CWsWorkunitsEx::deploySharedObject(IEspContext &context, StringBuffer &wuid, const char *filename, const char *cluster, const char *name, const MemoryBuffer &obj, const char *dir, const char *xml)
  3314. {
  3315. StringBuffer dllpath, dllname;
  3316. StringBuffer srcname(filename);
  3317. if (!srcname.length())
  3318. srcname.append(name).append(SharedObjectExtension);
  3319. writeSharedObject(srcname.str(), obj, dir, dllpath, dllname);
  3320. NewWsWorkunit wu(context);
  3321. StringBufferAdaptor isvWuid(wuid);
  3322. wu->getWuid(isvWuid);
  3323. wu->setClusterName(cluster);
  3324. wu->commit();
  3325. StringBuffer dllXML;
  3326. if (getWorkunitXMLFromFile(dllpath.str(), dllXML))
  3327. {
  3328. Owned<ILocalWorkUnit> embeddedWU = createLocalWorkUnit();
  3329. embeddedWU->loadXML(dllXML.str());
  3330. queryExtendedWU(wu)->copyWorkUnit(embeddedWU, true);
  3331. }
  3332. wu.associateDll(dllpath.str(), dllname.str());
  3333. if (name && *name)
  3334. wu->setJobName(name);
  3335. //clean slate, copy only select items from processed workunit xml
  3336. if (xml && *xml)
  3337. {
  3338. Owned<IPropertyTree> srcxml = createPTreeFromXMLString(xml);
  3339. if (srcxml->hasProp("@jobName"))
  3340. wu->setJobName(srcxml->queryProp("@jobName"));
  3341. if (srcxml->hasProp("@token"))
  3342. wu->setSecurityToken(srcxml->queryProp("@token"));
  3343. if (srcxml->hasProp("Query/Text"))
  3344. wu.setQueryText(srcxml->queryProp("Query/Text"));
  3345. }
  3346. wu->setState(WUStateCompiled);
  3347. wu->commit();
  3348. wu.clear();
  3349. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  3350. }
  3351. void CWsWorkunitsEx::deploySharedObject(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp, const char *dir, const char *xml)
  3352. {
  3353. if (isEmpty(req.getFileName()))
  3354. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File name required when deploying a shared object.");
  3355. const char *cluster = req.getCluster();
  3356. if (isEmpty(cluster))
  3357. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name required when deploying a shared object.");
  3358. const MemoryBuffer *uncompressed = &req.getObject();
  3359. MemoryBuffer mb;
  3360. if (isDeploymentTypeCompressed(req.getObjType()))
  3361. {
  3362. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  3363. uncompressed = &mb;
  3364. }
  3365. StringBuffer wuid;
  3366. deploySharedObject(context, wuid, req.getFileName(), cluster, req.getName(), *uncompressed, dir, xml);
  3367. WsWuInfo winfo(context, wuid.str());
  3368. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  3369. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  3370. }
  3371. bool CWsWorkunitsEx::onWUDeployWorkunit(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  3372. {
  3373. const char *type = skipCompressedTypeQualifier(req.getObjType());
  3374. try
  3375. {
  3376. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  3377. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  3378. if (notEmpty(req.getCluster()) && !isValidCluster(req.getCluster()))
  3379. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", req.getCluster());
  3380. if (!type || !*type)
  3381. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit unspecified object type.");
  3382. if (strieq(type, "archive")|| strieq(type, "ecl_text"))
  3383. deployEclOrArchive(context, req, resp);
  3384. else if (strieq(type, "shared_object"))
  3385. deploySharedObject(context, req, resp, queryDirectory.str());
  3386. else
  3387. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit '%s' unknown object type.", type);
  3388. }
  3389. catch(IException* e)
  3390. {
  3391. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3392. }
  3393. return true;
  3394. }
  3395. #ifdef _USE_ZLIB
  3396. void CWsWorkunitsEx::addProcessLogfile(IZZIPor* zipper, Owned<IConstWorkUnit> &cwu, WsWuInfo &winfo, const char * process, PointerArray &mbArr)
  3397. {
  3398. Owned<IPropertyTreeIterator> procs = cwu->getProcesses(process, NULL);
  3399. ForEach (*procs)
  3400. {
  3401. StringBuffer logSpec;
  3402. IPropertyTree& proc = procs->query();
  3403. proc.getProp("@log",logSpec);
  3404. if (!logSpec.length())
  3405. continue;
  3406. StringBuffer pid;
  3407. pid.appendf("%d",proc.getPropInt("@pid"));
  3408. MemoryBuffer * pMB = NULL;
  3409. try
  3410. {
  3411. pMB = new MemoryBuffer;
  3412. if (0 == stricmp(process, "EclAgent"))
  3413. winfo.getWorkunitEclAgentLog(logSpec.str(), pid.str(), *pMB);
  3414. else if (0 == stricmp(process, "Thor"))
  3415. winfo.getWorkunitThorLog(logSpec.str(), *pMB);
  3416. else
  3417. {
  3418. delete pMB;
  3419. return;
  3420. }
  3421. mbArr.append(pMB);
  3422. }
  3423. catch(IException *e)
  3424. {
  3425. StringBuffer s;
  3426. e->errorMessage(s);
  3427. pMB->append(s.str());
  3428. e->Release();
  3429. mbArr.append(pMB);
  3430. }
  3431. if (pMB && pMB->length())
  3432. {
  3433. const char * logName = logSpec.str();
  3434. for (const char * p=logSpec; *p; p++)
  3435. {
  3436. if (*p == '\\' || *p == '/')
  3437. logName = p+1;
  3438. }
  3439. zipper->addContentToZIP(pMB->length(), pMB->bufferBase(), (char*)logName, true);
  3440. }
  3441. }
  3442. }
  3443. #endif
  3444. bool CWsWorkunitsEx::onWUCreateZAPInfo(IEspContext &context, IEspWUCreateZAPInfoRequest &req, IEspWUCreateZAPInfoResponse &resp)
  3445. {
  3446. try
  3447. {
  3448. #ifndef _USE_ZLIB
  3449. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  3450. #else
  3451. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3452. Owned<IConstWorkUnit> cwu = factory->openWorkUnit(req.getWuid(), false);
  3453. if(!cwu.get())
  3454. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Cannot open workunit %s.", req.getWuid());
  3455. //Create output report file
  3456. StringBuffer zipFile;
  3457. StringBuffer userName;
  3458. if (context.queryUser())
  3459. userName.append(context.queryUser()->getName());
  3460. zipFile.append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".zip");
  3461. SCMStringBuffer temp;
  3462. StringBuffer sb;
  3463. sb.append("Workunit: ").append(cwu->getWuid(temp)).append("\r\n");
  3464. sb.append("User: ").append(cwu->getUser(temp).str()).append("\r\n");
  3465. sb.append("Build Version:").append(req.getBuildVersion()).append("\r\n");
  3466. sb.append("Cluster: ").append(cwu->getClusterName(temp).str()).append("\r\n");
  3467. if (req.getESPIPAddress())
  3468. sb.append("ESP: ").append(req.getESPIPAddress()).append("\r\n");
  3469. if (req.getThorIPAddress())
  3470. sb.append("Thor: ").append(req.getThorIPAddress()).append("\r\n");
  3471. //Exceptions/Warnings/Info
  3472. Owned<IConstWUExceptionIterator> exceptions = &cwu->getExceptions();
  3473. StringBuffer info, warn, err;
  3474. ForEach(*exceptions)
  3475. {
  3476. switch (exceptions->query().getSeverity())
  3477. {
  3478. case ExceptionSeverityInformation:
  3479. info.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  3480. break;
  3481. case ExceptionSeverityWarning:
  3482. warn.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  3483. break;
  3484. case ExceptionSeverityError:
  3485. err.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  3486. break;
  3487. }
  3488. }
  3489. if (err.length())
  3490. sb.append("Exceptions: ").append("\r\n").append(err);
  3491. if (warn.length())
  3492. sb.append("Warnings: ").append("\r\n").append(warn);
  3493. if (info.length())
  3494. sb.append("Information: ").append("\r\n").append(info);
  3495. //User provided Information
  3496. sb.append("Problem: ").append(req.getProblemDescription()).append("\r\n\r\n");
  3497. sb.append("What Changed: ").append(req.getWhatChanged()).append("\r\n\r\n");
  3498. sb.append("Timing: ").append(req.getWhereSlow()).append("\r\n\r\n");
  3499. //Zip all files together
  3500. {
  3501. IZZIPor* zipper = createZZIPor();
  3502. #ifdef _DEBUG
  3503. zipper->setTraceLevel(100);
  3504. #endif
  3505. StringBuffer fs;
  3506. //add report file to ZIP
  3507. fs.append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".txt");
  3508. zipper->addContentToZIP(sb.length(), (void*)sb.str(), (char*)fs.str(), false);
  3509. //add ECL query/archive to zip
  3510. Owned<IConstWUQuery> query = cwu->getQuery();
  3511. StringBuffer eclContents;//String buffers containing file contents must persist until ziptofile is called !
  3512. StringBuffer archiveContents;//String buffers containing file contents must persist until ziptofile is called !
  3513. if(query)
  3514. {
  3515. //Add archive if present
  3516. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  3517. ForEach(*iter)
  3518. {
  3519. IConstWUAssociatedFile & cur = iter->query();
  3520. SCMStringBuffer ssb;
  3521. cur.getDescription(ssb);
  3522. if (0 == stricmp(ssb.str(), "archive"))
  3523. {
  3524. cur.getName(ssb);
  3525. if (ssb.length())
  3526. {
  3527. fs.clear().append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".archive");
  3528. try
  3529. {
  3530. archiveContents.loadFile(ssb.str());
  3531. zipper->addContentToZIP(archiveContents.length(), (void*)archiveContents.str(), (char*)fs.str(), true);
  3532. }
  3533. catch (IException *E)
  3534. {
  3535. DBGLOG("Error accessing archive file %s", ssb.str());
  3536. E->Release();
  3537. }
  3538. break;
  3539. }
  3540. }
  3541. }
  3542. //Add Query
  3543. query->getQueryText(temp);
  3544. if (temp.length())
  3545. {
  3546. fs.clear().append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".ecl");
  3547. eclContents.append(temp.str());
  3548. zipper->addContentToZIP(eclContents.length(), (void*)eclContents.str(), (char*)fs.str(), true);
  3549. }
  3550. }
  3551. //Add logfiles to ZIP
  3552. WsWuInfo winfo(context, cwu);
  3553. PointerArray eclAgentLogs;//array of dynamically allocated MemoryBuffers
  3554. PointerArray thorLogs;
  3555. addProcessLogfile(zipper, cwu, winfo, "EclAgent", eclAgentLogs);
  3556. addProcessLogfile(zipper, cwu, winfo, "Thor", thorLogs);
  3557. //Add Workunit XML file
  3558. MemoryBuffer wuXmlMB;
  3559. winfo.getWorkunitXml(NULL, wuXmlMB);
  3560. fs.clear().append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".xml");
  3561. zipper->addContentToZIP(wuXmlMB.length(), (void*)wuXmlMB.toByteArray(), (char*)fs.str(), true);
  3562. //Write out ZIP file
  3563. zipper->zipToFile(zipFile.str());
  3564. for (aindex_t x=0; x<eclAgentLogs.length(); x++)
  3565. delete (MemoryBuffer*)eclAgentLogs.item(x);
  3566. for (aindex_t x=0; x<thorLogs.length(); x++)
  3567. delete (MemoryBuffer*)thorLogs.item(x);
  3568. }
  3569. //Download ZIP file to user
  3570. Owned<IFile> f = createIFile(zipFile.str());
  3571. Owned<IFileIO> io = f->open(IFOread);
  3572. MemoryBuffer mb;
  3573. void * data = mb.reserve((unsigned)io->size());
  3574. size32_t read = io->read(0, (unsigned)io->size(), data);
  3575. mb.setLength(read);
  3576. resp.setThefile(mb);
  3577. resp.setThefile_mimetype(HTTP_TYPE_OCTET_STREAM);
  3578. StringBuffer headerStr("attachment;filename=");
  3579. headerStr.append(zipFile.str());
  3580. context.addCustomerHeader("Content-disposition", headerStr.str());
  3581. io->close();
  3582. f->remove();
  3583. #endif
  3584. }
  3585. catch(IException* e)
  3586. {
  3587. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3588. }
  3589. return true;
  3590. }
  3591. bool CWsWorkunitsEx::onWUGetZAPInfo(IEspContext &context, IEspWUGetZAPInfoRequest &req, IEspWUGetZAPInfoResponse &resp)
  3592. {
  3593. try
  3594. {
  3595. StringBuffer wuid = req.getWUID();
  3596. WsWuHelpers::checkAndTrimWorkunit("WUGetZAPInfo", wuid);
  3597. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3598. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  3599. if(!cw)
  3600. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3601. StringBuffer EspIP, ThorIP;
  3602. resp.setWUID(wuid.str());
  3603. resp.setBuildVersion(getBuildVersion());
  3604. IpAddress ipaddr = queryHostIP();
  3605. ipaddr.getIpText(EspIP);
  3606. resp.setESPIPAddress(EspIP.str());
  3607. //Get Archive
  3608. Owned<IConstWUQuery> query = cw->getQuery();
  3609. if(query)
  3610. {
  3611. SCMStringBuffer queryText;
  3612. query->getQueryText(queryText);
  3613. if (queryText.length() && isArchiveQuery(queryText.str()))
  3614. resp.setArchive(queryText.str());
  3615. }
  3616. //Get Thor IP
  3617. BoolHash uniqueProcesses, uniqueThorIPs;
  3618. Owned<IStringIterator> thorInstances = cw->getProcesses("Thor");
  3619. ForEach (*thorInstances)
  3620. {
  3621. SCMStringBuffer processName;
  3622. thorInstances->str(processName);
  3623. if ((processName.length() < 1) || uniqueProcesses.getValue(processName.str()))
  3624. continue;
  3625. uniqueProcesses.setValue(processName.str(), true);
  3626. Owned<IStringIterator> thorLogs = cw->getLogs("Thor", processName.str());
  3627. ForEach (*thorLogs)
  3628. {
  3629. SCMStringBuffer logName;
  3630. thorLogs->str(logName);
  3631. if (!logName.length())
  3632. continue;
  3633. const char* thorIPPtr = NULL;
  3634. const char* ptr = logName.str();
  3635. while (ptr)
  3636. {
  3637. if (!thorIPPtr && (*ptr != '/'))
  3638. thorIPPtr = ptr;
  3639. else if (thorIPPtr && (*ptr == '/'))
  3640. break;
  3641. ptr++;
  3642. }
  3643. if (!thorIPPtr)
  3644. continue;
  3645. //Found a thor IP
  3646. if (ThorIP.length())
  3647. ThorIP.append(",");
  3648. if (!*ptr)
  3649. ThorIP.append(thorIPPtr);
  3650. else
  3651. ThorIP.append(ptr-thorIPPtr, thorIPPtr);
  3652. }
  3653. }
  3654. if (ThorIP.length())
  3655. resp.setThorIPAddress(ThorIP.str());
  3656. }
  3657. catch(IException* e)
  3658. {
  3659. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3660. }
  3661. return true;
  3662. }
  3663. bool CWsWorkunitsEx::onWUCheckFeatures(IEspContext &context, IEspWUCheckFeaturesRequest &req, IEspWUCheckFeaturesResponse &resp)
  3664. {
  3665. resp.setBuildVersionMajor(BUILD_VERSION_MAJOR);
  3666. resp.setBuildVersionMinor(BUILD_VERSION_MINOR);
  3667. resp.setBuildVersionPoint(BUILD_VERSION_POINT);
  3668. resp.setMaxRequestEntityLength(maxRequestEntityLength);
  3669. resp.updateDeployment().setUseCompression(true);
  3670. return true;
  3671. }