ws_workunitsService.cpp 208 KB

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