123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909 |
- /*##############################################################################
- HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ############################################################################## */
- #include "ws_workunitsService.hpp"
- #include "ws_fs.hpp"
- #include "jlib.hpp"
- #include "daclient.hpp"
- #include "dalienv.hpp"
- #include "dadfs.hpp"
- #include "daaudit.hpp"
- #include "exception_util.hpp"
- #include "wujobq.hpp"
- #include "eventqueue.hpp"
- #include "fileview.hpp"
- #include "hqlerror.hpp"
- #include "sacmd.hpp"
- #include "wuwebview.hpp"
- #include "portlist.h"
- #include "dllserver.hpp"
- #include "schedulectrl.hpp"
- #include "scheduleread.hpp"
- #include "dadfs.hpp"
- #include "dfuwu.hpp"
- #include "thorplugin.hpp"
- #include "roxiecontrol.hpp"
- #include "package.h"
- #ifdef _USE_ZLIB
- #include "zcrypt.hpp"
- #endif
- #define ESP_WORKUNIT_DIR "workunits/"
- class ExecuteExistingQueryInfo
- {
- public:
- ExecuteExistingQueryInfo(IConstWorkUnit *cw)
- {
- SCMStringBuffer isv;
- cw->getJobName(isv);
- const char *name = isv.str();
- const char *div = strchr(name, '.');
- if (div)
- {
- queryset.set(name, div-name);
- query.set(div+1);
- }
- }
- public:
- StringAttr queryset;
- StringAttr query;
- };
- typedef enum _WuActionType
- {
- ActionDelete=0,
- ActionProtect,
- ActionAbort,
- ActionRestore,
- ActionEventSchedule,
- ActionEventDeschedule,
- ActionChangeState,
- ActionPause,
- ActionPauseNow,
- ActionResume,
- ActionUnknown
- } WsWuActionType;
- void setActionResult(const char* wuid, int action, const char* result, StringBuffer& strAction, IArrayOf<IConstWUActionResult>* results)
- {
- if (!results || !wuid || !*wuid || !result || !*result)
- return;
- switch(action)
- {
- case ActionDelete:
- {
- strAction = "Delete";
- break;
- }
- case ActionProtect:
- {
- strAction = "Protect";
- break;
- }
- case ActionAbort:
- {
- strAction = "Abort";
- break;
- }
- case ActionRestore:
- {
- strAction = "Restore";
- break;
- }
- case ActionEventSchedule:
- {
- strAction = "EventSchedule";
- break;
- }
- case ActionEventDeschedule:
- {
- strAction = "EventDeschedule";
- break;
- }
- case ActionChangeState:
- {
- strAction = "ChangeState";
- break;
- }
- case ActionPause:
- {
- strAction = "Pause";
- break;
- }
- case ActionPauseNow:
- {
- strAction = "PauseNow";
- break;
- }
- case ActionResume:
- {
- strAction = "Resume";
- break;
- }
- default:
- {
- strAction = "Unknown";
- }
- }
- Owned<IEspWUActionResult> res = createWUActionResult("", "");
- res->setWuid(wuid);
- res->setAction(strAction.str());
- res->setResult(result);
- results->append(*res.getClear());
- }
- bool doAction(IEspContext& context, StringArray& wuids, int action, IProperties* params, IArrayOf<IConstWUActionResult>* results)
- {
- if (!wuids.length())
- return true;
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- bool bAllSuccess = true;
- for(aindex_t i=0; i<wuids.length();i++)
- {
- StringBuffer strAction;
- StringBuffer wuidStr = wuids.item(i);
- const char* wuid = wuidStr.trim().str();
- if (isEmpty(wuid))
- {
- WARNLOG("Empty Workunit ID");
- continue;
- }
- try
- {
- if (!looksLikeAWuid(wuid))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
- if ((action == ActionRestore) || (action == ActionEventDeschedule))
- {
- switch(action)
- {
- case ActionRestore:
- {
- SocketEndpoint ep;
- if (params->hasProp("sashaServerIP"))
- ep.set(params->queryProp("sashaServerIP"), params->getPropInt("sashaServerPort"));
- else
- getSashaNode(ep);
- Owned<ISashaCommand> cmd = createSashaCommand();
- cmd->setAction(SCA_RESTORE);
- cmd->addId(wuid);
- Owned<INode> node = createINode(ep);
- if (!node)
- throw MakeStringException(ECLWATCH_INODE_NOT_FOUND,"INode not found.");
- StringBuffer s;
- if (!cmd->send(node, 1*60*1000))
- throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to Archive server at %s.", ep.getUrlStr(s).str());
- if (cmd->numIds()==0)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Could not Archive/restore %s",wuid);
- StringBuffer reply;
- cmd->getId(0,reply);
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
- ensureWsWorkunitAccess(context, wuid, SecAccess_Write);
- break;
- }
- case ActionEventDeschedule:
- if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Full, false)
- || !context.validateFeatureAccess(OTHERS_WU_ACCESS, SecAccess_Full, false))
- ensureWsWorkunitAccess(context, wuid, SecAccess_Full);
- descheduleWorkunit(wuid);
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
- break;
- }
- }
- else
- {
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
- if ((action == ActionDelete) && (cw->getState() == WUStateWait))
- throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,"Cannot delete a workunit which is in a 'Wait' status.");
- switch(action)
- {
- case ActionPause:
- {
- ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
- WorkunitUpdate wu(&cw->lock());
- wu->setAction(WUActionPause);
- break;
- }
- case ActionPauseNow:
- {
- ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
- WorkunitUpdate wu(&cw->lock());
- wu->setAction(WUActionPauseNow);
- break;
- }
- case ActionResume:
- {
- ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
- WorkunitUpdate wu(&cw->lock());
- wu->setAction(WUActionResume);
- break;
- }
- case ActionDelete:
- ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
- {
- int state = cw->getState();
- switch (state)
- {
- case WUStateWait:
- case WUStateAborted:
- case WUStateCompleted:
- case WUStateFailed:
- case WUStateArchived:
- case WUStateCompiled:
- case WUStateUploadingFiles:
- break;
- default:
- {
- WorkunitUpdate wu(&cw->lock());
- wu->setState(WUStateFailed);
- }
- }
- cw.clear();
- factory->deleteWorkUnit(wuid);
- AuditSystemAccess(context.queryUserId(), true, "Deleted %s", wuid);
- }
- break;
- case ActionAbort:
- ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
- {
- if (cw->getState() == WUStateWait)
- {
- WorkunitUpdate wu(&cw->lock());
- wu->deschedule();
- wu->setState(WUStateAborted);
- }
- else
- secAbortWorkUnit(wuid, *context.querySecManager(), *context.queryUser());
- AuditSystemAccess(context.queryUserId(), true, "Aborted %s", wuid);
- }
- break;
- case ActionProtect:
- cw->protect(!params || params->getPropBool("Protect",true));
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
- break;
- case ActionChangeState:
- {
- if (params)
- {
- WUState state = (WUState) params->getPropInt("State");
- if (state > WUStateUnknown && state < WUStateSize)
- {
- WorkunitUpdate wu(&cw->lock());
- wu->setState(state);
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
- }
- }
- }
- break;
- case ActionEventSchedule:
- {
- WorkunitUpdate wu(&cw->lock());
- wu->schedule();
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
- }
- break;
- }
- }
- setActionResult(wuid, action, "Success", strAction, results);
- }
- catch (IException *e)
- {
- bAllSuccess = false;
- StringBuffer eMsg;
- StringBuffer failedMsg("Failed: ");
- setActionResult(wuid, action, failedMsg.append(e->errorMessage(eMsg)).str(), strAction, results);
- WARNLOG("Failed to %s for workunit: %s, %s", strAction.str(), wuid, eMsg.str());
- AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction.str(), wuid);
- e->Release();
- continue;
- }
- catch (...)
- {
- bAllSuccess = false;
- StringBuffer failedMsg;
- failedMsg.appendf("Unknown exception");
- setActionResult(wuid, action, failedMsg.str(), strAction, results);
- WARNLOG("Failed to %s for workunit: %s, %s", strAction.str(), wuid, failedMsg.str());
- AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction.str(), wuid);
- continue;
- }
- }
- int timeToWait = 0;
- if (params)
- timeToWait = params->getPropInt("BlockTillFinishTimer");
- if (timeToWait != 0)
- {
- for(aindex_t i=0; i<wuids.length();i++)
- {
- const char* wuid=wuids.item(i);
- if (isEmpty(wuid))
- continue;
- waitForWorkUnitToComplete(wuid, timeToWait);
- }
- }
- return bAllSuccess;
- }
- MapStringTo<int> wuActionTable;
- void CWsWorkunitsEx::init(IPropertyTree *cfg, const char *process, const char *service)
- {
- if (!daliClientActive())
- {
- ERRLOG("No Dali Connection Active.");
- throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
- }
- setPasswordsFromSDS();
- DBGLOG("Initializing %s service [process = %s]", service, process);
- refreshValidClusters();
- daliServers.set(cfg->queryProp("Software/EspProcess/@daliServers"));
- wuActionTable.setValue("delete", ActionDelete);
- wuActionTable.setValue("abort", ActionAbort);
- wuActionTable.setValue("pausenow", ActionPauseNow);
- wuActionTable.setValue("pause", ActionPause);
- wuActionTable.setValue("resume", ActionResume);
- wuActionTable.setValue("protect", ActionProtect);
- wuActionTable.setValue("unprotect", ActionProtect);
- wuActionTable.setValue("restore", ActionRestore);
- wuActionTable.setValue("reschedule", ActionEventSchedule);
- wuActionTable.setValue("deschedule", ActionEventDeschedule);
- wuActionTable.setValue("settofailed", ActionChangeState);
- awusCacheMinutes = AWUS_CACHE_MIN_DEFAULT;
- VStringBuffer xpath("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/AWUsCacheMinutes", process, service);
- cfg->getPropInt(xpath.str(), awusCacheMinutes);
- xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@netAddress", process, service);
- if (cfg->hasProp(xpath.str()))
- {
- sashaServerIp.set(cfg->queryProp(xpath.str()));
- xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@port", process, service);
- sashaServerPort = cfg->getPropInt(xpath.str(), DEFAULT_SASHA_PORT);
- }
- directories.set(cfg->queryPropTree("Software/Directories"));
- const char *name = cfg->queryProp("Software/EspProcess/@name");
- getConfigurationDirectory(directories, "query", "esp", name ? name : "esp", queryDirectory);
- recursiveCreateDirectory(queryDirectory.str());
- dataCache.setown(new DataCache(DATA_SIZE));
- archivedWuCache.setown(new ArchivedWuCache(AWUS_CACHE_SIZE));
- //Create a folder for temporarily holding gzip files by WUResultBin()
- Owned<IFile> tmpdir = createIFile(TEMPZIPDIR);
- if(!tmpdir->exists())
- tmpdir->createDirectory();
- recursiveCreateDirectory(ESP_WORKUNIT_DIR);
- m_sched.start();
- }
- void CWsWorkunitsEx::refreshValidClusters()
- {
- validClusters.kill();
- Owned<IStringIterator> it = getTargetClusters(NULL, NULL);
- ForEach(*it)
- {
- SCMStringBuffer s;
- IStringVal &val = it->str(s);
- if (!validClusters.getValue(val.str()))
- validClusters.setValue(val.str(), true);
- }
- }
- bool CWsWorkunitsEx::isValidCluster(const char *cluster)
- {
- if (!cluster || !*cluster)
- return false;
- CriticalBlock block(crit);
- if (validClusters.getValue(cluster))
- return true;
- if (validateTargetClusterName(cluster))
- {
- refreshValidClusters();
- return true;
- }
- return false;
- }
- bool CWsWorkunitsEx::onWUCreate(IEspContext &context, IEspWUCreateRequest &req, IEspWUCreateResponse &resp)
- {
- try
- {
- if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
- throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
- NewWsWorkunit wu(context);
- SCMStringBuffer wuid;
- resp.updateWorkunit().setWuid(wu->getWuid(wuid).str());
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- static bool origValueChanged(const char *newValue, const char *origValue, StringBuffer &s, bool nillable=true)
- {
- if (!nillable && isEmpty(newValue))
- return false;
- if(newValue && origValue)
- {
- if (!streq(origValue, newValue))
- {
- s.append(newValue).trim();
- return true;
- }
- return false;
- }
- if (newValue)
- {
- s.append(newValue).trim();
- return true;
- }
- return (origValue!=NULL);
- }
- bool CWsWorkunitsEx::onWUUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUUpdate", wuid);
- ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- if(req.getProtected() != req.getProtectedOrig())
- {
- cw->protect(req.getProtected());
- cw.clear();
- cw.setown(factory->openWorkUnit(wuid.str(), false));
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- }
- if ((req.getState() == WUStateRunning)||(req.getState() == WUStateDebugPaused)||(req.getState() == WUStateDebugRunning))
- {
- WsWuInfo winfo(context, cw);
- winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
- resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
- return true;
- }
- WorkunitUpdate wu(&cw->lock());
- if(!req.getState_isNull() && (req.getStateOrig_isNull() || req.getState() != req.getStateOrig()))
- {
- if (!req.getStateOrig_isNull() && cw->getState() != (WUState) req.getStateOrig())
- 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());
- WUState state = (WUState) req.getState();
- if(state < WUStateSize)
- wu->setState(state);
- }
- StringBuffer s;
- if (origValueChanged(req.getJobname(), req.getJobnameOrig(), s))
- wu->setJobName(s.trim().str());
- if (origValueChanged(req.getDescription(), req.getDescriptionOrig(), s.clear()))
- wu->setDebugValue("description", (req.getDescription() && *req.getDescription()) ? s.trim().str() : NULL, true);
- double version = context.getClientVersion();
- if (version > 1.04)
- {
- if (origValueChanged(req.getClusterSelection(), req.getClusterOrig(), s.clear(), false))
- {
- if (!isValidCluster(s.str()))
- throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", s.str());
- if (req.getState() == WUStateBlocked)
- switchWorkUnitQueue(wu.get(), s.str());
- else if ((req.getState() != WUStateSubmitted) && (req.getState() != WUStateRunning) && (req.getState() != WUStateDebugPaused) && (req.getState() != WUStateDebugRunning))
- wu->setClusterName(s.str());
- }
- }
- WsWuHelpers::setXmlParameters(wu, req.getXmlParams(), (req.getAction()==WUActionExecuteExisting));
- if (notEmpty(req.getQueryText()))
- {
- Owned<IWUQuery> query=wu->updateQuery();
- query->setQueryText(req.getQueryText());
- }
- if (version > 1.34 && notEmpty(req.getQueryMainDefinition()))
- {
- Owned<IWUQuery> query=wu->updateQuery();
- query->setQueryMainDefinition(req.getQueryMainDefinition());
- }
- if (!req.getResultLimit_isNull())
- wu->setResultLimit(req.getResultLimit());
- if (!req.getAction_isNull())
- {
- WUAction action = (WUAction) req.getAction();
- if(action < WUActionSize)
- wu->setAction(action);
- }
- if (!req.getPriorityClass_isNull())
- {
- WUPriorityClass priority = (WUPriorityClass) req.getPriorityClass();
- if(priority<PriorityClassSize)
- wu->setPriority(priority);
- }
- if (!req.getPriorityLevel_isNull())
- wu->setPriorityLevel(req.getPriorityLevel());
- if (origValueChanged(req.getScope(), req.getScopeOrig(), s.clear(), false))
- wu->setWuScope(s.str());
- ForEachItemIn(di, req.getDebugValues())
- {
- IConstDebugValue& item = req.getDebugValues().item(di);
- if (notEmpty(item.getName()))
- wu->setDebugValue(item.getName(), item.getValue(), true);
- }
- ForEachItemIn(ai, req.getApplicationValues())
- {
- IConstApplicationValue& item=req.getApplicationValues().item(ai);
- if(notEmpty(item.getApplication()) && notEmpty(item.getName()))
- wu->setApplicationValue(item.getApplication(), item.getName(), item.getValue(), true);
- }
- wu->commit();
- wu.clear();
- WsWuInfo winfo(context, cw);
- winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
- StringBuffer thorSlaveIP;
- if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
- thorSlaveIP = req.getThorSlaveIP();
- if (thorSlaveIP.length() > 0)
- {
- StringBuffer url;
- url.appendf("/WsWorkunits/WUInfo?Wuid=%s&ThorSlaveIP=%s", wuid.str(), thorSlaveIP.str());
- resp.setRedirectUrl(url.str());
- }
- else
- resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUCreateAndUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
- {
- try
- {
- if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
- throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
- NewWsWorkunit wu(context);
- SCMStringBuffer wuid;
- wu->getWuid(wuid);
- req.setWuid(wuid.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return onWUUpdate(context, req, resp);
- }
- static inline StringBuffer &appendUrlParameter(StringBuffer &url, const char *name, const char *value, bool &first)
- {
- if (notEmpty(value))
- {
- url.append(first ? '?' : '&').append(name).append('=').append(value);
- first=false;
- }
- return url;
- }
- bool CWsWorkunitsEx::onWUAction(IEspContext &context, IEspWUActionRequest &req, IEspWUActionResponse &resp)
- {
- try
- {
- StringBuffer sAction(req.getActionType());
- if (!sAction.length())
- throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined.");
- int *action=wuActionTable.getValue(sAction.toLowerCase().str());
- if (!action)
- throw MakeStringException(ECLWATCH_INVALID_INPUT,"Invalid Action '%s'.", sAction.str());
- Owned<IProperties> params = createProperties(true);
- params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
- if (*action==ActionProtect)
- params->setProp("Protect", streq(sAction.str(), "protect"));
- if (*action==ActionChangeState && streq(sAction.str(), "settofailed"))
- params->setProp("State",4);
- if ((*action==ActionRestore) && !sashaServerIp.isEmpty())
- {
- params->setProp("sashaServerIP", sashaServerIp.get());
- params->setProp("sashaServerPort", sashaServerPort);
- }
- IArrayOf<IConstWUActionResult> results;
- if (doAction(context, req.getWuids(), *action, params, &results) && *action!=ActionDelete && checkRedirect(context))
- {
- StringBuffer redirect;
- if(req.getPageFrom() && strieq(req.getPageFrom(), "wuid"))
- redirect.append("/WsWorkunits/WUInfo?Wuid=").append(req.getWuids().item(0));
- else if (req.getPageFrom() && strieq(req.getPageFrom(), "scheduler"))
- {
- redirect.set("/WsWorkunits/WUShowScheduled");
- bool first=true;
- appendUrlParameter(redirect, "Cluster", req.getEventServer(), first);
- appendUrlParameter(redirect, "EventName", req.getEventName(), first);
- }
- else
- {
- redirect.append("/WsWorkunits/WUQuery");
- bool first=true;
- appendUrlParameter(redirect, "PageSize", req.getPageSize(), first);
- appendUrlParameter(redirect, "PageStartFrom", req.getCurrentPage(), first);
- appendUrlParameter(redirect, "Sortby", req.getSortby(), first);
- appendUrlParameter(redirect, "Descending", req.getDescending() ? "1" : "0", first);
- appendUrlParameter(redirect, "State", req.getState(), first);
- appendUrlParameter(redirect, "Cluster", req.getCluster(), first);
- appendUrlParameter(redirect, "Owner", req.getOwner(), first);
- appendUrlParameter(redirect, "StartDate", req.getStartDate(), first);
- appendUrlParameter(redirect, "EndDate", req.getEndDate(), first);
- appendUrlParameter(redirect, "ECL", req.getECL(), first);
- appendUrlParameter(redirect, "Jobname", req.getJobname(), first);
- }
- resp.setRedirectUrl(redirect.str());
- }
- else
- resp.setActionResults(results);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUDelete(IEspContext &context, IEspWUDeleteRequest &req, IEspWUDeleteResponse &resp)
- {
- try
- {
- IArrayOf<IConstWUActionResult> results;
- Owned<IProperties> params = createProperties(true);
- params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
- if (!doAction(context,req.getWuids(), ActionDelete, params, &results))
- resp.setActionResults(results);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUAbort(IEspContext &context, IEspWUAbortRequest &req, IEspWUAbortResponse &resp)
- {
- try
- {
- IArrayOf<IConstWUActionResult> results;
- Owned<IProperties> params = createProperties(true);
- params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
- if (!doAction(context,req.getWuids(), ActionAbort, params, &results))
- resp.setActionResults(results);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUProtect(IEspContext &context, IEspWUProtectRequest &req, IEspWUProtectResponse &resp)\
- {
- try
- {
- IArrayOf<IConstWUActionResult> results;
- Owned<IProperties> params(createProperties(true));
- params->setProp("Protect", req.getProtect());
- params->setProp("BlockTillFinishTimer", 0);
- if (!doAction(context,req.getWuids(), ActionProtect, params, &results))
- resp.setActionResults(results);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUResubmit(IEspContext &context, IEspWUResubmitRequest &req, IEspWUResubmitResponse &resp)
- {
- try
- {
- Owned<IMultiException> me = MakeMultiException();
- SCMStringBuffer wuid;
- StringArray wuids;
- double version = context.getClientVersion();
- IArrayOf<IEspResubmittedWU> resubmittedWUs;
- for(aindex_t i=0; i<req.getWuids().length();i++)
- {
- StringBuffer requestWuid = req.getWuids().item(i);
- WsWuHelpers::checkAndTrimWorkunit("WUResubmit", requestWuid);
- ensureWsWorkunitAccess(context, requestWuid.str(), SecAccess_Write);
- wuid.set(requestWuid.str());
- try
- {
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- if(req.getCloneWorkunit() || req.getRecompile())
- {
- Owned<IConstWorkUnit> src(factory->openWorkUnit(wuid.str(), false));
- NewWsWorkunit wu(factory, context);
- wu->getWuid(wuid);
- queryExtendedWU(wu)->copyWorkUnit(src, false);
- SCMStringBuffer token;
- wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
- }
- wuids.append(wuid.str());
- Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str(), false));
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- //Dont allow resubmit of someone else's workunit
- if (context.querySecManager())
- {
- IUserDescriptor * owner = cw->queryUserDescriptor();
- if (!owner)
- throw MakeStringException(ECLWATCH_CANNOT_SUBMIT_WORKUNIT,"Workunit User Descriptor missing on %s", wuid.str());
- StringBuffer ownerUserName;
- owner->getUserName(ownerUserName);
- if (strcmp(context.queryUser()->getName(), ownerUserName.str()))
- throw MakeStringException(ECLWATCH_CANNOT_SUBMIT_WORKUNIT,"Cannot resubmit another user's workunit %s.", wuid.str());
- }
- WsWuHelpers::submitWsWorkunit(context, cw, NULL, NULL, 0, req.getRecompile(), req.getResetWorkflow(), false);
- if (version < 1.40)
- continue;
- Owned<IEspResubmittedWU> resubmittedWU = createResubmittedWU();
- resubmittedWU->setWUID(wuid.str());
- if (!streq(requestWuid.str(), wuid.str()))
- resubmittedWU->setParentWUID(requestWuid.str());
- resubmittedWUs.append(*resubmittedWU.getClear());
- }
- catch (IException *E)
- {
- me->append(*E);
- }
- catch (...)
- {
- me->append(*MakeStringException(0,"Unknown exception submitting %s",wuid.str()));
- }
- }
- if(me->ordinality())
- throw me.getLink();
- int timeToWait = req.getBlockTillFinishTimer();
- if (timeToWait != 0)
- {
- for(aindex_t i=0; i<wuids.length(); i++)
- waitForWorkUnitToComplete(wuids.item(i), timeToWait);
- }
- if (version >= 1.40)
- resp.setWUs(resubmittedWUs);
- if(wuids.length()==1)
- {
- resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuids.item(0)));
- }
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUPushEvent(IEspContext &context, IEspWUPushEventRequest &req, IEspWUPushEventResponse &resp)
- {
- try
- {
- const char *name = req.getEventName();
- const char *text = req.getEventText();
- const char *target = NULL;
- if (notEmpty(name) && notEmpty(text))
- {
- Owned<IScheduleEventPusher> pusher(getScheduleEventPusher());
- pusher->push(name, text, target);
- StringBuffer redirect("/WsWorkunits/WUShowScheduled");
- bool first=true;
- appendUrlParameter(redirect, "PushEventName", name, first);
- appendUrlParameter(redirect, "PushEventText", text, first);
- resp.setRedirectUrl(redirect.str());
- return true;
- }
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return false;
- }
- bool CWsWorkunitsEx::onWUSchedule(IEspContext &context, IEspWUScheduleRequest &req, IEspWUScheduleResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUSchedule", wuid);
- const char* cluster = req.getCluster();
- if (isEmpty(cluster))
- throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
- if (!isValidCluster(cluster))
- throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
- ensureWsWorkunitAccess(context, *wu.get(), SecAccess_Write);
- switch(wu->getState())
- {
- case WUStateDebugPaused:
- case WUStateDebugRunning:
- case WUStateRunning:
- case WUStateAborting:
- case WUStateBlocked:
- {
- SCMStringBuffer descr;
- throw MakeStringException(ECLWATCH_CANNOT_SCHEDULE_WORKUNIT, "Cannot schedule the workunit. Workunit state is '%s'.", wu->getStateDesc(descr).str());
- }
- }
- wu->clearExceptions();
- wu->setClusterName(cluster);
- if (notEmpty(req.getWhen()))
- {
- WsWuDateTime dt;
- dt.setString(req.getWhen());
- wu->setTimeScheduled(dt);
- }
- if(notEmpty(req.getSnapshot()))
- wu->setSnapshot(req.getSnapshot());
- wu->setState(WUStateScheduled);
- if (req.getMaxRunTime())
- wu->setDebugValueInt("maxRunTime", req.getMaxRunTime(), true);
- SCMStringBuffer token;
- wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
- AuditSystemAccess(context.queryUserId(), true, "Scheduled %s", wuid.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUSubmit(IEspContext &context, IEspWUSubmitRequest &req, IEspWUSubmitResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUSubmit", wuid);
- const char *cluster = req.getCluster();
- if (isEmpty(cluster))
- throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
- if (!isValidCluster(cluster))
- throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- if (cw->getAction()==WUActionExecuteExisting)
- {
- ExecuteExistingQueryInfo info(cw);
- if (info.queryset.isEmpty() || info.query.isEmpty())
- {
- WorkunitUpdate wu(&cw->lock());
- throw WsWuHelpers::noteException(wu, MakeStringException(ECLWATCH_INVALID_INPUT,"Queryset and/or query not specified"));
- }
- WsWuHelpers::runWsWuQuery(context, cw, info.queryset.sget(), info.query.sget(), cluster, NULL);
- }
- else
- WsWuHelpers::submitWsWorkunit(context, cw, cluster, req.getSnapshot(), req.getMaxRunTime(), true, false, false);
- if (req.getBlockTillFinishTimer() != 0)
- waitForWorkUnitToComplete(wuid.str(), req.getBlockTillFinishTimer());
- resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWURun(IEspContext &context, IEspWURunRequest &req, IEspWURunResponse &resp)
- {
- try
- {
- const char *cluster = req.getCluster();
- if (notEmpty(cluster) && !isValidCluster(cluster))
- throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
- StringBuffer wuidStr = req.getWuid();
- const char* runWuid = wuidStr.trim().str();
- StringBuffer wuid;
- if (runWuid && *runWuid)
- {
- if (!looksLikeAWuid(runWuid))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", runWuid);
- if (req.getCloneWorkunit())
- WsWuHelpers::runWsWorkunit(context, wuid, runWuid, cluster, req.getInput(), &req.getVariables(), &req.getDebugValues());
- else
- {
- WsWuHelpers::submitWsWorkunit(context, runWuid, cluster, NULL, 0, false, true, true, req.getInput(), &req.getVariables(), &req.getDebugValues());
- wuid.set(runWuid);
- }
- }
- else if (notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
- WsWuHelpers::runWsWuQuery(context, wuid, req.getQuerySet(), req.getQuery(), cluster, req.getInput());
- else
- throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
- int timeToWait = req.getWait();
- if (timeToWait != 0)
- waitForWorkUnitToComplete(wuid.str(), timeToWait);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if (!cw)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.", wuid.str());
- SCMStringBuffer stateDesc;
- resp.setState(cw->getStateDesc(stateDesc).str());
- resp.setWuid(wuid.str());
- switch (cw->getState())
- {
- case WUStateCompleted:
- case WUStateFailed:
- case WUStateUnknown:
- {
- SCMStringBuffer result;
- unsigned flags = WorkUnitXML_SeverityTags;
- if (req.getNoRootTag())
- flags |= WorkUnitXML_NoRoot;
- getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags);
- resp.setResults(result.str());
- break;
- }
- default:
- break;
- }
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUWaitCompiled(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUWaitCompiled", wuid);
- secWaitForWorkUnitToCompile(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait());
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- resp.setStateID(cw->getState());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUWaitComplete(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUWaitComplete", wuid);
- resp.setStateID(secWaitForWorkUnitToComplete(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait(), req.getReturnOnWait()));
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUCDebug(IEspContext &context, IEspWUDebugRequest &req, IEspWUDebugResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUCDebug", wuid);
- StringBuffer result;
- secDebugWorkunit(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getCommand(), result);
- resp.setResult(result);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUSyntaxCheckECL(IEspContext &context, IEspWUSyntaxCheckRequest &req, IEspWUSyntaxCheckResponse &resp)
- {
- try
- {
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- NewWsWorkunit wu(factory, context);
- wu->setAction(WUActionCheck);
- if(notEmpty(req.getModuleName()) && notEmpty(req.getAttributeName()))
- {
- wu->setApplicationValue("SyntaxCheck", "ModuleName", req.getModuleName(), true);
- wu->setApplicationValue("SyntaxCheck", "AttributeName", req.getAttributeName(), true);
- }
- ForEachItemIn(di, req.getDebugValues())
- {
- IConstDebugValue& item=req.getDebugValues().item(di);
- if(notEmpty(item.getName()))
- wu->setDebugValue(item.getName(), item.getValue(), true);
- }
- wu.setQueryText(req.getECL());
- SCMStringBuffer wuid;
- wu->getWuid(wuid);
- wu->commit();
- wu.clear();
- WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
- waitForWorkUnitToComplete(wuid.str(), req.getTimeToWait());
- Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str(), false));
- WsWUExceptions errors(*cw);
- resp.setErrors(errors);
- cw.clear();
- factory->deleteWorkUnit(wuid.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUCompileECL(IEspContext &context, IEspWUCompileECLRequest &req, IEspWUCompileECLResponse &resp)
- {
- try
- {
- ensureWsCreateWorkunitAccess(context);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- NewWsWorkunit wu(factory, context);
- if(req.getIncludeComplexity())
- {
- wu->setAction(WUActionCompile);
- wu->setDebugValueInt("calculateComplexity",1,true);
- }
- else
- wu->setAction(WUActionCheck);
- if(req.getModuleName() && req.getAttributeName())
- {
- wu->setApplicationValue("SyntaxCheck","ModuleName",req.getModuleName(),true);
- wu->setApplicationValue("SyntaxCheck","AttributeName",req.getAttributeName(),true);
- }
- if(req.getIncludeDependencies())
- wu->setApplicationValueInt("SyntaxCheck","IncludeDependencies",1,true);
- wu.setQueryText(req.getECL());
- SCMStringBuffer wuid;
- wu->getWuid(wuid);
- wu.clear();
- WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
- waitForWorkUnitToComplete(wuid.str(),req.getTimeToWait());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- SCMStringBuffer s;
- cw->getDebugValue("__Calculated__Complexity__",s);
- if(s.length())
- resp.setComplexity(s.str());
- WsWUExceptions errors(*cw);
- resp.setErrors(errors);
- if(!errors.ErrCount())
- {
- IArrayOf<IEspWUECLAttribute> dependencies;
- for(unsigned count=1;;count++)
- {
- SCMStringBuffer xml;
- cw->getApplicationValue("SyntaxCheck",StringBuffer("Dependency").append(count).str(),xml);
- if(!xml.length())
- break;
- Owned<IPropertyTree> dep=createPTreeFromXMLString(xml.str(), ipt_caseInsensitive);
- if(!dep)
- continue;
- Owned<IEspWUECLAttribute> att = createWUECLAttribute("","");
- att->setModuleName(dep->queryProp("@module"));
- att->setAttributeName(dep->queryProp("@name"));
- int flags = dep->getPropInt("@flags",0);
- if(flags & ob_locked)
- {
- if(flags & ob_lockedself)
- att->setIsCheckedOut(true);
- else
- att->setIsLocked(true);
- }
- if(flags & ob_sandbox)
- att->setIsSandbox(true);
- if(flags & ob_orphaned)
- att->setIsOrphaned(true);
- dependencies.append(*att.getLink());
- }
- resp.setDependencies(dependencies);
- }
- cw.clear();
- factory->deleteWorkUnit(wuid.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUGetDependancyTrees(IEspContext& context, IEspWUGetDependancyTreesRequest& req, IEspWUGetDependancyTreesResponse& resp)
- {
- try
- {
- DBGLOG("WUGetDependancyTrees");
- unsigned int timeMilliSec = 500;
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- NewWsWorkunit wu(factory, context);
- wu->setAction(WUActionCheck);
- if (notEmpty(req.getCluster()))
- wu->setClusterName(req.getCluster());
- if (notEmpty(req.getSnapshot()))
- wu->setSnapshot(req.getSnapshot());
- wu->setDebugValue("gatherDependenciesSelection",notEmpty(req.getItems()) ? req.getItems() : NULL,true);
- if (context.getClientVersion() > 1.12)
- {
- wu->setDebugValueInt("gatherDependencies", 1, true);
- const char *timeout = req.getTimeoutMilliSec();
- if (notEmpty(timeout))
- {
- const char *finger = timeout;
- while (*finger)
- {
- if (!isdigit(*finger++))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "Incorrect timeout value");
- }
- timeMilliSec = atol(timeout);
- }
- }
- SCMStringBuffer wuid;
- wu->getWuid(wuid);
- wu->commit();
- wu.clear();
- ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
- WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
- int state = waitForWorkUnitToComplete(wuid.str(), timeMilliSec);
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- WsWUExceptions errors(*cw);
- resp.setErrors(errors);
- MemoryBuffer temp;
- MemoryBuffer2IDataVal xmlresult(temp);
- Owned<IConstWUResult> result = cw->getResultBySequence(0);
- if (result)
- {
- result->getResultRaw(xmlresult, NULL, NULL);
- resp.setDependancyTrees(temp);
- }
- wu.setown(&cw->lock());
- wu->setState(WUStateAborted);
- wu->commit();
- wu.clear();
- factory->deleteWorkUnit(wuid.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool getWsWuInfoFromSasha(IEspContext &context, SocketEndpoint &ep, const char* wuid, IEspECLWorkunit *info)
- {
- Owned<INode> node = createINode(ep);
- Owned<ISashaCommand> cmd = createSashaCommand();
- cmd->addId(wuid);
- cmd->setAction(SCA_GET);
- if (!cmd->send(node, 1*60*1000))
- {
- StringBuffer url;
- DBGLOG("Could not connect to Sasha server at %s", ep.getUrlStr(url).str());
- throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.", url.str());
- }
- if (cmd->numIds()==0)
- {
- DBGLOG("Could not read archived workunit %s",wuid);
- throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
- }
- unsigned num = cmd->numResults();
- if (num < 1)
- return false;
- StringBuffer res;
- cmd->getResult(0, res);
- if(res.length() < 1)
- return false;
- Owned<IPropertyTree> wpt = createPTreeFromXMLString(res.str());
- if (!wpt)
- return false;
- const char * owner = wpt->queryProp("@submitID");
- ensureWsWorkunitAccessByOwnerId(context, owner, SecAccess_Read);
- info->setWuid(wuid);
- info->setArchived(true);
- if (notEmpty(owner))
- info->setOwner(owner);
- const char * state = wpt->queryProp("@state");
- if (notEmpty(state))
- info->setState(state);
- const char * cluster = wpt->queryProp("@clusterName");
- if (notEmpty(cluster))
- info->setCluster(cluster);
- const char * scope = wpt->queryProp("@scope");
- if (notEmpty(scope))
- info->setScope(scope);
- const char * jobName = wpt->queryProp("@jobName");
- if (notEmpty(jobName))
- info->setJobname(jobName);
- const char * description = wpt->queryProp("Debug/description");
- if (notEmpty(description))
- info->setDescription(description);
- const char * queryText = wpt->queryProp("Query/Text");
- if (notEmpty(queryText))
- info->updateQuery().setText(queryText);
- const char * protectedWU = wpt->queryProp("@protected");
- info->setProtected((protectedWU && *protectedWU!='0'));
- return true;
- }
- #define WUDETAILS_REFRESH_MINS 1
- void getArchivedWUInfo(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort, const char *wuid, IEspWUInfoResponse &resp)
- {
- SocketEndpoint ep;
- if (sashaServerIP && *sashaServerIP)
- ep.set(sashaServerIP, sashaServerPort);
- else
- getSashaNode(ep);
- if (getWsWuInfoFromSasha(context, ep, wuid, &resp.updateWorkunit()))
- {
- resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
- resp.setCanCompile(false);
- return;
- }
- throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Cannot find workunit %s.", wuid);
- return;
- }
- #define WUDETAILS_REFRESH_MINS 1
- bool CWsWorkunitsEx::onWUInfo(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
- if (req.getType() && strieq(req.getType(), "archived workunits"))
- getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
- else
- {
- try
- {
- //The access is checked here because getArchivedWUInfo() has its own access check.
- ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
- unsigned flags=0;
- if (req.getTruncateEclTo64k())
- flags|=WUINFO_TruncateEclTo64k;
- if (req.getIncludeExceptions())
- flags|=WUINFO_IncludeExceptions;
- if (req.getIncludeGraphs())
- flags|=WUINFO_IncludeGraphs;
- if (req.getIncludeSourceFiles())
- flags|=WUINFO_IncludeSourceFiles;
- if (req.getIncludeResults())
- flags|=WUINFO_IncludeResults;
- if (req.getIncludeVariables())
- flags|=WUINFO_IncludeVariables;
- if (req.getIncludeTimers())
- flags|=WUINFO_IncludeTimers;
- if (req.getIncludeDebugValues())
- flags|=WUINFO_IncludeDebugValues;
- if (req.getIncludeApplicationValues())
- flags|=WUINFO_IncludeApplicationValues;
- if (req.getIncludeWorkflows())
- flags|=WUINFO_IncludeWorkflows;
- if (!req.getSuppressResultSchemas())
- flags|=WUINFO_IncludeEclSchemas;
- if (req.getIncludeXmlSchemas())
- flags|=WUINFO_IncludeXmlSchema;
- if (req.getIncludeResultsViewNames())
- flags|=WUINFO_IncludeResultsViewNames;
- if (req.getIncludeResourceURLs())
- flags|=WUINFO_IncludeResourceURLs;
- WsWuInfo winfo(context, wuid.str());
- winfo.getInfo(resp.updateWorkunit(), flags);
- if (req.getIncludeResultsViewNames()||req.getIncludeResourceURLs())
- {
- StringArray views, urls;
- winfo.getResourceInfo(views, urls, flags);
- resp.setResultViews(views);
- resp.updateWorkunit().setResourceURLs(urls);
- }
- }
- catch (IException *e)
- {
- if (e->errorCode() != ECLWATCH_CANNOT_OPEN_WORKUNIT)
- throw e;
- getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
- e->Release();
- }
- switch (resp.getWorkunit().getStateID())
- {
- case WUStateCompiling:
- case WUStateCompiled:
- case WUStateScheduled:
- case WUStateSubmitted:
- case WUStateRunning:
- case WUStateAborting:
- case WUStateWait:
- case WUStateUploadingFiles:
- case WUStateDebugPaused:
- case WUStateDebugRunning:
- resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
- break;
- case WUStateBlocked:
- resp.setAutoRefresh(WUDETAILS_REFRESH_MINS*5);
- break;
- }
- resp.setCanCompile(notEmpty(context.queryUserId()));
- if (context.getClientVersion() > 1.24 && notEmpty(req.getThorSlaveIP()))
- resp.setThorSlaveIP(req.getThorSlaveIP());
- }
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUInfoDetails(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
- {
- return onWUInfo(context, req, resp);
- }
- bool CWsWorkunitsEx::onWUResultView(IEspContext &context, IEspWUResultViewRequest &req, IEspWUResultViewResponse &resp)
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUResultView", wuid);
- ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
- Owned<IWuWebView> wv = createWuWebView(wuid.str(), NULL, getCFD(), true);
- StringBuffer html;
- wv->renderSingleResult(req.getViewName(), req.getResultName(), html);
- resp.setResult(html.str());
- resp.setResult_mimetype("text/html");
- return true;
- }
- void doWUQueryBySingleWuid(IEspContext &context, const char *wuid, IEspWUQueryResponse &resp)
- {
- Owned<IEspECLWorkunit> info= createECLWorkunit("","");
- WsWuInfo winfo(context, wuid);
- winfo.getCommon(*info, 0);
- IArrayOf<IEspECLWorkunit> results;
- results.append(*info.getClear());
- resp.setWorkunits(results);
- resp.setPageSize(1);
- resp.setCount(1);
- }
- void doWUQueryByFile(IEspContext &context, const char *logicalFile, IEspWUQueryResponse &resp)
- {
- StringBuffer wuid;
- getWuidFromLogicalFileName(context, logicalFile, wuid);
- if (!wuid.length())
- throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw= factory->openWorkUnit(wuid.str(), false);
- if (!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
- if (getWsWorkunitAccess(context, *cw) < SecAccess_Read)
- throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED,"Cannot access the workunit for file %s.",logicalFile);
- SCMStringBuffer parent;
- if (!cw->getParentWuid(parent).length())
- doWUQueryBySingleWuid(context, wuid.str(), resp);
- resp.setFirst(false);
- resp.setPageSize(1);
- resp.setCount(1);
- }
- void doWUQueryByXPath(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
- {
- IArrayOf<IEspECLWorkunit> results;
- WsWuSearch wlist(context,req.getOwner(),req.getState(),req.getCluster(),req.getStartDate(),req.getEndDate(),req.getECL(),req.getJobname(),req.getApplicationName(),req.getApplicationKey(),req.getApplicationData());
- int count=(int)req.getPageSize();
- if (!count)
- count=100;
- if (wlist.getSize() < 1)
- {
- resp.setNumWUs(0);
- return;
- }
- if (wlist.getSize() < count)
- count = (int) wlist.getSize() - 1;
- WsWuSearch::iterator begin, end;
- if(notEmpty(req.getAfter()))
- {
- begin=wlist.locate(req.getAfter());
- end=min(begin+count,wlist.end());
- }
- else if (notEmpty(req.getBefore()))
- {
- end=wlist.locate(req.getBefore());
- begin=max(end-count,wlist.begin());
- }
- else
- {
- begin=wlist.begin();
- end=min(begin+count,wlist.end());
- }
- if(begin>wlist.begin() && begin<wlist.end())
- resp.setCurrent(begin->c_str());
- if (context.getClientVersion() > 1.02)
- {
- resp.setPageStartFrom(begin - wlist.begin() + 1);
- resp.setNumWUs((int)wlist.getSize());
- resp.setCount(end - begin);
- }
- if(end<wlist.end())
- resp.setNext(end->c_str());
- for(;begin!=end;begin++)
- {
- Owned<IEspECLWorkunit> info = createECLWorkunit("","");
- WsWuInfo winfo(context, begin->c_str());
- winfo.getCommon(*info, 0);
- results.append(*info.getClear());
- }
- resp.setPageSize(abs(count));
- resp.setWorkunits(results);
- return;
- }
- bool addWUQueryFilter(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *name, WUSortField value)
- {
- if (isEmpty(name))
- return false;
- filters[count++] = value;
- buff.append(name);
- return true;
- }
- bool addWUQueryFilterTime(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *stime, WUSortField value)
- {
- if (isEmpty(stime))
- return false;
- CDateTime dt;
- dt.setString(stime, NULL, true);
- unsigned year, month, day, hour, minute, second, nano;
- dt.getDate(year, month, day, true);
- dt.getTime(hour, minute, second, nano, true);
- VStringBuffer wuid("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
- filters[count++] = value;
- buff.append(wuid.str());
- return true;
- }
- bool addWUQueryFilterApplication(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *appname, const char *appkey, const char *appdata)
- {
- if (isEmpty(appname) && isEmpty(appkey) && isEmpty(appdata)) //no application filter
- return false;
- VStringBuffer path("Application/%s/%s", appname && *appname ? appname : "*", appkey && *appkey ? appkey : "*");
- if(appdata && *appdata)
- path.append("=?~\"").append(appdata).append("\"");
- filters[count++] = WUSFcustom;
- buff.append(path.str());
- return true;
- }
- void doWUQueryWithSort(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
- {
- SecAccessFlags accessOwn;
- SecAccessFlags accessOthers;
- getUserWuAccessFlags(context, accessOwn, accessOthers, true);
- double version = context.getClientVersion();
- IArrayOf<IEspECLWorkunit> results;
- int begin = 0;
- unsigned int count = 100;
- int pagesize = 100;
- if (version > 1.01)
- {
- pagesize = (int)req.getPageSize();
- if (!req.getCount_isNull())
- pagesize = req.getCount();
- if(pagesize < 1)
- pagesize = 100;
- begin = (int)req.getPageStartFrom();
- }
- else
- {
- count=(unsigned)req.getCount();
- if(!count)
- count=100;
- if (notEmpty(req.getAfter()))
- begin=atoi(req.getAfter());
- else if (notEmpty(req.getBefore()))
- begin=atoi(req.getBefore())-count;
- if (begin < 0)
- begin = 0;
- pagesize = count;
- }
- WUSortField sortorder[2] = {(WUSortField) (WUSFwuid | WUSFreverse), WUSFterm};
- if(notEmpty(req.getSortby()))
- {
- const char *sortby = req.getSortby();
- if (strieq(sortby, "Owner"))
- sortorder[0] = WUSFuser;
- else if (strieq(sortby, "JobName"))
- sortorder[0] = WUSFjob;
- else if (strieq(sortby, "Cluster"))
- sortorder[0] = WUSFcluster;
- else if (strieq(sortby, "RoxieCluster"))
- sortorder[0] = WUSFroxiecluster;
- else if (strieq(sortby, "Protected"))
- sortorder[0] = WUSFprotected;
- else if (strieq(sortby, "State"))
- sortorder[0] = WUSFstate;
- else if (strieq(sortby, "ThorTime"))
- sortorder[0] = (WUSortField) (WUSFtotalthortime+WUSFnumeric);
- else
- sortorder[0] = WUSFwuid;
- sortorder[0] = (WUSortField) (sortorder[0] | WUSFnocase);
- bool descending = req.getDescending();
- if (descending)
- sortorder[0] = (WUSortField) (sortorder[0] | WUSFreverse);
- }
- WUSortField filters[10];
- unsigned short filterCount = 0;
- MemoryBuffer filterbuf;
- bool bDoubleCheckState = false;
- if(req.getState() && *req.getState())
- {
- filters[filterCount++] = WUSFstate;
- if (!strieq(req.getState(), "unknown"))
- filterbuf.append(req.getState());
- else
- filterbuf.append("");
- if (strieq(req.getState(), "submitted"))
- bDoubleCheckState = true;
- }
- addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
- addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
- if(version > 1.07)
- addWUQueryFilter(filters, filterCount, filterbuf, req.getRoxieCluster(), WUSFroxiecluster);
- addWUQueryFilter(filters, filterCount, filterbuf, req.getLogicalFile(), WUSFfileread);
- addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
- addWUQueryFilter(filters, filterCount, filterbuf, req.getJobname(), (WUSortField) (WUSFjob | WUSFnocase));
- addWUQueryFilter(filters, filterCount, filterbuf, req.getECL(), (WUSortField) (WUSFecl | WUSFwild));
- addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
- addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
- addWUQueryFilterApplication(filters, filterCount, filterbuf, req.getApplicationName(), req.getApplicationKey(), req.getApplicationData());
- filters[filterCount] = WUSFterm;
- __int64 cacheHint = 0;
- if (!req.getCacheHint_isNull())
- cacheHint = req.getCacheHint();
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- unsigned numWUs;
- Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), begin, pagesize+1, "", &cacheHint, &numWUs);
- if (version >= 1.41)
- resp.setCacheHint(cacheHint);
- unsigned actualCount = 0;
- ForEach(*it)
- {
- IConstWorkUnit& cw = it->query();
- if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
- {
- numWUs--;
- continue;
- }
- if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
- {
- numWUs--;
- continue;
- }
- SCMStringBuffer parent;
- if (!cw.getParentWuid(parent).length())
- {
- const char* wuid = cw.getWuid(parent).str();
- if (!looksLikeAWuid(wuid))
- {
- numWUs--;
- continue;
- }
- actualCount++;
- Owned<IEspECLWorkunit> info = createECLWorkunit("","");
- WsWuInfo winfo(context, wuid);
- winfo.getCommon(*info, 0);
- results.append(*info.getClear());
- }
- }
- if (version > 1.02)
- {
- resp.setPageStartFrom(begin+1);
- resp.setNumWUs(numWUs);
- if (results.length() > (aindex_t)pagesize)
- results.pop();
- if(unsigned (begin + pagesize) < numWUs)
- {
- resp.setNextPage(begin + pagesize);
- resp.setPageEndAt(begin + pagesize);
- int last = begin + pagesize;
- while (numWUs > (unsigned) last + pagesize)
- last += pagesize;
- resp.setLastPage(last);
- }
- else
- {
- resp.setNextPage(-1);
- resp.setPageEndAt(numWUs);
- }
- if(begin > 0)
- {
- resp.setFirst(false);
- if (begin - pagesize > 0)
- resp.setPrevPage(begin - pagesize);
- else
- resp.setPrevPage(0);
- }
- resp.setPageSize(pagesize);
- }
- else
- {
- if(begin>0 && actualCount > 0)
- {
- char buf[10];
- itoa(begin, buf, 10);
- resp.setCurrent(buf);
- }
- if(count<actualCount)
- {
- char buf[10];
- itoa(begin+count, buf, 10);
- resp.setNext(buf);
- resp.setNumWUs(numWUs);
- if (results.length() > count)
- results.pop();
- }
- if(begin == 0 && actualCount <= count)
- resp.setFirst(false);
- resp.setCount(count);
- }
- resp.setWorkunits(results);
- return;
- }
- void doWUQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
- ArchivedWuCache &archivedWuCache, int cacheTime, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
- {
- SecAccessFlags accessOwn;
- SecAccessFlags accessOthers;
- getUserWuAccessFlags(context, accessOwn, accessOthers, true);
- __int64 pageSize = req.getPageSize();
- if(pageSize < 1)
- pageSize=100;
- __int64 displayStart = req.getPageStartFrom();
- __int64 displayEnd = displayStart + pageSize;
- unsigned dateLimit = 0;
- bool hasNextPage = true;
- SocketEndpoint ep;
- if (sashaServerIP && *sashaServerIP)
- ep.set(sashaServerIP, sashaServerPort);
- else
- getSashaNode(ep);
- Owned<INode> sashaserver = createINode(ep);
- CDateTime wuTimeFrom, wuTimeTo;
- if(notEmpty(req.getEndDate()))
- wuTimeTo.setString(req.getEndDate(), NULL, true);
- else
- wuTimeTo.setNow();
- if(notEmpty(req.getStartDate()))
- {
- wuTimeFrom.setString(req.getStartDate(), NULL, true);
- dateLimit = 1;
- }
- IArrayOf<IEspECLWorkunit> results;
- StringBuffer filter;
- addToQueryString(filter, "cluster", req.getCluster(), ';');
- addToQueryString(filter, "owner", req.getOwner(), ';');
- addToQueryString(filter, "jobName", req.getJobname(), ';');
- addToQueryString(filter, "state", req.getState(), ';');
- StringBuffer s;
- if (!req.getLastNDays_isNull() && req.getLastNDays()>0)
- addToQueryString(filter, "LastNDays", s.clear().append(req.getLastNDays()).str(), ';');
- else
- {
- addToQueryString(filter, "wuTimeFrom", req.getStartDate(), ';');
- addToQueryString(filter, "wuTimeTo", req.getEndDate(), ';');
- }
- addToQueryString(filter, "displayStart", s.append(displayStart).str(), ';');
- addToQueryString(filter, "pageSize", s.clear().append(pageSize).str(), ';');
- Owned<ArchivedWuCacheElement> found = archivedWuCache.lookup(context, filter, "AddWhenAvailable", cacheTime);
- if (found)
- {
- hasNextPage = found->m_hasNextPage;
- if (found->m_results.length())
- {
- ForEachItemIn(ai, found->m_results)
- {
- Owned<IEspECLWorkunit> info= createECLWorkunit("","");
- info->copy(found->m_results.item(ai));
- results.append(*info.getClear());
- }
- }
- }
- else
- {
- IArrayOf<IEspECLWorkunit> resultList;
- CDateTime timeTo = wuTimeTo;
- __int64 totalWus = 0;
- bool complete = false;
- while (!complete)
- {
- CDateTime timeFrom = timeTo;
- timeFrom.adjustTime(-1439); //one day earlier
- if (dateLimit > 0 && wuTimeFrom > timeFrom)
- timeFrom = wuTimeFrom;
- unsigned year0, month0, day0, hour0, minute0, second0, nano0;
- timeFrom.getDate(year0, month0, day0, true);
- timeFrom.getTime(hour0, minute0, second0, nano0, true);
- VStringBuffer wuFrom("%4d%02d%02d%02d%02d", year0, month0, day0, hour0, minute0);
- unsigned year, month, day, hour, minute, second, nano;
- timeTo.getDate(year, month, day, true);
- timeTo.getTime(hour, minute, second, nano, true);
- VStringBuffer wuTo("%4d%02d%02d%02d%02d", year, month, day, hour, minute);
- __int64 begin = 0;
- unsigned limit = 1000;
- bool continueSashaLoop = true;
- while (continueSashaLoop)
- {
- Owned<ISashaCommand> cmd = createSashaCommand();
- cmd->setAction(SCA_LIST);
- cmd->setOnline(false);
- cmd->setArchived(true);
- cmd->setAfter(wuFrom.str());
- cmd->setBefore(wuTo.str());
- cmd->setStart((unsigned)begin);
- cmd->setLimit(limit);
- if (notEmpty(req.getCluster()))
- cmd->setCluster(req.getCluster());
- if (notEmpty(req.getOwner()))
- cmd->setOwner(req.getOwner());
- if (notEmpty(req.getJobname()))
- cmd->setJobName(req.getJobname());
- if (notEmpty(req.getState()))
- cmd->setState(req.getState());
- cmd->setOutputFormat("owner,jobname,cluster,state");
- if (!cmd->send(sashaserver))
- {
- StringBuffer msg("Cannot connect to archive server at ");
- sashaserver->endpoint().getUrlStr(msg);
- throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER, "%s", msg.str());
- }
- unsigned actualCount = cmd->numIds();
- if (actualCount < 1)
- break;
- totalWus += actualCount;
- if (actualCount < limit)
- continueSashaLoop = false;
- for (unsigned ii=0; ii<actualCount; ii++)
- {
- const char *csline = cmd->queryId(ii);
- if (!csline)
- continue;
- StringArray wuidArray;
- wuidArray.appendList(csline, ",");
- if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cmd->queryOwner(), accessOwn, accessOthers) < SecAccess_Read)
- continue;
- const char* wuid = wuidArray.item(0);
- if (isEmpty(wuid))
- continue;
- __int64 addToPos = -1;
- ForEachItemIn(ridx, resultList)
- {
- IEspECLWorkunit& w = resultList.item(ridx);
- if (isEmpty(w.getWuid()))
- continue;
- if (strcmp(wuid, w.getWuid())>0)
- {
- addToPos = ridx;
- break;
- }
- }
- if (addToPos < 0 && (ridx > displayEnd))
- continue;
- Owned<IEspECLWorkunit> info= createECLWorkunit("","");
- info->setWuid(wuid);
- if (notEmpty(wuidArray.item(1)))
- info->setOwner(wuidArray.item(1));
- if (notEmpty(wuidArray.item(2)))
- info->setJobname(wuidArray.item(2));
- if (notEmpty(wuidArray.item(3)))
- info->setCluster(wuidArray.item(3));
- if (notEmpty(wuidArray.item(4)))
- info->setState(wuidArray.item(4));
- if (addToPos < 0)
- resultList.append(*info.getClear());
- else
- resultList.add(*info.getClear(), (aindex_t) addToPos);
- if (resultList.length() > displayEnd)
- resultList.pop();
- }
- begin += limit;
- }
- timeTo.adjustTime(-1440);//one day earlier
- if (dateLimit > 0 && wuTimeFrom > timeTo) //we reach the date limit
- {
- if (totalWus <= displayEnd)
- hasNextPage = false;
- complete = true;
- }
- else if ( resultList.length() >= displayEnd) //we have all we need
- complete = true;
- }
- if (displayEnd > resultList.length())
- displayEnd = resultList.length();
- for (aindex_t i = (aindex_t)displayStart; i < (aindex_t)displayEnd; i++)
- {
- Owned<IEspECLWorkunit> info = createECLWorkunit("","");
- info->copy(resultList.item(i));
- results.append(*info.getClear());
- }
- archivedWuCache.add(filter, "AddWhenAvailable", hasNextPage, results);
- }
- resp.setPageStartFrom(displayStart+1);
- resp.setPageEndAt(displayEnd);
- if(dateLimit < 1 || hasNextPage)
- resp.setNextPage(displayStart + pageSize);
- else
- resp.setNextPage(-1);
- if(displayStart > 0)
- {
- resp.setFirst(false);
- if (displayStart - pageSize > 0)
- resp.setPrevPage(displayStart - pageSize);
- else
- resp.setPrevPage(0);
- }
- resp.setPageSize(pageSize);
- resp.setWorkunits(results);
- resp.setType("archived only");
- return;
- }
- bool CWsWorkunitsEx::onWUQuery(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
- {
- try
- {
- StringBuffer wuidStr = req.getWuid();
- const char* wuid = wuidStr.trim().str();
- if (req.getType() && strieq(req.getType(), "archived workunits"))
- doWUQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
- else if(notEmpty(wuid) && looksLikeAWuid(wuid))
- doWUQueryBySingleWuid(context, wuid, resp);
- else if (notEmpty(req.getLogicalFile()) && req.getLogicalFileSearchType() && strieq(req.getLogicalFileSearchType(), "Created"))
- doWUQueryByFile(context, req.getLogicalFile(), resp);
- else
- doWUQueryWithSort(context, req, resp);
- resp.setState(req.getState());
- resp.setCluster(req.getCluster());
- resp.setRoxieCluster(req.getRoxieCluster());
- resp.setOwner(req.getOwner());
- resp.setStartDate(req.getStartDate());
- resp.setEndDate(req.getEndDate());
- double version = context.getClientVersion();
- StringBuffer basicQuery;
- addToQueryString(basicQuery, "State", req.getState());
- addToQueryString(basicQuery, "Cluster", req.getCluster());
- if (version > 1.07)
- addToQueryString(basicQuery, "RoxieCluster", req.getRoxieCluster());
- addToQueryString(basicQuery, "Owner", req.getOwner());
- addToQueryString(basicQuery, "StartDate", req.getStartDate());
- addToQueryString(basicQuery, "EndDate", req.getEndDate());
- if (version > 1.25 && req.getLastNDays() > -1)
- addToQueryString(basicQuery, "LastNDays", StringBuffer().append(req.getLastNDays()).str());
- addToQueryString(basicQuery, "ECL", req.getECL());
- addToQueryString(basicQuery, "Jobname", req.getJobname());
- addToQueryString(basicQuery, "Type", req.getType());
- if (addToQueryString(basicQuery, "LogicalFile", req.getLogicalFile()))
- addToQueryString(basicQuery, "LogicalFileSearchType", req.getLogicalFileSearchType());
- resp.setFilters(basicQuery.str());
- if (notEmpty(req.getSortby()) && !strstr(basicQuery.str(), StringBuffer(req.getSortby()).append('=').str()))
- {
- resp.setSortby(req.getSortby());
- addToQueryString(basicQuery, "Sortby", req.getSortby());
- if (req.getDescending())
- {
- resp.setDescending(req.getDescending());
- addToQueryString(basicQuery, "Descending", "1");
- }
- }
- resp.setBasicQuery(basicQuery.str());
- StringBuffer s;
- if(notEmpty(req.getECL()))
- resp.setECL(Utils::url_encode(req.getECL(), s).str());
- if(notEmpty(req.getJobname()))
- resp.setJobname(Utils::url_encode(req.getJobname(), s.clear()).str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- void appendResultSet(MemoryBuffer& mb, INewResultSet* result, const char *name, __int64 start, unsigned& count, __int64& total, bool bin, bool xsd, ESPSerializationFormat fmt)
- {
- if (!result)
- return;
- Owned<IResultSetCursor> cursor(result->createCursor());
- total=result->getNumRows();
- if(bin)
- count = getResultBin(mb, result, (unsigned)start, count);
- else
- {
- struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
- {
- MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
- IMPLEMENT_IINTERFACE;
- virtual const char * str() const { UNIMPLEMENTED; }
- virtual void set(const char *val) { buffer.append(strlen(val),val); }
- virtual void clear() { } // support appending only
- virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
- virtual unsigned length() const { return buffer.length(); };
- MemoryBuffer & buffer;
- } adaptor(mb);
- if (fmt==ESPSerializationJSON)
- count = getResultJSON(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL);
- else
- count = getResultXml(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL);
- }
- }
- void getWsWuResult(IEspContext &context, const char* wuid, const char *name, const char *logical, unsigned index, __int64 start, unsigned& count, __int64& total, IStringVal& resname, bool bin, MemoryBuffer& mb, bool xsd=true)
- {
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
- Owned<IConstWUResult> result;
- if (notEmpty(name))
- result.setown(cw->getResultByName(name));
- else if (notEmpty(logical))
- {
- Owned<IConstWUResultIterator> it = &cw->getResults();
- ForEach(*it)
- {
- IConstWUResult &r = it->query();
- SCMStringBuffer filename;
- if(strieq(r.getResultLogicalName(filename).str(), logical))
- {
- result.setown(LINK(&r));
- break;
- }
- }
- }
- else
- result.setown(cw->getResultBySequence(index));
- if (!result)
- throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
- if (!resname.length())
- result->getResultName(resname);
- Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
- SCMStringBuffer logicalName;
- result->getResultLogicalName(logicalName);
- Owned<INewResultSet> rs;
- if (logicalName.length())
- {
- SCMStringBuffer cluster; //MORE is this wrong cluster?
- rs.setown(resultSetFactory->createNewFileResultSet(logicalName.str(), cw->getClusterName(cluster).str()));
- }
- else
- rs.setown(resultSetFactory->createNewResultSet(result, wuid));
- appendResultSet(mb, rs, name, start, count, total, bin, xsd, context.getResponseFormat());
- }
- void openSaveFile(IEspContext &context, int opt, const char* filename, const char* origMimeType, MemoryBuffer& buf, IEspWULogFileResponse &resp)
- {
- if (opt < 1)
- {
- resp.setThefile(buf);
- resp.setThefile_mimetype(origMimeType);
- }
- else if (opt < 2)
- {
- StringBuffer headerStr("attachment;");
- if (filename && *filename)
- {
- const char* pFileName = strrchr(filename, PATHSEPCHAR);
- if (pFileName)
- headerStr.appendf("filename=%s", pFileName+1);
- else
- headerStr.appendf("filename=%s", filename);
- }
- MemoryBuffer buf0;
- unsigned i = 0;
- char* p = (char*) buf.toByteArray();
- while (i < buf.length())
- {
- if (p[0] != 10)
- buf0.append(p[0]);
- else
- buf0.append(0x0d);
- p++;
- i++;
- }
- resp.setThefile(buf);
- resp.setThefile_mimetype(origMimeType);
- context.addCustomerHeader("Content-disposition", headerStr.str());
- }
- else
- {
- #ifndef _USE_ZLIB
- throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
- #else
- StringBuffer fileNameStr, headerStr("attachment;");
- if (notEmpty(filename))
- {
- fileNameStr.append(filename);
- headerStr.append("filename=").append(filename).append((opt>2) ? ".gz" : ".zip");
- }
- else
- fileNameStr.append("file");
- StringBuffer ifname;
- ifname.appendf("%s%sT%xAT%x", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick()).append((opt>2)? "" : ".zip");
- IZZIPor* Zipor = createZZIPor();
- int ret = 0;
- if (opt > 2)
- ret = Zipor->gzipToFile(buf.length(), (void*)buf.toByteArray(), ifname.str());
- else
- ret = Zipor->zipToFile(buf.length(), (void*)buf.toByteArray(), fileNameStr.str(), ifname.str());
- releaseIZ(Zipor);
- if (ret < 0)
- {
- Owned<IFile> rFile = createIFile(ifname.str());
- if (rFile->exists())
- rFile->remove();
- throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
- }
- Owned <IFile> rf = createIFile(ifname.str());
- if (!rf->exists())
- throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
- MemoryBuffer out;
- Owned <IFileIO> fio = rf->open(IFOread);
- read(fio, 0, (size32_t) rf->size(), out);
- resp.setThefile(out);
- fio.clear();
- rf->remove();
- resp.setThefile_mimetype((opt > 2) ? "application/x-gzip" : "application/zip");
- context.addCustomerHeader("Content-disposition", headerStr.str());
- #endif
- }
- }
- bool CWsWorkunitsEx::onWUFile(IEspContext &context,IEspWULogFileRequest &req, IEspWULogFileResponse &resp)
- {
- try
- {
- StringBuffer wuidStr = req.getWuid();
- const char* wuidIn = wuidStr.trim().str();
- if (wuidIn && *wuidIn)
- {
- if (!looksLikeAWuid(wuidIn))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID");
- ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
- }
- StringAttr wuid(wuidIn);
- if (wuid.isEmpty() && notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
- {
- Owned<IPropertyTree> registry = getQueryRegistry(req.getQuerySet(), false);
- if (!registry)
- throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", req.getQuerySet());
- Owned<IPropertyTree> query = resolveQueryAlias(registry, req.getQuery());
- if (!query)
- throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", req.getQuery());
- resp.setQuerySet(req.getQuerySet());
- resp.setQueryName(query->queryProp("@name"));
- resp.setQueryId(query->queryProp("@id"));
- wuid.set(query->queryProp("@wuid"));
- }
- int opt = req.getOption();
- if (!wuid.isEmpty())
- {
- resp.setWuid(wuid.get());
- MemoryBuffer mb;
- WsWuInfo winfo(context, wuid);
- if (strieq(File_ArchiveQuery, req.getType()))
- {
- winfo.getWorkunitArchiveQuery(mb);
- openSaveFile(context, opt, "ArchiveQuery.xml", HTTP_TYPE_APPLICATION_XML, mb, resp);
- }
- else if (strieq(File_Cpp,req.getType()) && notEmpty(req.getName()))
- {
- winfo.getWorkunitCpp(req.getName(), req.getDescription(), req.getIPAddress(),mb, opt > 0);
- openSaveFile(context, opt, req.getName(), HTTP_TYPE_TEXT_PLAIN, mb, resp);
- }
- else if (strieq(File_DLL,req.getType()))
- {
- StringBuffer name;
- winfo.getWorkunitDll(name, mb);
- resp.setFileName(name.str());
- resp.setDaliServer(daliServers.get());
- openSaveFile(context, opt, req.getName(), HTTP_TYPE_OCTET_STREAM, mb, resp);
- }
- else if (strieq(File_Res,req.getType()))
- {
- winfo.getWorkunitResTxt(mb);
- openSaveFile(context, opt, "res.txt", HTTP_TYPE_TEXT_PLAIN, mb, resp);
- }
- else if (strncmp(req.getType(), File_ThorLog, 7) == 0)
- {
- winfo.getWorkunitThorLog(req.getName(), mb);
- openSaveFile(context, opt, "thormaster.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
- }
- else if (strieq(File_ThorSlaveLog,req.getType()))
- {
- StringBuffer logDir;
- getConfigurationDirectory(directories, "log", "thor", req.getProcess(), logDir);
- winfo.getWorkunitThorSlaveLog(req.getClusterGroup(), req.getIPAddress(), req.getLogDate(), logDir.str(), req.getSlaveNumber(), mb, false);
- openSaveFile(context, opt, "ThorSlave.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
- }
- else if (strieq(File_EclAgentLog,req.getType()))
- {
- winfo.getWorkunitEclAgentLog(req.getName(), req.getProcess(), mb);
- openSaveFile(context, opt, "eclagent.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
- }
- else if (strieq(File_XML,req.getType()) && notEmpty(req.getName()))
- {
- const char* name = req.getName();
- const char* ptr = strrchr(name, '/');
- if (ptr)
- ptr++;
- else
- ptr = name;
- winfo.getWorkunitAssociatedXml(name, req.getIPAddress(), req.getPlainText(), req.getDescription(), opt > 0, mb);
- openSaveFile(context, opt, ptr, HTTP_TYPE_APPLICATION_XML, mb, resp);
- }
- else if (strieq(File_XML,req.getType()))
- {
- winfo.getWorkunitXml(req.getPlainText(), mb);
- resp.setThefile(mb);
- const char* plainText = req.getPlainText();
- if (plainText && (!stricmp(plainText, "yes")))
- resp.setThefile_mimetype(HTTP_TYPE_TEXT_PLAIN);
- else
- resp.setThefile_mimetype(HTTP_TYPE_APPLICATION_XML);
- }
- }
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUResultBin(IEspContext &context,IEspWUResultBinRequest &req, IEspWUResultBinResponse &resp)
- {
- try
- {
- StringBuffer wuidStr = req.getWuid();
- const char* wuidIn = wuidStr.trim().str();
- if (wuidIn && *wuidIn)
- {
- if (!looksLikeAWuid(wuidIn))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuidIn);
- ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
- }
- MemoryBuffer mb;
- __int64 total=0;
- __int64 start = req.getStart() > 0 ? req.getStart() : 0;
- unsigned count = req.getCount(), requested=count;
- SCMStringBuffer name;
- bool bin = (req.getFormat() && strieq(req.getFormat(),"raw"));
- if (notEmpty(wuidIn) && notEmpty(req.getResultName()))
- getWsWuResult(context, wuidIn, req.getResultName(), NULL, 0, start, count, total, name, bin, mb);
- else if (notEmpty(wuidIn) && (req.getSequence() >= 0))
- getWsWuResult(context, wuidIn, NULL, NULL, req.getSequence(), start, count, total, name, bin,mb);
- else if (notEmpty(req.getLogicalName()))
- {
- const char* logicalName = req.getLogicalName();
- StringBuffer wuid;
- getWuidFromLogicalFileName(context, logicalName, wuid);
- if (!wuid.length())
- throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.",logicalName);
- getWsWuResult(context, wuid.str(), NULL, logicalName, 0, start, count, total, name, bin, mb);
- }
- else
- throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
- if(stricmp(req.getFormat(),"xls")==0)
- {
- Owned<IProperties> params(createProperties());
- params->setProp("showCount",0);
- StringBuffer xml;
- xml.append("<WUResultExcel><Result>").append(mb.length(), mb.toByteArray()).append("</Result></WUResultExcel>");
- if (xml.length() > MAXXLSTRANSFER)
- 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.");
- StringBuffer xls;
- xsltTransform(xml.str(), StringBuffer(getCFD()).append("./smc_xslt/result.xslt").str(), params, xls);
- MemoryBuffer out;
- out.setBuffer(xls.length(), (void*)xls.str());
- resp.setResult(out);
- resp.setResult_mimetype("application/vnd.ms-excel");
- }
- #ifdef _USE_ZLIB
- else if(strieq(req.getFormat(),"zip") || strieq(req.getFormat(),"gzip"))
- {
- bool gzip = strieq(req.getFormat(),"gzip");
- StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
- xml.append("<Result>").append(mb.length(),mb.toByteArray()).append("</Result>");
- VStringBuffer ifname("%s%sT%xAT%x%s", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick(), gzip ? "" : ".zip");
- IZZIPor* Zipor = createZZIPor();
- int ret = 0;
- if (gzip)
- ret = Zipor->gzipToFile(xml.length(), (void*)xml.str(), ifname.str());
- else
- ret = Zipor->zipToFile(xml.length(), (void*)xml.str(), "WUResult.xml", ifname.str());
- releaseIZ(Zipor);
- if (ret < 0)
- {
- Owned<IFile> rFile = createIFile(ifname.str());
- if (rFile->exists())
- rFile->remove();
- throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "The data cannot be compressed.");
- }
- MemoryBuffer out;
- Owned <IFile> rf = createIFile(ifname.str());
- if (rf->exists())
- {
- Owned <IFileIO> fio = rf->open(IFOread);
- read(fio, 0, (size32_t) rf->size(), out);
- resp.setResult(out);
- }
- if (gzip)
- {
- resp.setResult_mimetype("application/x-gzip");
- context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.gz");
- }
- else
- {
- resp.setResult_mimetype("application/zip");
- context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.zip");
- }
- Owned<IFile> rFile = createIFile(ifname.str());
- if (rFile->exists())
- rFile->remove();
- }
- #endif
- else
- {
- resp.setResult(mb);
- }
- resp.setName(name.str());
- resp.setWuid(wuidIn);
- resp.setSequence(req.getSequence());
- resp.setStart(start);
- if (requested > total)
- requested = (unsigned)total;
- resp.setRequested(requested);
- resp.setCount(count);
- resp.setTotal(total);
- resp.setFormat(req.getFormat());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUResultSummary(IEspContext &context, IEspWUResultSummaryRequest &req, IEspWUResultSummaryResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUResultSummary", wuid);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
- resp.setWuid(wuid.str());
- resp.setSequence(req.getSequence());
- IArrayOf<IEspECLResult> results;
- Owned<IConstWUResult> r = cw->getResultBySequence(req.getSequence());
- if (r)
- {
- WsWuInfo winfo(context, cw);
- winfo.getResult(*r, results, 0);
- resp.setFormat(r->getResultFormat());
- resp.setResult(results.item(0));
- }
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- void getFileResults(IEspContext &context, const char* logicalName, const char* cluster,__int64 start, unsigned& count,__int64& total,IStringVal& resname,bool bin, MemoryBuffer& buf, bool xsd)
- {
- Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
- Owned<INewResultSet> result(resultSetFactory->createNewFileResultSet(logicalName, cluster));
- appendResultSet(buf, result, resname.str(), start, count, total, bin, xsd, context.getResponseFormat());
- }
- void getWorkunitCluster(IEspContext &context, const char* wuid, SCMStringBuffer& cluster, bool checkArchiveWUs)
- {
- if (isEmpty(wuid))
- return;
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
- if (cw)
- cw->getClusterName(cluster);
- else if (checkArchiveWUs)
- {
- Owned<IPropertyTree> wuProps;// = getArchivedWorkUnitProperties(wuid);
- if (wuProps)
- cluster.set(wuProps->queryProp("@clusterName"));
- }
- }
- bool CWsWorkunitsEx::onWUResult(IEspContext &context, IEspWUResultRequest &req, IEspWUResultResponse &resp)
- {
- try
- {
- StringBuffer wuidStr = req.getWuid();
- const char* wuid = wuidStr.trim().str();
- if (wuid && *wuid)
- {
- if (!looksLikeAWuid(wuid))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
- ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
- }
- MemoryBuffer mb;
- SCMStringBuffer name;
- __int64 total=0;
- __int64 start = req.getStart() > 0 ? req.getStart() : 0;
- unsigned count=req.getCount() ? req.getCount() : 100, requested=count;
- unsigned seq = req.getSequence();
- bool inclXsd = !req.getSuppressXmlSchema();
- VStringBuffer filter("start=%"I64F"d;count=%d", start, count);
- addToQueryString(filter, "clusterName", req.getCluster(), ';');
- addToQueryString(filter, "logicalName", req.getLogicalName(), ';');
- if (wuid && *wuid)
- addToQueryString(filter, "wuid", wuid, ';');
- addToQueryString(filter, "resultName", req.getResultName(), ';');
- filter.appendf(";seq=%d;", seq);
- if (inclXsd)
- filter.append("xsd;");
- if (context.getResponseFormat()==ESPSerializationJSON)
- filter.append("json;");
- const char* logicalName = req.getLogicalName();
- const char* clusterName = req.getCluster();
- const char* resultName = req.getResultName();
- Owned<DataCacheElement> data = dataCache->lookup(context, filter, awusCacheMinutes);
- if (data)
- {
- mb.append(data->m_data.c_str());
- name.set(data->m_name.c_str());
- logicalName = data->m_logicalName.c_str();
- wuid = data->m_wuid.c_str();
- resultName = data->m_resultName.c_str();
- seq = data->m_seq;
- start = data->m_start;
- count = data->m_rowcount;
- requested = (unsigned)data->m_requested;
- total = data->m_total;
- if (notEmpty(logicalName))
- resp.setLogicalName(logicalName);
- else
- {
- if (notEmpty(wuid))
- resp.setWuid(wuid);
- resp.setSequence(seq);
- }
- }
- else
- {
- if(logicalName && *logicalName)
- {
- StringBuffer lwuid;
- getWuidFromLogicalFileName(context, logicalName, lwuid);
- SCMStringBuffer cluster;
- if (lwuid.length())
- getWorkunitCluster(context, lwuid.str(), cluster, true);
- if (cluster.length())
- {
- getFileResults(context, logicalName, cluster.str(), start, count, total, name, false, mb, inclXsd);
- resp.setLogicalName(logicalName);
- }
- else if (notEmpty(clusterName))
- {
- getFileResults(context, logicalName, clusterName, start, count, total, name, false, mb, inclXsd);
- resp.setLogicalName(logicalName);
- }
- else
- throw MakeStringException(ECLWATCH_INVALID_INPUT,"Need valid target cluster to browse file %s.",logicalName);
- }
- else if (notEmpty(wuid) && notEmpty(resultName))
- {
- name.set(resultName);
- getWsWuResult(context, wuid, resultName, NULL, 0, start, count, total, name, false, mb, inclXsd);
- resp.setWuid(wuid);
- resp.setSequence(seq);
- }
- else
- {
- getWsWuResult(context, wuid, NULL, NULL, seq, start, count, total, name, false, mb, inclXsd);
- resp.setWuid(wuid);
- resp.setSequence(seq);
- }
- mb.append(0);
- if (requested > total)
- requested = (unsigned)total;
- dataCache->add(filter, mb.toByteArray(), name.str(), logicalName, wuid, resultName, seq, start, count, requested, total);
- }
- resp.setName(name.str());
- resp.setStart(start);
- if (clusterName && *clusterName)
- resp.setCluster(clusterName);
- resp.setRequested(requested);
- resp.setCount(count);
- resp.setTotal(total);
- resp.setResult(mb.toByteArray());
- context.queryXslParameters()->setProp("escapeResults","1");
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- void getScheduledWUs(IEspContext &context, const char *serverName, const char *eventName, IArrayOf<IEspScheduledWU> & results)
- {
- if (notEmpty(serverName))
- {
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IScheduleReader> reader = getScheduleReader(serverName, eventName);
- Owned<IScheduleReaderIterator> it(reader->getIterator());
- while(it->isValidEventName())
- {
- StringBuffer ieventName;
- it->getEventName(ieventName);
- while(it->isValidEventText())
- {
- StringBuffer ieventText;
- it->getEventText(ieventText);
- while(it->isValidWuid())
- {
- StringBuffer wuid;
- it->getWuid(wuid);
- if (wuid.length())
- {
- Owned<IEspScheduledWU> scheduledWU = createScheduledWU("");
- scheduledWU->setWuid(wuid.str());
- scheduledWU->setCluster(serverName);
- if (ieventName.length())
- scheduledWU->setEventName(ieventName.str());
- if (ieventText.str())
- scheduledWU->setEventText(ieventText.str());
- try
- {
- SCMStringBuffer s;
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if (cw)
- scheduledWU->setJobName(cw->getJobName(s).str());
- }
- catch (IException *e)
- {
- e->Release();
- }
- results.append(*scheduledWU.getLink());
- }
- it->nextWuid();
- }
- it->nextEventText();
- }
- it->nextEventName();
- }
- }
- return;
- }
- bool CWsWorkunitsEx::onWUShowScheduled(IEspContext &context, IEspWUShowScheduledRequest & req, IEspWUShowScheduledResponse & resp)
- {
- try
- {
- DBGLOG("WUShowScheduled");
- const char *clusterName = req.getCluster();
- const char *eventName = req.getEventName();
- IArrayOf<IEspScheduledWU> results;
- if(notEmpty(req.getPushEventName()))
- resp.setPushEventName(req.getPushEventName());
- if(notEmpty(req.getPushEventText()))
- resp.setPushEventText(req.getPushEventText());
- Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
- Owned<IConstEnvironment> environment = factory->openEnvironmentByFile();
- Owned<IPropertyTree> root = &environment->getPTree();
- if (!root)
- throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
- unsigned i = 0;
- Owned<IPropertyTreeIterator> ic = root->getElements("Software/Topology/Cluster");
- IArrayOf<IEspServerInfo> servers;
- ForEach(*ic)
- {
- IPropertyTree &cluster = ic->query();
- const char *iclusterName = cluster.queryProp("@name");
- if (isEmpty(iclusterName))
- continue;
- if(isEmpty(clusterName))
- getScheduledWUs(context, iclusterName, eventName, results);
- else if (strieq(clusterName, iclusterName))
- {
- getScheduledWUs(context, clusterName, eventName, results);
- resp.setClusterSelected(i+1);
- }
- Owned<IEspServerInfo> server = createServerInfo("");
- server->setName(iclusterName);
- servers.append(*server.getLink());
- i++;
- }
- if (servers.length())
- resp.setClusters(servers);
- if (results.length())
- resp.setWorkunits(results);
- bool first=false;
- StringBuffer Query("PageFrom=Scheduler");
- appendUrlParameter(Query, "EventName", eventName, first);
- appendUrlParameter(Query, "ECluster", clusterName, first);
- resp.setQuery(Query.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUExport(IEspContext &context, IEspWUExportRequest &req, IEspWUExportResponse &resp)
- {
- try
- {
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- WsWuSearch ws(context, req.getOwner(), req.getState(), req.getCluster(), req.getStartDate(), req.getEndDate(), req.getECL(), req.getJobname());
- StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Workunits>");
- for(WsWuSearch::iterator it=ws.begin(); it!=ws.end(); it++)
- {
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(it->c_str(), false);
- if (cw)
- exportWorkUnitToXML(cw, xml, true, false);
- }
- xml.append("</Workunits>");
- MemoryBuffer mb;
- mb.setBuffer(xml.length(),(void*)xml.str());
- resp.setExportData(mb);
- resp.setExportData_mimetype(HTTP_TYPE_APPLICATION_XML);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUListLocalFileRequired(IEspContext& context, IEspWUListLocalFileRequiredRequest& req, IEspWUListLocalFileRequiredResponse& resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUListLocalFileRequired", wuid);
- ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if (!cw)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Workunit %s not found.", wuid.str());
- IArrayOf<IEspLogicalFileUpload> localFiles;
- Owned<IConstLocalFileUploadIterator> it = cw->getLocalFileUploads();
- ForEach(*it)
- {
- Owned<IConstLocalFileUpload> file = it->get();
- if(!file)
- continue;
- Owned<IEspLogicalFileUpload> up = createLogicalFileUpload();
- SCMStringBuffer s;
- up->setType(file->queryType());
- up->setSource(file->getSource(s).str());
- up->setDestination(file->getDestination(s).str());
- up->setEventTag(file->getEventTag(s).str());
- localFiles.append(*up.getLink());
- }
- resp.setLocalFileUploads(localFiles);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- typedef enum wsEclTypes_
- {
- wsEclTypeUnknown,
- xsdString,
- xsdBoolean,
- xsdDecimal,
- xsdFloat,
- xsdDouble,
- xsdDuration,
- xsdDateTime,
- xsdTime,
- xsdDate,
- xsdYearMonth,
- xsdYear,
- xsdMonthDay,
- xsdDay,
- xsdMonth,
- xsdHexBinary,
- xsdBase64Binary,
- xsdAnyURI,
- xsdQName,
- xsdNOTATION,
- xsdNormalizedString,
- xsdToken,
- xsdLanguage,
- xsdNMTOKEN,
- xsdNMTOKENS,
- xsdName,
- xsdNCName,
- xsdID,
- xsdIDREF,
- xsdIDREFS,
- xsdENTITY,
- xsdENTITIES,
- xsdInteger,
- xsdNonPositiveInteger,
- xsdNegativeInteger,
- xsdLong,
- xsdInt,
- xsdShort,
- xsdByte,
- xsdNonNegativeInteger,
- xsdUnsignedLong,
- xsdUnsignedInt,
- xsdUnsignedShort,
- xsdUnsignedByte,
- xsdPositiveInteger,
- tnsRawDataFile,
- tnsCsvDataFile,
- tnsEspStringArray,
- tnsEspIntArray,
- tnsXmlDataSet,
- maxWsEclType
- } wsEclType;
- bool CWsWorkunitsEx::onWUAddLocalFileToWorkunit(IEspContext& context, IEspWUAddLocalFileToWorkunitRequest& req, IEspWUAddLocalFileToWorkunitResponse& resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUAddLocalFileToWorkunit", wuid);
- ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
- resp.setWuid(wuid.str());
- const char* varname = req.getName();
- if (isEmpty(varname))
- {
- resp.setResult("Name is not defined!");
- return true;
- }
- resp.setName(varname);
- wsEclType type = (wsEclType) req.getType();
- const char *val = req.getVal();
- unsigned len = req.getLength();
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
- if (!wu)
- {
- resp.setResult("Workunit not found!");
- return true;
- }
- Owned<IWUResult> wuRslt = wu->updateResultByName(varname);
- if (isEmpty(val))
- val=req.getDefVal();
- if (notEmpty(val))
- {
- switch (type)
- {
- case xsdBoolean:
- wuRslt->setResultBool((strieq(val, "1") || strieq(val, "true") || strieq(val, "on")));
- wuRslt->setResultStatus(ResultStatusSupplied);
- break;
- case xsdDecimal:
- case xsdFloat:
- case xsdDouble:
- wuRslt->setResultReal(atof(val));
- wuRslt->setResultStatus(ResultStatusSupplied);
- break;
- case xsdInteger:
- case xsdNonPositiveInteger:
- case xsdNegativeInteger:
- case xsdLong:
- case xsdInt:
- case xsdShort:
- case xsdByte:
- case xsdNonNegativeInteger:
- case xsdUnsignedLong:
- case xsdUnsignedInt:
- case xsdUnsignedShort:
- case xsdUnsignedByte:
- case xsdPositiveInteger:
- wuRslt->setResultInt(_atoi64(val));
- wuRslt->setResultStatus(ResultStatusSupplied);
- break;
- case tnsEspIntArray:
- case tnsEspStringArray:
- wuRslt->setResultRaw(len, val, ResultFormatXmlSet);
- break;
- case tnsRawDataFile:
- wuRslt->setResultRaw(len, val, ResultFormatRaw);
- break;
- case tnsXmlDataSet:
- wuRslt->setResultRaw(len, val, ResultFormatXml);
- break;
- case tnsCsvDataFile:
- case xsdBase64Binary: //tbd
- case xsdHexBinary:
- break;
- default:
- wuRslt->setResultString(val, len);
- wuRslt->setResultStatus(ResultStatusSupplied);
- break;
- }
- }
- resp.setResult("Result has been set as required!");
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- void getClusterConfig(char const * clusterType, char const * clusterName, char const * processName, StringBuffer& netAddress)
- {
- Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
- Owned<IConstEnvironment> environment = factory->openEnvironmentByFile();
- Owned<IPropertyTree> pRoot = &environment->getPTree();
- VStringBuffer xpath("Software/%s[@name='%s']", clusterType, clusterName);
- IPropertyTree* pCluster = pRoot->queryPropTree(xpath.str());
- if (!pCluster)
- throw MakeStringException(ECLWATCH_CLUSTER_NOT_IN_ENV_INFO, "'%s %s' is not defined.", clusterType, clusterName);
- const char* port = pCluster->queryProp(xpath.set(processName).append("@port").str());
- const char* computer = pCluster->queryProp(xpath.set(processName).append("@computer").str());
- if (isEmpty(computer))
- throw MakeStringException(ECLWATCH_INVALID_CLUSTER_INFO, "'%s %s: %s' is not defined.", clusterType, clusterName, processName);
- Owned<IConstMachineInfo> pMachine = environment->getMachine(computer);
- if (pMachine)
- {
- StringBufferAdaptor s(netAddress);
- pMachine->getNetAddress(s);
- #ifdef MACHINE_IP
- if (streq(netAddress.str(), "."))
- netAddress = MACHINE_IP;
- #endif
- netAddress.append(':').append(port);
- }
- return;
- }
- bool CWsWorkunitsEx::onWUProcessGraph(IEspContext &context,IEspWUProcessGraphRequest &req, IEspWUProcessGraphResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUProcessGraph", wuid);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
- Owned <IConstWUGraph> graph = cw->getGraph(req.getName());
- Owned <IPropertyTree> xgmml = graph->getXGMMLTree(true); // merge in graph progress information
- StringBuffer xml;
- resp.setTheGraph(toXML(xgmml.get(), xml).str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool isRunning(IConstWorkUnit &cw)
- {
- // MORE - move into workunit interface
- switch (cw.getState())
- {
- case WUStateFailed:
- case WUStateAborted:
- case WUStateCompleted:
- return false;
- default:
- return true;
- }
- }
- bool CWsWorkunitsEx::onWUGetGraph(IEspContext& context, IEspWUGetGraphRequest& req, IEspWUGetGraphResponse& resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUGetGraph", wuid);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
- WUGraphIDType id;
- SCMStringBuffer runningGraph;
- bool running= (isRunning(*cw) && cw->getRunningGraph(runningGraph,id));
- IArrayOf<IEspECLGraphEx> graphs;
- Owned<IConstWUGraphIterator> it = &cw->getGraphs(GraphTypeAny);
- ForEach(*it)
- {
- IConstWUGraph &graph = it->query();
- if(!graph.isValid())
- continue;
- SCMStringBuffer name, label, type;
- graph.getName(name);
- graph.getLabel(label);
- graph.getTypeName(type);
- if(isEmpty(req.getGraphName()) || strieq(name.str(), req.getGraphName()))
- {
- Owned<IEspECLGraphEx> g = createECLGraphEx("","");
- g->setName(name.str());
- g->setLabel(label.str());
- g->setType(type.str());
- if(running && streq(name.str(), runningGraph.str()))
- {
- g->setRunning(true);
- g->setRunningId(id);
- }
- Owned<IPropertyTree> xgmml = graph.getXGMMLTree(true);
- // New functionality, if a subgraph id is specified and we only want to load the xgmml for that subgraph
- // then we need to conditionally pull a propertytree from the xgmml graph one and use that for the xgmml.
- StringBuffer xml;
- if (notEmpty(req.getSubGraphId()))
- {
- VStringBuffer xpath("//node[@id='%s']", req.getSubGraphId());
- toXML(xgmml->queryPropTree(xpath.str()), xml);
- }
- else
- toXML(xgmml, xml);
- g->setGraph(xml.str());
- if (context.getClientVersion() > 1.20)
- {
- Owned<IConstWUGraphProgress> progress = cw->getGraphProgress(name.str());
- if (progress)
- {
- WUGraphState graphstate= progress->queryGraphState();
- if (graphstate == WUGraphComplete)
- g->setComplete(true);
- else if (graphstate == WUGraphFailed)
- g->setFailed(true);
- }
- }
- graphs.append(*g.getClear());
- }
- }
- resp.setGraphs(graphs);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onGVCAjaxGraph(IEspContext &context, IEspGVCAjaxGraphRequest &req, IEspGVCAjaxGraphResponse &resp)
- {
- try
- {
- resp.setName(req.getName());
- resp.setGraphName(req.getGraphName());
- resp.setGraphType("eclwatch");
- double version = context.getClientVersion();
- if (version > 1.19)
- resp.setSubGraphId(req.getSubGraphId());
- if (version > 1.20)
- resp.setSubGraphOnly(req.getSubGraphOnly());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUGraphInfo(IEspContext &context,IEspWUGraphInfoRequest &req, IEspWUGraphInfoResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUGraphInfo", wuid);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
- resp.setWuid(wuid.str());
- resp.setName(req.getName());
- resp.setRunning(isRunning(*cw));
- if (notEmpty(req.getGID()))
- resp.setGID(req.getGID());
- if(!req.getBatchWU_isNull())
- resp.setBatchWU(req.getBatchWU());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUGVCGraphInfo(IEspContext &context,IEspWUGVCGraphInfoRequest &req, IEspWUGVCGraphInfoResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUGVCGraphInfo", wuid);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
- resp.setWuid(wuid.str());
- resp.setName(req.getName());
- resp.setRunning(isRunning(*cw));
- if (notEmpty(req.getGID()))
- resp.setGID(req.getGID());
- if(!req.getBatchWU_isNull())
- resp.setBatchWU(req.getBatchWU());
- StringBuffer xml("<Control><Endpoint><Query id=\"Gordon.Extractor.0\">");
- xml.appendf("<Graph id=\"%s\">", req.getName());
- if (context.getClientVersion() > 1.17)
- {
- xml.append("<Subgraph>");
- xml.append(req.getSubgraphId_isNull() ? 0 : req.getSubgraphId());
- xml.append("</Subgraph>");
- }
- xml.append("</Graph></Query></Endpoint></Control>");
- resp.setTheGraph(xml.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUGraphTiming(IEspContext &context, IEspWUGraphTimingRequest &req, IEspWUGraphTimingResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWuid();
- WsWuHelpers::checkAndTrimWorkunit("WUGraphTiming", wuid);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
- resp.updateWorkunit().setWuid(wuid.str());
- WsWuInfo winfo(context, cw);
- IArrayOf<IConstECLTimingData> timingData;
- winfo.getGraphTimingData(timingData, 0);
- resp.updateWorkunit().setTimingData(timingData);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- int CWsWorkunitsSoapBindingEx::onGetForm(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
- {
- try
- {
- StringBuffer xml;
- StringBuffer xslt;
- if(strieq(method,"WUQuery") || strieq(method,"WUJobList"))
- {
- Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
- Owned<IConstEnvironment> environment = factory->openEnvironmentByFile();
- Owned<IPropertyTree> root = &environment->getPTree();
- if (!root)
- throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
- if(strieq(method,"WUQuery"))
- {
- SecAccessFlags accessOwn;
- SecAccessFlags accessOthers;
- getUserWuAccessFlags(context, accessOwn, accessOthers, false);
- xml.append("<WUQuery>");
- if ((accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
- xml.appendf("<ErrorMessage>Access to workunit is denied.</ErrorMessage>");
- else
- {
- MapStringTo<bool> added;
- Owned<IPropertyTreeIterator> it = root->getElements("Software/Topology/Cluster");
- ForEach(*it)
- {
- const char *name = it->query().queryProp("@name");
- if (notEmpty(name) && !added.getValue(name))
- {
- added.setValue(name, true);
- appendXMLTag(xml, "Cluster", name);
- }
- }
- }
- xml.append("</WUQuery>");
- xslt.append(getCFD()).append("./smc_xslt/wuid_search.xslt");
- }
- else if (strieq(method,"WUJobList"))
- {
- StringBuffer cluster;
- request->getParameter("Cluster", cluster);
- StringBuffer range;
- request->getParameter("Range",range);
- Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(cluster);
- xml.append("<WUJobList>");
- if (range.length())
- appendXMLTag(xml, "Range", range.str());
- if (clusterInfo)
- {
- const StringArray &thorInstances = clusterInfo->getThorProcesses();
- ForEachItemIn(i, thorInstances)
- {
- xml.append("<Cluster").append('>').append(thorInstances.item(i)).append("</Cluster>");
- }
- }
- xml.append("<TargetCluster>").append(cluster).append("</TargetCluster>");
- xml.append("</WUJobList>");
- xslt.append(getCFD()).append("./smc_xslt/jobs_search.xslt");
- response->addHeader("Expires", "0");
- }
- }
- if (xslt.length() && xml.length())
- {
- StringBuffer html;
- xsltTransform(xml.str(), xslt.str(), NULL, html);
- response->setContent(html.str());
- response->setContentType(HTTP_TYPE_TEXT_HTML_UTF8);
- response->send();
- return 0;
- }
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return onGetNotFound(context, request, response, service);
- }
- void deployEclOrArchive(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
- {
- NewWsWorkunit wu(context);
- SCMStringBuffer wuid;
- wu->getWuid(wuid);
- wu->setAction(WUActionCompile);
- StringBuffer name(req.getName());
- if (!name.trim().length() && notEmpty(req.getFileName()))
- splitFilename(req.getFileName(), NULL, NULL, &name, NULL);
- if (name.length())
- wu->setJobName(name.str());
- if (req.getObject().length())
- {
- StringBuffer text(req.getObject().length(), req.getObject().toByteArray());
- wu.setQueryText(text.str());
- }
- if (req.getQueryMainDefinition())
- wu.setQueryMain(req.getQueryMainDefinition());
- if (req.getSnapshot())
- wu->setSnapshot(req.getSnapshot());
- if (!req.getResultLimit_isNull())
- wu->setResultLimit(req.getResultLimit());
- wu->commit();
- wu.clear();
- WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), NULL, 0, true, false, false, NULL, NULL, &req.getDebugValues());
- waitForWorkUnitToCompile(wuid.str(), req.getWait());
- WsWuInfo winfo(context, wuid.str());
- winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
- winfo.getExceptions(resp.updateWorkunit(), WUINFO_All);
- name.clear();
- if (notEmpty(resp.updateWorkunit().getJobname()))
- origValueChanged(req.getName(), resp.updateWorkunit().getJobname(), name, false);
- if (name.length()) //non generated user specified name, so override #Workunit('name')
- {
- WorkunitUpdate wx(&winfo.cw->lock());
- wx->setJobName(name.str());
- resp.updateWorkunit().setJobname(name.str());
- }
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
- }
- StringBuffer &sharedObjectFileName(StringBuffer &filename, const char *name, const char *ext, unsigned copy)
- {
- filename.append((name && *name) ? name : "workunit");
- if (copy)
- filename.append('-').append(copy);
- if (notEmpty(ext))
- filename.append(ext);
- return filename;
- }
- inline StringBuffer &buildFullDllPath(StringBuffer &dllpath, StringBuffer &dllname, const char *dir, const char *name, const char *ext, unsigned copy)
- {
- return addPathSepChar(dllpath.set(dir)).append(sharedObjectFileName(dllname, name, ext, copy));
- }
- void writeSharedObject(const char *srcpath, const MemoryBuffer &obj, const char *dir, StringBuffer &dllpath, StringBuffer &dllname)
- {
- StringBuffer name, ext;
- if (srcpath && *srcpath)
- splitFilename(srcpath, NULL, NULL, &name, &ext);
- unsigned copy=0;
- buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), copy);
- while (checkFileExists(dllpath.str()))
- buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), ++copy);
- DBGLOG("Writing workunit dll: %s", dllpath.str());
- Owned<IFile> f = createIFile(dllpath.str());
- Owned<IFileIO> io = f->open(IFOcreate);
- io->write(0, obj.length(), obj.toByteArray());
- }
- 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)
- {
- StringBuffer dllpath, dllname;
- StringBuffer srcname(filename);
- if (!srcname.length())
- srcname.append(name).append(SharedObjectExtension);
- writeSharedObject(srcname.str(), obj, dir, dllpath, dllname);
- NewWsWorkunit wu(context);
- StringBufferAdaptor isvWuid(wuid);
- wu->getWuid(isvWuid);
- wu->setClusterName(cluster);
- wu->commit();
- StringBuffer dllXML;
- if (getWorkunitXMLFromFile(dllpath.str(), dllXML))
- {
- Owned<ILocalWorkUnit> embeddedWU = createLocalWorkUnit();
- embeddedWU->loadXML(dllXML.str());
- queryExtendedWU(wu)->copyWorkUnit(embeddedWU, true);
- }
- wu.associateDll(dllpath.str(), dllname.str());
- if (name && *name)
- wu->setJobName(name);
- //clean slate, copy only select items from processed workunit xml
- if (xml && *xml)
- {
- Owned<IPropertyTree> srcxml = createPTreeFromXMLString(xml);
- if (srcxml->hasProp("@jobName"))
- wu->setJobName(srcxml->queryProp("@jobName"));
- if (srcxml->hasProp("@token"))
- wu->setSecurityToken(srcxml->queryProp("@token"));
- if (srcxml->hasProp("Query/Text"))
- wu.setQueryText(srcxml->queryProp("Query/Text"));
- }
- wu->setState(WUStateCompiled);
- wu->commit();
- wu.clear();
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
- }
- void CWsWorkunitsEx::deploySharedObject(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp, const char *dir, const char *xml)
- {
- if (isEmpty(req.getFileName()))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "File name required when deploying a shared object.");
- const char *cluster = req.getCluster();
- if (isEmpty(cluster))
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name required when deploying a shared object.");
- StringBuffer wuid;
- deploySharedObject(context, wuid, req.getFileName(), cluster, req.getName(), req.getObject(), dir, xml);
- WsWuInfo winfo(context, wuid.str());
- winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
- AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
- }
- bool CWsWorkunitsEx::onWUDeployWorkunit(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
- {
- const char *type = req.getObjType();
- try
- {
- if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
- throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
- if (notEmpty(req.getCluster()) && !isValidCluster(req.getCluster()))
- throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", req.getCluster());
- if (strieq(type, "archive")|| strieq(type, "ecl_text"))
- deployEclOrArchive(context, req, resp);
- else if (strieq(type, "shared_object"))
- deploySharedObject(context, req, resp, queryDirectory.str());
- else
- throw MakeStringException(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit '%s' unkown object type.", type);
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- #ifdef _USE_ZLIB
- void CWsWorkunitsEx::addProcessLogfile(IZZIPor* zipper, Owned<IConstWorkUnit> &cwu, WsWuInfo &winfo, const char * process, PointerArray &mbArr)
- {
- Owned<IPropertyTreeIterator> procs = cwu->getProcesses(process, NULL);
- ForEach (*procs)
- {
- StringBuffer logSpec;
- IPropertyTree& proc = procs->query();
- proc.getProp("@log",logSpec);
- if (!logSpec.length())
- continue;
- StringBuffer pid;
- pid.appendf("%d",proc.getPropInt("@pid"));
- MemoryBuffer * pMB = NULL;
- try
- {
- pMB = new MemoryBuffer;
- if (0 == stricmp(process, "EclAgent"))
- winfo.getWorkunitEclAgentLog(logSpec.str(), pid.str(), *pMB);
- else if (0 == stricmp(process, "Thor"))
- winfo.getWorkunitThorLog(logSpec.str(), *pMB);
- else
- {
- delete pMB;
- return;
- }
- mbArr.append(pMB);
- }
- catch(IException *e)
- {
- StringBuffer s;
- e->errorMessage(s);
- pMB->append(s.str());
- e->Release();
- mbArr.append(pMB);
- }
- if (pMB && pMB->length())
- {
- const char * logName = logSpec.str();
- for (const char * p=logSpec; *p; p++)
- {
- if (*p == '\\' || *p == '/')
- logName = p+1;
- }
- zipper->addContentToZIP(pMB->length(), pMB->bufferBase(), (char*)logName, true);
- }
- }
- }
- #endif
- bool CWsWorkunitsEx::onWUCreateZAPInfo(IEspContext &context, IEspWUCreateZAPInfoRequest &req, IEspWUCreateZAPInfoResponse &resp)
- {
- try
- {
- #ifndef _USE_ZLIB
- throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
- #else
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cwu = factory->openWorkUnit(req.getWuid(), false);
- if(!cwu.get())
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Cannot open workunit %s.", req.getWuid());
- //Create output report file
- StringBuffer zipFile;
- StringBuffer userName;
- if (context.queryUser())
- userName.append(context.queryUser()->getName());
- zipFile.append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".zip");
- SCMStringBuffer temp;
- StringBuffer sb;
- sb.append("Workunit: ").append(cwu->getWuid(temp)).append("\r\n");
- sb.append("User: ").append(cwu->getUser(temp).str()).append("\r\n");
- sb.append("Build Version:").append(req.getBuildVersion()).append("\r\n");
- sb.append("Cluster: ").append(cwu->getClusterName(temp).str()).append("\r\n");
- if (req.getESPIPAddress())
- sb.append("ESP: ").append(req.getESPIPAddress()).append("\r\n");
- if (req.getThorIPAddress())
- sb.append("Thor: ").append(req.getThorIPAddress()).append("\r\n");
- //Exceptions/Warnings/Info
- Owned<IConstWUExceptionIterator> exceptions = &cwu->getExceptions();
- StringBuffer info, warn, err;
- ForEach(*exceptions)
- {
- switch (exceptions->query().getSeverity())
- {
- case ExceptionSeverityInformation:
- info.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
- break;
- case ExceptionSeverityWarning:
- warn.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
- break;
- case ExceptionSeverityError:
- err.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
- break;
- }
- }
- if (err.length())
- sb.append("Exceptions: ").append("\r\n").append(err);
- if (warn.length())
- sb.append("Warnings: ").append("\r\n").append(warn);
- if (info.length())
- sb.append("Information: ").append("\r\n").append(info);
- //User provided Information
- sb.append("Problem: ").append(req.getProblemDescription()).append("\r\n\r\n");
- sb.append("What Changed: ").append(req.getWhatChanged()).append("\r\n\r\n");
- sb.append("Timing: ").append(req.getWhereSlow()).append("\r\n\r\n");
- //Zip all files together
- {
- IZZIPor* zipper = createZZIPor();
- #ifdef _DEBUG
- zipper->setTraceLevel(100);
- #endif
- StringBuffer fs;
- //add report file to ZIP
- fs.append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".txt");
- zipper->addContentToZIP(sb.length(), (void*)sb.str(), (char*)fs.str(), false);
- //add ECL query/archive to zip
- Owned<IConstWUQuery> query = cwu->getQuery();
- StringBuffer eclContents;//String buffers containing file contents must persist until ziptofile is called !
- StringBuffer archiveContents;//String buffers containing file contents must persist until ziptofile is called !
- if(query)
- {
- //Add archive if present
- Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
- ForEach(*iter)
- {
- IConstWUAssociatedFile & cur = iter->query();
- SCMStringBuffer ssb;
- cur.getDescription(ssb);
- if (0 == stricmp(ssb.str(), "archive"))
- {
- cur.getName(ssb);
- if (ssb.length())
- {
- fs.clear().append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".archive");
- try
- {
- archiveContents.loadFile(ssb.str());
- zipper->addContentToZIP(archiveContents.length(), (void*)archiveContents.str(), (char*)fs.str(), true);
- }
- catch (IException *E)
- {
- DBGLOG("Error accessing archive file %s", ssb.str());
- E->Release();
- }
- break;
- }
- }
- }
- //Add Query
- query->getQueryText(temp);
- if (temp.length())
- {
- fs.clear().append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".ecl");
- eclContents.append(temp.str());
- zipper->addContentToZIP(eclContents.length(), (void*)eclContents.str(), (char*)fs.str(), true);
- }
- }
- //Add logfiles to ZIP
- WsWuInfo winfo(context, cwu);
- PointerArray eclAgentLogs;//array of dynamically allocated MemoryBuffers
- PointerArray thorLogs;
- addProcessLogfile(zipper, cwu, winfo, "EclAgent", eclAgentLogs);
- addProcessLogfile(zipper, cwu, winfo, "Thor", thorLogs);
- //Add Workunit XML file
- MemoryBuffer wuXmlMB;
- winfo.getWorkunitXml(NULL, wuXmlMB);
- fs.clear().append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str()).append(".xml");
- zipper->addContentToZIP(wuXmlMB.length(), (void*)wuXmlMB.toByteArray(), (char*)fs.str(), true);
- //Write out ZIP file
- zipper->zipToFile(zipFile.str());
- for (aindex_t x=0; x<eclAgentLogs.length(); x++)
- delete (MemoryBuffer*)eclAgentLogs.item(x);
- for (aindex_t x=0; x<thorLogs.length(); x++)
- delete (MemoryBuffer*)thorLogs.item(x);
- }
- //Download ZIP file to user
- Owned<IFile> f = createIFile(zipFile.str());
- Owned<IFileIO> io = f->open(IFOread);
- MemoryBuffer mb;
- void * data = mb.reserve((unsigned)io->size());
- size32_t read = io->read(0, (unsigned)io->size(), data);
- mb.setLength(read);
- resp.setThefile(mb);
- resp.setThefile_mimetype(HTTP_TYPE_OCTET_STREAM);
- StringBuffer headerStr("attachment;filename=");
- headerStr.append(zipFile.str());
- context.addCustomerHeader("Content-disposition", headerStr.str());
- io->close();
- f->remove();
- #endif
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
- bool CWsWorkunitsEx::onWUGetZAPInfo(IEspContext &context, IEspWUGetZAPInfoRequest &req, IEspWUGetZAPInfoResponse &resp)
- {
- try
- {
- StringBuffer wuid = req.getWUID();
- WsWuHelpers::checkAndTrimWorkunit("WUGetZAPInfo", wuid);
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
- Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
- if(!cw)
- throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
- StringBuffer EspIP, ThorIP;
- resp.setWUID(wuid.str());
- resp.setBuildVersion(getBuildVersion());
- IpAddress ipaddr = queryHostIP();
- ipaddr.getIpText(EspIP);
- resp.setESPIPAddress(EspIP.str());
- //Get Archive
- Owned<IConstWUQuery> query = cw->getQuery();
- if(query)
- {
- SCMStringBuffer queryText;
- query->getQueryText(queryText);
- if (queryText.length() && isArchiveQuery(queryText.str()))
- resp.setArchive(queryText.str());
- }
- //Get Thor IP
- BoolHash uniqueProcesses, uniqueThorIPs;
- Owned<IStringIterator> thorInstances = cw->getProcesses("Thor");
- ForEach (*thorInstances)
- {
- SCMStringBuffer processName;
- thorInstances->str(processName);
- if ((processName.length() < 1) || uniqueProcesses.getValue(processName.str()))
- continue;
- uniqueProcesses.setValue(processName.str(), true);
- Owned<IStringIterator> thorLogs = cw->getLogs("Thor", processName.str());
- ForEach (*thorLogs)
- {
- SCMStringBuffer logName;
- thorLogs->str(logName);
- if (!logName.length())
- continue;
- const char* thorIPPtr = NULL;
- const char* ptr = logName.str();
- while (ptr)
- {
- if (!thorIPPtr && (*ptr != '/'))
- thorIPPtr = ptr;
- else if (thorIPPtr && (*ptr == '/'))
- break;
- ptr++;
- }
- if (!thorIPPtr)
- continue;
- //Found a thor IP
- if (ThorIP.length())
- ThorIP.append(",");
- if (!*ptr)
- ThorIP.append(thorIPPtr);
- else
- ThorIP.append(ptr-thorIPPtr, thorIPPtr);
- }
- }
- if (ThorIP.length())
- resp.setThorIPAddress(ThorIP.str());
- }
- catch(IException* e)
- {
- FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
- }
- return true;
- }
|