ws_workunitsService.cpp 209 KB

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