ws_workunitsService.cpp 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "ws_workunitsService.hpp"
  14. #include "ws_fs.hpp"
  15. #include "jlib.hpp"
  16. #include "jflz.hpp"
  17. #include "daclient.hpp"
  18. #include "dalienv.hpp"
  19. #include "dadfs.hpp"
  20. #include "daaudit.hpp"
  21. #include "exception_util.hpp"
  22. #include "wujobq.hpp"
  23. #include "eventqueue.hpp"
  24. #include "fileview.hpp"
  25. #include "hqlerror.hpp"
  26. #include "sacmd.hpp"
  27. #include "wuwebview.hpp"
  28. #include "portlist.h"
  29. #include "dllserver.hpp"
  30. #include "schedulectrl.hpp"
  31. #include "scheduleread.hpp"
  32. #include "dadfs.hpp"
  33. #include "dfuwu.hpp"
  34. #include "thorplugin.hpp"
  35. #include "roxiecontrol.hpp"
  36. #include "deftype.hpp"
  37. #include "thorxmlwrite.hpp"
  38. #include "fvdatasource.hpp"
  39. #include "fvresultset.ipp"
  40. #include "ws_wudetails.hpp"
  41. #include "rtlformat.hpp"
  42. #include "package.h"
  43. #ifdef _USE_ZLIB
  44. #include "zcrypt.hpp"
  45. #endif
  46. #define ESP_WORKUNIT_DIR "workunits/"
  47. const char* zipFolder = "tempzipfiles" PATHSEPSTR;
  48. #define SDS_LOCK_TIMEOUT (5*60*1000) // 5 mins
  49. const unsigned CHECK_QUERY_STATUS_THREAD_POOL_SIZE = 25;
  50. class ExecuteExistingQueryInfo
  51. {
  52. public:
  53. ExecuteExistingQueryInfo(IConstWorkUnit *cw)
  54. {
  55. const char *name = cw->queryJobName();
  56. const char *div = strchr(name, '.');
  57. if (div)
  58. {
  59. queryset.set(name, div-name);
  60. query.set(div+1);
  61. }
  62. }
  63. public:
  64. StringAttr queryset;
  65. StringAttr query;
  66. };
  67. //The ECLWUActionNames[] has to match with the ESPenum ECLWUActions in the ecm file.
  68. static unsigned NumOfECLWUActionNames = 11;
  69. static const char *ECLWUActionNames[] = { "Abort", "Delete", "Deschedule", "Reschedule", "Pause",
  70. "PauseNow", "Protect", "Unprotect", "Restore", "Resume", "SetToFailed", NULL };
  71. class CECLWUActionsEx : public SoapEnumParamNew<CECLWUActions>
  72. {
  73. public:
  74. CECLWUActionsEx() : SoapEnumParamNew<CECLWUActions>() { init("ECLWUActions","string", ECLWUActionNames); }
  75. };
  76. static CECLWUActionsEx eclWUActionType;
  77. void setActionResult(const char* wuid, CECLWUActions action, const char* result, const char* strAction, IArrayOf<IConstWUActionResult>* results)
  78. {
  79. if (!results || !wuid || !*wuid || !result || !*result)
  80. return;
  81. Owned<IEspWUActionResult> res = createWUActionResult("", "");
  82. res->setWuid(wuid);
  83. res->setAction(strAction);
  84. res->setResult(result);
  85. results->append(*res.getClear());
  86. }
  87. bool doAction(IEspContext& context, StringArray& wuids, CECLWUActions action, IProperties* params, IArrayOf<IConstWUActionResult>* results)
  88. {
  89. if (!wuids.length())
  90. return true;
  91. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  92. bool bAllSuccess = true;
  93. const char* strAction = (action < NumOfECLWUActionNames) ? ECLWUActionNames[action] : "Unknown Action";
  94. for(aindex_t i=0; i<wuids.length();i++)
  95. {
  96. StringBuffer wuidStr = wuids.item(i);
  97. const char* wuid = wuidStr.trim().str();
  98. if (isEmpty(wuid))
  99. {
  100. WARNLOG("Empty Workunit ID");
  101. continue;
  102. }
  103. try
  104. {
  105. if (!looksLikeAWuid(wuid, 'W'))
  106. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  107. PROGLOG("%s %s", strAction, wuid);
  108. if ((action == CECLWUActions_Restore) || (action == CECLWUActions_EventDeschedule))
  109. {
  110. switch(action)
  111. {
  112. case CECLWUActions_Restore:
  113. {
  114. SocketEndpoint ep;
  115. if (params->hasProp("sashaServerIP"))
  116. ep.set(params->queryProp("sashaServerIP"), params->getPropInt("sashaServerPort"));
  117. else
  118. getSashaNode(ep);
  119. Owned<ISashaCommand> cmd = createSashaCommand();
  120. cmd->setAction(SCA_RESTORE);
  121. cmd->addId(wuid);
  122. Owned<INode> node = createINode(ep);
  123. if (!node)
  124. throw MakeStringException(ECLWATCH_INODE_NOT_FOUND,"INode not found.");
  125. StringBuffer s;
  126. if (!cmd->send(node, 1*60*1000))
  127. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to Archive server at %s.", ep.getUrlStr(s).str());
  128. if (cmd->numIds()==0)
  129. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Could not Archive/restore %s",wuid);
  130. StringBuffer reply;
  131. cmd->getId(0,reply);
  132. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  133. ensureWsWorkunitAccess(context, wuid, SecAccess_Write);
  134. break;
  135. }
  136. case CECLWUActions_EventDeschedule:
  137. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Full, false)
  138. || !context.validateFeatureAccess(OTHERS_WU_ACCESS, SecAccess_Full, false))
  139. ensureWsWorkunitAccess(context, wuid, SecAccess_Full);
  140. descheduleWorkunit(wuid);
  141. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  142. break;
  143. }
  144. }
  145. else
  146. {
  147. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  148. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  149. if(!cw)
  150. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  151. if ((action == CECLWUActions_Delete) && (cw->getState() == WUStateWait))
  152. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,"Cannot delete a workunit which is in a 'Wait' status.");
  153. switch(action)
  154. {
  155. case CECLWUActions_Pause:
  156. {
  157. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  158. WorkunitUpdate wu(&cw->lock());
  159. wu->setAction(WUActionPause);
  160. break;
  161. }
  162. case CECLWUActions_PauseNow:
  163. {
  164. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  165. WorkunitUpdate wu(&cw->lock());
  166. wu->setAction(WUActionPauseNow);
  167. break;
  168. }
  169. case CECLWUActions_Resume:
  170. {
  171. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  172. WorkunitUpdate wu(&cw->lock());
  173. wu->setAction(WUActionResume);
  174. break;
  175. }
  176. case CECLWUActions_Delete:
  177. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  178. {
  179. cw.clear();
  180. if (!factory->deleteWorkUnit(wuid))
  181. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "%s: Workunit cannot be deleted. Please check ESP log.", wuid);
  182. AuditSystemAccess(context.queryUserId(), true, "Deleted %s", wuid);
  183. }
  184. break;
  185. case CECLWUActions_Abort:
  186. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  187. {
  188. if (cw->getState() == WUStateWait)
  189. {
  190. WorkunitUpdate wu(&cw->lock());
  191. wu->deschedule();
  192. wu->setState(WUStateAborted);
  193. }
  194. else
  195. abortWorkUnit(wuid, context.querySecManager(), context.queryUser());
  196. AuditSystemAccess(context.queryUserId(), true, "Aborted %s", wuid);
  197. }
  198. break;
  199. case CECLWUActions_Protect:
  200. case CECLWUActions_Unprotect:
  201. cw->protect((action == CECLWUActions_Protect) ? true:false);
  202. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  203. break;
  204. case CECLWUActions_SetToFailed:
  205. {
  206. WorkunitUpdate wu(&cw->lock());
  207. wu->setState(WUStateFailed);
  208. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  209. }
  210. break;
  211. case CECLWUActions_EventReschedule:
  212. {
  213. WorkunitUpdate wu(&cw->lock());
  214. wu->schedule();
  215. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  216. }
  217. break;
  218. }
  219. }
  220. PROGLOG("%s %s done", strAction, wuid);
  221. setActionResult(wuid, action, "Success", strAction, results);
  222. }
  223. catch (IException *e)
  224. {
  225. bAllSuccess = false;
  226. StringBuffer eMsg;
  227. StringBuffer failedMsg("Failed: ");
  228. setActionResult(wuid, action, failedMsg.append(e->errorMessage(eMsg)).str(), strAction, results);
  229. WARNLOG("Failed to %s for workunit: %s, %s", strAction, wuid, eMsg.str());
  230. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction, wuid);
  231. e->Release();
  232. continue;
  233. }
  234. catch (...)
  235. {
  236. bAllSuccess = false;
  237. StringBuffer failedMsg;
  238. failedMsg.appendf("Unknown exception");
  239. setActionResult(wuid, action, failedMsg.str(), strAction, results);
  240. WARNLOG("Failed to %s for workunit: %s, %s", strAction, wuid, failedMsg.str());
  241. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction, wuid);
  242. continue;
  243. }
  244. }
  245. int timeToWait = 0;
  246. if (params)
  247. timeToWait = params->getPropInt("BlockTillFinishTimer");
  248. if (timeToWait != 0)
  249. {
  250. for(aindex_t i=0; i<wuids.length();i++)
  251. {
  252. const char* wuid=wuids.item(i);
  253. if (isEmpty(wuid))
  254. continue;
  255. waitForWorkUnitToComplete(wuid, timeToWait);
  256. }
  257. }
  258. return bAllSuccess;
  259. }
  260. bool doProtectWorkunits(IEspContext& context, StringArray& wuids, IArrayOf<IConstWUActionResult>* results)
  261. {
  262. Owned<IProperties> params(createProperties(true));
  263. params->setProp("BlockTillFinishTimer", 0);
  264. return doAction(context, wuids, CECLWUActions_Protect, params, results);
  265. }
  266. bool doUnProtectWorkunits(IEspContext& context, StringArray& wuids, IArrayOf<IConstWUActionResult>* results)
  267. {
  268. Owned<IProperties> params(createProperties(true));
  269. params->setProp("BlockTillFinishTimer", 0);
  270. return doAction(context, wuids, CECLWUActions_Unprotect, params, results);
  271. }
  272. static void checkUpdateQuerysetLibraries()
  273. {
  274. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  275. if (!globalLock)
  276. return;
  277. IPropertyTree *root = globalLock->queryRoot();
  278. if (!root)
  279. return;
  280. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  281. Owned<IPropertyTreeIterator> querySets = root->getElements("QuerySet");
  282. ForEach(*querySets)
  283. {
  284. IPropertyTree &querySet = querySets->query();
  285. if (querySet.hasProp("@updatedLibraries")) //only need to do this once, then publish and copy will keep up to date
  286. continue;
  287. Owned<IPropertyTreeIterator> queries = querySet.getElements("Query");
  288. ForEach(*queries)
  289. {
  290. IPropertyTree &query = queries->query();
  291. if (query.hasProp("@libCount"))
  292. continue;
  293. const char *wuid = query.queryProp("@wuid");
  294. if (!wuid || !*wuid)
  295. continue;
  296. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  297. if (!cw)
  298. continue;
  299. checkAddLibrariesToQueryEntry(&query, cw);
  300. }
  301. querySet.setPropBool("@updatedLibraries", true);
  302. }
  303. }
  304. void CWsWorkunitsEx::init(IPropertyTree *cfg, const char *process, const char *service)
  305. {
  306. if (!daliClientActive())
  307. {
  308. ERRLOG("No Dali Connection Active.");
  309. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  310. }
  311. setPasswordsFromSDS();
  312. DBGLOG("Initializing %s service [process = %s]", service, process);
  313. checkUpdateQuerysetLibraries();
  314. refreshValidClusters();
  315. daliServers.set(cfg->queryProp("Software/EspProcess/@daliServers"));
  316. const char *computer = cfg->queryProp("Software/EspProcess/@computer");
  317. if (daliServers.isEmpty() || !computer || streq(computer, "localhost")) //otherwise can't assume environment "." netAddresses are the same as my address
  318. queryHostIP().getIpText(envLocalAddress);
  319. else
  320. {
  321. //a bit weird, but other netAddresses in the environment are not the same localhost as this server
  322. //use the address of the DALI
  323. const char *finger = daliServers.get();
  324. while (*finger && !strchr(":;,", *finger))
  325. envLocalAddress.append(*finger++);
  326. }
  327. awusCacheMinutes = AWUS_CACHE_MIN_DEFAULT;
  328. VStringBuffer xpath("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/AWUsCacheMinutes", process, service);
  329. cfg->getPropInt(xpath.str(), awusCacheMinutes);
  330. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@netAddress", process, service);
  331. if (cfg->hasProp(xpath.str()))
  332. {
  333. sashaServerIp.set(cfg->queryProp(xpath.str()));
  334. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@port", process, service);
  335. sashaServerPort = cfg->getPropInt(xpath.str(), DEFAULT_SASHA_PORT);
  336. }
  337. maxRequestEntityLength = cfg->getPropInt("Software[1]/EspProcess[1]/EspProtocol[@type='http_protocol'][1]/@maxRequestEntityLength");
  338. directories.set(cfg->queryPropTree("Software/Directories"));
  339. const char *name = cfg->queryProp("Software/EspProcess/@name");
  340. getConfigurationDirectory(directories, "query", "esp", name ? name : "esp", queryDirectory);
  341. recursiveCreateDirectory(queryDirectory.str());
  342. dataCache.setown(new DataCache(DATA_SIZE));
  343. archivedWuCache.setown(new ArchivedWuCache(AWUS_CACHE_SIZE));
  344. wuArchiveCache.setown(new WUArchiveCache(WUARCHIVE_CACHE_SIZE));
  345. //Create a folder for temporarily holding gzip files by WUResultBin()
  346. Owned<IFile> tmpdir = createIFile(TEMPZIPDIR);
  347. if(!tmpdir->exists())
  348. tmpdir->createDirectory();
  349. recursiveCreateDirectory(ESP_WORKUNIT_DIR);
  350. m_sched.start();
  351. filesInUse.subscribe();
  352. //Start thread pool
  353. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ClusterQueryStateThreadPoolSize", process, service);
  354. Owned<CClusterQueryStateThreadFactory> threadFactory = new CClusterQueryStateThreadFactory();
  355. clusterQueryStatePool.setown(createThreadPool("CheckAndSetClusterQueryState Thread Pool", threadFactory, NULL,
  356. cfg->getPropInt(xpath.str(), CHECK_QUERY_STATUS_THREAD_POOL_SIZE)));
  357. }
  358. void CWsWorkunitsEx::refreshValidClusters()
  359. {
  360. validClusters.kill();
  361. Owned<IStringIterator> it = getTargetClusters(NULL, NULL);
  362. ForEach(*it)
  363. {
  364. SCMStringBuffer s;
  365. IStringVal &val = it->str(s);
  366. bool* found = validClusters.getValue(val.str());
  367. if (!found || !*found)
  368. validClusters.setValue(val.str(), true);
  369. }
  370. }
  371. bool CWsWorkunitsEx::isValidCluster(const char *cluster)
  372. {
  373. if (!cluster || !*cluster)
  374. return false;
  375. CriticalBlock block(crit);
  376. bool* found = validClusters.getValue(cluster);
  377. if (found && *found)
  378. return true;
  379. if (validateTargetClusterName(cluster))
  380. {
  381. refreshValidClusters();
  382. return true;
  383. }
  384. return false;
  385. }
  386. bool CWsWorkunitsEx::onWUCreate(IEspContext &context, IEspWUCreateRequest &req, IEspWUCreateResponse &resp)
  387. {
  388. try
  389. {
  390. NewWsWorkunit wu(context);
  391. resp.updateWorkunit().setWuid(wu->queryWuid());
  392. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wu->queryWuid());
  393. }
  394. catch(IException* e)
  395. {
  396. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  397. }
  398. return true;
  399. }
  400. bool origValueChanged(const char *newValue, const char *origValue, StringBuffer &s, bool nillable)
  401. {
  402. if (!nillable && isEmpty(newValue))
  403. return false;
  404. if(newValue && origValue)
  405. {
  406. if (!streq(origValue, newValue))
  407. {
  408. s.append(newValue).trim();
  409. return true;
  410. }
  411. return false;
  412. }
  413. if (newValue)
  414. {
  415. s.append(newValue).trim();
  416. return true;
  417. }
  418. return (origValue!=NULL);
  419. }
  420. bool CWsWorkunitsEx::onWUUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  421. {
  422. try
  423. {
  424. StringBuffer wuid = req.getWuid();
  425. WsWuHelpers::checkAndTrimWorkunit("WUUpdate", wuid);
  426. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  427. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  428. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  429. if(!cw)
  430. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  431. PROGLOG("WUUpdate: %s", wuid.str());
  432. if(req.getProtected() != req.getProtectedOrig())
  433. {
  434. cw->protect(req.getProtected());
  435. cw.clear();
  436. cw.setown(factory->openWorkUnit(wuid.str()));
  437. if(!cw)
  438. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  439. }
  440. if ((req.getState() == WUStateRunning)||(req.getState() == WUStateDebugPaused)||(req.getState() == WUStateDebugRunning))
  441. {
  442. WsWuInfo winfo(context, cw);
  443. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  444. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  445. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  446. return true;
  447. }
  448. WorkunitUpdate wu(&cw->lock());
  449. if(!req.getState_isNull() && (req.getStateOrig_isNull() || req.getState() != req.getStateOrig()))
  450. {
  451. if (!req.getStateOrig_isNull() && cw->getState() != (WUState) req.getStateOrig())
  452. 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());
  453. WUState state = (WUState) req.getState();
  454. if(state < WUStateSize)
  455. wu->setState(state);
  456. }
  457. StringBuffer s;
  458. if (origValueChanged(req.getJobname(), req.getJobnameOrig(), s))
  459. wu->setJobName(s.trim().str());
  460. if (origValueChanged(req.getDescription(), req.getDescriptionOrig(), s.clear()))
  461. wu->setDebugValue("description", (req.getDescription() && *req.getDescription()) ? s.trim().str() : NULL, true);
  462. double version = context.getClientVersion();
  463. if (version > 1.04)
  464. {
  465. if (origValueChanged(req.getClusterSelection(), req.getClusterOrig(), s.clear(), false))
  466. {
  467. if (!isValidCluster(s.str()))
  468. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", s.str());
  469. if (req.getState() == WUStateBlocked)
  470. switchWorkUnitQueue(wu.get(), s.str());
  471. else if ((req.getState() != WUStateSubmitted) && (req.getState() != WUStateRunning) && (req.getState() != WUStateDebugPaused) && (req.getState() != WUStateDebugRunning))
  472. wu->setClusterName(s.str());
  473. }
  474. }
  475. WsWuHelpers::setXmlParameters(wu, req.getXmlParams(), (req.getAction()==WUActionExecuteExisting));
  476. if (notEmpty(req.getQueryText()))
  477. {
  478. Owned<IWUQuery> query=wu->updateQuery();
  479. query->setQueryText(req.getQueryText());
  480. }
  481. if (version > 1.34 && notEmpty(req.getQueryMainDefinition()))
  482. {
  483. Owned<IWUQuery> query=wu->updateQuery();
  484. query->setQueryMainDefinition(req.getQueryMainDefinition());
  485. }
  486. if (!req.getResultLimit_isNull())
  487. wu->setResultLimit(req.getResultLimit());
  488. if (!req.getAction_isNull())
  489. {
  490. WUAction action = (WUAction) req.getAction();
  491. if(action < WUActionSize)
  492. wu->setAction(action);
  493. }
  494. if (!req.getPriorityClass_isNull())
  495. {
  496. WUPriorityClass priority = (WUPriorityClass) req.getPriorityClass();
  497. if(priority<PriorityClassSize)
  498. wu->setPriority(priority);
  499. }
  500. if (!req.getPriorityLevel_isNull())
  501. wu->setPriorityLevel(req.getPriorityLevel());
  502. if (origValueChanged(req.getScope(), req.getScopeOrig(), s.clear(), false))
  503. wu->setWuScope(s.str());
  504. ForEachItemIn(di, req.getDebugValues())
  505. {
  506. IConstDebugValue& item = req.getDebugValues().item(di);
  507. const char *debugName = item.getName();
  508. if (notEmpty(debugName) && *debugName!='-')
  509. wu->setDebugValue(item.getName(), item.getValue(), true);
  510. }
  511. ForEachItemIn(ai, req.getApplicationValues())
  512. {
  513. IConstApplicationValue& item=req.getApplicationValues().item(ai);
  514. if(notEmpty(item.getApplication()) && notEmpty(item.getName()))
  515. wu->setApplicationValue(item.getApplication(), item.getName(), item.getValue(), true);
  516. }
  517. wu->commit();
  518. wu.clear();
  519. WsWuInfo winfo(context, cw);
  520. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  521. StringBuffer thorSlaveIP;
  522. if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
  523. thorSlaveIP = req.getThorSlaveIP();
  524. if (thorSlaveIP.length() > 0)
  525. {
  526. StringBuffer url;
  527. url.appendf("/WsWorkunits/WUInfo?Wuid=%s&ThorSlaveIP=%s", wuid.str(), thorSlaveIP.str());
  528. resp.setRedirectUrl(url.str());
  529. }
  530. else
  531. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  532. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  533. }
  534. catch(IException* e)
  535. {
  536. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  537. }
  538. return true;
  539. }
  540. bool CWsWorkunitsEx::onWUCreateAndUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  541. {
  542. try
  543. {
  544. const char* wuid = req.getWuid();
  545. if (!wuid || !*wuid)
  546. {
  547. NewWsWorkunit wu(context);
  548. req.setWuid(wu->queryWuid());
  549. }
  550. }
  551. catch(IException* e)
  552. {
  553. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  554. }
  555. return onWUUpdate(context, req, resp);
  556. }
  557. static inline StringBuffer &appendUrlParameter(StringBuffer &url, const char *name, const char *value, bool &first)
  558. {
  559. if (notEmpty(value))
  560. {
  561. url.append(first ? '?' : '&').append(name).append('=').append(value);
  562. first=false;
  563. }
  564. return url;
  565. }
  566. bool CWsWorkunitsEx::onWUAction(IEspContext &context, IEspWUActionRequest &req, IEspWUActionResponse &resp)
  567. {
  568. try
  569. {
  570. CECLWUActions action;
  571. double version = context.getClientVersion();
  572. if (version >= 1.57)
  573. action = req.getWUActionType();
  574. else
  575. action = eclWUActionType.toEnum(req.getActionType());
  576. if (action == ECLWUActions_Undefined)
  577. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined.");
  578. Owned<IProperties> params = createProperties(true);
  579. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  580. if ((action == CECLWUActions_Restore) && !sashaServerIp.isEmpty())
  581. {
  582. params->setProp("sashaServerIP", sashaServerIp.get());
  583. params->setProp("sashaServerPort", sashaServerPort);
  584. }
  585. IArrayOf<IConstWUActionResult> results;
  586. if (doAction(context, req.getWuids(), action, params, &results) && (action != CECLWUActions_Delete) && checkRedirect(context))
  587. {
  588. StringBuffer redirect;
  589. if(req.getPageFrom() && strieq(req.getPageFrom(), "wuid"))
  590. redirect.append("/WsWorkunits/WUInfo?Wuid=").append(req.getWuids().item(0));
  591. else if (req.getPageFrom() && strieq(req.getPageFrom(), "scheduler"))
  592. {
  593. redirect.set("/WsWorkunits/WUShowScheduled");
  594. bool first=true;
  595. appendUrlParameter(redirect, "Cluster", req.getEventServer(), first);
  596. appendUrlParameter(redirect, "EventName", req.getEventName(), first);
  597. }
  598. else
  599. {
  600. redirect.append("/WsWorkunits/WUQuery");
  601. bool first=true;
  602. appendUrlParameter(redirect, "PageSize", req.getPageSize(), first);
  603. appendUrlParameter(redirect, "PageStartFrom", req.getCurrentPage(), first);
  604. appendUrlParameter(redirect, "Sortby", req.getSortby(), first);
  605. appendUrlParameter(redirect, "Descending", req.getDescending() ? "1" : "0", first);
  606. appendUrlParameter(redirect, "State", req.getState(), first);
  607. appendUrlParameter(redirect, "Cluster", req.getCluster(), first);
  608. appendUrlParameter(redirect, "Owner", req.getOwner(), first);
  609. appendUrlParameter(redirect, "StartDate", req.getStartDate(), first);
  610. appendUrlParameter(redirect, "EndDate", req.getEndDate(), first);
  611. appendUrlParameter(redirect, "ECL", req.getECL(), first);
  612. appendUrlParameter(redirect, "Jobname", req.getJobname(), first);
  613. }
  614. resp.setRedirectUrl(redirect.str());
  615. }
  616. else
  617. resp.setActionResults(results);
  618. }
  619. catch(IException* e)
  620. {
  621. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  622. }
  623. return true;
  624. }
  625. bool CWsWorkunitsEx::onWUDelete(IEspContext &context, IEspWUDeleteRequest &req, IEspWUDeleteResponse &resp)
  626. {
  627. try
  628. {
  629. IArrayOf<IConstWUActionResult> results;
  630. Owned<IProperties> params = createProperties(true);
  631. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  632. if (!doAction(context,req.getWuids(), CECLWUActions_Delete, params, &results))
  633. resp.setActionResults(results);
  634. }
  635. catch(IException* e)
  636. {
  637. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  638. }
  639. return true;
  640. }
  641. bool CWsWorkunitsEx::onWUAbort(IEspContext &context, IEspWUAbortRequest &req, IEspWUAbortResponse &resp)
  642. {
  643. try
  644. {
  645. IArrayOf<IConstWUActionResult> results;
  646. Owned<IProperties> params = createProperties(true);
  647. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  648. if (!doAction(context,req.getWuids(), CECLWUActions_Abort, params, &results))
  649. resp.setActionResults(results);
  650. }
  651. catch(IException* e)
  652. {
  653. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  654. }
  655. return true;
  656. }
  657. bool CWsWorkunitsEx::onWUProtect(IEspContext &context, IEspWUProtectRequest &req, IEspWUProtectResponse &resp)\
  658. {
  659. try
  660. {
  661. IArrayOf<IConstWUActionResult> results;
  662. Owned<IProperties> params(createProperties(true));
  663. params->setProp("BlockTillFinishTimer", 0);
  664. CECLWUActions action = req.getProtect() ? CECLWUActions_Protect : CECLWUActions_Unprotect;
  665. if (!doAction(context,req.getWuids(), action, params, &results))
  666. resp.setActionResults(results);
  667. }
  668. catch(IException* e)
  669. {
  670. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  671. }
  672. return true;
  673. }
  674. bool CWsWorkunitsEx::onWUResubmit(IEspContext &context, IEspWUResubmitRequest &req, IEspWUResubmitResponse &resp)
  675. {
  676. try
  677. {
  678. Owned<IMultiException> me = MakeMultiException();
  679. StringAttr wuid;
  680. StringArray wuids;
  681. double version = context.getClientVersion();
  682. IArrayOf<IEspResubmittedWU> resubmittedWUs;
  683. for(aindex_t i=0; i<req.getWuids().length();i++)
  684. {
  685. StringBuffer requestWuid = req.getWuids().item(i);
  686. WsWuHelpers::checkAndTrimWorkunit("WUResubmit", requestWuid);
  687. ensureWsWorkunitAccess(context, requestWuid.str(), SecAccess_Write);
  688. PROGLOG("WUResubmit: %s", requestWuid.str());
  689. wuid.set(requestWuid.str());
  690. try
  691. {
  692. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  693. if(req.getCloneWorkunit() || req.getRecompile())
  694. {
  695. Owned<IConstWorkUnit> src(factory->openWorkUnit(wuid.str()));
  696. NewWsWorkunit wu(factory, context);
  697. wuid.set(wu->queryWuid());
  698. queryExtendedWU(wu)->copyWorkUnit(src, false, false);
  699. SCMStringBuffer token;
  700. wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
  701. }
  702. wuids.append(wuid.str());
  703. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str()));
  704. if(!cw)
  705. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  706. WsWuHelpers::submitWsWorkunit(context, cw, NULL, NULL, 0, req.getRecompile(), req.getResetWorkflow(), false);
  707. if (version < 1.40)
  708. continue;
  709. Owned<IEspResubmittedWU> resubmittedWU = createResubmittedWU();
  710. resubmittedWU->setWUID(wuid.str());
  711. if (!streq(requestWuid.str(), wuid.str()))
  712. resubmittedWU->setParentWUID(requestWuid.str());
  713. resubmittedWUs.append(*resubmittedWU.getClear());
  714. }
  715. catch (IException *E)
  716. {
  717. me->append(*E);
  718. }
  719. catch (...)
  720. {
  721. me->append(*MakeStringException(0,"Unknown exception submitting %s",wuid.str()));
  722. }
  723. }
  724. if(me->ordinality())
  725. throw me.getLink();
  726. int timeToWait = req.getBlockTillFinishTimer();
  727. if (timeToWait != 0)
  728. {
  729. for(aindex_t i=0; i<wuids.length(); i++)
  730. waitForWorkUnitToComplete(wuids.item(i), timeToWait);
  731. }
  732. if (version >= 1.40)
  733. resp.setWUs(resubmittedWUs);
  734. if(wuids.length()==1)
  735. {
  736. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuids.item(0)));
  737. }
  738. }
  739. catch(IException* e)
  740. {
  741. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  742. }
  743. return true;
  744. }
  745. bool CWsWorkunitsEx::onWUPushEvent(IEspContext &context, IEspWUPushEventRequest &req, IEspWUPushEventResponse &resp)
  746. {
  747. try
  748. {
  749. const char *name = req.getEventName();
  750. const char *text = req.getEventText();
  751. const char *target = NULL;
  752. if (notEmpty(name) && notEmpty(text))
  753. {
  754. PROGLOG("WUPushEvent: EventName %s, EventText %s", name, text);
  755. Owned<IScheduleEventPusher> pusher(getScheduleEventPusher());
  756. pusher->push(name, text, target);
  757. StringBuffer redirect("/WsWorkunits/WUShowScheduled");
  758. bool first=true;
  759. appendUrlParameter(redirect, "PushEventName", name, first);
  760. appendUrlParameter(redirect, "PushEventText", text, first);
  761. resp.setRedirectUrl(redirect.str());
  762. return true;
  763. }
  764. }
  765. catch(IException* e)
  766. {
  767. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  768. }
  769. return false;
  770. }
  771. bool CWsWorkunitsEx::onWUSchedule(IEspContext &context, IEspWUScheduleRequest &req, IEspWUScheduleResponse &resp)
  772. {
  773. try
  774. {
  775. StringBuffer wuid = req.getWuid();
  776. WsWuHelpers::checkAndTrimWorkunit("WUSchedule", wuid);
  777. const char* cluster = req.getCluster();
  778. if (isEmpty(cluster))
  779. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  780. if (!isValidCluster(cluster))
  781. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  782. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  783. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  784. ensureWsWorkunitAccess(context, *wu.get(), SecAccess_Write);
  785. switch(wu->getState())
  786. {
  787. case WUStateDebugPaused:
  788. case WUStateDebugRunning:
  789. case WUStateRunning:
  790. case WUStateAborting:
  791. case WUStateBlocked:
  792. throw MakeStringException(ECLWATCH_CANNOT_SCHEDULE_WORKUNIT, "Cannot schedule the workunit. Workunit state is '%s'.", wu->queryStateDesc());
  793. }
  794. PROGLOG("WUSchedule: %s", wuid.str());
  795. wu->clearExceptions();
  796. wu->setClusterName(cluster);
  797. if (notEmpty(req.getWhen()))
  798. {
  799. WsWuDateTime dt;
  800. dt.setString(req.getWhen());
  801. wu->setTimeScheduled(dt);
  802. }
  803. if(notEmpty(req.getSnapshot()))
  804. wu->setSnapshot(req.getSnapshot());
  805. wu->setState(WUStateScheduled);
  806. if (req.getMaxRunTime())
  807. wu->setDebugValueInt("maxRunTime", req.getMaxRunTime(), true);
  808. SCMStringBuffer token;
  809. wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
  810. AuditSystemAccess(context.queryUserId(), true, "Scheduled %s", wuid.str());
  811. }
  812. catch(IException* e)
  813. {
  814. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  815. }
  816. return true;
  817. }
  818. bool CWsWorkunitsEx::onWUSubmit(IEspContext &context, IEspWUSubmitRequest &req, IEspWUSubmitResponse &resp)
  819. {
  820. try
  821. {
  822. StringBuffer wuid = req.getWuid();
  823. WsWuHelpers::checkAndTrimWorkunit("WUSubmit", wuid);
  824. const char *cluster = req.getCluster();
  825. if (isEmpty(cluster))
  826. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  827. if (!isValidCluster(cluster))
  828. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  829. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  830. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  831. if(!cw)
  832. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  833. if (cw->getAction()==WUActionExecuteExisting)
  834. {
  835. ExecuteExistingQueryInfo info(cw);
  836. if (info.queryset.isEmpty() || info.query.isEmpty())
  837. {
  838. WorkunitUpdate wu(&cw->lock());
  839. throw WsWuHelpers::noteException(wu, MakeStringException(ECLWATCH_INVALID_INPUT,"Queryset and/or query not specified"));
  840. }
  841. WsWuHelpers::runWsWuQuery(context, cw, info.queryset.str(), info.query.str(), cluster, NULL);
  842. }
  843. else
  844. WsWuHelpers::submitWsWorkunit(context, cw, cluster, req.getSnapshot(), req.getMaxRunTime(), true, false, false);
  845. PROGLOG("WUSubmit: %s", wuid.str());
  846. if (req.getBlockTillFinishTimer() != 0)
  847. waitForWorkUnitToComplete(wuid.str(), req.getBlockTillFinishTimer());
  848. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  849. }
  850. catch(IException* e)
  851. {
  852. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  853. }
  854. return true;
  855. }
  856. ErrorSeverity checkGetExceptionSeverity(CWUExceptionSeverity severity)
  857. {
  858. switch (severity)
  859. {
  860. case CWUExceptionSeverity_INFO:
  861. return SeverityInformation;
  862. case CWUExceptionSeverity_WARNING:
  863. return SeverityWarning;
  864. case CWUExceptionSeverity_ERROR:
  865. return SeverityError;
  866. case CWUExceptionSeverity_ALERT:
  867. return SeverityAlert;
  868. }
  869. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT,"invalid exception severity");
  870. }
  871. bool CWsWorkunitsEx::onWURun(IEspContext &context, IEspWURunRequest &req, IEspWURunResponse &resp)
  872. {
  873. try
  874. {
  875. const char *cluster = req.getCluster();
  876. if (notEmpty(cluster) && !isValidCluster(cluster))
  877. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  878. StringBuffer wuidStr = req.getWuid();
  879. const char* runWuid = wuidStr.trim().str();
  880. StringBuffer wuid;
  881. ErrorSeverity severity = checkGetExceptionSeverity(req.getExceptionSeverity());
  882. if (runWuid && *runWuid)
  883. {
  884. if (!looksLikeAWuid(runWuid, 'W'))
  885. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", runWuid);
  886. PROGLOG("WURun: %s", runWuid);
  887. if (req.getCloneWorkunit())
  888. WsWuHelpers::runWsWorkunit(context, wuid, runWuid, cluster, req.getInput(), &req.getVariables(),
  889. &req.getDebugValues(), &req.getApplicationValues());
  890. else
  891. {
  892. WsWuHelpers::submitWsWorkunit(context, runWuid, cluster, NULL, 0, false, true, true, req.getInput(),
  893. &req.getVariables(), &req.getDebugValues(), &req.getApplicationValues());
  894. wuid.set(runWuid);
  895. }
  896. }
  897. else if (notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  898. {
  899. PROGLOG("WURun: QuerySet %s, Query %s", req.getQuerySet(), req.getQuery());
  900. WsWuHelpers::runWsWuQuery(context, wuid, req.getQuerySet(), req.getQuery(), cluster, req.getInput(),
  901. &req.getApplicationValues());
  902. }
  903. else
  904. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
  905. int timeToWait = req.getWait();
  906. if (timeToWait != 0)
  907. waitForWorkUnitToComplete(wuid.str(), timeToWait);
  908. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  909. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  910. if (!cw)
  911. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.", wuid.str());
  912. resp.setState(cw->queryStateDesc());
  913. resp.setWuid(wuid.str());
  914. switch (cw->getState())
  915. {
  916. case WUStateCompleted:
  917. case WUStateFailed:
  918. case WUStateUnknown:
  919. {
  920. SCMStringBuffer result;
  921. unsigned flags = WorkUnitXML_SeverityTags;
  922. if (req.getNoRootTag())
  923. flags |= WorkUnitXML_NoRoot;
  924. getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  925. resp.setResults(result.str());
  926. break;
  927. }
  928. default:
  929. break;
  930. }
  931. }
  932. catch(IException* e)
  933. {
  934. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  935. }
  936. return true;
  937. }
  938. bool CWsWorkunitsEx::onWUFullResult(IEspContext &context, IEspWUFullResultRequest &req, IEspWUFullResultResponse &resp)
  939. {
  940. try
  941. {
  942. StringBuffer wuid = req.getWuid();
  943. WsWuHelpers::checkAndTrimWorkunit("WUFullResult", wuid);
  944. ErrorSeverity severity = checkGetExceptionSeverity(req.getExceptionSeverity());
  945. if (!wuid.length())
  946. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
  947. if (!looksLikeAWuid(wuid, 'W'))
  948. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid.str());
  949. PROGLOG("WUFullResults: %s", wuid.str());
  950. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  951. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  952. if (!cw)
  953. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.", wuid.str());
  954. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  955. resp.setWuid(wuid.str());
  956. switch (cw->getState())
  957. {
  958. case WUStateCompleted:
  959. case WUStateFailed:
  960. case WUStateUnknown:
  961. {
  962. SCMStringBuffer result;
  963. unsigned flags = WorkUnitXML_SeverityTags;
  964. if (req.getNoRootTag())
  965. flags |= WorkUnitXML_NoRoot;
  966. if (context.getResponseFormat()==ESPSerializationJSON)
  967. getFullWorkUnitResultsJSON(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  968. else
  969. getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  970. resp.setResults(result.str());
  971. break;
  972. }
  973. default:
  974. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT, "Cannot get results Workunit %s %s.", wuid.str(), getWorkunitStateStr(cw->getState()));
  975. }
  976. }
  977. catch(IException* e)
  978. {
  979. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  980. }
  981. return true;
  982. }
  983. bool CWsWorkunitsEx::onWUWaitCompiled(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  984. {
  985. try
  986. {
  987. StringBuffer wuid = req.getWuid();
  988. WsWuHelpers::checkAndTrimWorkunit("WUWaitCompiled", wuid);
  989. PROGLOG("WUWaitCompiled: %s", wuid.str());
  990. secWaitForWorkUnitToCompile(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait());
  991. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  992. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  993. if(!cw)
  994. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  995. resp.setStateID(cw->getState());
  996. }
  997. catch(IException* e)
  998. {
  999. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1000. }
  1001. return true;
  1002. }
  1003. bool CWsWorkunitsEx::onWUWaitComplete(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  1004. {
  1005. try
  1006. {
  1007. StringBuffer wuid = req.getWuid();
  1008. WsWuHelpers::checkAndTrimWorkunit("WUWaitComplete", wuid);
  1009. PROGLOG("WUWaitComplete: %s", wuid.str());
  1010. resp.setStateID(secWaitForWorkUnitToComplete(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait(), req.getReturnOnWait()));
  1011. }
  1012. catch(IException* e)
  1013. {
  1014. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1015. }
  1016. return true;
  1017. }
  1018. bool CWsWorkunitsEx::onWUCDebug(IEspContext &context, IEspWUDebugRequest &req, IEspWUDebugResponse &resp)
  1019. {
  1020. try
  1021. {
  1022. StringBuffer wuid = req.getWuid();
  1023. WsWuHelpers::checkAndTrimWorkunit("WUCDebug", wuid);
  1024. PROGLOG("WUCDebug: %s", wuid.str());
  1025. StringBuffer result;
  1026. secDebugWorkunit(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getCommand(), result);
  1027. resp.setResult(result);
  1028. }
  1029. catch(IException* e)
  1030. {
  1031. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1032. }
  1033. return true;
  1034. }
  1035. bool CWsWorkunitsEx::onWUSyntaxCheckECL(IEspContext &context, IEspWUSyntaxCheckRequest &req, IEspWUSyntaxCheckResponse &resp)
  1036. {
  1037. try
  1038. {
  1039. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1040. NewWsWorkunit wu(factory, context);
  1041. wu->setAction(WUActionCheck);
  1042. if(notEmpty(req.getModuleName()) && notEmpty(req.getAttributeName()))
  1043. {
  1044. wu->setApplicationValue("SyntaxCheck", "ModuleName", req.getModuleName(), true);
  1045. wu->setApplicationValue("SyntaxCheck", "AttributeName", req.getAttributeName(), true);
  1046. }
  1047. ForEachItemIn(di, req.getDebugValues())
  1048. {
  1049. IConstDebugValue& item=req.getDebugValues().item(di);
  1050. const char *debugName = item.getName();
  1051. if (notEmpty(debugName) && *debugName!='-')
  1052. wu->setDebugValue(item.getName(), item.getValue(), true);
  1053. }
  1054. wu.setQueryText(req.getECL());
  1055. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  1056. wu->commit();
  1057. wu.clear();
  1058. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1059. waitForWorkUnitToComplete(wuid.str(), req.getTimeToWait());
  1060. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str()));
  1061. WsWUExceptions errors(*cw);
  1062. resp.setErrors(errors);
  1063. StringBuffer msg;
  1064. WUState st = cw->getState();
  1065. cw.clear();
  1066. switch (st)
  1067. {
  1068. case WUStateAborted:
  1069. case WUStateCompleted:
  1070. case WUStateFailed:
  1071. if (!factory->deleteWorkUnit(wuid.str()))
  1072. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Workunit %s cannot be deleted.", wuid.str());
  1073. break;
  1074. default:
  1075. abortWorkUnit(wuid.str(), context.querySecManager(), context.queryUser());
  1076. if (!factory->deleteWorkUnit(wuid.str()))
  1077. {
  1078. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,
  1079. "WUSyntaxCheckECL has timed out. Workunit %s cannot be deleted now. You may delete it when its status changes.", wuid.str());
  1080. }
  1081. if (context.getClientVersion() < 1.57)
  1082. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "WUSyntaxCheckECL has timed out.");
  1083. resp.setMessage("WUSyntaxCheckECL has timed out.");
  1084. break;
  1085. }
  1086. }
  1087. catch(IException* e)
  1088. {
  1089. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1090. }
  1091. return true;
  1092. }
  1093. bool CWsWorkunitsEx::onWUCompileECL(IEspContext &context, IEspWUCompileECLRequest &req, IEspWUCompileECLResponse &resp)
  1094. {
  1095. try
  1096. {
  1097. ensureWsCreateWorkunitAccess(context);
  1098. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1099. NewWsWorkunit wu(factory, context);
  1100. if(req.getIncludeComplexity())
  1101. {
  1102. wu->setAction(WUActionCompile);
  1103. wu->setDebugValueInt("calculateComplexity",1,true);
  1104. }
  1105. else
  1106. wu->setAction(WUActionCheck);
  1107. if(req.getModuleName() && req.getAttributeName())
  1108. {
  1109. wu->setApplicationValue("SyntaxCheck","ModuleName",req.getModuleName(),true);
  1110. wu->setApplicationValue("SyntaxCheck","AttributeName",req.getAttributeName(),true);
  1111. }
  1112. if(req.getIncludeDependencies())
  1113. wu->setApplicationValueInt("SyntaxCheck","IncludeDependencies",1,true);
  1114. wu.setQueryText(req.getECL());
  1115. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear() StringAttr wuid(wu->queryWuid());
  1116. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1117. waitForWorkUnitToComplete(wuid.str(),req.getTimeToWait());
  1118. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1119. SCMStringBuffer s;
  1120. cw->getDebugValue("__Calculated__Complexity__",s);
  1121. if(s.length())
  1122. resp.setComplexity(s.str());
  1123. WsWUExceptions errors(*cw);
  1124. resp.setErrors(errors);
  1125. if(!errors.ErrCount())
  1126. {
  1127. IArrayOf<IEspWUECLAttribute> dependencies;
  1128. for(unsigned count=1;;count++)
  1129. {
  1130. SCMStringBuffer xml;
  1131. cw->getApplicationValue("SyntaxCheck",StringBuffer("Dependency").append(count).str(),xml);
  1132. if(!xml.length())
  1133. break;
  1134. Owned<IPropertyTree> dep=createPTreeFromXMLString(xml.str(), ipt_caseInsensitive);
  1135. if(!dep)
  1136. continue;
  1137. Owned<IEspWUECLAttribute> att = createWUECLAttribute("","");
  1138. att->setModuleName(dep->queryProp("@module"));
  1139. att->setAttributeName(dep->queryProp("@name"));
  1140. int flags = dep->getPropInt("@flags",0);
  1141. if(flags & ob_locked)
  1142. {
  1143. if(flags & ob_lockedself)
  1144. att->setIsCheckedOut(true);
  1145. else
  1146. att->setIsLocked(true);
  1147. }
  1148. if(flags & ob_sandbox)
  1149. att->setIsSandbox(true);
  1150. if(flags & ob_orphaned)
  1151. att->setIsOrphaned(true);
  1152. dependencies.append(*att.getLink());
  1153. }
  1154. resp.setDependencies(dependencies);
  1155. }
  1156. cw.clear();
  1157. if (!factory->deleteWorkUnit(wuid.str()))
  1158. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "%s: Workunit cannot be deleted. Please check ESP log.", wuid.str());
  1159. }
  1160. catch(IException* e)
  1161. {
  1162. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1163. }
  1164. return true;
  1165. }
  1166. bool CWsWorkunitsEx::onWUGetDependancyTrees(IEspContext& context, IEspWUGetDependancyTreesRequest& req, IEspWUGetDependancyTreesResponse& resp)
  1167. {
  1168. try
  1169. {
  1170. unsigned int timeMilliSec = 500;
  1171. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1172. NewWsWorkunit wu(factory, context);
  1173. wu->setAction(WUActionCheck);
  1174. if (notEmpty(req.getCluster()))
  1175. wu->setClusterName(req.getCluster());
  1176. if (notEmpty(req.getSnapshot()))
  1177. wu->setSnapshot(req.getSnapshot());
  1178. wu->setDebugValue("gatherDependenciesSelection",notEmpty(req.getItems()) ? req.getItems() : NULL,true);
  1179. if (context.getClientVersion() > 1.12)
  1180. {
  1181. wu->setDebugValueInt("gatherDependencies", 1, true);
  1182. const char *timeout = req.getTimeoutMilliSec();
  1183. if (notEmpty(timeout))
  1184. {
  1185. const char *finger = timeout;
  1186. while (*finger)
  1187. {
  1188. if (!isdigit(*finger++))
  1189. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Incorrect timeout value");
  1190. }
  1191. timeMilliSec = atol(timeout);
  1192. }
  1193. }
  1194. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  1195. wu->commit();
  1196. wu.clear();
  1197. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1198. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1199. int state = waitForWorkUnitToComplete(wuid.str(), timeMilliSec);
  1200. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1201. WsWUExceptions errors(*cw);
  1202. resp.setErrors(errors);
  1203. MemoryBuffer temp;
  1204. MemoryBuffer2IDataVal xmlresult(temp);
  1205. Owned<IConstWUResult> result = cw->getResultBySequence(0);
  1206. if (result)
  1207. {
  1208. result->getResultRaw(xmlresult, NULL, NULL);
  1209. resp.setDependancyTrees(temp);
  1210. }
  1211. wu.setown(&cw->lock());
  1212. wu->setState(WUStateAborted);
  1213. wu->commit();
  1214. wu.clear();
  1215. if (!factory->deleteWorkUnit(wuid.str()))
  1216. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "%s: Workunit cannot be deleted. Please check ESP log.", wuid.str());
  1217. }
  1218. catch(IException* e)
  1219. {
  1220. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1221. }
  1222. return true;
  1223. }
  1224. bool getWsWuInfoFromSasha(IEspContext &context, SocketEndpoint &ep, const char* wuid, IEspECLWorkunit *info)
  1225. {
  1226. Owned<INode> node = createINode(ep);
  1227. Owned<ISashaCommand> cmd = createSashaCommand();
  1228. cmd->addId(wuid);
  1229. cmd->setAction(SCA_GET);
  1230. if (!cmd->send(node, 1*60*1000))
  1231. {
  1232. StringBuffer url;
  1233. DBGLOG("Could not connect to Sasha server at %s", ep.getUrlStr(url).str());
  1234. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.", url.str());
  1235. }
  1236. if (cmd->numIds()==0)
  1237. {
  1238. DBGLOG("Could not read archived workunit %s",wuid);
  1239. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
  1240. }
  1241. unsigned num = cmd->numResults();
  1242. if (num < 1)
  1243. return false;
  1244. StringBuffer res;
  1245. cmd->getResult(0, res);
  1246. if(res.length() < 1)
  1247. return false;
  1248. Owned<IPropertyTree> wpt = createPTreeFromXMLString(res.str());
  1249. if (!wpt)
  1250. return false;
  1251. const char * owner = wpt->queryProp("@submitID");
  1252. ensureWsWorkunitAccessByOwnerId(context, owner, SecAccess_Read);
  1253. PROGLOG("GetArchivedWUInfo: %s", wuid);
  1254. info->setWuid(wuid);
  1255. info->setArchived(true);
  1256. if (notEmpty(owner))
  1257. info->setOwner(owner);
  1258. const char * state = wpt->queryProp("@state");
  1259. if (notEmpty(state))
  1260. info->setState(state);
  1261. const char * cluster = wpt->queryProp("@clusterName");
  1262. if (notEmpty(cluster))
  1263. info->setCluster(cluster);
  1264. if (context.querySecManager())
  1265. {
  1266. const char * scope = wpt->queryProp("@scope");
  1267. if (notEmpty(scope))
  1268. info->setScope(scope);
  1269. }
  1270. const char * jobName = wpt->queryProp("@jobName");
  1271. if (notEmpty(jobName))
  1272. info->setJobname(jobName);
  1273. const char * description = wpt->queryProp("Debug/description");
  1274. if (notEmpty(description))
  1275. info->setDescription(description);
  1276. const char * queryText = wpt->queryProp("Query/Text");
  1277. if (notEmpty(queryText))
  1278. info->updateQuery().setText(queryText);
  1279. const char * protectedWU = wpt->queryProp("@protected");
  1280. info->setProtected((protectedWU && *protectedWU!='0'));
  1281. return true;
  1282. }
  1283. #define WUDETAILS_REFRESH_MINS 1
  1284. void getArchivedWUInfo(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort, const char *wuid, IEspWUInfoResponse &resp)
  1285. {
  1286. SocketEndpoint ep;
  1287. if (sashaServerIP && *sashaServerIP)
  1288. ep.set(sashaServerIP, sashaServerPort);
  1289. else
  1290. getSashaNode(ep);
  1291. if (getWsWuInfoFromSasha(context, ep, wuid, &resp.updateWorkunit()))
  1292. {
  1293. resp.setCanCompile(false);
  1294. return;
  1295. }
  1296. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Cannot find workunit %s.", wuid);
  1297. return;
  1298. }
  1299. #define WUDETAILS_REFRESH_MINS 1
  1300. bool CWsWorkunitsEx::onWUInfo(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1301. {
  1302. try
  1303. {
  1304. StringBuffer wuid = req.getWuid();
  1305. WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
  1306. double version = context.getClientVersion();
  1307. if (req.getType() && strieq(req.getType(), "archived workunits"))
  1308. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1309. else
  1310. {
  1311. try
  1312. {
  1313. //The access is checked here because getArchivedWUInfo() has its own access check.
  1314. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1315. PROGLOG("WUInfo: %s", wuid.str());
  1316. unsigned long flags=0;
  1317. if (req.getTruncateEclTo64k())
  1318. flags|=WUINFO_TruncateEclTo64k;
  1319. if (req.getIncludeExceptions())
  1320. flags|=WUINFO_IncludeExceptions;
  1321. if (req.getIncludeGraphs())
  1322. flags|=WUINFO_IncludeGraphs;
  1323. if (req.getIncludeSourceFiles())
  1324. flags|=WUINFO_IncludeSourceFiles;
  1325. if (req.getIncludeResults())
  1326. flags|=WUINFO_IncludeResults;
  1327. if (req.getIncludeVariables())
  1328. flags|=WUINFO_IncludeVariables;
  1329. if (req.getIncludeTimers())
  1330. flags|=WUINFO_IncludeTimers;
  1331. if (req.getIncludeDebugValues())
  1332. flags|=WUINFO_IncludeDebugValues;
  1333. if (req.getIncludeApplicationValues())
  1334. flags|=WUINFO_IncludeApplicationValues;
  1335. if (req.getIncludeWorkflows())
  1336. flags|=WUINFO_IncludeWorkflows;
  1337. if (!req.getSuppressResultSchemas())
  1338. flags|=WUINFO_IncludeEclSchemas;
  1339. if (req.getIncludeXmlSchemas())
  1340. flags|=WUINFO_IncludeXmlSchema;
  1341. if (req.getIncludeResultsViewNames())
  1342. flags|=WUINFO_IncludeResultsViewNames;
  1343. if (req.getIncludeResourceURLs())
  1344. flags|=WUINFO_IncludeResourceURLs;
  1345. if (req.getIncludeECL())
  1346. flags|=WUINFO_IncludeECL;
  1347. if (req.getIncludeHelpers())
  1348. flags|=WUINFO_IncludeHelpers;
  1349. if (req.getIncludeAllowedClusters())
  1350. flags|=WUINFO_IncludeAllowedClusters;
  1351. WsWuInfo winfo(context, wuid.str());
  1352. winfo.getInfo(resp.updateWorkunit(), flags);
  1353. if (req.getIncludeResultsViewNames()||req.getIncludeResourceURLs()||(version >= 1.50))
  1354. {
  1355. StringArray views, urls;
  1356. winfo.getResourceInfo(views, urls, WUINFO_IncludeResultsViewNames|WUINFO_IncludeResourceURLs);
  1357. IEspECLWorkunit& eclWU = resp.updateWorkunit();
  1358. if (req.getIncludeResultsViewNames())
  1359. resp.setResultViews(views);
  1360. if (req.getIncludeResourceURLs())
  1361. eclWU.setResourceURLs(urls);
  1362. if (version >= 1.50)
  1363. {
  1364. eclWU.setResultViewCount(views.length());
  1365. eclWU.setResourceURLCount(urls.length());
  1366. }
  1367. }
  1368. }
  1369. catch (IException *e)
  1370. {
  1371. if (e->errorCode() != ECLWATCH_CANNOT_OPEN_WORKUNIT)
  1372. throw e;
  1373. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1374. e->Release();
  1375. }
  1376. switch (resp.getWorkunit().getStateID())
  1377. {
  1378. case WUStateCompiling:
  1379. case WUStateCompiled:
  1380. case WUStateScheduled:
  1381. case WUStateSubmitted:
  1382. case WUStateRunning:
  1383. case WUStateAborting:
  1384. case WUStateWait:
  1385. case WUStateUploadingFiles:
  1386. case WUStateDebugPaused:
  1387. case WUStateDebugRunning:
  1388. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1389. break;
  1390. case WUStateBlocked:
  1391. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS*5);
  1392. break;
  1393. }
  1394. resp.setCanCompile(notEmpty(context.queryUserId()));
  1395. if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
  1396. resp.setThorSlaveIP(req.getThorSlaveIP());
  1397. ISecManager* secmgr = context.querySecManager();
  1398. if (!secmgr)
  1399. resp.setSecMethod(NULL);
  1400. else
  1401. resp.setSecMethod(secmgr->querySecMgrTypeName());
  1402. }
  1403. }
  1404. catch(IException* e)
  1405. {
  1406. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1407. }
  1408. return true;
  1409. }
  1410. bool CWsWorkunitsEx::onWUInfoDetails(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1411. {
  1412. return onWUInfo(context, req, resp);
  1413. }
  1414. bool CWsWorkunitsEx::onWUResultView(IEspContext &context, IEspWUResultViewRequest &req, IEspWUResultViewResponse &resp)
  1415. {
  1416. StringBuffer wuid = req.getWuid();
  1417. WsWuHelpers::checkAndTrimWorkunit("WUResultView", wuid);
  1418. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1419. PROGLOG("WUResultView: %s", wuid.str());
  1420. Owned<IWuWebView> wv = createWuWebView(wuid.str(), NULL, NULL, getCFD(), true);
  1421. StringBuffer html;
  1422. wv->renderSingleResult(req.getViewName(), req.getResultName(), html);
  1423. resp.setResult(html.str());
  1424. resp.setResult_mimetype("text/html");
  1425. return true;
  1426. }
  1427. void doWUQueryBySingleWuid(IEspContext &context, const char *wuid, IEspWUQueryResponse &resp)
  1428. {
  1429. Owned<IEspECLWorkunit> info= createECLWorkunit("","");
  1430. WsWuInfo winfo(context, wuid);
  1431. winfo.getCommon(*info, 0);
  1432. IArrayOf<IEspECLWorkunit> results;
  1433. results.append(*info.getClear());
  1434. resp.setWorkunits(results);
  1435. resp.setPageSize(1);
  1436. resp.setCount(1);
  1437. PROGLOG("getWUInfo: %s", wuid);
  1438. }
  1439. void doWUQueryByFile(IEspContext &context, const char *logicalFile, IEspWUQueryResponse &resp)
  1440. {
  1441. StringBuffer wuid;
  1442. getWuidFromLogicalFileName(context, logicalFile, wuid);
  1443. if (!wuid.length())
  1444. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1445. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1446. Owned<IConstWorkUnit> cw= factory->openWorkUnit(wuid.str());
  1447. if (!cw)
  1448. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1449. if (getWsWorkunitAccess(context, *cw) < SecAccess_Read)
  1450. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED,"Cannot access the workunit for file %s.",logicalFile);
  1451. doWUQueryBySingleWuid(context, wuid.str(), resp);
  1452. resp.setFirst(false);
  1453. resp.setPageSize(1);
  1454. resp.setCount(1);
  1455. }
  1456. bool addWUQueryFilter(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *name, WUSortField value)
  1457. {
  1458. if (isEmpty(name))
  1459. return false;
  1460. filters[count++] = value;
  1461. if ((value & WUSFwild) != 0 && !containsWildcard(name))
  1462. buff.append("*").append(name).append("*");
  1463. else
  1464. buff.append(name);
  1465. return true;
  1466. }
  1467. bool addWUQueryFilterTime(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *stime, WUSortField value)
  1468. {
  1469. if (isEmpty(stime))
  1470. return false;
  1471. CDateTime dt;
  1472. dt.setString(stime, NULL, true);
  1473. unsigned year, month, day, hour, minute, second, nano;
  1474. dt.getDate(year, month, day, true);
  1475. dt.getTime(hour, minute, second, nano, true);
  1476. VStringBuffer wuid("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
  1477. filters[count++] = value;
  1478. buff.append(wuid.str());
  1479. return true;
  1480. }
  1481. bool addWUQueryFilterApplication(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *appname, const char *appkey, const char *appdata)
  1482. {
  1483. if (isEmpty(appname))
  1484. return false; // appname must be specified
  1485. if (isEmpty(appkey) && isEmpty(appdata)) //one or other is required ( MORE - see if cassandra can relax that)
  1486. return false;
  1487. VStringBuffer path("%s/%s", appname, appkey && *appkey ? appkey : "*");
  1488. buff.append(path.str());
  1489. buff.append(appdata);
  1490. filters[count++] = WUSFappvalue;
  1491. return true;
  1492. }
  1493. void readWUQuerySortOrder(const char* sortBy, const bool descending, WUSortField& sortOrder)
  1494. {
  1495. if (isEmpty(sortBy))
  1496. {
  1497. sortOrder = (WUSortField) (WUSFwuid | WUSFreverse);
  1498. return;
  1499. }
  1500. if (strieq(sortBy, "Owner"))
  1501. sortOrder = WUSFuser;
  1502. else if (strieq(sortBy, "JobName"))
  1503. sortOrder = WUSFjob;
  1504. else if (strieq(sortBy, "Cluster"))
  1505. sortOrder = WUSFcluster;
  1506. else if (strieq(sortBy, "Protected"))
  1507. sortOrder = WUSFprotected;
  1508. else if (strieq(sortBy, "State"))
  1509. sortOrder = WUSFstate;
  1510. else if (strieq(sortBy, "ClusterTime"))
  1511. sortOrder = (WUSortField) (WUSFtotalthortime+WUSFnumeric);
  1512. else
  1513. sortOrder = WUSFwuid;
  1514. sortOrder = (WUSortField) (sortOrder | WUSFnocase);
  1515. if (descending)
  1516. sortOrder = (WUSortField) (sortOrder | WUSFreverse);
  1517. }
  1518. void doWUQueryWithSort(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1519. {
  1520. SecAccessFlags accessOwn;
  1521. SecAccessFlags accessOthers;
  1522. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1523. double version = context.getClientVersion();
  1524. IArrayOf<IEspECLWorkunit> results;
  1525. int begin = 0;
  1526. unsigned int count = 100;
  1527. int pagesize = 100;
  1528. if (version > 1.01)
  1529. {
  1530. pagesize = (int)req.getPageSize();
  1531. if (!req.getCount_isNull())
  1532. pagesize = req.getCount();
  1533. if(pagesize < 1)
  1534. pagesize = 100;
  1535. begin = (int)req.getPageStartFrom();
  1536. }
  1537. else
  1538. {
  1539. count=(unsigned)req.getCount();
  1540. if(!count)
  1541. count=100;
  1542. if (notEmpty(req.getAfter()))
  1543. begin=atoi(req.getAfter());
  1544. else if (notEmpty(req.getBefore()))
  1545. begin=atoi(req.getBefore())-count;
  1546. if (begin < 0)
  1547. begin = 0;
  1548. pagesize = count;
  1549. }
  1550. WUSortField sortorder;
  1551. readWUQuerySortOrder(req.getSortby(), req.getDescending(), sortorder);
  1552. WUSortField filters[10];
  1553. unsigned short filterCount = 0;
  1554. MemoryBuffer filterbuf;
  1555. // Query filters should be added in order of expected power - add the most restrictive filters first
  1556. bool bDoubleCheckState = false;
  1557. if(req.getState() && *req.getState())
  1558. {
  1559. filters[filterCount++] = WUSFstate;
  1560. if (!strieq(req.getState(), "unknown"))
  1561. filterbuf.append(req.getState());
  1562. else
  1563. filterbuf.append("");
  1564. if (strieq(req.getState(), "submitted"))
  1565. bDoubleCheckState = true;
  1566. }
  1567. addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
  1568. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1569. addWUQueryFilter(filters, filterCount, filterbuf, req.getLogicalFile(), (WUSortField) (WUSFfileread | WUSFnocase));
  1570. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1571. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobname(), (WUSortField) (WUSFjob | WUSFnocase));
  1572. addWUQueryFilter(filters, filterCount, filterbuf, req.getECL(), (WUSortField) (WUSFecl | WUSFwild));
  1573. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1574. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1575. if (version < 1.55)
  1576. addWUQueryFilterApplication(filters, filterCount, filterbuf, req.getApplicationName(), req.getApplicationKey(), req.getApplicationData());
  1577. else
  1578. {
  1579. IArrayOf<IConstApplicationValue>& applicationFilters = req.getApplicationValues();
  1580. ForEachItemIn(i, applicationFilters)
  1581. {
  1582. IConstApplicationValue &item = applicationFilters.item(i);
  1583. addWUQueryFilterApplication(filters, filterCount, filterbuf, item.getApplication(), item.getName(), item.getValue());
  1584. }
  1585. }
  1586. filters[filterCount] = WUSFterm;
  1587. __int64 cacheHint = 0;
  1588. if (!req.getCacheHint_isNull())
  1589. cacheHint = req.getCacheHint();
  1590. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1591. unsigned numWUs;
  1592. PROGLOG("WUQuery: getWorkUnitsSorted");
  1593. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), begin, pagesize+1, &cacheHint, &numWUs); // MORE - need security flags here!
  1594. if (version >= 1.41)
  1595. resp.setCacheHint(cacheHint);
  1596. PROGLOG("WUQuery: getWorkUnitsSorted done");
  1597. unsigned actualCount = 0;
  1598. ForEach(*it)
  1599. {
  1600. IConstWorkUnitInfo& cw = it->query();
  1601. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1602. {
  1603. numWUs--;
  1604. continue;
  1605. }
  1606. // This test is presumably trying to remove the global workunit, though it's not the right way to do so (since it will mess up page counts etc)
  1607. const char* wuid = cw.queryWuid();
  1608. if (!looksLikeAWuid(wuid, 'W'))
  1609. {
  1610. numWUs--;
  1611. continue;
  1612. }
  1613. actualCount++;
  1614. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1615. info->setWuid(cw.queryWuid());
  1616. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1617. {
  1618. info->setState("<Hidden>");
  1619. results.append(*info.getClear());
  1620. continue;
  1621. }
  1622. info->setProtected(cw.isProtected() ? 1 : 0);
  1623. info->setJobname(cw.queryJobName());
  1624. info->setOwner(cw.queryUser());
  1625. info->setCluster(cw.queryClusterName());
  1626. SCMStringBuffer s;
  1627. // info.setSnapshot(cw->getSnapshot(s).str());
  1628. info->setStateID(cw.getState());
  1629. info->setState(cw.queryStateDesc());
  1630. unsigned totalThorTimeMS = cw.getTotalThorTime();
  1631. StringBuffer totalThorTimeStr;
  1632. formatDuration(totalThorTimeStr, totalThorTimeMS);
  1633. if (version > 1.52)
  1634. info->setTotalClusterTime(totalThorTimeStr.str());
  1635. else
  1636. info->setTotalThorTime(totalThorTimeStr.str());
  1637. //if (cw->isPausing())
  1638. // info.setIsPausing(true);
  1639. // getEventScheduleFlag(info);
  1640. WsWuDateTime dt;
  1641. cw.getTimeScheduled(dt);
  1642. if(dt.isValid())
  1643. info->setDateTimeScheduled(dt.getString(s).str());
  1644. if (version >= 1.55)
  1645. {
  1646. IArrayOf<IEspApplicationValue> av;
  1647. Owned<IConstWUAppValueIterator> app(&cw.getApplicationValues());
  1648. ForEach(*app)
  1649. {
  1650. IConstWUAppValue& val=app->query();
  1651. Owned<IEspApplicationValue> t= createApplicationValue("","");
  1652. t->setApplication(val.queryApplication());
  1653. t->setName(val.queryName());
  1654. t->setValue(val.queryValue());
  1655. av.append(*t.getLink());
  1656. }
  1657. info->setApplicationValues(av);
  1658. }
  1659. results.append(*info.getClear());
  1660. }
  1661. if (version > 1.02)
  1662. {
  1663. resp.setPageStartFrom(begin+1);
  1664. resp.setNumWUs(numWUs);
  1665. if (results.length() > (aindex_t)pagesize)
  1666. results.pop();
  1667. if(unsigned (begin + pagesize) < numWUs)
  1668. {
  1669. resp.setNextPage(begin + pagesize);
  1670. resp.setPageEndAt(begin + pagesize);
  1671. int last = begin + pagesize;
  1672. while (numWUs > (unsigned) last + pagesize)
  1673. last += pagesize;
  1674. resp.setLastPage(last);
  1675. }
  1676. else
  1677. {
  1678. resp.setNextPage(-1);
  1679. resp.setPageEndAt(numWUs);
  1680. }
  1681. if(begin > 0)
  1682. {
  1683. resp.setFirst(false);
  1684. if (begin - pagesize > 0)
  1685. resp.setPrevPage(begin - pagesize);
  1686. else
  1687. resp.setPrevPage(0);
  1688. }
  1689. resp.setPageSize(pagesize);
  1690. }
  1691. else
  1692. {
  1693. if(begin>0 && actualCount > 0)
  1694. {
  1695. char buf[10];
  1696. itoa(begin, buf, 10);
  1697. resp.setCurrent(buf);
  1698. }
  1699. if(count<actualCount)
  1700. {
  1701. char buf[10];
  1702. itoa(begin+count, buf, 10);
  1703. resp.setNext(buf);
  1704. resp.setNumWUs(numWUs);
  1705. if (results.length() > count)
  1706. results.pop();
  1707. }
  1708. if(begin == 0 && actualCount <= count)
  1709. resp.setFirst(false);
  1710. resp.setCount(count);
  1711. }
  1712. resp.setWorkunits(results);
  1713. return;
  1714. }
  1715. void doWULightWeightQueryWithSort(IEspContext &context, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  1716. {
  1717. SecAccessFlags accessOwn;
  1718. SecAccessFlags accessOthers;
  1719. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1720. double version = context.getClientVersion();
  1721. int pageStartFrom = 0;
  1722. int pageSize = 100;
  1723. if (!req.getPageStartFrom_isNull())
  1724. pageStartFrom = req.getPageStartFrom();
  1725. if (!req.getPageSize_isNull())
  1726. pageSize = req.getPageSize();
  1727. WUSortField sortOrder;
  1728. readWUQuerySortOrder(req.getSortBy(), req.getDescending(), sortOrder);
  1729. WUSortField filters[10];
  1730. unsigned short filterCount = 0;
  1731. MemoryBuffer filterbuf;
  1732. // Query filters should be added in order of expected power - add the most restrictive filters first
  1733. bool bDoubleCheckState = false;
  1734. if(req.getState() && *req.getState())
  1735. {
  1736. filters[filterCount++] = WUSFstate;
  1737. if (!strieq(req.getState(), "unknown"))
  1738. filterbuf.append(req.getState());
  1739. else
  1740. filterbuf.append("");
  1741. if (strieq(req.getState(), "submitted"))
  1742. bDoubleCheckState = true;
  1743. }
  1744. addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
  1745. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1746. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1747. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobName(), (WUSortField) (WUSFjob | WUSFnocase));
  1748. //StartDate example: 2015-08-26T14:26:00
  1749. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1750. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1751. IArrayOf<IConstApplicationValue>& applicationFilters = req.getApplicationValues();
  1752. ForEachItemIn(i, applicationFilters)
  1753. {
  1754. IConstApplicationValue &item = applicationFilters.item(i);
  1755. addWUQueryFilterApplication(filters, filterCount, filterbuf, item.getApplication(), item.getName(), item.getValue());
  1756. }
  1757. filters[filterCount] = WUSFterm;
  1758. __int64 cacheHint = 0;
  1759. if (!req.getCacheHint_isNull())
  1760. cacheHint = req.getCacheHint();
  1761. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1762. unsigned numWUs;
  1763. PROGLOG("getWorkUnitsSorted(LightWeight)");
  1764. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortOrder, filters, filterbuf.bufferBase(), pageStartFrom, pageSize+1, &cacheHint, &numWUs); // MORE - need security flags here!
  1765. resp.setCacheHint(cacheHint);
  1766. PROGLOG("getWorkUnitsSorted(LightWeight) done");
  1767. IArrayOf<IEspECLWorkunitLW> results;
  1768. ForEach(*it)
  1769. {
  1770. IConstWorkUnitInfo& cw = it->query();
  1771. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1772. {
  1773. numWUs--;
  1774. continue;
  1775. }
  1776. // This test is presumably trying to remove the global workunit, though it's not the right way to do so (since it will mess up page counts etc)
  1777. const char* wuid = cw.queryWuid();
  1778. if (!looksLikeAWuid(wuid, 'W'))
  1779. {
  1780. numWUs--;
  1781. continue;
  1782. }
  1783. Owned<IEspECLWorkunitLW> info = createECLWorkunitLW("","");
  1784. info->setWuid(cw.queryWuid());
  1785. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1786. {
  1787. info->setStateDesc("<Hidden>");
  1788. results.append(*info.getClear());
  1789. continue;
  1790. }
  1791. SCMStringBuffer s;
  1792. info->setIsProtected(cw.isProtected() ? 1 : 0);
  1793. info->setJobName(cw.queryJobName());
  1794. info->setWuScope(cw.queryWuScope());
  1795. info->setOwner(cw.queryUser());
  1796. info->setClusterName(cw.queryClusterName());
  1797. info->setState(cw.getState());
  1798. info->setStateDesc(cw.queryStateDesc());
  1799. info->setAction(cw.getAction());
  1800. info->setActionDesc(cw.queryActionDesc());
  1801. info->setPriority(cw.getPriority());
  1802. info->setPriorityLevel(cw.getPriorityLevel());
  1803. info->setPriorityDesc(cw.queryPriorityDesc());
  1804. info->setTotalClusterTime(cw.getTotalThorTime());
  1805. WsWuDateTime dt;
  1806. cw.getTimeScheduled(dt);
  1807. if(dt.isValid())
  1808. info->setDateTimeScheduled(dt.getString(s).str());
  1809. IArrayOf<IEspApplicationValue> av;
  1810. Owned<IConstWUAppValueIterator> app(&cw.getApplicationValues());
  1811. ForEach(*app)
  1812. {
  1813. IConstWUAppValue& val=app->query();
  1814. Owned<IEspApplicationValue> t= createApplicationValue("","");
  1815. t->setApplication(val.queryApplication());
  1816. t->setName(val.queryName());
  1817. t->setValue(val.queryValue());
  1818. av.append(*t.getClear());
  1819. }
  1820. info->setApplicationValues(av);
  1821. results.append(*info.getClear());
  1822. }
  1823. resp.setNumWUs(numWUs);
  1824. if (results.length() > (aindex_t)pageSize)
  1825. results.pop();
  1826. resp.setWorkunits(results);
  1827. return;
  1828. }
  1829. class CArchivedWUsReader : public CInterface, implements IArchivedWUsReader
  1830. {
  1831. IEspContext& context;
  1832. unsigned pageFrom, pageSize;
  1833. StringAttr sashaServerIP;
  1834. unsigned sashaServerPort;
  1835. unsigned cacheMinutes;
  1836. StringBuffer filterStr;
  1837. ArchivedWuCache& archivedWuCache;
  1838. unsigned numberOfWUsReturned;
  1839. bool hasMoreWU;
  1840. void readDateFilters(const char* startDateReq, const char* endDateReq, StringBuffer& from, StringBuffer& to)
  1841. {
  1842. CDateTime timeFrom, timeTo;
  1843. if(notEmpty(endDateReq))
  1844. {//endDateReq example: 2015-08-26T14:26:00
  1845. unsigned year, month, day, hour, minute, second, nano;
  1846. timeTo.setString(endDateReq, NULL, true);
  1847. timeTo.getDate(year, month, day, true);
  1848. timeTo.getTime(hour, minute, second, nano, true);
  1849. to.setf("%4d%02d%02d%02d%02d%02d", year, month, day, hour, minute, second);
  1850. }
  1851. if(isEmpty(startDateReq))
  1852. return;
  1853. timeFrom.setString(startDateReq, NULL, true);
  1854. if (timeFrom >= timeTo)
  1855. return;
  1856. unsigned year0, month0, day0, hour0, minute0, second0, nano0;
  1857. timeFrom.getDate(year0, month0, day0, true);
  1858. timeFrom.getTime(hour0, minute0, second0, nano0, true);
  1859. from.setf("%4d%02d%02d%02d%02d%02d", year0, month0, day0, hour0, minute0, second0);
  1860. return;
  1861. }
  1862. bool addToFilterString(const char *name, const char *value)
  1863. {
  1864. if (isEmpty(name) || isEmpty(value))
  1865. return false;
  1866. filterStr.append(';').append(name).append("=").append(value);
  1867. return true;
  1868. }
  1869. bool addToFilterString(const char *name, unsigned value)
  1870. {
  1871. if (isEmpty(name))
  1872. return false;
  1873. filterStr.append(';').append(name).append("=").append(value);
  1874. return true;
  1875. }
  1876. void setFilterString(IEspWUQueryRequest& req)
  1877. {
  1878. filterStr.set("0");
  1879. addToFilterString("wuid", req.getWuid());
  1880. addToFilterString("cluster", req.getCluster());
  1881. addToFilterString("owner", req.getOwner());
  1882. addToFilterString("jobName", req.getJobname());
  1883. addToFilterString("state", req.getState());
  1884. addToFilterString("timeFrom", req.getStartDate());
  1885. addToFilterString("timeTo", req.getEndDate());
  1886. addToFilterString("pageStart", pageFrom);
  1887. addToFilterString("pageSize", pageSize);
  1888. if (sashaServerIP && *sashaServerIP)
  1889. {
  1890. addToFilterString("sashaServerIP", sashaServerIP.get());
  1891. addToFilterString("sashaServerPort", sashaServerPort);
  1892. }
  1893. }
  1894. void setFilterStringLW(IEspWULightWeightQueryRequest& req)
  1895. {
  1896. filterStr.set("1");
  1897. addToFilterString("wuid", req.getWuid());
  1898. addToFilterString("cluster", req.getCluster());
  1899. addToFilterString("owner", req.getOwner());
  1900. addToFilterString("jobName", req.getJobName());
  1901. addToFilterString("state", req.getState());
  1902. addToFilterString("timeFrom", req.getStartDate());
  1903. addToFilterString("timeTo", req.getEndDate());
  1904. addToFilterString("pageStart", pageFrom);
  1905. addToFilterString("pageSize", pageSize);
  1906. if (sashaServerIP && *sashaServerIP)
  1907. {
  1908. addToFilterString("sashaServerIP", sashaServerIP.get());
  1909. addToFilterString("sashaServerPort", sashaServerPort);
  1910. }
  1911. }
  1912. void initSashaCommand(ISashaCommand* cmd)
  1913. {
  1914. cmd->setAction(SCA_LIST);
  1915. cmd->setOutputFormat("owner,jobname,cluster,state");
  1916. cmd->setOnline(false);
  1917. cmd->setArchived(true);
  1918. cmd->setStart(pageFrom);
  1919. cmd->setLimit(pageSize+1); //read an extra WU to check hasMoreWU
  1920. }
  1921. void setSashaCommand(IEspWUQueryRequest& req, ISashaCommand* cmd)
  1922. {
  1923. if (notEmpty(req.getWuid()))
  1924. cmd->addId(req.getWuid());
  1925. if (notEmpty(req.getCluster()))
  1926. cmd->setCluster(req.getCluster());
  1927. if (notEmpty(req.getOwner()))
  1928. cmd->setOwner(req.getOwner());
  1929. if (notEmpty(req.getJobname()))
  1930. cmd->setJobName(req.getJobname());
  1931. if (notEmpty(req.getState()))
  1932. cmd->setState(req.getState());
  1933. StringBuffer timeFrom, timeTo;
  1934. readDateFilters(req.getStartDate(), req.getEndDate(), timeFrom, timeTo);
  1935. if (timeFrom.length())
  1936. cmd->setAfter(timeFrom.str());
  1937. if (timeTo.length())
  1938. cmd->setBefore(timeTo.str());
  1939. return;
  1940. }
  1941. void setSashaCommandLW(IEspWULightWeightQueryRequest& req, ISashaCommand* cmd)
  1942. {
  1943. if (notEmpty(req.getWuid()))
  1944. cmd->addId(req.getWuid());
  1945. if (notEmpty(req.getCluster()))
  1946. cmd->setCluster(req.getCluster());
  1947. if (notEmpty(req.getOwner()))
  1948. cmd->setOwner(req.getOwner());
  1949. if (notEmpty(req.getJobName()))
  1950. cmd->setJobName(req.getJobName());
  1951. if (notEmpty(req.getState()))
  1952. cmd->setState(req.getState());
  1953. StringBuffer timeFrom, timeTo;
  1954. readDateFilters(req.getStartDate(), req.getEndDate(), timeFrom, timeTo);
  1955. if (timeFrom.length())
  1956. cmd->setAfter(timeFrom.str());
  1957. if (timeTo.length())
  1958. cmd->setBefore(timeTo.str());
  1959. return;
  1960. }
  1961. IEspECLWorkunit *createArchivedWUEntry(StringArray& wuDataArray, bool canAccess)
  1962. {
  1963. Owned<IEspECLWorkunit> info= createECLWorkunit();
  1964. info->setWuid(wuDataArray.item(0));
  1965. if (!canAccess)
  1966. {
  1967. info->setState("<Hidden>");
  1968. return info.getClear();
  1969. }
  1970. const char* owner = wuDataArray.item(1);
  1971. const char* jobName = wuDataArray.item(2);
  1972. const char* cluster = wuDataArray.item(3);
  1973. const char* state = wuDataArray.item(4);
  1974. if (notEmpty(owner))
  1975. info->setOwner(owner);
  1976. if (notEmpty(jobName))
  1977. info->setJobname(jobName);
  1978. if (notEmpty(cluster))
  1979. info->setCluster(cluster);
  1980. if (notEmpty(state))
  1981. info->setState(state);
  1982. return info.getClear();
  1983. }
  1984. IEspECLWorkunitLW *createArchivedLWWUEntry(StringArray& wuDataArray, bool canAccess)
  1985. {
  1986. Owned<IEspECLWorkunitLW> info= createECLWorkunitLW();
  1987. info->setWuid(wuDataArray.item(0));
  1988. if (!canAccess)
  1989. {
  1990. info->setStateDesc("<Hidden>");
  1991. return info.getClear();
  1992. }
  1993. const char* owner = wuDataArray.item(1);
  1994. const char* jobName = wuDataArray.item(2);
  1995. const char* cluster = wuDataArray.item(3);
  1996. const char* state = wuDataArray.item(4);
  1997. if (notEmpty(owner))
  1998. info->setOwner(owner);
  1999. if (notEmpty(jobName))
  2000. info->setJobName(jobName);
  2001. if (notEmpty(cluster))
  2002. info->setClusterName(cluster);
  2003. if (notEmpty(state))
  2004. info->setStateDesc(state);
  2005. return info.getClear();
  2006. }
  2007. static int compareWuids(IInterface * const *_a, IInterface * const *_b)
  2008. {
  2009. IEspECLWorkunit *a = *(IEspECLWorkunit **)_a;
  2010. IEspECLWorkunit *b = *(IEspECLWorkunit **)_b;
  2011. return strcmp(b->getWuid(), a->getWuid());
  2012. }
  2013. static int compareLWWuids(IInterface * const *_a, IInterface * const *_b)
  2014. {
  2015. IEspECLWorkunitLW *a = *(IEspECLWorkunitLW **)_a;
  2016. IEspECLWorkunitLW *b = *(IEspECLWorkunitLW **)_b;
  2017. return strcmp(b->getWuid(), a->getWuid());
  2018. }
  2019. public:
  2020. IMPLEMENT_IINTERFACE_USING(CInterface);
  2021. CArchivedWUsReader(IEspContext& _context, const char* _sashaServerIP, unsigned _sashaServerPort, ArchivedWuCache& _archivedWuCache,
  2022. unsigned _cacheMinutes, unsigned _pageFrom, unsigned _pageSize)
  2023. : context(_context), sashaServerIP(_sashaServerIP), sashaServerPort(_sashaServerPort),
  2024. archivedWuCache(_archivedWuCache), cacheMinutes(_cacheMinutes), pageFrom(_pageFrom), pageSize(_pageSize)
  2025. {
  2026. hasMoreWU = false;
  2027. numberOfWUsReturned = 0;
  2028. }
  2029. void getArchivedWUs(bool lightWeight, IEspWUQueryRequest& req, IEspWULightWeightQueryRequest& reqLW, IArrayOf<IEspECLWorkunit>& archivedWUs, IArrayOf<IEspECLWorkunitLW>& archivedLWWUs)
  2030. {
  2031. if (!lightWeight)
  2032. setFilterString(req);
  2033. else
  2034. setFilterStringLW(reqLW);
  2035. Owned<ArchivedWuCacheElement> cachedResults = archivedWuCache.lookup(context, filterStr, "AddWhenAvailable", cacheMinutes);
  2036. if (cachedResults)
  2037. {
  2038. hasMoreWU = cachedResults->m_hasNextPage;
  2039. numberOfWUsReturned = cachedResults->numWUsReturned;
  2040. if (!lightWeight && cachedResults->m_results.length())
  2041. {
  2042. ForEachItemIn(i, cachedResults->m_results)
  2043. archivedWUs.append(*LINK(&cachedResults->m_results.item(i)));
  2044. }
  2045. if (lightWeight && cachedResults->resultsLW.length())
  2046. {
  2047. ForEachItemIn(i, cachedResults->resultsLW)
  2048. archivedLWWUs.append(*LINK(&cachedResults->resultsLW.item(i)));
  2049. }
  2050. return;
  2051. }
  2052. SocketEndpoint ep;
  2053. if (sashaServerIP && *sashaServerIP)
  2054. ep.set(sashaServerIP, sashaServerPort);
  2055. else
  2056. getSashaNode(ep);
  2057. Owned<INode> sashaserver = createINode(ep);
  2058. Owned<ISashaCommand> cmd = createSashaCommand();
  2059. initSashaCommand(cmd);
  2060. if (!lightWeight)
  2061. setSashaCommand(req, cmd);
  2062. else
  2063. setSashaCommandLW(reqLW, cmd);
  2064. if (!cmd->send(sashaserver))
  2065. {
  2066. StringBuffer msg("Cannot connect to archive server at ");
  2067. sashaserver->endpoint().getUrlStr(msg);
  2068. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER, "%s", msg.str());
  2069. }
  2070. numberOfWUsReturned = cmd->numIds();
  2071. hasMoreWU = (numberOfWUsReturned > pageSize);
  2072. if (hasMoreWU)
  2073. numberOfWUsReturned--;
  2074. if (numberOfWUsReturned == 0)
  2075. return;
  2076. SecAccessFlags accessOwn, accessOthers;
  2077. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  2078. for (unsigned i=0; i<numberOfWUsReturned; i++)
  2079. {
  2080. const char *csline = cmd->queryId(i);
  2081. if (!csline || !*csline)
  2082. continue;
  2083. StringArray wuDataArray;
  2084. wuDataArray.appendList(csline, ",");
  2085. const char* wuid = wuDataArray.item(0);
  2086. if (isEmpty(wuid))
  2087. {
  2088. WARNLOG("Empty WUID in SCA_LIST response"); // JCS->KW - have u ever seen this happen?
  2089. continue;
  2090. }
  2091. const char* owner = wuDataArray.item(1);
  2092. bool canAccess = chooseWuAccessFlagsByOwnership(context.queryUserId(), owner, accessOwn, accessOthers) >= SecAccess_Read;
  2093. if (!lightWeight)
  2094. {
  2095. Owned<IEspECLWorkunit> info = createArchivedWUEntry(wuDataArray, canAccess);
  2096. archivedWUs.append(*info.getClear());
  2097. }
  2098. else
  2099. {
  2100. Owned<IEspECLWorkunitLW> info = createArchivedLWWUEntry(wuDataArray, canAccess);
  2101. archivedLWWUs.append(*info.getClear());
  2102. }
  2103. }
  2104. if (!lightWeight)
  2105. archivedWUs.sort(compareWuids);
  2106. else
  2107. archivedLWWUs.sort(compareLWWuids);
  2108. archivedWuCache.add(filterStr, "AddWhenAvailable", hasMoreWU, numberOfWUsReturned, archivedWUs, archivedLWWUs);
  2109. return;
  2110. };
  2111. bool getHasMoreWU() { return hasMoreWU; };
  2112. unsigned getNumberOfWUsReturned() { return numberOfWUsReturned; };
  2113. };
  2114. void doWUQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
  2115. ArchivedWuCache &archivedWuCache, unsigned cacheMinutes, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  2116. {
  2117. unsigned pageStart = (unsigned) req.getPageStartFrom();
  2118. unsigned pageSize = (unsigned) req.getPageSize();
  2119. if(pageSize < 1)
  2120. pageSize=500;
  2121. Owned<IArchivedWUsReader> archiveWUsReader = new CArchivedWUsReader(context, sashaServerIP, sashaServerPort, archivedWuCache,
  2122. cacheMinutes, pageStart, pageSize);
  2123. IArrayOf<IEspECLWorkunit> archivedWUs;
  2124. IArrayOf<IEspECLWorkunitLW> dummyWUs;
  2125. Owned<CWULightWeightQueryRequest> dummyReq = new CWULightWeightQueryRequest("WsWorkunits");
  2126. PROGLOG("getWorkUnitsFromArchive");
  2127. archiveWUsReader->getArchivedWUs(false, req, *dummyReq, archivedWUs, dummyWUs);
  2128. PROGLOG("getWorkUnitsFromArchive done");
  2129. resp.setWorkunits(archivedWUs);
  2130. resp.setNumWUs(archiveWUsReader->getNumberOfWUsReturned());
  2131. resp.setType("archived only");
  2132. resp.setPageSize(pageSize);
  2133. resp.setPageStartFrom(pageStart+1);
  2134. resp.setPageEndAt(pageStart + archiveWUsReader->getNumberOfWUsReturned());
  2135. if(pageStart > 0)
  2136. { //This is not the first page;
  2137. resp.setFirst(false);
  2138. resp.setPrevPage((pageStart > pageSize) ? pageStart - pageSize: 0);
  2139. }
  2140. if (archiveWUsReader->getHasMoreWU())
  2141. resp.setNextPage(pageStart + pageSize);
  2142. return;
  2143. }
  2144. void doWULightWeightQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
  2145. ArchivedWuCache &archivedWuCache, unsigned cacheMinutes, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  2146. {
  2147. int pageStart = 0;
  2148. int pageSize=500;
  2149. if (!req.getPageStartFrom_isNull())
  2150. pageStart = req.getPageStartFrom();
  2151. if (!req.getPageSize_isNull())
  2152. pageSize = req.getPageSize();
  2153. Owned<IArchivedWUsReader> archiveWUsReader = new CArchivedWUsReader(context, sashaServerIP, sashaServerPort, archivedWuCache,
  2154. cacheMinutes, pageStart, pageSize);
  2155. Owned<CWUQueryRequest> dummyReq = new CWUQueryRequest("WsWorkunits");
  2156. IArrayOf<IEspECLWorkunit> dummyWUs;
  2157. IArrayOf<IEspECLWorkunitLW> archivedWUs;
  2158. PROGLOG("getWorkUnitsFromArchive(LightWeight)");
  2159. archiveWUsReader->getArchivedWUs(true, *dummyReq, req, dummyWUs, archivedWUs);
  2160. PROGLOG("getWorkUnitsFromArchive(LightWeight) done");
  2161. resp.setWorkunits(archivedWUs);
  2162. resp.setNumWUs(archiveWUsReader->getNumberOfWUsReturned());
  2163. return;
  2164. }
  2165. bool CWsWorkunitsEx::onWUQuery(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  2166. {
  2167. try
  2168. {
  2169. StringBuffer wuidStr = req.getWuid();
  2170. const char* wuid = wuidStr.trim().str();
  2171. if (req.getType() && strieq(req.getType(), "archived workunits"))
  2172. doWUQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
  2173. else if(notEmpty(wuid) && looksLikeAWuid(wuid, 'W'))
  2174. doWUQueryBySingleWuid(context, wuid, resp);
  2175. else if (notEmpty(req.getLogicalFile()) && req.getLogicalFileSearchType() && strieq(req.getLogicalFileSearchType(), "Created"))
  2176. doWUQueryByFile(context, req.getLogicalFile(), resp);
  2177. else
  2178. doWUQueryWithSort(context, req, resp);
  2179. resp.setState(req.getState());
  2180. resp.setCluster(req.getCluster());
  2181. resp.setRoxieCluster(req.getRoxieCluster());
  2182. resp.setOwner(req.getOwner());
  2183. resp.setStartDate(req.getStartDate());
  2184. resp.setEndDate(req.getEndDate());
  2185. double version = context.getClientVersion();
  2186. StringBuffer basicQuery;
  2187. addToQueryString(basicQuery, "State", req.getState());
  2188. addToQueryString(basicQuery, "Cluster", req.getCluster());
  2189. addToQueryString(basicQuery, "Owner", req.getOwner());
  2190. addToQueryString(basicQuery, "StartDate", req.getStartDate());
  2191. addToQueryString(basicQuery, "EndDate", req.getEndDate());
  2192. if (version > 1.25 && req.getLastNDays() > -1)
  2193. addToQueryString(basicQuery, "LastNDays", StringBuffer().append(req.getLastNDays()).str());
  2194. addToQueryString(basicQuery, "ECL", req.getECL());
  2195. addToQueryString(basicQuery, "Jobname", req.getJobname());
  2196. addToQueryString(basicQuery, "Type", req.getType());
  2197. if (addToQueryString(basicQuery, "LogicalFile", req.getLogicalFile()))
  2198. addToQueryString(basicQuery, "LogicalFileSearchType", req.getLogicalFileSearchType());
  2199. resp.setFilters(basicQuery.str());
  2200. if (notEmpty(req.getSortby()) && !strstr(basicQuery.str(), StringBuffer(req.getSortby()).append('=').str()))
  2201. {
  2202. resp.setSortby(req.getSortby());
  2203. addToQueryString(basicQuery, "Sortby", req.getSortby());
  2204. if (req.getDescending())
  2205. {
  2206. resp.setDescending(req.getDescending());
  2207. addToQueryString(basicQuery, "Descending", "1");
  2208. }
  2209. }
  2210. resp.setBasicQuery(basicQuery.str());
  2211. StringBuffer s;
  2212. if(notEmpty(req.getECL()))
  2213. resp.setECL(Utils::url_encode(req.getECL(), s).str());
  2214. if(notEmpty(req.getJobname()))
  2215. resp.setJobname(Utils::url_encode(req.getJobname(), s.clear()).str());
  2216. }
  2217. catch(IException* e)
  2218. {
  2219. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2220. }
  2221. return true;
  2222. }
  2223. bool CWsWorkunitsEx::onWULightWeightQuery(IEspContext &context, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  2224. {
  2225. try
  2226. {
  2227. if (req.getType() && strieq(req.getType(), "archived workunits"))
  2228. doWULightWeightQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
  2229. else
  2230. doWULightWeightQueryWithSort(context, req, resp);
  2231. }
  2232. catch(IException* e)
  2233. {
  2234. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2235. }
  2236. return true;
  2237. }
  2238. ITypeInfo * containsSingleSimpleFieldBlankXPath(IResultSetMetaData * meta)
  2239. {
  2240. if (meta->getColumnCount() != 1)
  2241. return NULL;
  2242. CResultSetMetaData * castMeta = static_cast<CResultSetMetaData *>(meta);
  2243. const char * xpath = castMeta->queryXPath(0);
  2244. if (xpath && (*xpath == 0))
  2245. {
  2246. return castMeta->queryType(0);
  2247. }
  2248. return NULL;
  2249. }
  2250. void csvSplitXPath(const char *xpath, StringBuffer &s, const char *&name, const char **childname=NULL)
  2251. {
  2252. if (!xpath)
  2253. return;
  2254. const char * slash = strchr(xpath, '/');
  2255. if (!slash)
  2256. {
  2257. name = xpath;
  2258. if (childname)
  2259. *childname = NULL;
  2260. }
  2261. else
  2262. {
  2263. if (!childname || strchr(slash+1, '/')) //output ignores xpaths that are too deep
  2264. return;
  2265. name = s.clear().append(slash-xpath, xpath).str();
  2266. *childname = slash+1;
  2267. }
  2268. }
  2269. void getCSVHeaders(const IResultSetMetaData& metaIn, CommonCSVWriter* writer, unsigned& layer)
  2270. {
  2271. StringBuffer xname;
  2272. const CResultSetMetaData& cMeta = static_cast<const CResultSetMetaData &>(metaIn);
  2273. IFvDataSourceMetaData* meta = cMeta.getMeta();
  2274. int columnCount = metaIn.getColumnCount();
  2275. for (unsigned idx = 0; idx < columnCount; idx++)
  2276. {
  2277. const CResultSetColumnInfo& column = cMeta.getColumn(idx);
  2278. unsigned flag = column.flag;
  2279. const char * name = meta->queryName(idx);
  2280. const char * childname = NULL;
  2281. switch (flag)
  2282. {
  2283. case FVFFbeginif:
  2284. case FVFFendif:
  2285. break;
  2286. case FVFFbeginrecord:
  2287. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2288. writer->outputBeginNested(name, false, true);
  2289. break;
  2290. case FVFFendrecord:
  2291. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2292. writer->outputEndNested(name, true);
  2293. break;
  2294. case FVFFdataset:
  2295. {
  2296. childname = "Row";
  2297. csvSplitXPath(meta->queryXPath(idx), xname, name, &childname);
  2298. ITypeInfo* singleFieldType = (name && *name && childname && *childname)
  2299. ? containsSingleSimpleFieldBlankXPath(column.childMeta.get()) : NULL;
  2300. if (!singleFieldType)
  2301. {
  2302. bool nameValid = (name && *name);
  2303. if (nameValid || (childname && *childname))
  2304. {
  2305. if (nameValid)
  2306. writer->outputBeginNested(name, false, true);
  2307. if (childname && *childname)
  2308. writer->outputBeginNested(childname, false, !nameValid);
  2309. const CResultSetMetaData *childMeta = static_cast<const CResultSetMetaData *>(column.childMeta.get());
  2310. getCSVHeaders(*childMeta, writer, ++layer);
  2311. layer--;
  2312. if (childname && *childname)
  2313. writer->outputEndNested(childname, !nameValid);
  2314. if (nameValid)
  2315. writer->outputEndNested(name, true);
  2316. }
  2317. }
  2318. break;
  2319. }
  2320. case FVFFblob: //for now FileViewer will output the string "[blob]"
  2321. {
  2322. Owned<ITypeInfo> stringType = makeStringType(UNKNOWN_LENGTH, NULL, NULL);
  2323. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2324. StringBuffer eclTypeName;
  2325. stringType->getECLType(eclTypeName);
  2326. writer->outputCSVHeader(name, eclTypeName.str());
  2327. }
  2328. break;
  2329. default:
  2330. {
  2331. ITypeInfo & type = *column.type;
  2332. if (type.getTypeCode() == type_set)
  2333. {
  2334. childname = "Item";
  2335. csvSplitXPath(meta->queryXPath(idx), xname, name, &childname);
  2336. writer->outputBeginNested(name, true, true);
  2337. writer->outputEndNested(name, true);
  2338. }
  2339. else
  2340. {
  2341. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2342. StringBuffer eclTypeName;
  2343. type.getECLType(eclTypeName);
  2344. writer->outputCSVHeader(name, eclTypeName.str());
  2345. }
  2346. break;
  2347. }
  2348. }
  2349. }
  2350. }
  2351. unsigned getResultCSV(IStringVal& ret, INewResultSet* result, const char* name, __int64 start, unsigned& count)
  2352. {
  2353. unsigned headerLayer = 0;
  2354. CSVOptions csvOptions;
  2355. csvOptions.delimiter.set(",");
  2356. csvOptions.terminator.set("\n");
  2357. csvOptions.includeHeader = true;
  2358. Owned<CommonCSVWriter> writer = new CommonCSVWriter(XWFtrim, csvOptions);
  2359. const IResultSetMetaData & meta = result->getMetaData();
  2360. getCSVHeaders(meta, writer, headerLayer);
  2361. writer->finishCSVHeaders();
  2362. Owned<IResultSetCursor> cursor = result->createCursor();
  2363. count = writeResultCursorXml(*writer, cursor, name, start, count, NULL);
  2364. ret.set(writer->str());
  2365. return count;
  2366. }
  2367. void appendResultSet(MemoryBuffer& mb, INewResultSet* result, const char *name, __int64 start, unsigned& count, __int64& total, bool bin, bool xsd, ESPSerializationFormat fmt, const IProperties *xmlns)
  2368. {
  2369. if (!result)
  2370. return;
  2371. total=result->getNumRows();
  2372. if(bin)
  2373. count = getResultBin(mb, result, (unsigned)start, count);
  2374. else
  2375. {
  2376. struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
  2377. {
  2378. MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
  2379. IMPLEMENT_IINTERFACE;
  2380. virtual const char * str() const { UNIMPLEMENTED; }
  2381. virtual void set(const char *val) { buffer.append(strlen(val),val); }
  2382. virtual void clear() { } // support appending only
  2383. virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
  2384. virtual unsigned length() const { return buffer.length(); };
  2385. MemoryBuffer & buffer;
  2386. } adaptor(mb);
  2387. if (fmt==ESPSerializationCSV)
  2388. count = getResultCSV(adaptor, result, name, (unsigned) start, count);
  2389. else if (fmt==ESPSerializationJSON)
  2390. count = getResultJSON(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL);
  2391. else
  2392. count = getResultXml(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL, xmlns);
  2393. }
  2394. }
  2395. INewResultSet* createFilteredResultSet(INewResultSet* result, IArrayOf<IConstNamedValue>* filterBy)
  2396. {
  2397. if (!result || !filterBy || !filterBy->length())
  2398. return NULL;
  2399. Owned<IFilteredResultSet> filter = result->createFiltered();
  2400. const IResultSetMetaData &meta = result->getMetaData();
  2401. unsigned columnCount = meta.getColumnCount();
  2402. ForEachItemIn(i, *filterBy)
  2403. {
  2404. IConstNamedValue &item = filterBy->item(i);
  2405. const char *name = item.getName();
  2406. const char *value = item.getValue();
  2407. if (!name || !*name || !value || !*value)
  2408. continue;
  2409. for(unsigned col = 0; col < columnCount; col++)
  2410. {
  2411. SCMStringBuffer scmbuf;
  2412. meta.getColumnLabel(scmbuf, col);
  2413. if (strieq(scmbuf.str(), name))
  2414. {
  2415. filter->addFilter(col, value);
  2416. break;
  2417. }
  2418. }
  2419. }
  2420. return filter->create();
  2421. }
  2422. void getWsWuResult(IEspContext &context, const char* wuid, const char *name, const char *logical, unsigned index, __int64 start,
  2423. unsigned& count, __int64& total, IStringVal& resname, bool bin, IArrayOf<IConstNamedValue>* filterBy, MemoryBuffer& mb,
  2424. WUState& wuState, bool xsd=true)
  2425. {
  2426. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2427. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  2428. if(!cw)
  2429. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  2430. Owned<IConstWUResult> result;
  2431. if (notEmpty(name))
  2432. result.setown(cw->getResultByName(name));
  2433. else if (notEmpty(logical))
  2434. {
  2435. Owned<IConstWUResultIterator> it = &cw->getResults();
  2436. ForEach(*it)
  2437. {
  2438. IConstWUResult &r = it->query();
  2439. SCMStringBuffer filename;
  2440. if(strieq(r.getResultLogicalName(filename).str(), logical))
  2441. {
  2442. result.setown(LINK(&r));
  2443. break;
  2444. }
  2445. }
  2446. }
  2447. else
  2448. result.setown(cw->getResultBySequence(index));
  2449. if (!result)
  2450. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2451. if (!resname.length())
  2452. result->getResultName(resname);
  2453. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  2454. SCMStringBuffer logicalName;
  2455. result->getResultLogicalName(logicalName);
  2456. Owned<INewResultSet> rs;
  2457. if (logicalName.length())
  2458. {
  2459. rs.setown(resultSetFactory->createNewFileResultSet(logicalName.str(), cw->queryClusterName())); //MORE is this wrong cluster?
  2460. }
  2461. else
  2462. rs.setown(resultSetFactory->createNewResultSet(result, wuid));
  2463. if (!filterBy || !filterBy->length())
  2464. appendResultSet(mb, rs, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryResultXmlns());
  2465. else
  2466. {
  2467. Owned<INewResultSet> filteredResult = createFilteredResultSet(rs, filterBy);
  2468. appendResultSet(mb, filteredResult, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryResultXmlns());
  2469. }
  2470. wuState = cw->getState();
  2471. }
  2472. void checkFileSizeLimit(unsigned long xmlSize, unsigned long sizeLimit)
  2473. {
  2474. if ((sizeLimit > 0) && (xmlSize > sizeLimit))
  2475. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE,
  2476. "The file size (%ld bytes) exceeds the size limit (%ld bytes). You may set 'Option > 1' or use 'Download_XML' link to get compressed file.",
  2477. xmlSize, sizeLimit);
  2478. }
  2479. void openSaveFile(IEspContext &context, int opt, __int64 sizeLimit, const char* filename, const char* origMimeType, MemoryBuffer& buf, IEspWULogFileResponse &resp)
  2480. {
  2481. if (opt < 1)
  2482. {
  2483. checkFileSizeLimit(buf.length(), sizeLimit);
  2484. resp.setThefile(buf);
  2485. resp.setThefile_mimetype(origMimeType);
  2486. }
  2487. else if (opt < 2)
  2488. {
  2489. checkFileSizeLimit(buf.length(), sizeLimit);
  2490. StringBuffer headerStr("attachment;");
  2491. if (filename && *filename)
  2492. {
  2493. const char* pFileName = strrchr(filename, PATHSEPCHAR);
  2494. if (pFileName)
  2495. headerStr.appendf("filename=%s", pFileName+1);
  2496. else
  2497. headerStr.appendf("filename=%s", filename);
  2498. }
  2499. MemoryBuffer buf0;
  2500. unsigned i = 0;
  2501. char* p = (char*) buf.toByteArray();
  2502. while (i < buf.length())
  2503. {
  2504. if (p[0] != 10)
  2505. buf0.append(p[0]);
  2506. else
  2507. buf0.append(0x0d);
  2508. p++;
  2509. i++;
  2510. }
  2511. resp.setThefile(buf);
  2512. resp.setThefile_mimetype(origMimeType);
  2513. context.addCustomerHeader("Content-disposition", headerStr.str());
  2514. }
  2515. else
  2516. {
  2517. #ifndef _USE_ZLIB
  2518. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2519. #else
  2520. StringBuffer fileNameStr, headerStr("attachment;");
  2521. if (notEmpty(filename))
  2522. {
  2523. fileNameStr.append(filename);
  2524. headerStr.append("filename=").append(filename).append((opt>2) ? ".gz" : ".zip");
  2525. }
  2526. else
  2527. fileNameStr.append("file");
  2528. StringBuffer ifname;
  2529. ifname.appendf("%s%sT%xAT%x", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick()).append((opt>2)? "" : ".zip");
  2530. IZZIPor* Zipor = createZZIPor();
  2531. int ret = 0;
  2532. if (opt > 2)
  2533. ret = Zipor->gzipToFile(buf.length(), (void*)buf.toByteArray(), ifname.str());
  2534. else
  2535. ret = Zipor->zipToFile(buf.length(), (void*)buf.toByteArray(), fileNameStr.str(), ifname.str());
  2536. releaseIZ(Zipor);
  2537. if (ret < 0)
  2538. {
  2539. Owned<IFile> rFile = createIFile(ifname.str());
  2540. if (rFile->exists())
  2541. rFile->remove();
  2542. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2543. }
  2544. Owned <IFile> rf = createIFile(ifname.str());
  2545. if (!rf->exists())
  2546. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2547. MemoryBuffer out;
  2548. Owned <IFileIO> fio = rf->open(IFOread);
  2549. read(fio, 0, (size32_t) rf->size(), out);
  2550. resp.setThefile(out);
  2551. fio.clear();
  2552. rf->remove();
  2553. resp.setThefile_mimetype((opt > 2) ? "application/x-gzip" : "application/zip");
  2554. context.addCustomerHeader("Content-disposition", headerStr.str());
  2555. #endif
  2556. }
  2557. }
  2558. bool CWsWorkunitsEx::onWUFile(IEspContext &context,IEspWULogFileRequest &req, IEspWULogFileResponse &resp)
  2559. {
  2560. try
  2561. {
  2562. StringBuffer wuidStr = req.getWuid();
  2563. const char* wuidIn = wuidStr.trim().str();
  2564. if (wuidIn && *wuidIn)
  2565. {
  2566. if (!looksLikeAWuid(wuidIn, 'W'))
  2567. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID");
  2568. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2569. }
  2570. StringAttr wuid(wuidIn);
  2571. if (wuid.isEmpty() && notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  2572. {
  2573. Owned<IPropertyTree> registry = getQueryRegistry(req.getQuerySet(), false);
  2574. if (!registry)
  2575. throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", req.getQuerySet());
  2576. Owned<IPropertyTree> query = resolveQueryAlias(registry, req.getQuery());
  2577. if (!query)
  2578. throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", req.getQuery());
  2579. resp.setQuerySet(req.getQuerySet());
  2580. resp.setQueryName(query->queryProp("@name"));
  2581. resp.setQueryId(query->queryProp("@id"));
  2582. wuid.set(query->queryProp("@wuid"));
  2583. }
  2584. int opt = req.getOption();
  2585. if (!wuid.isEmpty())
  2586. {
  2587. VStringBuffer logMsg("WUFile: %s", wuid.str());
  2588. if (notEmpty(req.getType()))
  2589. logMsg.append(", ").append(req.getType());
  2590. if (opt > 1)
  2591. logMsg.append(", download gzip");
  2592. else if (opt > 0)
  2593. logMsg.append(", download");
  2594. PROGLOG("%s", logMsg.str());
  2595. resp.setWuid(wuid.get());
  2596. MemoryBuffer mb;
  2597. WsWuInfo winfo(context, wuid);
  2598. if (strieq(File_ArchiveQuery, req.getType()))
  2599. {
  2600. winfo.getWorkunitArchiveQuery(mb);
  2601. openSaveFile(context, opt, req.getSizeLimit(), "ArchiveQuery.xml", HTTP_TYPE_APPLICATION_XML, mb, resp);
  2602. }
  2603. else if (strieq(File_Cpp,req.getType()) && notEmpty(req.getName()))
  2604. {
  2605. winfo.getWorkunitCpp(req.getName(), req.getDescription(), req.getIPAddress(),mb, opt > 0);
  2606. openSaveFile(context, opt, req.getSizeLimit(), req.getName(), HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2607. }
  2608. else if (strieq(File_DLL,req.getType()))
  2609. {
  2610. StringBuffer name;
  2611. winfo.getWorkunitDll(name, mb);
  2612. resp.setFileName(name.str());
  2613. resp.setDaliServer(daliServers.get());
  2614. openSaveFile(context, opt, req.getSizeLimit(), req.getName(), HTTP_TYPE_OCTET_STREAM, mb, resp);
  2615. }
  2616. else if (strieq(File_Res,req.getType()))
  2617. {
  2618. winfo.getWorkunitResTxt(mb);
  2619. openSaveFile(context, opt, req.getSizeLimit(), "res.txt", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2620. }
  2621. else if (strncmp(req.getType(), File_ThorLog, 7) == 0)
  2622. {
  2623. winfo.getWorkunitThorLog(req.getName(), mb);
  2624. openSaveFile(context, opt, req.getSizeLimit(), "thormaster.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2625. }
  2626. else if (strieq(File_ThorSlaveLog,req.getType()))
  2627. {
  2628. StringBuffer logDir;
  2629. getConfigurationDirectory(directories, "log", "thor", req.getProcess(), logDir);
  2630. winfo.getWorkunitThorSlaveLog(req.getClusterGroup(), req.getIPAddress(), req.getLogDate(), logDir.str(), req.getSlaveNumber(), mb, false);
  2631. openSaveFile(context, opt, req.getSizeLimit(), "ThorSlave.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2632. }
  2633. else if (strieq(File_EclAgentLog,req.getType()))
  2634. {
  2635. winfo.getWorkunitEclAgentLog(req.getName(), req.getProcess(), mb);
  2636. openSaveFile(context, opt, req.getSizeLimit(), "eclagent.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2637. }
  2638. else if (strieq(File_XML,req.getType()) && notEmpty(req.getName()))
  2639. {
  2640. const char* name = req.getName();
  2641. const char* ptr = strrchr(name, '/');
  2642. if (ptr)
  2643. ptr++;
  2644. else
  2645. ptr = name;
  2646. winfo.getWorkunitAssociatedXml(name, req.getIPAddress(), req.getPlainText(), req.getDescription(), opt > 0, true, mb);
  2647. openSaveFile(context, opt, req.getSizeLimit(), ptr, HTTP_TYPE_APPLICATION_XML, mb, resp);
  2648. }
  2649. else if (strieq(File_XML,req.getType()) || strieq(File_WUECL,req.getType()))
  2650. {
  2651. StringBuffer mimeType, fileName;
  2652. if (strieq(File_WUECL,req.getType()))
  2653. {
  2654. fileName.setf("%s.ecl", wuid.get());
  2655. winfo.getWorkunitQueryShortText(mb);
  2656. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2657. }
  2658. else
  2659. {
  2660. fileName.setf("%s.xml", wuid.get());
  2661. winfo.getWorkunitXml(req.getPlainText(), mb);
  2662. if (opt < 2)
  2663. {
  2664. const char* plainText = req.getPlainText();
  2665. if (plainText && (!stricmp(plainText, "yes")))
  2666. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2667. else
  2668. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2669. }
  2670. else
  2671. {
  2672. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2673. }
  2674. }
  2675. openSaveFile(context, opt, req.getSizeLimit(), fileName.str(), mimeType.str(), mb, resp);
  2676. }
  2677. PROGLOG("%s -- done", logMsg.str());
  2678. }
  2679. }
  2680. catch(IException* e)
  2681. {
  2682. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2683. }
  2684. return true;
  2685. }
  2686. void CWsWorkunitsEx::readWUFile(const char *wuid, WsWuInfo &winfo, IConstWUFileOption &item, bool forDownload, MemoryBuffer &mb, StringBuffer &fileName, StringBuffer &fileMimeType)
  2687. {
  2688. CWUFileType fileType = item.getFileType();
  2689. switch (fileType)
  2690. {
  2691. case CWUFileType_ArchiveQuery:
  2692. winfo.getWorkunitArchiveQuery(mb);
  2693. fileMimeType.set(HTTP_TYPE_APPLICATION_XML);
  2694. fileName.set("ArchiveQuery.xml");
  2695. break;
  2696. case CWUFileType_CPP:
  2697. {
  2698. const char *tail=pathTail(item.getName());
  2699. fileName.set(tail ? tail : item.getName());
  2700. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2701. winfo.getWorkunitCpp(item.getName(), item.getDescription(), item.getIPAddress(),mb, forDownload);
  2702. break;
  2703. }
  2704. case CWUFileType_DLL:
  2705. {
  2706. const char *tail=pathTail(item.getName());
  2707. fileName.set(tail ? tail : item.getName());
  2708. fileMimeType.set(HTTP_TYPE_OCTET_STREAM);
  2709. break;
  2710. }
  2711. case CWUFileType_Res:
  2712. winfo.getWorkunitResTxt(mb);
  2713. fileName.set("res.txt");
  2714. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2715. break;
  2716. case CWUFileType_ThorLog:
  2717. winfo.getWorkunitThorLog(item.getName(), mb);
  2718. fileName.set("thormaster.log");
  2719. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2720. break;
  2721. case CWUFileType_ThorSlaveLog:
  2722. {
  2723. StringBuffer logDir;
  2724. getConfigurationDirectory(directories, "log", "thor", item.getProcess(), logDir);
  2725. winfo.getWorkunitThorSlaveLog(item.getClusterGroup(), item.getIPAddress(), item.getLogDate(), logDir.str(), item.getSlaveNumber(), mb, false);
  2726. fileName.set("ThorSlave.log");
  2727. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2728. break;
  2729. }
  2730. case CWUFileType_EclAgentLog:
  2731. winfo.getWorkunitEclAgentLog(item.getName(), item.getProcess(), mb);
  2732. fileName.set("eclagent.log");
  2733. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2734. break;
  2735. case CWUFileType_XML:
  2736. {
  2737. StringBuffer name = item.getName();
  2738. if (!name.isEmpty())
  2739. {
  2740. const char *tail=pathTail(name.str());
  2741. fileName.set(tail ? tail : name.str());
  2742. winfo.getWorkunitAssociatedXml(fileName.str(), item.getIPAddress(), item.getPlainText(), item.getDescription(), forDownload, true, mb);
  2743. }
  2744. else
  2745. {
  2746. fileName.setf("%s.xml", wuid);
  2747. winfo.getWorkunitXml(item.getPlainText(), mb);
  2748. }
  2749. const char* plainText = item.getPlainText();
  2750. if (plainText && strieq(plainText, "yes"))
  2751. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2752. else
  2753. fileMimeType.set(HTTP_TYPE_APPLICATION_XML);
  2754. break;
  2755. }
  2756. case CWUFileType_WUECL:
  2757. fileName.setf("%s.ecl", wuid);
  2758. winfo.getWorkunitQueryShortText(mb);
  2759. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2760. break;
  2761. default:
  2762. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Unsupported file type %d.", fileType);
  2763. }
  2764. }
  2765. void CWsWorkunitsEx::zipAFolderToMB(const char *folderToZIP, const char *zipFileName, bool gzip, MemoryBuffer &mb)
  2766. {
  2767. StringBuffer folderToZIPEx, zipFileNameWithPath, zipCommand;
  2768. zipFileNameWithPath.set(zipFolder).append(zipFileName);
  2769. folderToZIPEx.set(folderToZIP).append("/*");
  2770. {
  2771. Owned<IFile> oldZIPFile = createIFile(zipFileNameWithPath.str());
  2772. if (oldZIPFile->exists())
  2773. oldZIPFile->remove();
  2774. }
  2775. if (!gzip)
  2776. zipCommand.appendf("zip -j %s %s", zipFileNameWithPath.str(), folderToZIPEx.str());
  2777. else
  2778. zipCommand.appendf("tar -czf %s %s", zipFileNameWithPath.str(), folderToZIPEx.str());
  2779. if (system(zipCommand.str()) != 0)
  2780. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Failed to execute system command %s. Please make sure that zip utility is installed.", zipCommand.str());
  2781. Owned<IFile> f = createIFile(zipFileNameWithPath.str());
  2782. Owned<IFileIO> io = f->open(IFOread);
  2783. void * data = mb.reserve((unsigned)io->size());
  2784. size32_t read = io->read(0, (unsigned)io->size(), data);
  2785. mb.setLength(read);
  2786. io->close();
  2787. f->remove();
  2788. }
  2789. void CWsWorkunitsEx::setAttachmentFileName(IEspContext &context, const char *fileName)
  2790. {
  2791. VStringBuffer headerStr("attachment;filename=%s", fileName);
  2792. context.addCustomerHeader("Content-disposition", headerStr.str());
  2793. }
  2794. bool CWsWorkunitsEx::onWUDownloadFiles(IEspContext &context, IEspWUDownloadFilesRequest &req, IEspWUDownloadFilesResponse &resp)
  2795. {
  2796. try
  2797. {
  2798. StringBuffer wuid = req.getWuid();
  2799. if (wuid.trim().isEmpty())
  2800. {
  2801. StringBuffer querySet = req.getQuerySet();
  2802. StringBuffer queryReq = req.getQuery();
  2803. if (queryReq.trim().isEmpty() || querySet.trim().isEmpty())
  2804. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WU ID or QuerySet/Query not specified");
  2805. Owned<IPropertyTree> registry = getQueryRegistry(querySet.str(), false);
  2806. if (!registry)
  2807. throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", querySet.str());
  2808. Owned<IPropertyTree> query = resolveQueryAlias(registry, queryReq.str());
  2809. if (!query)
  2810. throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", queryReq.str());
  2811. resp.setQuerySet(querySet.str());
  2812. resp.setQueryName(query->queryProp("@name"));
  2813. resp.setQueryId(query->queryProp("@id"));
  2814. wuid.set(query->queryProp("@wuid"));
  2815. }
  2816. if (!looksLikeAWuid(wuid, 'W'))
  2817. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID");
  2818. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  2819. IArrayOf<IConstWUFileOption> &wuFileOptions = req.getWUFileOptions();
  2820. if (!wuFileOptions.ordinality())
  2821. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No WU file specified");
  2822. CWUFileDownloadOption opt = req.getDownloadOption();
  2823. if ((wuFileOptions.length() > 1) && ((opt == CWUFileDownloadOption_OriginalText) || (opt == CWUFileDownloadOption_Attachment)))
  2824. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cannot download multiple files without zip");
  2825. Owned<IFile> zipDir;
  2826. StringBuffer folderToZIP, zipFileName;
  2827. if ((opt == CWUFileDownloadOption_ZIP) || (opt == CWUFileDownloadOption_GZIP))
  2828. {
  2829. StringBuffer userName;
  2830. if (context.queryUser())
  2831. userName.append(context.queryUser()->getName());
  2832. zipFileName.set("WUFiles_").append(wuid.str());
  2833. folderToZIP.set(zipFolder).append(zipFileName.str()).append('_').append(userName.str());
  2834. if (opt == CWUFileDownloadOption_ZIP)
  2835. zipFileName.append(".zip");
  2836. else
  2837. zipFileName.append(".gzip");
  2838. zipDir.setown(createIFile(folderToZIP));
  2839. if (!zipDir->exists())
  2840. zipDir->createDirectory();
  2841. else
  2842. cleanZAPFolder(zipDir, false);
  2843. }
  2844. resp.setWuid(wuid.str());
  2845. WsWuInfo winfo(context, wuid.str());
  2846. ForEachItemIn(i, wuFileOptions)
  2847. {
  2848. IConstWUFileOption &item = wuFileOptions.item(i);
  2849. MemoryBuffer mb;
  2850. StringBuffer downloadFileName, downloadFileMimeType;
  2851. readWUFile(wuid.str(), winfo, item, opt != CWUFileDownloadOption_OriginalText, mb, downloadFileName, downloadFileMimeType);
  2852. if (item.getFileType() == CWUFileType_DLL)
  2853. {
  2854. StringBuffer name;
  2855. winfo.getWorkunitDll(name, mb);
  2856. resp.setFileName(name.str());
  2857. resp.setDaliServer(daliServers.get());
  2858. }
  2859. if ((opt == CWUFileDownloadOption_OriginalText) || (opt == CWUFileDownloadOption_Attachment))
  2860. {
  2861. checkFileSizeLimit(mb.length(), item.getSizeLimit());
  2862. resp.setThefile(mb);
  2863. resp.setThefile_mimetype(downloadFileMimeType.str());
  2864. if (opt == CWUFileDownloadOption_Attachment)
  2865. setAttachmentFileName(context, downloadFileName.str());
  2866. break;
  2867. }
  2868. else
  2869. {
  2870. StringBuffer aZIPFile = folderToZIP;
  2871. aZIPFile.append(PATHSEPCHAR).append(downloadFileName.str());
  2872. Owned<IFile> wuIFile = createIFile(aZIPFile.str());
  2873. Owned<IFileIO> wuIFileIO = wuIFile->open(IFOcreate);
  2874. if (wuIFileIO)
  2875. wuIFileIO->write(0, mb.length(), mb.bufferBase());
  2876. }
  2877. }
  2878. if ((opt == CWUFileDownloadOption_ZIP) || (opt == CWUFileDownloadOption_GZIP))
  2879. {
  2880. MemoryBuffer mb;
  2881. zipAFolderToMB(folderToZIP.str(), zipFileName.str(), opt == CWUFileDownloadOption_GZIP, mb);
  2882. //Remove the temporary files and the folder
  2883. cleanZAPFolder(zipDir, true);
  2884. resp.setThefile(mb);
  2885. resp.setThefile_mimetype(HTTP_TYPE_OCTET_STREAM);
  2886. setAttachmentFileName(context, zipFileName.str());
  2887. }
  2888. }
  2889. catch(IException* e)
  2890. {
  2891. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2892. }
  2893. return true;
  2894. }
  2895. bool CWsWorkunitsEx::onWUResultBin(IEspContext &context,IEspWUResultBinRequest &req, IEspWUResultBinResponse &resp)
  2896. {
  2897. try
  2898. {
  2899. StringBuffer wuidStr = req.getWuid();
  2900. const char* wuidIn = wuidStr.trim().str();
  2901. if (wuidIn && *wuidIn)
  2902. {
  2903. if (!looksLikeAWuid(wuidIn, 'W'))
  2904. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuidIn);
  2905. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2906. }
  2907. MemoryBuffer mb;
  2908. __int64 total=0;
  2909. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  2910. unsigned count = req.getCount(), requested=count;
  2911. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  2912. SCMStringBuffer name;
  2913. if(strieq(req.getFormat(),"csv"))
  2914. context.setResponseFormat(ESPSerializationCSV);
  2915. WUState wuState = WUStateUnknown;
  2916. bool bin = (req.getFormat() && strieq(req.getFormat(),"raw"));
  2917. if (notEmpty(wuidIn) && notEmpty(req.getResultName()))
  2918. {
  2919. PROGLOG("WUResultBin: wuid %s, ResultName %s", wuidIn, req.getResultName());
  2920. getWsWuResult(context, wuidIn, req.getResultName(), NULL, 0, start, count, total, name, bin, filterBy, mb, wuState);
  2921. }
  2922. else if (notEmpty(wuidIn) && (req.getSequence() >= 0))
  2923. {
  2924. PROGLOG("WUResultBin: wuid %s, Sequence %d", wuidIn, req.getSequence());
  2925. getWsWuResult(context, wuidIn, NULL, NULL, req.getSequence(), start, count, total, name, bin,filterBy, mb, wuState);
  2926. }
  2927. else if (notEmpty(req.getLogicalName()))
  2928. {
  2929. const char* logicalName = req.getLogicalName();
  2930. StringBuffer wuid;
  2931. getWuidFromLogicalFileName(context, logicalName, wuid);
  2932. if (!wuid.length())
  2933. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.",logicalName);
  2934. PROGLOG("WUResultBin: %s", req.getLogicalName());
  2935. getWsWuResult(context, wuid.str(), NULL, logicalName, 0, start, count, total, name, bin, filterBy, mb, wuState);
  2936. }
  2937. else
  2938. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2939. if(strieq(req.getFormat(),"csv"))
  2940. {
  2941. resp.setResult(mb);
  2942. resp.setResult_mimetype("text/csv");
  2943. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.csv");
  2944. }
  2945. else if(stricmp(req.getFormat(),"xls")==0)
  2946. {
  2947. Owned<IProperties> params(createProperties());
  2948. params->setProp("showCount",0);
  2949. StringBuffer xml;
  2950. xml.append("<WUResultExcel><Result>").append(mb.length(), mb.toByteArray()).append("</Result></WUResultExcel>");
  2951. if (xml.length() > MAXXLSTRANSFER)
  2952. 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.");
  2953. StringBuffer xls;
  2954. xsltTransform(xml.str(), StringBuffer(getCFD()).append("./smc_xslt/result.xslt").str(), params, xls);
  2955. MemoryBuffer out;
  2956. out.setBuffer(xls.length(), (void*)xls.str());
  2957. resp.setResult(out);
  2958. resp.setResult_mimetype("application/vnd.ms-excel");
  2959. }
  2960. #ifdef _USE_ZLIB
  2961. else if(strieq(req.getFormat(),"zip") || strieq(req.getFormat(),"gzip"))
  2962. {
  2963. bool gzip = strieq(req.getFormat(),"gzip");
  2964. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2965. xml.append("<Result>").append(mb.length(),mb.toByteArray()).append("</Result>");
  2966. VStringBuffer ifname("%s%sT%xAT%x%s", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick(), gzip ? "" : ".zip");
  2967. IZZIPor* Zipor = createZZIPor();
  2968. int ret = 0;
  2969. if (gzip)
  2970. ret = Zipor->gzipToFile(xml.length(), (void*)xml.str(), ifname.str());
  2971. else
  2972. ret = Zipor->zipToFile(xml.length(), (void*)xml.str(), "WUResult.xml", ifname.str());
  2973. releaseIZ(Zipor);
  2974. if (ret < 0)
  2975. {
  2976. Owned<IFile> rFile = createIFile(ifname.str());
  2977. if (rFile->exists())
  2978. rFile->remove();
  2979. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "The data cannot be compressed.");
  2980. }
  2981. MemoryBuffer out;
  2982. Owned <IFile> rf = createIFile(ifname.str());
  2983. if (rf->exists())
  2984. {
  2985. Owned <IFileIO> fio = rf->open(IFOread);
  2986. read(fio, 0, (size32_t) rf->size(), out);
  2987. resp.setResult(out);
  2988. }
  2989. if (gzip)
  2990. {
  2991. resp.setResult_mimetype("application/x-gzip");
  2992. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.gz");
  2993. }
  2994. else
  2995. {
  2996. resp.setResult_mimetype("application/zip");
  2997. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.zip");
  2998. }
  2999. Owned<IFile> rFile = createIFile(ifname.str());
  3000. if (rFile->exists())
  3001. rFile->remove();
  3002. }
  3003. #endif
  3004. else
  3005. {
  3006. resp.setResult(mb);
  3007. }
  3008. resp.setName(name.str());
  3009. resp.setWuid(wuidIn);
  3010. resp.setSequence(req.getSequence());
  3011. resp.setStart(start);
  3012. if (requested > total)
  3013. requested = (unsigned)total;
  3014. resp.setRequested(requested);
  3015. resp.setCount(count);
  3016. resp.setTotal(total);
  3017. resp.setFormat(req.getFormat());
  3018. }
  3019. catch(IException* e)
  3020. {
  3021. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3022. }
  3023. return true;
  3024. }
  3025. bool CWsWorkunitsEx::onWUResultSummary(IEspContext &context, IEspWUResultSummaryRequest &req, IEspWUResultSummaryResponse &resp)
  3026. {
  3027. try
  3028. {
  3029. StringBuffer wuid = req.getWuid();
  3030. WsWuHelpers::checkAndTrimWorkunit("WUResultSummary", wuid);
  3031. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3032. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3033. if(!cw)
  3034. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3035. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3036. PROGLOG("WUResultSummary: %s", wuid.str());
  3037. resp.setWuid(wuid.str());
  3038. resp.setSequence(req.getSequence());
  3039. IArrayOf<IEspECLResult> results;
  3040. Owned<IConstWUResult> r = cw->getResultBySequence(req.getSequence());
  3041. if (r)
  3042. {
  3043. WsWuInfo winfo(context, cw);
  3044. winfo.getResult(*r, results, 0);
  3045. resp.setFormat(r->getResultFormat());
  3046. resp.setResult(results.item(0));
  3047. }
  3048. }
  3049. catch(IException* e)
  3050. {
  3051. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3052. }
  3053. return true;
  3054. }
  3055. void getFileResults(IEspContext &context, const char* logicalName, const char* cluster,__int64 start, unsigned& count,__int64& total,
  3056. IStringVal& resname,bool bin, IArrayOf<IConstNamedValue>* filterBy, MemoryBuffer& buf, bool xsd)
  3057. {
  3058. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  3059. Owned<INewResultSet> result(resultSetFactory->createNewFileResultSet(logicalName, cluster));
  3060. if (!filterBy || !filterBy->length())
  3061. appendResultSet(buf, result, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  3062. else
  3063. {
  3064. Owned<INewResultSet> filteredResult = createFilteredResultSet(result, filterBy);
  3065. appendResultSet(buf, filteredResult, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  3066. }
  3067. }
  3068. void getWorkunitCluster(IEspContext &context, const char* wuid, SCMStringBuffer& cluster, bool checkArchiveWUs)
  3069. {
  3070. if (isEmpty(wuid))
  3071. return;
  3072. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3073. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  3074. if (cw)
  3075. cluster.set(cw->queryClusterName());
  3076. else if (checkArchiveWUs)
  3077. {
  3078. Owned<IPropertyTree> wuProps;// = getArchivedWorkUnitProperties(wuid);
  3079. if (wuProps)
  3080. cluster.set(wuProps->queryProp("@clusterName"));
  3081. }
  3082. }
  3083. bool CWsWorkunitsEx::onWUResult(IEspContext &context, IEspWUResultRequest &req, IEspWUResultResponse &resp)
  3084. {
  3085. try
  3086. {
  3087. StringBuffer wuidStr = req.getWuid();
  3088. const char* wuid = wuidStr.trim().str();
  3089. if (wuid && *wuid)
  3090. {
  3091. if (!looksLikeAWuid(wuid, 'W'))
  3092. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  3093. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  3094. }
  3095. MemoryBuffer mb;
  3096. SCMStringBuffer name;
  3097. __int64 total=0;
  3098. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  3099. unsigned count=req.getCount() ? req.getCount() : 100, requested=count;
  3100. unsigned seq = req.getSequence();
  3101. bool inclXsd = !req.getSuppressXmlSchema();
  3102. VStringBuffer filter("start=%" I64F "d;count=%d", start, count);
  3103. addToQueryString(filter, "clusterName", req.getCluster(), ';');
  3104. addToQueryString(filter, "logicalName", req.getLogicalName(), ';');
  3105. if (wuid && *wuid)
  3106. addToQueryString(filter, "wuid", wuid, ';');
  3107. addToQueryString(filter, "resultName", req.getResultName(), ';');
  3108. filter.appendf(";seq=%d;", seq);
  3109. if (inclXsd)
  3110. filter.append("xsd;");
  3111. if (context.getResponseFormat()==ESPSerializationJSON)
  3112. filter.append("json;");
  3113. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  3114. ForEachItemIn(i, *filterBy)
  3115. {
  3116. IConstNamedValue &item = filterBy->item(i);
  3117. const char *name = item.getName();
  3118. const char *value = item.getValue();
  3119. if (name && *name && value && *value)
  3120. addToQueryString(filter, name, value, ';');
  3121. }
  3122. const char* logicalName = req.getLogicalName();
  3123. const char* clusterName = req.getCluster();
  3124. const char* resultName = req.getResultName();
  3125. Owned<DataCacheElement> data;
  3126. if (!req.getBypassCachedResult())
  3127. data.setown(dataCache->lookup(context, filter, awusCacheMinutes));
  3128. if (data)
  3129. {
  3130. PROGLOG("Retrieving Cached WUResult: %s", filter.str());
  3131. mb.append(data->m_data.c_str());
  3132. name.set(data->m_name.c_str());
  3133. logicalName = data->m_logicalName.c_str();
  3134. wuid = data->m_wuid.c_str();
  3135. resultName = data->m_resultName.c_str();
  3136. seq = data->m_seq;
  3137. start = data->m_start;
  3138. count = data->m_rowcount;
  3139. requested = (unsigned)data->m_requested;
  3140. total = data->m_total;
  3141. if (notEmpty(logicalName))
  3142. resp.setLogicalName(logicalName);
  3143. else
  3144. {
  3145. if (notEmpty(wuid))
  3146. resp.setWuid(wuid);
  3147. resp.setSequence(seq);
  3148. }
  3149. }
  3150. else
  3151. {
  3152. PROGLOG("Retrieving WUResult: %s", filter.str());
  3153. WUState wuState = WUStateUnknown;
  3154. if(logicalName && *logicalName)
  3155. {
  3156. StringBuffer lwuid;
  3157. getWuidFromLogicalFileName(context, logicalName, lwuid);
  3158. SCMStringBuffer cluster;
  3159. if (lwuid.length())
  3160. getWorkunitCluster(context, lwuid.str(), cluster, true);
  3161. if (cluster.length())
  3162. {
  3163. getFileResults(context, logicalName, cluster.str(), start, count, total, name, false, filterBy, mb, inclXsd);
  3164. resp.setLogicalName(logicalName);
  3165. }
  3166. else if (notEmpty(clusterName))
  3167. {
  3168. getFileResults(context, logicalName, clusterName, start, count, total, name, false, filterBy, mb, inclXsd);
  3169. resp.setLogicalName(logicalName);
  3170. }
  3171. else
  3172. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Need valid target cluster to browse file %s.",logicalName);
  3173. Owned<IWorkUnitFactory> wf = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3174. Owned<IConstWorkUnit> cw = wf->openWorkUnit(lwuid.str());
  3175. if (cw)
  3176. wuState = cw->getState();
  3177. }
  3178. else if (notEmpty(wuid) && notEmpty(resultName))
  3179. {
  3180. name.set(resultName);
  3181. getWsWuResult(context, wuid, resultName, NULL, 0, start, count, total, name, false, filterBy, mb, wuState, inclXsd);
  3182. resp.setWuid(wuid);
  3183. resp.setSequence(seq);
  3184. }
  3185. else
  3186. {
  3187. getWsWuResult(context, wuid, NULL, NULL, seq, start, count, total, name, false, filterBy, mb, wuState, inclXsd);
  3188. resp.setWuid(wuid);
  3189. resp.setSequence(seq);
  3190. }
  3191. mb.append(0);
  3192. if (requested > total)
  3193. requested = (unsigned)total;
  3194. switch (wuState)
  3195. {
  3196. case WUStateCompleted:
  3197. case WUStateAborted:
  3198. case WUStateFailed:
  3199. case WUStateArchived:
  3200. dataCache->add(filter, mb.toByteArray(), name.str(), logicalName, wuid, resultName, seq, start, count, requested, total);
  3201. break;
  3202. }
  3203. }
  3204. resp.setName(name.str());
  3205. resp.setStart(start);
  3206. if (clusterName && *clusterName)
  3207. resp.setCluster(clusterName);
  3208. resp.setRequested(requested);
  3209. resp.setCount(count);
  3210. resp.setTotal(total);
  3211. resp.setResult(mb.toByteArray());
  3212. context.queryXslParameters()->setProp("escapeResults","1");
  3213. }
  3214. catch(IException* e)
  3215. {
  3216. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3217. }
  3218. return true;
  3219. }
  3220. void getScheduledWUs(IEspContext &context, const char *stateReq, const char *jobNameReq, const char *serverName, const char *eventName, IArrayOf<IEspScheduledWU> & results)
  3221. {
  3222. double version = context.getClientVersion();
  3223. if (notEmpty(serverName))
  3224. {
  3225. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3226. Owned<IScheduleReader> reader = getScheduleReader(serverName, eventName);
  3227. Owned<IScheduleReaderIterator> it(reader->getIterator());
  3228. while(it->isValidEventName())
  3229. {
  3230. StringBuffer ieventName;
  3231. it->getEventName(ieventName);
  3232. while(it->isValidEventText())
  3233. {
  3234. StringBuffer ieventText;
  3235. it->getEventText(ieventText);
  3236. while(it->isValidWuid())
  3237. {
  3238. StringBuffer wuid;
  3239. it->getWuid(wuid);
  3240. if (wuid.length())
  3241. {
  3242. bool match = true;
  3243. unsigned stateID = WUStateUnknown;
  3244. StringBuffer jobName, owner;
  3245. SCMStringBuffer state;
  3246. try
  3247. {
  3248. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3249. if (cw)
  3250. {
  3251. jobName.set(cw->queryJobName());
  3252. owner.set(cw->queryUser());
  3253. }
  3254. if (!isEmptyString(jobNameReq) && (jobName.isEmpty() || !WildMatch(jobName.str(), jobNameReq, true)))
  3255. match = false;
  3256. else if (!isEmptyString(stateReq))
  3257. {
  3258. if (!cw)
  3259. match = false;
  3260. else
  3261. {
  3262. if ((cw->getState() == WUStateScheduled) && cw->aborting())
  3263. {
  3264. stateID = WUStateAborting;
  3265. state.set("aborting");
  3266. }
  3267. else
  3268. {
  3269. stateID = cw->getState();
  3270. state.set(cw->queryStateDesc());
  3271. }
  3272. if (!strieq(stateReq, state.str()))
  3273. match = false;
  3274. }
  3275. }
  3276. }
  3277. catch (IException *e)
  3278. {
  3279. EXCLOG(e, "Get scheduled WUs");
  3280. e->Release();
  3281. match = false;
  3282. }
  3283. if (!match)
  3284. {
  3285. it->nextWuid();
  3286. continue;
  3287. }
  3288. Owned<IEspScheduledWU> scheduledWU = createScheduledWU("");
  3289. scheduledWU->setWuid(wuid.str());
  3290. scheduledWU->setCluster(serverName);
  3291. if (ieventName.length())
  3292. scheduledWU->setEventName(ieventName.str());
  3293. if (ieventText.str())
  3294. scheduledWU->setEventText(ieventText.str());
  3295. if (jobName.length())
  3296. scheduledWU->setJobName(jobName.str());
  3297. if (version >= 1.51)
  3298. {
  3299. if (owner.length())
  3300. scheduledWU->setOwner(owner.str());
  3301. if (state.length())
  3302. {
  3303. scheduledWU->setStateID(stateID);
  3304. scheduledWU->setState(state.str());
  3305. }
  3306. }
  3307. results.append(*scheduledWU.getLink());
  3308. }
  3309. it->nextWuid();
  3310. }
  3311. it->nextEventText();
  3312. }
  3313. it->nextEventName();
  3314. }
  3315. }
  3316. return;
  3317. }
  3318. bool CWsWorkunitsEx::onWUShowScheduled(IEspContext &context, IEspWUShowScheduledRequest & req, IEspWUShowScheduledResponse & resp)
  3319. {
  3320. try
  3321. {
  3322. const char *clusterName = req.getCluster();
  3323. const char *eventName = req.getEventName();
  3324. const char *state = req.getState();
  3325. IArrayOf<IEspScheduledWU> results;
  3326. if(notEmpty(req.getPushEventName()))
  3327. resp.setPushEventName(req.getPushEventName());
  3328. if(notEmpty(req.getPushEventText()))
  3329. resp.setPushEventText(req.getPushEventText());
  3330. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  3331. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3332. Owned<IPropertyTree> root = &environment->getPTree();
  3333. if (!root)
  3334. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  3335. unsigned i = 0;
  3336. Owned<IPropertyTreeIterator> ic = root->getElements("Software/Topology/Cluster");
  3337. IArrayOf<IEspServerInfo> servers;
  3338. ForEach(*ic)
  3339. {
  3340. IPropertyTree &cluster = ic->query();
  3341. const char *iclusterName = cluster.queryProp("@name");
  3342. if (isEmpty(iclusterName))
  3343. continue;
  3344. if(isEmpty(clusterName))
  3345. getScheduledWUs(context, state, req.getJobName(), iclusterName, eventName, results);
  3346. else if (strieq(clusterName, iclusterName))
  3347. {
  3348. getScheduledWUs(context, state, req.getJobName(), clusterName, eventName, results);
  3349. resp.setClusterSelected(i+1);
  3350. }
  3351. Owned<IEspServerInfo> server = createServerInfo("");
  3352. server->setName(iclusterName);
  3353. servers.append(*server.getLink());
  3354. i++;
  3355. }
  3356. if (servers.length())
  3357. resp.setClusters(servers);
  3358. if (results.length())
  3359. resp.setWorkunits(results);
  3360. bool first=false;
  3361. StringBuffer Query("PageFrom=Scheduler");
  3362. appendUrlParameter(Query, "EventName", eventName, first);
  3363. appendUrlParameter(Query, "ECluster", clusterName, first);
  3364. resp.setQuery(Query.str());
  3365. }
  3366. catch(IException* e)
  3367. {
  3368. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3369. }
  3370. return true;
  3371. }
  3372. bool CWsWorkunitsEx::onWUExport(IEspContext &context, IEspWUExportRequest &req, IEspWUExportResponse &resp)
  3373. {
  3374. try
  3375. {
  3376. if (req.getECL() && *req.getECL())
  3377. throw makeStringException(0, "WUExport no longer supports filtering by ECL text");
  3378. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3379. WsWuSearch ws(context, req.getOwner(), req.getState(), req.getCluster(), req.getStartDate(), req.getEndDate(), req.getJobname());
  3380. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Workunits>");
  3381. for(WsWuSearch::iterator it=ws.begin(); it!=ws.end(); it++)
  3382. {
  3383. Owned<IConstWorkUnit> cw = factory->openWorkUnit(it->c_str());
  3384. if (cw)
  3385. exportWorkUnitToXML(cw, xml, true, false, true);
  3386. }
  3387. xml.append("</Workunits>");
  3388. MemoryBuffer mb;
  3389. mb.setBuffer(xml.length(),(void*)xml.str());
  3390. resp.setExportData(mb);
  3391. resp.setExportData_mimetype(HTTP_TYPE_APPLICATION_XML);
  3392. }
  3393. catch(IException* e)
  3394. {
  3395. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3396. }
  3397. return true;
  3398. }
  3399. bool CWsWorkunitsEx::onWUListLocalFileRequired(IEspContext& context, IEspWUListLocalFileRequiredRequest& req, IEspWUListLocalFileRequiredResponse& resp)
  3400. {
  3401. try
  3402. {
  3403. StringBuffer wuid = req.getWuid();
  3404. WsWuHelpers::checkAndTrimWorkunit("WUListLocalFileRequired", wuid);
  3405. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  3406. PROGLOG("WUListLocalFileRequired: %s", wuid.str());
  3407. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3408. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3409. if (!cw)
  3410. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Workunit %s not found.", wuid.str());
  3411. IArrayOf<IEspLogicalFileUpload> localFiles;
  3412. Owned<IConstLocalFileUploadIterator> it = cw->getLocalFileUploads();
  3413. ForEach(*it)
  3414. {
  3415. Owned<IConstLocalFileUpload> file = it->get();
  3416. if(!file)
  3417. continue;
  3418. Owned<IEspLogicalFileUpload> up = createLogicalFileUpload();
  3419. SCMStringBuffer s;
  3420. up->setType(file->queryType());
  3421. up->setSource(file->getSource(s).str());
  3422. up->setDestination(file->getDestination(s).str());
  3423. up->setEventTag(file->getEventTag(s).str());
  3424. localFiles.append(*up.getLink());
  3425. }
  3426. resp.setLocalFileUploads(localFiles);
  3427. }
  3428. catch(IException* e)
  3429. {
  3430. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3431. }
  3432. return true;
  3433. }
  3434. typedef enum wsEclTypes_
  3435. {
  3436. wsEclTypeUnknown,
  3437. xsdString,
  3438. xsdBoolean,
  3439. xsdDecimal,
  3440. xsdFloat,
  3441. xsdDouble,
  3442. xsdDuration,
  3443. xsdDateTime,
  3444. xsdTime,
  3445. xsdDate,
  3446. xsdYearMonth,
  3447. xsdYear,
  3448. xsdMonthDay,
  3449. xsdDay,
  3450. xsdMonth,
  3451. xsdHexBinary,
  3452. xsdBase64Binary,
  3453. xsdAnyURI,
  3454. xsdQName,
  3455. xsdNOTATION,
  3456. xsdNormalizedString,
  3457. xsdToken,
  3458. xsdLanguage,
  3459. xsdNMTOKEN,
  3460. xsdNMTOKENS,
  3461. xsdName,
  3462. xsdNCName,
  3463. xsdID,
  3464. xsdIDREF,
  3465. xsdIDREFS,
  3466. xsdENTITY,
  3467. xsdENTITIES,
  3468. xsdInteger,
  3469. xsdNonPositiveInteger,
  3470. xsdNegativeInteger,
  3471. xsdLong,
  3472. xsdInt,
  3473. xsdShort,
  3474. xsdByte,
  3475. xsdNonNegativeInteger,
  3476. xsdUnsignedLong,
  3477. xsdUnsignedInt,
  3478. xsdUnsignedShort,
  3479. xsdUnsignedByte,
  3480. xsdPositiveInteger,
  3481. tnsRawDataFile,
  3482. tnsCsvDataFile,
  3483. tnsEspStringArray,
  3484. tnsEspIntArray,
  3485. tnsXmlDataSet,
  3486. maxWsEclType
  3487. } wsEclType;
  3488. bool CWsWorkunitsEx::onWUAddLocalFileToWorkunit(IEspContext& context, IEspWUAddLocalFileToWorkunitRequest& req, IEspWUAddLocalFileToWorkunitResponse& resp)
  3489. {
  3490. try
  3491. {
  3492. StringBuffer wuid = req.getWuid();
  3493. WsWuHelpers::checkAndTrimWorkunit("WUAddLocalFileToWorkunit", wuid);
  3494. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  3495. resp.setWuid(wuid.str());
  3496. const char* varname = req.getName();
  3497. if (isEmpty(varname))
  3498. {
  3499. resp.setResult("Name is not defined!");
  3500. return true;
  3501. }
  3502. resp.setName(varname);
  3503. PROGLOG("WUAddLocalFileToWorkunit: %s, name %s", wuid.str(), varname);
  3504. wsEclType type = (wsEclType) req.getType();
  3505. const char *val = req.getVal();
  3506. unsigned len = req.getLength();
  3507. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3508. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  3509. if (!wu)
  3510. {
  3511. resp.setResult("Workunit not found!");
  3512. return true;
  3513. }
  3514. Owned<IWUResult> wuRslt = wu->updateResultByName(varname);
  3515. if (isEmpty(val))
  3516. val=req.getDefVal();
  3517. if (notEmpty(val))
  3518. {
  3519. switch (type)
  3520. {
  3521. case xsdBoolean:
  3522. wuRslt->setResultBool((strieq(val, "1") || strieq(val, "true") || strieq(val, "on")));
  3523. wuRslt->setResultStatus(ResultStatusSupplied);
  3524. break;
  3525. case xsdDecimal:
  3526. case xsdFloat:
  3527. case xsdDouble:
  3528. wuRslt->setResultReal(atof(val));
  3529. wuRslt->setResultStatus(ResultStatusSupplied);
  3530. break;
  3531. case xsdInteger:
  3532. case xsdNonPositiveInteger:
  3533. case xsdNegativeInteger:
  3534. case xsdLong:
  3535. case xsdInt:
  3536. case xsdShort:
  3537. case xsdByte:
  3538. case xsdNonNegativeInteger:
  3539. case xsdUnsignedLong:
  3540. case xsdUnsignedInt:
  3541. case xsdUnsignedShort:
  3542. case xsdUnsignedByte:
  3543. case xsdPositiveInteger:
  3544. wuRslt->setResultInt(_atoi64(val));
  3545. wuRslt->setResultStatus(ResultStatusSupplied);
  3546. break;
  3547. case tnsEspIntArray:
  3548. case tnsEspStringArray:
  3549. wuRslt->setResultRaw(len, val, ResultFormatXmlSet);
  3550. break;
  3551. case tnsRawDataFile:
  3552. wuRslt->setResultRaw(len, val, ResultFormatRaw);
  3553. break;
  3554. case tnsXmlDataSet:
  3555. wuRslt->setResultRaw(len, val, ResultFormatXml);
  3556. break;
  3557. case tnsCsvDataFile:
  3558. case xsdBase64Binary: //tbd
  3559. case xsdHexBinary:
  3560. break;
  3561. default:
  3562. wuRslt->setResultString(val, len);
  3563. wuRslt->setResultStatus(ResultStatusSupplied);
  3564. break;
  3565. }
  3566. }
  3567. resp.setResult("Result has been set as required!");
  3568. }
  3569. catch(IException* e)
  3570. {
  3571. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3572. }
  3573. return true;
  3574. }
  3575. void getClusterConfig(char const * clusterType, char const * clusterName, char const * processName, StringBuffer& netAddress)
  3576. {
  3577. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  3578. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3579. Owned<IPropertyTree> pRoot = &environment->getPTree();
  3580. VStringBuffer xpath("Software/%s[@name='%s']", clusterType, clusterName);
  3581. IPropertyTree* pCluster = pRoot->queryPropTree(xpath.str());
  3582. if (!pCluster)
  3583. throw MakeStringException(ECLWATCH_CLUSTER_NOT_IN_ENV_INFO, "'%s %s' is not defined.", clusterType, clusterName);
  3584. const char* port = pCluster->queryProp(xpath.set(processName).append("@port").str());
  3585. const char* computer = pCluster->queryProp(xpath.set(processName).append("@computer").str());
  3586. if (isEmpty(computer))
  3587. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_INFO, "'%s %s: %s' is not defined.", clusterType, clusterName, processName);
  3588. Owned<IConstMachineInfo> pMachine = environment->getMachine(computer);
  3589. if (pMachine)
  3590. {
  3591. StringBufferAdaptor s(netAddress);
  3592. pMachine->getNetAddress(s);
  3593. #ifdef MACHINE_IP
  3594. if (streq(netAddress.str(), "."))
  3595. netAddress = MACHINE_IP;
  3596. #endif
  3597. netAddress.append(':').append(port);
  3598. }
  3599. return;
  3600. }
  3601. bool CWsWorkunitsEx::onWUGetGraphNameAndTypes(IEspContext &context,IEspWUGetGraphNameAndTypesRequest &req, IEspWUGetGraphNameAndTypesResponse &resp)
  3602. {
  3603. try
  3604. {
  3605. StringBuffer wuid = req.getWuid();
  3606. WsWuHelpers::checkAndTrimWorkunit("WUGraphQuery", wuid);
  3607. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  3608. PROGLOG("WUGetGraphNameAndTypes: %s", wuid.str());
  3609. StringBuffer type = req.getType();
  3610. WUGraphType graphType = GraphTypeAny;
  3611. if (type.trim().length())
  3612. graphType = getGraphTypeFromString(type.str());
  3613. IArrayOf<IEspNameAndType> graphNameAndTypes;
  3614. WsWuInfo winfo(context, wuid.str());
  3615. winfo.getWUGraphNameAndTypes(graphType, graphNameAndTypes);
  3616. resp.setGraphNameAndTypes(graphNameAndTypes);
  3617. }
  3618. catch(IException* e)
  3619. {
  3620. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3621. }
  3622. return true;
  3623. }
  3624. bool CWsWorkunitsEx::onWUProcessGraph(IEspContext &context,IEspWUProcessGraphRequest &req, IEspWUProcessGraphResponse &resp)
  3625. {
  3626. try
  3627. {
  3628. StringBuffer wuid = req.getWuid();
  3629. WsWuHelpers::checkAndTrimWorkunit("WUProcessGraph", wuid);
  3630. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3631. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3632. if(!cw)
  3633. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3634. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3635. if (isEmpty(req.getName()))
  3636. throw MakeStringException(ECLWATCH_GRAPH_NOT_FOUND, "Please specify a graph name.");
  3637. Owned<IConstWUGraph> graph = cw->getGraph(req.getName());
  3638. if (!graph)
  3639. throw MakeStringException(ECLWATCH_GRAPH_NOT_FOUND, "Invalid graph name: %s for %s", req.getName(), wuid.str());
  3640. PROGLOG("WUProcessGraph: %s, Graph Name %s", wuid.str(), req.getName());
  3641. StringBuffer xml;
  3642. Owned<IPropertyTree> xgmml = graph->getXGMMLTree(true); // merge in graph progress information
  3643. toXML(xgmml.get(), xml);
  3644. resp.setTheGraph(xml.str());
  3645. }
  3646. catch(IException* e)
  3647. {
  3648. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3649. }
  3650. return true;
  3651. }
  3652. bool isRunning(IConstWorkUnit &cw)
  3653. {
  3654. // MORE - move into workunit interface
  3655. switch (cw.getState())
  3656. {
  3657. case WUStateFailed:
  3658. case WUStateAborted:
  3659. case WUStateCompleted:
  3660. return false;
  3661. default:
  3662. return true;
  3663. }
  3664. }
  3665. void CWsWorkunitsEx::readGraph(IEspContext& context, const char* subGraphId, WUGraphIDType& id, bool running,
  3666. IConstWUGraph* graph, IArrayOf<IEspECLGraphEx>& graphs)
  3667. {
  3668. SCMStringBuffer name, label, type;
  3669. graph->getName(name);
  3670. graph->getLabel(label);
  3671. graph->getTypeName(type);
  3672. Owned<IEspECLGraphEx> g = createECLGraphEx("","");
  3673. g->setName(name.str());
  3674. g->setLabel(label.str());
  3675. g->setType(type.str());
  3676. WUGraphState graphState = graph->getState();
  3677. if (running && (WUGraphRunning == graphState))
  3678. {
  3679. g->setRunning(true);
  3680. g->setRunningId(id);
  3681. }
  3682. else if (context.getClientVersion() > 1.20)
  3683. {
  3684. if (WUGraphComplete == graphState)
  3685. g->setComplete(true);
  3686. else if (WUGraphFailed == graphState)
  3687. g->setFailed(true);
  3688. }
  3689. Owned<IPropertyTree> xgmml = graph->getXGMMLTree(true);
  3690. // New functionality, if a subgraph id is specified and we only want to load the xgmml for that subgraph
  3691. // then we need to conditionally pull a propertytree from the xgmml graph one and use that for the xgmml.
  3692. //JCSMORE this should be part of the API and therefore allow *only* the subtree to be pulled from the backend.
  3693. StringBuffer xml;
  3694. if (notEmpty(subGraphId))
  3695. {
  3696. VStringBuffer xpath("//node[@id='%s']", subGraphId);
  3697. toXML(xgmml->queryPropTree(xpath.str()), xml);
  3698. }
  3699. else
  3700. toXML(xgmml, xml);
  3701. g->setGraph(xml.str());
  3702. graphs.append(*g.getClear());
  3703. }
  3704. bool CWsWorkunitsEx::onWUGetGraph(IEspContext& context, IEspWUGetGraphRequest& req, IEspWUGetGraphResponse& resp)
  3705. {
  3706. try
  3707. {
  3708. StringBuffer wuid = req.getWuid();
  3709. WsWuHelpers::checkAndTrimWorkunit("WUGetGraph", wuid);
  3710. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3711. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3712. if(!cw)
  3713. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3714. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3715. WUGraphIDType id;
  3716. SCMStringBuffer runningGraph;
  3717. bool running = (isRunning(*cw) && cw->getRunningGraph(runningGraph,id));
  3718. IArrayOf<IEspECLGraphEx> graphs;
  3719. if (isEmpty(req.getGraphName())) // JCS->GS - is this really required??
  3720. {
  3721. PROGLOG("WUGetGraph: %s", wuid.str());
  3722. Owned<IConstWUGraphIterator> it = &cw->getGraphs(GraphTypeAny);
  3723. ForEach(*it)
  3724. readGraph(context, req.getSubGraphId(), id, running, &it->query(), graphs);
  3725. }
  3726. else
  3727. {
  3728. PROGLOG("WUGetGraph: %s, Graph Name %s", wuid.str(), req.getGraphName());
  3729. Owned<IConstWUGraph> graph = cw->getGraph(req.getGraphName());
  3730. if (graph)
  3731. readGraph(context, req.getSubGraphId(), id, running, graph, graphs);
  3732. }
  3733. resp.setGraphs(graphs);
  3734. }
  3735. catch(IException* e)
  3736. {
  3737. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3738. }
  3739. return true;
  3740. }
  3741. bool CWsWorkunitsEx::onGVCAjaxGraph(IEspContext &context, IEspGVCAjaxGraphRequest &req, IEspGVCAjaxGraphResponse &resp)
  3742. {
  3743. try
  3744. {
  3745. resp.setName(req.getName());
  3746. resp.setGraphName(req.getGraphName());
  3747. resp.setGraphType("eclwatch");
  3748. double version = context.getClientVersion();
  3749. if (version > 1.19)
  3750. resp.setSubGraphId(req.getSubGraphId());
  3751. if (version > 1.20)
  3752. resp.setSubGraphOnly(req.getSubGraphOnly());
  3753. }
  3754. catch(IException* e)
  3755. {
  3756. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3757. }
  3758. return true;
  3759. }
  3760. bool CWsWorkunitsEx::onWUDetails(IEspContext &context, IEspWUDetailsRequest &req, IEspWUDetailsResponse &resp)
  3761. {
  3762. try
  3763. {
  3764. StringBuffer wuid = req.getWUID();
  3765. WsWuHelpers::checkAndTrimWorkunit("WUDetails", wuid);
  3766. PROGLOG("WUDetails: %s", wuid.str());
  3767. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3768. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3769. if(!cw)
  3770. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3771. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3772. WUDetails wuDetails(cw, wuid);
  3773. wuDetails.processRequest(req, resp);
  3774. }
  3775. catch(IException* e)
  3776. {
  3777. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3778. }
  3779. return true;
  3780. }
  3781. bool CWsWorkunitsEx::onWUDetailsMeta(IEspContext &context, IEspWUDetailsMetaRequest &req, IEspWUDetailsMetaResponse &resp)
  3782. {
  3783. try
  3784. {
  3785. StringArray statistics;
  3786. for (unsigned i=StatisticKind::StKindAll+1; i<StatisticKind::StMax;++i)
  3787. {
  3788. const char * s = queryStatisticName((StatisticKind)i);
  3789. if (s && *s)
  3790. statistics.append(s);
  3791. }
  3792. resp.setStatistics(statistics);
  3793. StringArray attributes;
  3794. for (unsigned i=WuAttr::WAAll+1; i<WuAttr::WAMax; ++i)
  3795. {
  3796. const char * s = queryWuAttributeName((WuAttr)i);
  3797. if (s && *s)
  3798. attributes.append(s);
  3799. }
  3800. resp.setAttributes(attributes);
  3801. StringArray scopeTypes;
  3802. for (unsigned i=StatisticScopeType::SSTall+1; i<StatisticScopeType::SSTmax; ++i)
  3803. {
  3804. const char * s = queryScopeTypeName((StatisticScopeType)i);
  3805. if (s && *s)
  3806. scopeTypes.append(s);
  3807. }
  3808. resp.setScopeTypes(scopeTypes);
  3809. StringArray measures;
  3810. for (unsigned i=StatisticMeasure::SMeasureAll+1; i<StatisticMeasure::SMeasureMax; ++i)
  3811. {
  3812. const char *s = queryMeasureName((StatisticMeasure)i);
  3813. if (s && *s)
  3814. measures.append(s);
  3815. }
  3816. resp.setMeasures(measures);
  3817. }
  3818. catch(IException* e)
  3819. {
  3820. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3821. }
  3822. return true;
  3823. }
  3824. bool CWsWorkunitsEx::onWUGraphInfo(IEspContext &context,IEspWUGraphInfoRequest &req, IEspWUGraphInfoResponse &resp)
  3825. {
  3826. try
  3827. {
  3828. StringBuffer wuid = req.getWuid();
  3829. WsWuHelpers::checkAndTrimWorkunit("WUGraphInfo", wuid);
  3830. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3831. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3832. if(!cw)
  3833. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3834. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  3835. resp.setWuid(wuid.str());
  3836. resp.setName(req.getName());
  3837. resp.setRunning(isRunning(*cw));
  3838. if (notEmpty(req.getGID()))
  3839. resp.setGID(req.getGID());
  3840. if(!req.getBatchWU_isNull())
  3841. resp.setBatchWU(req.getBatchWU());
  3842. }
  3843. catch(IException* e)
  3844. {
  3845. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3846. }
  3847. return true;
  3848. }
  3849. bool CWsWorkunitsEx::onWUGVCGraphInfo(IEspContext &context,IEspWUGVCGraphInfoRequest &req, IEspWUGVCGraphInfoResponse &resp)
  3850. {
  3851. try
  3852. {
  3853. StringBuffer wuid = req.getWuid();
  3854. WsWuHelpers::checkAndTrimWorkunit("WUGVCGraphInfo", wuid);
  3855. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3856. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3857. if(!cw)
  3858. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3859. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3860. resp.setWuid(wuid.str());
  3861. resp.setName(req.getName());
  3862. resp.setRunning(isRunning(*cw));
  3863. if (notEmpty(req.getGID()))
  3864. resp.setGID(req.getGID());
  3865. if(!req.getBatchWU_isNull())
  3866. resp.setBatchWU(req.getBatchWU());
  3867. StringBuffer xml("<Control><Endpoint><Query id=\"Gordon.Extractor.0\">");
  3868. xml.appendf("<Graph id=\"%s\">", req.getName());
  3869. if (context.getClientVersion() > 1.17)
  3870. {
  3871. xml.append("<Subgraph>");
  3872. xml.append(req.getSubgraphId_isNull() ? 0 : req.getSubgraphId());
  3873. xml.append("</Subgraph>");
  3874. }
  3875. xml.append("</Graph></Query></Endpoint></Control>");
  3876. resp.setTheGraph(xml.str());
  3877. }
  3878. catch(IException* e)
  3879. {
  3880. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3881. }
  3882. return true;
  3883. }
  3884. bool CWsWorkunitsEx::onWUGraphTiming(IEspContext &context, IEspWUGraphTimingRequest &req, IEspWUGraphTimingResponse &resp)
  3885. {
  3886. try
  3887. {
  3888. StringBuffer wuid = req.getWuid();
  3889. WsWuHelpers::checkAndTrimWorkunit("WUGraphTiming", wuid);
  3890. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3891. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3892. if(!cw)
  3893. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3894. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3895. PROGLOG("WUGraphTiming: %s", wuid.str());
  3896. resp.updateWorkunit().setWuid(wuid.str());
  3897. WsWuInfo winfo(context, cw);
  3898. IArrayOf<IConstECLTimingData> timingData;
  3899. winfo.getGraphTimingData(timingData);
  3900. resp.updateWorkunit().setTimingData(timingData);
  3901. }
  3902. catch(IException* e)
  3903. {
  3904. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3905. }
  3906. return true;
  3907. }
  3908. int CWsWorkunitsSoapBindingEx::onGetForm(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
  3909. {
  3910. try
  3911. {
  3912. StringBuffer xml;
  3913. StringBuffer xslt;
  3914. if(strieq(method,"WUQuery") || strieq(method,"WUJobList"))
  3915. {
  3916. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  3917. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3918. Owned<IPropertyTree> root = &environment->getPTree();
  3919. if (!root)
  3920. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  3921. if(strieq(method,"WUQuery"))
  3922. {
  3923. SecAccessFlags accessOwn;
  3924. SecAccessFlags accessOthers;
  3925. getUserWuAccessFlags(context, accessOwn, accessOthers, false);
  3926. xml.append("<WUQuery>");
  3927. if ((accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  3928. xml.appendf("<ErrorMessage>Access to workunit is denied.</ErrorMessage>");
  3929. else
  3930. {
  3931. MapStringTo<bool> added;
  3932. Owned<IPropertyTreeIterator> it = root->getElements("Software/Topology/Cluster");
  3933. ForEach(*it)
  3934. {
  3935. const char *name = it->query().queryProp("@name");
  3936. if (notEmpty(name) && !added.getValue(name))
  3937. {
  3938. added.setValue(name, true);
  3939. appendXMLTag(xml, "Cluster", name);
  3940. }
  3941. }
  3942. }
  3943. xml.append("</WUQuery>");
  3944. xslt.append(getCFD()).append("./smc_xslt/wuid_search.xslt");
  3945. }
  3946. else if (strieq(method,"WUJobList"))
  3947. {
  3948. StringBuffer cluster, defaultProcess, range;
  3949. request->getParameter("Cluster", cluster);
  3950. request->getParameter("Process",defaultProcess);
  3951. request->getParameter("Range",range);
  3952. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(cluster);
  3953. xml.append("<WUJobList>");
  3954. if (range.length())
  3955. appendXMLTag(xml, "Range", range.str());
  3956. if (clusterInfo)
  3957. {
  3958. const StringArray &thorInstances = clusterInfo->getThorProcesses();
  3959. ForEachItemIn(i, thorInstances)
  3960. {
  3961. const char* instance = thorInstances.item(i);
  3962. if (defaultProcess.length() && strieq(instance, defaultProcess.str()))
  3963. xml.append("<Cluster selected=\"1\">").append(instance).append("</Cluster>");
  3964. else
  3965. xml.append("<Cluster>").append(instance).append("</Cluster>");
  3966. }
  3967. }
  3968. xml.append("<TargetCluster>").append(cluster).append("</TargetCluster>");
  3969. xml.append("</WUJobList>");
  3970. xslt.append(getCFD()).append("./smc_xslt/jobs_search.xslt");
  3971. response->addHeader("Expires", "0");
  3972. }
  3973. }
  3974. if (xslt.length() && xml.length())
  3975. {
  3976. StringBuffer html;
  3977. xsltTransform(xml.str(), xslt.str(), NULL, html);
  3978. response->setContent(html.str());
  3979. response->setContentType(HTTP_TYPE_TEXT_HTML_UTF8);
  3980. response->send();
  3981. return 0;
  3982. }
  3983. }
  3984. catch(IException* e)
  3985. {
  3986. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3987. }
  3988. return onGetNotFound(context, request, response, service);
  3989. }
  3990. bool isDeploymentTypeCompressed(const char *type)
  3991. {
  3992. if (type && *type)
  3993. return (0==strncmp(type, "compressed_", strlen("compressed_")));
  3994. return false;
  3995. }
  3996. const char *skipCompressedTypeQualifier(const char *type)
  3997. {
  3998. if (isDeploymentTypeCompressed(type))
  3999. type += strlen("compressed_");
  4000. return type;
  4001. }
  4002. void deployEclOrArchive(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  4003. {
  4004. NewWsWorkunit wu(context);
  4005. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  4006. wu->setAction(WUActionCompile);
  4007. StringBuffer name(req.getName());
  4008. if (!name.trim().length() && notEmpty(req.getFileName()))
  4009. splitFilename(req.getFileName(), NULL, NULL, &name, NULL);
  4010. if (name.length())
  4011. wu->setJobName(name.str());
  4012. if (req.getObject().length())
  4013. {
  4014. MemoryBuffer mb;
  4015. const MemoryBuffer *uncompressed = &req.getObject();
  4016. if (isDeploymentTypeCompressed(req.getObjType()))
  4017. {
  4018. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  4019. uncompressed = &mb;
  4020. }
  4021. StringBuffer text(uncompressed->length(), uncompressed->toByteArray());
  4022. wu.setQueryText(text.str());
  4023. }
  4024. if (req.getQueryMainDefinition())
  4025. wu.setQueryMain(req.getQueryMainDefinition());
  4026. if (req.getSnapshot())
  4027. wu->setSnapshot(req.getSnapshot());
  4028. if (!req.getResultLimit_isNull())
  4029. wu->setResultLimit(req.getResultLimit());
  4030. wu->commit();
  4031. wu.clear();
  4032. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), NULL, 0, true, false, false, NULL, NULL, &req.getDebugValues());
  4033. waitForWorkUnitToCompile(wuid.str(), req.getWait());
  4034. WsWuInfo winfo(context, wuid.str());
  4035. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  4036. winfo.getExceptions(resp.updateWorkunit(), WUINFO_All);
  4037. name.clear();
  4038. if (notEmpty(resp.updateWorkunit().getJobname()))
  4039. origValueChanged(req.getName(), resp.updateWorkunit().getJobname(), name, false);
  4040. if (name.length()) //non generated user specified name, so override #Workunit('name')
  4041. {
  4042. WorkunitUpdate wx(&winfo.cw->lock());
  4043. wx->setJobName(name.str());
  4044. resp.updateWorkunit().setJobname(name.str());
  4045. }
  4046. PROGLOG("WUDeploy generates: %s", wuid.str());
  4047. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4048. }
  4049. StringBuffer &sharedObjectFileName(StringBuffer &filename, const char *name, const char *ext, unsigned copy)
  4050. {
  4051. filename.append((name && *name) ? name : "workunit");
  4052. if (copy)
  4053. filename.append('_').append(copy);
  4054. if (notEmpty(ext))
  4055. filename.append(ext);
  4056. return filename;
  4057. }
  4058. inline StringBuffer &buildFullDllPath(StringBuffer &dllpath, StringBuffer &dllname, const char *dir, const char *name, const char *ext, unsigned copy)
  4059. {
  4060. return addPathSepChar(dllpath.set(dir)).append(sharedObjectFileName(dllname, name, ext, copy));
  4061. }
  4062. void writeTempSharedObject(const MemoryBuffer &obj, const char *dir, StringBuffer &filename)
  4063. {
  4064. OwnedIFileIO io = createUniqueFile(dir, "query_copy_dll_", NULL, filename);
  4065. io->write(0, obj.length(), obj.toByteArray());
  4066. }
  4067. void writeSharedObject(const char *srcpath, const MemoryBuffer &obj, const char *dir, StringBuffer &dllpath, StringBuffer &dllname)
  4068. {
  4069. StringBuffer name, ext;
  4070. if (srcpath && *srcpath)
  4071. splitFilename(srcpath, NULL, NULL, &name, &ext);
  4072. unsigned copy=0;
  4073. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), copy);
  4074. unsigned crc=0;
  4075. StringBuffer tempDllName;
  4076. const unsigned attempts = 3; // max attempts
  4077. for (unsigned i=0; i<attempts; i++)
  4078. {
  4079. while (checkFileExists(dllpath.str()))
  4080. {
  4081. if (crc==0)
  4082. crc = crc32(obj.toByteArray(), obj.length(), 0);
  4083. if (crc == crc_file(dllpath.str()))
  4084. {
  4085. DBGLOG("Workunit dll already exists: %s", dllpath.str());
  4086. if (tempDllName.length())
  4087. removeFileTraceIfFail(tempDllName);
  4088. return;
  4089. }
  4090. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), ++copy);
  4091. }
  4092. if (!tempDllName.length())
  4093. writeTempSharedObject(obj, dir, tempDllName);
  4094. try
  4095. {
  4096. renameFile(dllpath, tempDllName, false);
  4097. return;
  4098. }
  4099. catch (IException *e)
  4100. {
  4101. EXCLOG(e, "writeSharedObject"); //pretty small window for another copy of this dll to sneak by
  4102. e->Release();
  4103. }
  4104. }
  4105. throw MakeStringException(ECLWATCH_CANNOT_COPY_DLL, "Failed copying shared object %s", srcpath);
  4106. }
  4107. void deploySharedObject(IEspContext &context, StringBuffer &wuid, const char *filename, const char *cluster, const char *name, const MemoryBuffer &obj, const char *dir, const char *xml)
  4108. {
  4109. StringBuffer dllpath, dllname;
  4110. StringBuffer srcname(filename);
  4111. unsigned crc = 0;
  4112. Owned<IPropertyTree> srcxml;
  4113. if (xml && *xml)
  4114. {
  4115. srcxml.setown(createPTreeFromXMLString(xml));
  4116. if (srcxml && wuid.length())
  4117. {
  4118. crc = srcxml->getPropInt("Query[1]/Associated[1]/File[@type='dll'][1]/@crc", 0);
  4119. if (crc)
  4120. {
  4121. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4122. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  4123. if (cw)
  4124. {
  4125. //is this a previous copy of same query, or a WUID collision?
  4126. if (cw->getHash() == (unsigned) srcxml->getPropInt64("@hash", 0))
  4127. {
  4128. Owned<IConstWUQuery> query = cw->getQuery();
  4129. if (query && crc == query->getQueryDllCrc())
  4130. return;
  4131. }
  4132. }
  4133. }
  4134. }
  4135. }
  4136. if (!srcname.length())
  4137. srcname.append(name).append(SharedObjectExtension);
  4138. writeSharedObject(srcname.str(), obj, dir, dllpath, dllname);
  4139. NewWsWorkunit wu(context, wuid); //duplicate wuid made unique
  4140. wuid.set(wu->queryWuid());
  4141. wu->setClusterName(cluster);
  4142. wu->commit();
  4143. StringBuffer dllXML;
  4144. if (getWorkunitXMLFromFile(dllpath.str(), dllXML))
  4145. {
  4146. Owned<ILocalWorkUnit> embeddedWU = createLocalWorkUnit(dllXML.str());
  4147. queryExtendedWU(wu)->copyWorkUnit(embeddedWU, true, true);
  4148. }
  4149. wu.associateDll(dllpath.str(), dllname.str());
  4150. if (name && *name)
  4151. wu->setJobName(name);
  4152. //clean slate, copy only select items from processed workunit xml
  4153. if (srcxml)
  4154. {
  4155. if (srcxml->hasProp("@jobName"))
  4156. wu->setJobName(srcxml->queryProp("@jobName"));
  4157. if (srcxml->hasProp("@token"))
  4158. wu->setSecurityToken(srcxml->queryProp("@token"));
  4159. if (srcxml->hasProp("Query/Text"))
  4160. wu.setQueryText(srcxml->queryProp("Query/Text"));
  4161. }
  4162. wu->setState(WUStateCompiled);
  4163. wu->commit();
  4164. wu.clear();
  4165. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4166. }
  4167. void CWsWorkunitsEx::deploySharedObjectReq(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp, const char *dir, const char *xml)
  4168. {
  4169. if (isEmpty(req.getFileName()))
  4170. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File name required when deploying a shared object.");
  4171. const char *cluster = req.getCluster();
  4172. if (isEmpty(cluster))
  4173. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name required when deploying a shared object.");
  4174. const MemoryBuffer *uncompressed = &req.getObject();
  4175. MemoryBuffer mb;
  4176. if (isDeploymentTypeCompressed(req.getObjType()))
  4177. {
  4178. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  4179. uncompressed = &mb;
  4180. }
  4181. StringBuffer wuid;
  4182. deploySharedObject(context, wuid, req.getFileName(), cluster, req.getName(), *uncompressed, dir, xml);
  4183. WsWuInfo winfo(context, wuid.str());
  4184. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  4185. PROGLOG("WUDeploy generates: %s", wuid.str());
  4186. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4187. }
  4188. bool CWsWorkunitsEx::onWUDeployWorkunit(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  4189. {
  4190. const char *type = skipCompressedTypeQualifier(req.getObjType());
  4191. try
  4192. {
  4193. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  4194. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  4195. if (notEmpty(req.getCluster()) && !isValidCluster(req.getCluster()))
  4196. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", req.getCluster());
  4197. if (!type || !*type)
  4198. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit unspecified object type.");
  4199. if (strieq(type, "archive")|| strieq(type, "ecl_text"))
  4200. deployEclOrArchive(context, req, resp);
  4201. else if (strieq(type, "shared_object"))
  4202. deploySharedObjectReq(context, req, resp, queryDirectory.str());
  4203. else
  4204. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit '%s' unknown object type.", type);
  4205. }
  4206. catch(IException* e)
  4207. {
  4208. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4209. }
  4210. return true;
  4211. }
  4212. void CWsWorkunitsEx::createZAPFile(const char* fileName, size32_t len, const void* data)
  4213. {
  4214. if (!fileName || !*fileName)
  4215. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"File name not specified.");
  4216. Owned<IFile> wuInfoIFile = createIFile(fileName);
  4217. Owned<IFileIO> wuInfoIO = wuInfoIFile->open(IFOcreate);
  4218. if (wuInfoIO)
  4219. wuInfoIO->write(0, len, data);
  4220. }
  4221. void CWsWorkunitsEx::cleanZAPFolder(IFile* zipDir, bool removeFolder)
  4222. {
  4223. if (!zipDir)
  4224. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Invalid file interface for the zip folder.");
  4225. Owned<IDirectoryIterator> iter = zipDir->directoryFiles(NULL,false,false);
  4226. ForEach(*iter)
  4227. {
  4228. OwnedIFile thisFile = createIFile(iter->query().queryFilename());
  4229. if (thisFile->isFile() == foundYes)
  4230. thisFile->remove();
  4231. }
  4232. if (removeFolder)
  4233. zipDir->remove();
  4234. }
  4235. void CWsWorkunitsEx::addProcessLogfile(Owned<IConstWorkUnit>& cwu, WsWuInfo& winfo, const char* process, const char* path)
  4236. {
  4237. Owned<IPropertyTreeIterator> procs = cwu->getProcesses(process, NULL);
  4238. ForEach (*procs)
  4239. {
  4240. StringBuffer logSpec;
  4241. IPropertyTree& proc = procs->query();
  4242. proc.getProp("@log",logSpec);
  4243. if (!logSpec.length())
  4244. continue;
  4245. const char* processName = proc.queryName();
  4246. if (isEmpty(processName))
  4247. continue;
  4248. StringBuffer pid;
  4249. pid.appendf("%d",proc.getPropInt("@pid"));
  4250. MemoryBuffer mb;
  4251. try
  4252. {
  4253. if (strieq(process, "EclAgent"))
  4254. winfo.getWorkunitEclAgentLog(logSpec.str(), pid.str(), mb);
  4255. else if (strieq(process, "Thor"))
  4256. winfo.getWorkunitThorLog(logSpec.str(), mb);
  4257. }
  4258. catch(IException *e)
  4259. {
  4260. StringBuffer s;
  4261. e->errorMessage(s);
  4262. DBGLOG("Error accessing Process Log file %s: %s", logSpec.str(), s.str());
  4263. mb.append(s.str());
  4264. e->Release();
  4265. }
  4266. if (!mb.length())
  4267. continue;
  4268. const char * logName = logSpec.str();
  4269. for (const char * p=logSpec; *p; p++)
  4270. {
  4271. if (*p == '\\' || *p == '/')
  4272. logName = p+1;
  4273. }
  4274. VStringBuffer fileName("%s%c%s_%s", path, PATHSEPCHAR, processName, logName);
  4275. createZAPFile(fileName.str(), mb.length(), mb.bufferBase());
  4276. }
  4277. }
  4278. void CWsWorkunitsEx::addThorSlaveLogfile(Owned<IConstWorkUnit>& cwu, WsWuInfo& winfo, const char* path)
  4279. {
  4280. if (cwu->getWuidVersion() <= 0)
  4281. return;
  4282. StringAttr clusterName(cwu->queryClusterName());
  4283. if (clusterName.isEmpty()) //Cluster name may not be set yet
  4284. return;
  4285. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  4286. if (!clusterInfo)
  4287. {
  4288. WARNLOG("Cannot find TargetClusterInfo for workunit %s", cwu->queryWuid());
  4289. return;
  4290. }
  4291. unsigned numberOfSlaveLogs = clusterInfo->getNumberOfSlaveLogs();
  4292. BoolHash uniqueProcesses;
  4293. Owned<IStringIterator> thorInstances = cwu->getProcesses("Thor");
  4294. ForEach (*thorInstances)
  4295. {
  4296. SCMStringBuffer processName;
  4297. thorInstances->str(processName);
  4298. if (processName.length() == 0)
  4299. continue;
  4300. bool* found = uniqueProcesses.getValue(processName.str());
  4301. if (found && *found)
  4302. continue;
  4303. uniqueProcesses.setValue(processName.str(), true);
  4304. StringBuffer groupName, logDir;
  4305. getClusterThorGroupName(groupName, processName.str());
  4306. if (groupName.isEmpty())
  4307. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed to get Thor Group Name for %s", processName.str());
  4308. getConfigurationDirectory(directories, "log", "thor", processName.str(), logDir);
  4309. Owned<IStringIterator> thorLogs = cwu->getLogs("Thor", processName.str());
  4310. ForEach (*thorLogs)
  4311. {
  4312. SCMStringBuffer logName;
  4313. thorLogs->str(logName);
  4314. if (logName.length() == 0)
  4315. continue;
  4316. const char* pStr = logName.str();
  4317. const char* ppStr = strstr(pStr, "/thormaster.");
  4318. if (!ppStr)
  4319. {
  4320. WARNLOG("Invalid thorlog entry in workunit xml: %s", logName.str());
  4321. continue;
  4322. }
  4323. ppStr += 12;
  4324. StringBuffer logDate = ppStr;
  4325. logDate.setLength(10);
  4326. for (unsigned i = 0; i < numberOfSlaveLogs; i++)
  4327. {
  4328. MemoryBuffer mb;
  4329. winfo.getWorkunitThorSlaveLog(groupName.str(), NULL, logDate.str(), logDir.str(), i+1, mb, false);
  4330. if (!mb.length())
  4331. continue;
  4332. VStringBuffer fileName("%s%c%s_thorslave.%d.%s.log", path, PATHSEPCHAR, processName.str(), i+1, logDate.str());
  4333. createZAPFile(fileName.str(), mb.length(), mb.bufferBase());
  4334. }
  4335. }
  4336. }
  4337. }
  4338. void CWsWorkunitsEx::createZAPWUInfoFile(IEspWUCreateZAPInfoRequest &req, Owned<IConstWorkUnit>& cwu, const char* pathNameStr)
  4339. {
  4340. StringBuffer sb;
  4341. sb.append("Workunit: ").append(cwu->queryWuid()).append("\r\n");
  4342. sb.append("User: ").append(cwu->queryUser()).append("\r\n");
  4343. sb.append("Build Version:").append(getBuildVersion()).append("\r\n");
  4344. sb.append("Cluster: ").append(cwu->queryClusterName()).append("\r\n");
  4345. if (req.getESPIPAddress())
  4346. sb.append("ESP: ").append(req.getESPIPAddress()).append("\r\n");
  4347. else
  4348. {
  4349. StringBuffer EspIP;
  4350. IpAddress ipaddr = queryHostIP();
  4351. ipaddr.getIpText(EspIP);
  4352. sb.append("ESP: ").append(EspIP.str()).append("\r\n");
  4353. }
  4354. if (req.getThorIPAddress())
  4355. sb.append("Thor: ").append(req.getThorIPAddress()).append("\r\n");
  4356. //Exceptions/Warnings/Info
  4357. Owned<IConstWUExceptionIterator> exceptions = &cwu->getExceptions();
  4358. StringBuffer info, warn, err, alert;
  4359. ForEach(*exceptions)
  4360. {
  4361. SCMStringBuffer temp;
  4362. switch (exceptions->query().getSeverity())
  4363. {
  4364. case SeverityInformation:
  4365. info.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4366. break;
  4367. case SeverityWarning:
  4368. warn.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4369. break;
  4370. case SeverityError:
  4371. err.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4372. break;
  4373. case SeverityAlert:
  4374. alert.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4375. break;
  4376. }
  4377. }
  4378. if (err.length())
  4379. sb.append("Exceptions: ").append("\r\n").append(err);
  4380. if (warn.length())
  4381. sb.append("Warnings: ").append("\r\n").append(warn);
  4382. if (info.length())
  4383. sb.append("Information: ").append("\r\n").append(info);
  4384. if (alert.length())
  4385. sb.append("Alert: ").append("\r\n").append(alert);
  4386. //User provided Information
  4387. sb.append("Problem: ").append(req.getProblemDescription()).append("\r\n\r\n");
  4388. sb.append("What Changed: ").append(req.getWhatChanged()).append("\r\n\r\n");
  4389. sb.append("Timing: ").append(req.getWhereSlow()).append("\r\n\r\n");
  4390. VStringBuffer fileName("%s.txt", pathNameStr);
  4391. createZAPFile(fileName.str(), sb.length(), sb.str());
  4392. }
  4393. void CWsWorkunitsEx::createZAPWUXMLFile(WsWuInfo &winfo, const char* pathNameStr)
  4394. {
  4395. MemoryBuffer mb;
  4396. winfo.getWorkunitXml(NULL, mb);
  4397. VStringBuffer fileName("%s.xml", pathNameStr);
  4398. createZAPFile(fileName.str(), mb.length(), mb.bufferBase());
  4399. }
  4400. void CWsWorkunitsEx::createZAPECLQueryArchiveFiles(Owned<IConstWorkUnit>& cwu, const char* pathNameStr)
  4401. {
  4402. Owned<IConstWUQuery> query = cwu->getQuery();
  4403. if(!query)
  4404. return;
  4405. //Add archive if present
  4406. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  4407. ForEach(*iter)
  4408. {
  4409. IConstWUAssociatedFile & cur = iter->query();
  4410. SCMStringBuffer ssb, ip;
  4411. cur.getDescription(ssb);
  4412. if (!strieq(ssb.str(), "archive"))
  4413. continue;
  4414. cur.getName(ssb);
  4415. cur.getIp(ip);
  4416. if (!ssb.length() || !ip.length())
  4417. continue;
  4418. StringBuffer fileName, archiveContents;
  4419. try
  4420. {
  4421. SocketEndpoint ep(ip.str());
  4422. RemoteFilename rfn;
  4423. rfn.setRemotePath(ssb.str());
  4424. rfn.setIp(ep);
  4425. Owned<IFile> rFile = createIFile(rfn);
  4426. if (!rFile)
  4427. {
  4428. DBGLOG("Cannot open %s on %s", ssb.str(), ip.str());
  4429. continue;
  4430. }
  4431. archiveContents.loadFile(rFile);
  4432. }
  4433. catch (IException *e)
  4434. {
  4435. StringBuffer s;
  4436. e->errorMessage(s);
  4437. DBGLOG("Error accessing archive file %s: %s", ssb.str(), s.str());
  4438. archiveContents.insert(0, "Error accessing archive file ").appendf("%s: %s\r\n\r\n", ssb.str(), s.str());
  4439. e->Release();
  4440. }
  4441. fileName.setf("%s.archive", pathNameStr);
  4442. createZAPFile(fileName.str(), archiveContents.length(), archiveContents.str());
  4443. break;
  4444. }
  4445. //Add Query
  4446. SCMStringBuffer temp;
  4447. query->getQueryText(temp);
  4448. if (temp.length())
  4449. {
  4450. VStringBuffer fileName("%s.ecl", pathNameStr);
  4451. createZAPFile(fileName.str(), temp.length(), temp.str());
  4452. }
  4453. }
  4454. void CWsWorkunitsEx::createZAPWUGraphProgressFile(const char* wuid, const char* pathNameStr)
  4455. {
  4456. Owned<IPropertyTree> graphProgress = getWUGraphProgress(wuid, true);
  4457. if (graphProgress)
  4458. {
  4459. StringBuffer graphProgressXML;
  4460. toXML(graphProgress, graphProgressXML, 1, XML_Format);
  4461. VStringBuffer fileName("%s.graphprogress", pathNameStr);
  4462. createZAPFile(fileName.str(), graphProgressXML.length(), graphProgressXML.str());
  4463. }
  4464. }
  4465. bool CWsWorkunitsEx::onWUCreateZAPInfo(IEspContext &context, IEspWUCreateZAPInfoRequest &req, IEspWUCreateZAPInfoResponse &resp)
  4466. {
  4467. try
  4468. {
  4469. StringBuffer wuid = req.getWuid();
  4470. WsWuHelpers::checkAndTrimWorkunit("WUCreateZAPInfo", wuid);
  4471. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4472. Owned<IConstWorkUnit> cwu = factory->openWorkUnit(wuid.str());
  4473. if(!cwu.get())
  4474. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Cannot open workunit %s.", req.getWuid());
  4475. ensureWsWorkunitAccess(context, *cwu, SecAccess_Read);
  4476. PROGLOG("WUCreateZAPInfo: %s", wuid.str());
  4477. StringBuffer userName, nameStr, fileName;
  4478. StringBuffer zipFileName, zipFileNameWithPath, zipCommand, folderToZIP;
  4479. if (context.queryUser())
  4480. userName.append(context.queryUser()->getName());
  4481. nameStr.append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str());
  4482. //create a folder for WU ZAP files
  4483. folderToZIP.append(zipFolder).append(nameStr.str());
  4484. Owned<IFile> zipDir = createIFile(folderToZIP.str());
  4485. if (!zipDir->exists())
  4486. zipDir->createDirectory();
  4487. else
  4488. cleanZAPFolder(zipDir, false);
  4489. //create WU ZAP files
  4490. VStringBuffer pathNameStr("%s/%s", folderToZIP.str(), nameStr.str());
  4491. createZAPWUInfoFile(req, cwu, pathNameStr.str());
  4492. createZAPECLQueryArchiveFiles(cwu, pathNameStr.str());
  4493. WsWuInfo winfo(context, cwu);
  4494. createZAPWUXMLFile(winfo, pathNameStr.str());
  4495. createZAPWUGraphProgressFile(req.getWuid(), pathNameStr.str());
  4496. addProcessLogfile(cwu, winfo, "EclAgent", folderToZIP.str());
  4497. addProcessLogfile(cwu, winfo, "Thor", folderToZIP.str());
  4498. if (req.getIncludeThorSlaveLog())
  4499. addThorSlaveLogfile(cwu, winfo, folderToZIP.str());
  4500. //Write out to ZIP file
  4501. const char* zipFName = req.getZAPFileName();
  4502. if (!zipFName || !*zipFName)
  4503. zipFileName.append(nameStr.str()).append(".zip");
  4504. else
  4505. {
  4506. zipFileName.set(zipFName);
  4507. const char* ext = pathExtension(zipFName);
  4508. if (!ext || !strieq(ext, ".zip"))
  4509. zipFileName.append(".zip");
  4510. }
  4511. zipFileNameWithPath.append(zipFolder).append(zipFileName.str());
  4512. pathNameStr.set(folderToZIP.str()).append("/*");
  4513. const char* password;
  4514. double version = context.getClientVersion();
  4515. if (version >= 1.70)
  4516. password = req.getZAPPassword();
  4517. else
  4518. password = req.getPassword();
  4519. if (password && *password)
  4520. zipCommand.appendf("zip -j --password %s %s %s", password, zipFileNameWithPath.str(), pathNameStr.str());
  4521. else
  4522. zipCommand.appendf("zip -j %s %s", zipFileNameWithPath.str(), pathNameStr.str());
  4523. int zipRet = system(zipCommand.str());
  4524. //Remove the temporary files and the folder
  4525. cleanZAPFolder(zipDir, true);
  4526. if (zipRet != 0)
  4527. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Failed to execute system command 'zip'. Please make sure that zip utility is installed.");
  4528. //Download ZIP file to user
  4529. Owned<IFile> f = createIFile(zipFileNameWithPath.str());
  4530. Owned<IFileIO> io = f->open(IFOread);
  4531. MemoryBuffer mb;
  4532. void * data = mb.reserve((unsigned)io->size());
  4533. size32_t read = io->read(0, (unsigned)io->size(), data);
  4534. mb.setLength(read);
  4535. resp.setThefile(mb);
  4536. resp.setThefile_mimetype(HTTP_TYPE_OCTET_STREAM);
  4537. resp.setZAPFileName(zipFileName.str());
  4538. StringBuffer headerStr("attachment;filename=");
  4539. headerStr.append(zipFileName.str());
  4540. context.addCustomerHeader("Content-disposition", headerStr.str());
  4541. io->close();
  4542. f->remove();
  4543. }
  4544. catch(IException* e)
  4545. {
  4546. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4547. }
  4548. return true;
  4549. }
  4550. bool CWsWorkunitsEx::onWUGetZAPInfo(IEspContext &context, IEspWUGetZAPInfoRequest &req, IEspWUGetZAPInfoResponse &resp)
  4551. {
  4552. try
  4553. {
  4554. StringBuffer wuid = req.getWUID();
  4555. WsWuHelpers::checkAndTrimWorkunit("WUGetZAPInfo", wuid);
  4556. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4557. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  4558. if(!cw)
  4559. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  4560. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  4561. PROGLOG("WUGetZAPInfo: %s", wuid.str());
  4562. StringBuffer EspIP, ThorIP;
  4563. resp.setWUID(wuid.str());
  4564. resp.setBuildVersion(getBuildVersion());
  4565. IpAddress ipaddr = queryHostIP();
  4566. ipaddr.getIpText(EspIP);
  4567. resp.setESPIPAddress(EspIP.str());
  4568. //Get Archive
  4569. Owned<IConstWUQuery> query = cw->getQuery();
  4570. if(query)
  4571. {
  4572. SCMStringBuffer queryText;
  4573. query->getQueryText(queryText);
  4574. if (queryText.length() && isArchiveQuery(queryText.str()))
  4575. resp.setArchive(queryText.str());
  4576. }
  4577. //Get Thor IP
  4578. BoolHash uniqueProcesses;
  4579. Owned<IStringIterator> thorInstances = cw->getProcesses("Thor");
  4580. ForEach (*thorInstances)
  4581. {
  4582. SCMStringBuffer processName;
  4583. thorInstances->str(processName);
  4584. if (processName.length() < 1)
  4585. continue;
  4586. bool* found = uniqueProcesses.getValue(processName.str());
  4587. if (found && *found)
  4588. continue;
  4589. uniqueProcesses.setValue(processName.str(), true);
  4590. Owned<IStringIterator> thorLogs = cw->getLogs("Thor", processName.str());
  4591. ForEach (*thorLogs)
  4592. {
  4593. SCMStringBuffer logName;
  4594. thorLogs->str(logName);
  4595. if (!logName.length())
  4596. continue;
  4597. const char* thorIPPtr = NULL;
  4598. const char* ptr = logName.str();
  4599. while (ptr)
  4600. {
  4601. if (!thorIPPtr && (*ptr != '/'))
  4602. thorIPPtr = ptr;
  4603. else if (thorIPPtr && (*ptr == '/'))
  4604. break;
  4605. ptr++;
  4606. }
  4607. if (!thorIPPtr)
  4608. continue;
  4609. //Found a thor IP
  4610. if (ThorIP.length())
  4611. ThorIP.append(",");
  4612. if (!*ptr)
  4613. ThorIP.append(thorIPPtr);
  4614. else
  4615. ThorIP.append(ptr-thorIPPtr, thorIPPtr);
  4616. }
  4617. }
  4618. if (ThorIP.length())
  4619. resp.setThorIPAddress(ThorIP.str());
  4620. }
  4621. catch(IException* e)
  4622. {
  4623. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4624. }
  4625. return true;
  4626. }
  4627. bool CWsWorkunitsEx::onWUCheckFeatures(IEspContext &context, IEspWUCheckFeaturesRequest &req, IEspWUCheckFeaturesResponse &resp)
  4628. {
  4629. resp.setBuildVersionMajor(BUILD_VERSION_MAJOR);
  4630. resp.setBuildVersionMinor(BUILD_VERSION_MINOR);
  4631. resp.setBuildVersionPoint(BUILD_VERSION_POINT);
  4632. resp.setMaxRequestEntityLength(maxRequestEntityLength);
  4633. resp.updateDeployment().setUseCompression(true);
  4634. return true;
  4635. }
  4636. static const char * checkGetStatsNullInput(const char * s)
  4637. {
  4638. if (!s || !*s)
  4639. return nullptr;
  4640. return s;
  4641. }
  4642. static const char * checkGetStatsInput(const char * s)
  4643. {
  4644. if (!s || !*s)
  4645. return "*";
  4646. return s;
  4647. }
  4648. bool CWsWorkunitsEx::onWUGetStats(IEspContext &context, IEspWUGetStatsRequest &req, IEspWUGetStatsResponse &resp)
  4649. {
  4650. //This function is deprecated for 7.x and will be removed shortly afterwards.
  4651. //Anything that cannot be implemented with the scope iterator is implemented as a post filter
  4652. try
  4653. {
  4654. const char* creatorType = checkGetStatsNullInput(req.getCreatorType());
  4655. const char* creator = checkGetStatsNullInput(req.getCreator());
  4656. const char* scopeType = checkGetStatsNullInput(req.getScopeType());
  4657. const char* scope = checkGetStatsNullInput(req.getScope());
  4658. const char* kind = checkGetStatsNullInput(req.getKind());
  4659. const char* measure = req.getMeasure();
  4660. WuScopeFilter filter;
  4661. StatisticsFilter statsFilter(creatorType, creator, "*", "*", "*", "*");
  4662. filter.addOutputProperties(PTstatistics);
  4663. if (scopeType)
  4664. filter.addScopeType(scopeType);
  4665. if (scope)
  4666. filter.addScope(scope);
  4667. if (kind)
  4668. filter.addOutputStatistic(kind);
  4669. if (measure)
  4670. filter.setMeasure(measure);
  4671. if (!req.getMinScopeDepth_isNull() && !req.getMaxScopeDepth_isNull())
  4672. filter.setDepth(req.getMinScopeDepth(), req.getMaxScopeDepth());
  4673. else if (!req.getMinScopeDepth_isNull())
  4674. filter.setDepth(req.getMinScopeDepth(), req.getMinScopeDepth());
  4675. if (!req.getMinValue_isNull() || !req.getMaxValue_isNull())
  4676. {
  4677. unsigned __int64 lowValue = 0;
  4678. unsigned __int64 highValue = MaxStatisticValue;
  4679. if (!req.getMinValue_isNull())
  4680. lowValue = (unsigned __int64)req.getMinValue();
  4681. if (!req.getMaxValue_isNull())
  4682. highValue = (unsigned __int64)req.getMaxValue();
  4683. statsFilter.setValueRange(lowValue, highValue);
  4684. }
  4685. const char * textFilter = req.getFilter();
  4686. if (textFilter)
  4687. statsFilter.setFilter(textFilter);
  4688. filter.setIncludeNesting(0).finishedFilter();
  4689. bool createDescriptions = false;
  4690. if (!req.getCreateDescriptions_isNull())
  4691. createDescriptions = req.getCreateDescriptions();
  4692. StringBuffer wuid = req.getWUID();
  4693. PROGLOG("WUGetStats: %s", wuid.str());
  4694. IArrayOf<IEspWUStatisticItem> statistics;
  4695. if (strchr(wuid, '*'))
  4696. {
  4697. WUSortField filters[2];
  4698. MemoryBuffer filterbuf;
  4699. filters[0] = WUSFwildwuid;
  4700. filterbuf.append(wuid.str());
  4701. filters[1] = WUSFterm;
  4702. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4703. Owned<IConstWorkUnitIterator> iter = factory->getWorkUnitsSorted((WUSortField) (WUSFwuid), filters, filterbuf.bufferBase(), 0, INT_MAX, NULL, NULL);
  4704. ForEach(*iter)
  4705. {
  4706. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(iter->query().queryWuid());
  4707. if (workunit)
  4708. {
  4709. //No need to check for access since the list is already filtered
  4710. WsWuInfo winfo(context, workunit->queryWuid());
  4711. winfo.getStats(filter, statsFilter, createDescriptions, statistics);
  4712. }
  4713. }
  4714. }
  4715. else
  4716. {
  4717. WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
  4718. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4719. WsWuInfo winfo(context, wuid);
  4720. winfo.getStats(filter, statsFilter, createDescriptions, statistics);
  4721. }
  4722. resp.setStatistics(statistics);
  4723. resp.setWUID(wuid.str());
  4724. }
  4725. catch(IException* e)
  4726. {
  4727. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4728. }
  4729. return true;
  4730. }
  4731. IPropertyTree* CWsWorkunitsEx::getWorkunitArchive(IEspContext &context, WsWuInfo& winfo, const char* wuid, unsigned cacheMinutes)
  4732. {
  4733. Owned<WUArchiveCacheElement> wuArchive = wuArchiveCache->lookup(context, wuid, cacheMinutes);
  4734. if (wuArchive)
  4735. return wuArchive->archive.getLink();
  4736. Owned<IPropertyTree> archive = winfo.getWorkunitArchive();
  4737. if (!archive)
  4738. return NULL;
  4739. wuArchiveCache->add(wuid, archive.getLink());
  4740. return archive.getClear();
  4741. }
  4742. bool CWsWorkunitsEx::onWUListArchiveFiles(IEspContext &context, IEspWUListArchiveFilesRequest &req, IEspWUListArchiveFilesResponse &resp)
  4743. {
  4744. try
  4745. {
  4746. const char* wuid = req.getWUID();
  4747. if (isEmpty(wuid))
  4748. throw MakeStringException(ECLWATCH_NO_WUID_SPECIFIED, "No workunit defined.");
  4749. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4750. PROGLOG("WUListArchiveFiles: %s", wuid);
  4751. WsWuInfo winfo(context, wuid);
  4752. Owned<IPropertyTree> archive = getWorkunitArchive(context, winfo, wuid, WUARCHIVE_CACHE_MINITES);
  4753. if (!archive)
  4754. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No workunit archive found for %s.", wuid);
  4755. IArrayOf<IEspWUArchiveModule> modules;
  4756. IArrayOf<IEspWUArchiveFile> files;
  4757. winfo.listArchiveFiles(archive, "", modules, files);
  4758. if (modules.length())
  4759. resp.setArchiveModules(modules);
  4760. if (files.length())
  4761. resp.setFiles(files);
  4762. if (!modules.length() && !files.length())
  4763. resp.setMessage("Files not found");
  4764. }
  4765. catch(IException* e)
  4766. {
  4767. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4768. }
  4769. return true;
  4770. }
  4771. bool CWsWorkunitsEx::onWUGetArchiveFile(IEspContext &context, IEspWUGetArchiveFileRequest &req, IEspWUGetArchiveFileResponse &resp)
  4772. {
  4773. try
  4774. {
  4775. const char* wuid = req.getWUID();
  4776. const char* moduleName = req.getModuleName();
  4777. const char* attrName = req.getFileName();
  4778. if (isEmpty(wuid))
  4779. throw MakeStringException(ECLWATCH_NO_WUID_SPECIFIED, "No workunit defined.");
  4780. if (isEmpty(moduleName) && isEmpty(attrName))
  4781. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No file name defined.");
  4782. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4783. PROGLOG("WUGetArchiveFile: %s", wuid);
  4784. WsWuInfo winfo(context, wuid);
  4785. Owned<IPropertyTree> archive = getWorkunitArchive(context, winfo, wuid, WUARCHIVE_CACHE_MINITES);
  4786. if (!archive)
  4787. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No workunit archive found for %s.", wuid);
  4788. StringBuffer file;
  4789. winfo.getArchiveFile(archive, moduleName, attrName, req.getPath(), file);
  4790. if (file.length())
  4791. resp.setFile(file.str());
  4792. else
  4793. resp.setMessage("File not found");
  4794. }
  4795. catch(IException* e)
  4796. {
  4797. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4798. }
  4799. return true;
  4800. }