workunit.cpp 448 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806
  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 <string>
  14. #include <unordered_set>
  15. #include "jlib.hpp"
  16. #include "workunit.hpp"
  17. #include "jprop.hpp"
  18. #include "jmisc.hpp"
  19. #include "jexcept.hpp"
  20. #include "jiter.ipp"
  21. #include "jptree.hpp"
  22. #include "jtime.ipp"
  23. #include "jencrypt.hpp"
  24. #include "junicode.hpp"
  25. #include "jlzw.hpp"
  26. #include "jregexp.hpp"
  27. #include "eclrtl.hpp"
  28. #include "deftype.hpp"
  29. #include <time.h>
  30. #include "mpbase.hpp"
  31. #include "daclient.hpp"
  32. #include "dadfs.hpp"
  33. #include "dafdesc.hpp"
  34. #include "dasds.hpp"
  35. #include "danqs.hpp"
  36. #include "dautils.hpp"
  37. #include "dllserver.hpp"
  38. #include "thorplugin.hpp"
  39. #include "thorhelper.hpp"
  40. #include "workflow.hpp"
  41. #include "nbcd.hpp"
  42. #include "seclib.hpp"
  43. #include "wuerror.hpp"
  44. #include "wujobq.hpp"
  45. #ifndef _CONTAINERIZED
  46. #include "environment.hpp"
  47. #endif
  48. #include "daqueue.hpp"
  49. #include "workunit.ipp"
  50. #include "digisign.hpp"
  51. #include <list>
  52. #include <string>
  53. #include <algorithm>
  54. using namespace cryptohelper;
  55. static int workUnitTraceLevel = 1;
  56. static StringBuffer &getXPath(StringBuffer &wuRoot, const char *wuid)
  57. {
  58. // MORE - can fold in the date
  59. return wuRoot.append("/WorkUnits/").append(wuid);
  60. }
  61. //To be called by eclserver, but esp etc. won't know, so we need to store it.
  62. static StringBuffer & appendLibrarySuffix(StringBuffer & suffix)
  63. {
  64. #ifdef _WIN32
  65. suffix.append("W");
  66. #else
  67. suffix.append("L");
  68. #endif
  69. #ifdef __64BIT__
  70. suffix.append("64");
  71. #else
  72. suffix.append("32");
  73. #endif
  74. return suffix;
  75. }
  76. typedef MapStringTo<bool> UniqueScopes;
  77. static void wuAccessError(const char *username, const char *action, const char *wuscope, const char *wuid, bool excpt, bool log)
  78. {
  79. StringBuffer err;
  80. err.append("Workunit Access Denied - action: ").append(action).append(" user:").append(username ? username : "<Unknown>");
  81. if (wuid)
  82. err.append(" workunit:").append(wuid);
  83. if (wuscope)
  84. err.append(" scope:").append(wuscope);
  85. //MORE - we would need more information passed in from outside if we want to make the audit message format the same as from higher level ESP calls
  86. SYSLOG(AUDIT_TYPE_ACCESS_FAILURE, err.str());
  87. if (log)
  88. LOG(MCuserError, "%s", err.str());
  89. if (excpt)
  90. throw MakeStringException(WUERR_AccessError, "%s", err.str());
  91. }
  92. static bool checkWuScopeSecAccess(const char *wuscope, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  93. {
  94. if (!secmgr || !secuser)
  95. return true;
  96. bool ret = secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, wuscope)>=required;
  97. if (!ret && (log || excpt))
  98. wuAccessError(secuser->getName(), action, wuscope, NULL, excpt, log);
  99. return ret;
  100. }
  101. static bool checkWuScopeListSecAccess(const char *wuscope, ISecResourceList *scopes, int required, const char *action, bool excpt, bool log)
  102. {
  103. if (!scopes)
  104. return true;
  105. bool ret=true;
  106. if (wuscope)
  107. {
  108. Owned<ISecResource> res=scopes->getResource(wuscope);
  109. if (!res || res->getAccessFlags()<required)
  110. ret=false;
  111. }
  112. else
  113. {
  114. for (int seq=0; ret && seq<scopes->count(); seq++)
  115. {
  116. ISecResource *res=scopes->queryResource(seq);
  117. if (res && res->getAccessFlags()<required)
  118. return false;
  119. }
  120. }
  121. if (!ret && (log || excpt))
  122. wuAccessError(NULL, action, wuscope, NULL, excpt, log);
  123. return ret;
  124. }
  125. static bool checkWuSecAccess(IConstWorkUnit &cw, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  126. {
  127. if (!secmgr || !secuser)
  128. return true;
  129. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw.queryWuScope())>=required;
  130. if (!ret && (log || excpt))
  131. {
  132. wuAccessError(secuser->getName(), action, cw.queryWuScope(), cw.queryWuid(), excpt, log);
  133. }
  134. return ret;
  135. }
  136. static bool checkWuSecAccess(const char *wuid, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  137. {
  138. if (!secmgr || !secuser)
  139. return true;
  140. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  141. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  142. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw->queryWuScope())>=required;
  143. if (!ret && (log || excpt))
  144. {
  145. wuAccessError(secuser->getName(), action, cw->queryWuScope(), cw->queryWuid(), excpt, log);
  146. }
  147. return ret;
  148. }
  149. void doDescheduleWorkkunit(char const * wuid)
  150. {
  151. StringBuffer xpath;
  152. xpath.append("*/*/*/");
  153. ncnameEscape(wuid, xpath);
  154. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  155. if(!conn) return;
  156. Owned<IPropertyTree> root = conn->getRoot();
  157. bool more;
  158. do more = root->removeProp(xpath.str()); while(more);
  159. }
  160. //======================================================
  161. /*
  162. * Graph progress support
  163. */
  164. CWuGraphStats::CWuGraphStats(IPropertyTree *_progress, StatisticCreatorType _creatorType, const char * _creator, unsigned wfid, const char * _rootScope, unsigned _id)
  165. : progress(_progress), creatorType(_creatorType), creator(_creator), id(_id)
  166. {
  167. StatsScopeId graphScopeId;
  168. verifyex(graphScopeId.setScopeText(_rootScope));
  169. StatsScopeId rootScopeId(SSTworkflow,wfid);
  170. collector.setown(createStatisticsGatherer(_creatorType, _creator, rootScopeId));
  171. collector->beginScope(graphScopeId);
  172. }
  173. void CWuGraphStats::beforeDispose()
  174. {
  175. Owned<IStatisticCollection> stats = collector->getResult();
  176. MemoryBuffer compressed;
  177. {
  178. MemoryBuffer serialized;
  179. serializeStatisticCollection(serialized, stats);
  180. compressToBuffer(compressed, serialized.length(), serialized.toByteArray());
  181. }
  182. unsigned minActivity = 0;
  183. unsigned maxActivity = 0;
  184. stats->getMinMaxActivity(minActivity, maxActivity);
  185. StringBuffer tag;
  186. tag.append("sg").append(id);
  187. //Replace the particular subgraph statistics added by this creator
  188. IPropertyTree * subgraph = progress->setPropTree(tag);
  189. subgraph->setProp("@c", queryCreatorTypeName(creatorType));
  190. subgraph->setProp("@creator", creator);
  191. subgraph->setPropInt("@minActivity", minActivity);
  192. subgraph->setPropInt("@maxActivity", maxActivity);
  193. subgraph->setPropBin("Stats", compressed.length(), compressed.toByteArray());
  194. if (!progress->getPropBool("@stats", false))
  195. progress->setPropBool("@stats", true);
  196. }
  197. IStatisticGatherer & CWuGraphStats::queryStatsBuilder()
  198. {
  199. return *collector;
  200. }
  201. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  202. {
  203. public:
  204. IMPLEMENT_IINTERFACE;
  205. CConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress) : wuid(_wuid), graphName(_graphName), progress(_progress)
  206. {
  207. if (!progress)
  208. progress.setown(createPTree());
  209. formatVersion = progress->getPropInt("@format", PROGRESS_FORMAT_V);
  210. }
  211. virtual IPropertyTree * getProgressTree()
  212. {
  213. if (progress->getPropBool("@stats"))
  214. return createProcessTreeFromStats(); // Should we cache that?
  215. return LINK(progress);
  216. }
  217. virtual unsigned queryFormatVersion()
  218. {
  219. return formatVersion;
  220. }
  221. protected:
  222. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  223. {
  224. formatVersion = PROGRESS_FORMAT_V;
  225. }
  226. static void expandStats(IPropertyTree * target, IStatisticCollection & collection)
  227. {
  228. StringBuffer formattedValue;
  229. unsigned numStats = collection.getNumStatistics();
  230. for (unsigned i=0; i < numStats; i++)
  231. {
  232. StatisticKind kind;
  233. unsigned __int64 value;
  234. collection.getStatistic(kind, value, i);
  235. formatStatistic(formattedValue.clear(), value, kind);
  236. target->setProp(queryTreeTag(kind), formattedValue);
  237. }
  238. }
  239. void expandProcessTreeFromStats(IPropertyTree * rootTarget, IPropertyTree * target, IStatisticCollection * collection)
  240. {
  241. expandStats(target, *collection);
  242. StringBuffer scopeName;
  243. Owned<IStatisticCollectionIterator> activityIter = &collection->getScopes(NULL, false);
  244. ForEach(*activityIter)
  245. {
  246. IStatisticCollection & cur = activityIter->query();
  247. cur.getScope(scopeName.clear());
  248. const char * id = scopeName.str();
  249. const char * tag;
  250. IPropertyTree * curTarget = target;
  251. switch (cur.queryScopeType())
  252. {
  253. case SSTedge:
  254. tag = "edge";
  255. id += strlen(EdgeScopePrefix);
  256. break;
  257. case SSTactivity:
  258. tag = "node";
  259. id += strlen(ActivityScopePrefix);
  260. break;
  261. case SSTsubgraph:
  262. //All subgraphs are added a root elements in the progress tree
  263. curTarget = rootTarget;
  264. tag = "node";
  265. id += strlen(SubGraphScopePrefix);
  266. break;
  267. case SSTchildgraph:
  268. case SSTworkflow:
  269. case SSTgraph:
  270. // SSTworkflow and SSTgraph may be safely ignored. They are not required to produce the statistics.
  271. continue;
  272. case SSTfunction:
  273. //MORE:Should function scopes be included in the graph scope somehow, and if so how?
  274. continue;
  275. default:
  276. throwUnexpected();
  277. }
  278. IPropertyTree * next = curTarget->addPropTree(tag);
  279. next->setProp("@id", id);
  280. expandProcessTreeFromStats(rootTarget, next, &cur);
  281. }
  282. }
  283. IPropertyTree * createProcessTreeFromStats()
  284. {
  285. MemoryBuffer compressed;
  286. MemoryBuffer serialized;
  287. Owned<IPropertyTree> progressTree = createPTree();
  288. Owned<IPropertyTreeIterator> iter = progress->getElements("sg*");
  289. ForEach(*iter)
  290. {
  291. IPropertyTree & curSubGraph = iter->query();
  292. curSubGraph.getPropBin("Stats", compressed.clear());
  293. //Protect against updates that delete the stats while we are iterating
  294. if (compressed.length())
  295. {
  296. decompressToBuffer(serialized.clear(), compressed);
  297. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  298. expandProcessTreeFromStats(progressTree, progressTree, collection);
  299. }
  300. }
  301. return progressTree.getClear();
  302. }
  303. protected:
  304. Linked<IPropertyTree> progress;
  305. StringAttr wuid, graphName;
  306. unsigned formatVersion;
  307. };
  308. extern WORKUNIT_API IConstWUGraphProgress *createConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress)
  309. {
  310. return new CConstGraphProgress(_wuid, _graphName, _progress);
  311. }
  312. //--------------------------------------------------------------------------------------------------------------------
  313. /*
  314. * Create a user friendly description a scope/stats combination. Only currently used for elapsed time for root subgraphs
  315. */
  316. static void createDefaultDescription(StringBuffer & description, StatisticKind kind, StatisticScopeType scopeType, const char * scope)
  317. {
  318. switch (kind)
  319. {
  320. case StTimeElapsed:
  321. {
  322. if (scopeType != SSTsubgraph)
  323. break;
  324. //Create a default description for a root subgraph
  325. const char * colon = strchr(scope, ':');
  326. if (!colon)
  327. break;
  328. const char * subgraph = colon+1;
  329. //Check for nested subgraph
  330. if (strchr(subgraph, ':'))
  331. break;
  332. assertex(strncmp(subgraph, SubGraphScopePrefix, strlen(SubGraphScopePrefix)) == 0);
  333. StringAttr graphname;
  334. graphname.set(scope, colon - scope);
  335. unsigned subId = atoi(subgraph + strlen(SubGraphScopePrefix));
  336. formatGraphTimerLabel(description, graphname, 0, subId);
  337. return;
  338. }
  339. }
  340. describeScope(description, scope);
  341. }
  342. /* Represents a single statistic */
  343. class ExtractedStatistic : public CInterfaceOf<IConstWUStatistic>
  344. {
  345. public:
  346. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const
  347. {
  348. if (!description && createDefault)
  349. {
  350. StringBuffer desc;
  351. createDefaultDescription(desc, kind, scopeType, scope);
  352. str.set(desc);
  353. return str;
  354. }
  355. str.set(description);
  356. return str;
  357. }
  358. virtual IStringVal & getCreator(IStringVal & str) const
  359. {
  360. str.set(creator);
  361. return str;
  362. }
  363. virtual const char * queryScope() const
  364. {
  365. return scope ? scope : "";
  366. }
  367. virtual IStringVal & getFormattedValue(IStringVal & str) const
  368. {
  369. StringBuffer formatted;
  370. formatStatistic(formatted, value, measure);
  371. str.set(formatted);
  372. return str;
  373. }
  374. virtual StatisticMeasure getMeasure() const
  375. {
  376. return measure;
  377. }
  378. virtual StatisticKind getKind() const
  379. {
  380. return kind;
  381. }
  382. virtual StatisticCreatorType getCreatorType() const
  383. {
  384. return creatorType;
  385. }
  386. virtual StatisticScopeType getScopeType() const
  387. {
  388. return scopeType;
  389. }
  390. virtual unsigned __int64 getValue() const
  391. {
  392. return value;
  393. }
  394. virtual unsigned __int64 getCount() const
  395. {
  396. return count;
  397. }
  398. virtual unsigned __int64 getMax() const
  399. {
  400. return max;
  401. }
  402. virtual unsigned __int64 getTimestamp() const
  403. {
  404. return timeStamp;
  405. }
  406. public:
  407. StringBuffer creator;
  408. StringBuffer description;
  409. StringBuffer scope;
  410. StatisticMeasure measure;
  411. StatisticKind kind;
  412. StatisticCreatorType creatorType;
  413. StatisticScopeType scopeType;
  414. unsigned __int64 value;
  415. unsigned __int64 count;
  416. unsigned __int64 max;
  417. unsigned __int64 timeStamp;
  418. };
  419. //---------------------------------------------------------------------------------------------------------------------
  420. /*
  421. * The following compare functions are used to ensure that comparison are consistent with
  422. * compareScopeName() in jstats. This ensures that the scope iterators from different sources
  423. * are processed in a consistent order
  424. */
  425. static int compareGraphNode(IInterface * const *ll, IInterface * const *rr)
  426. {
  427. IPropertyTree *l = (IPropertyTree *) *ll;
  428. IPropertyTree *r = (IPropertyTree *) *rr;
  429. unsigned lwfid = l->getPropInt("@wfid");
  430. unsigned rwfid = r->getPropInt("@wfid");
  431. if (lwfid != rwfid)
  432. return lwfid > rwfid ? +1 : -1;
  433. const char * lname = l->queryName();
  434. const char * rname = r->queryName();
  435. return compareScopeName(lname, rname);
  436. }
  437. static int compareSubGraphStatsNode(IInterface * const *ll, IInterface * const *rr)
  438. {
  439. IPropertyTree *l = (IPropertyTree *) *ll;
  440. IPropertyTree *r = (IPropertyTree *) *rr;
  441. return compareScopeName(l->queryName(), r->queryName());
  442. }
  443. static int compareSubGraphNode(IInterface * const *ll, IInterface * const *rr)
  444. {
  445. IPropertyTree *l = (IPropertyTree *) *ll;
  446. IPropertyTree *r = (IPropertyTree *) *rr;
  447. return l->getPropInt("@id") - r->getPropInt("@id");
  448. }
  449. static int compareActivityNode(IInterface * const *ll, IInterface * const *rr)
  450. {
  451. IPropertyTree *l = (IPropertyTree *) *ll;
  452. IPropertyTree *r = (IPropertyTree *) *rr;
  453. return l->getPropInt("@id") - r->getPropInt("@id");
  454. }
  455. static int compareEdgeNode(IInterface * const *ll, IInterface * const *rr)
  456. {
  457. IPropertyTree *l = (IPropertyTree *) *ll;
  458. IPropertyTree *r = (IPropertyTree *) *rr;
  459. //MORE: Edge needs more work
  460. const char * leftId = l->queryProp("@id");
  461. const char * rightId = r->queryProp("@id");
  462. unsigned leftAc = atoi(leftId);
  463. unsigned rightAc = atoi(rightId);
  464. if (leftAc != rightAc)
  465. return (int)(leftAc - rightAc);
  466. const char * leftSep = strchr(leftId, '_');
  467. const char * rightSep = strchr(rightId, '_');
  468. assertex(leftSep && rightSep);
  469. return atoi(leftSep+1) - atoi(rightSep+1);
  470. }
  471. //---------------------------------------------------------------------------------------------------------------------
  472. /*
  473. * A class for implementing a scope iterator that walks through graph progress information
  474. */
  475. class CConstGraphProgressScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  476. {
  477. public:
  478. CConstGraphProgressScopeIterator(const char * wuid, const ScopeFilter & _filter, __uint64 _minVersion) : filter(_filter), minVersion(_minVersion)
  479. {
  480. //Examine the filter, and determine if we only need to look at a single graph/subgraph
  481. StringAttr singleGraph;
  482. const StringArray & scopesToMatch = filter.queryScopes();
  483. if (scopesToMatch)
  484. {
  485. bool seenGraph = false;
  486. bool seenSubGraph = false;
  487. ForEachItemIn(iScope, scopesToMatch)
  488. {
  489. StringArray ids;
  490. ids.appendList(scopesToMatch.item(iScope), ":");
  491. ForEachItemIn(i, ids)
  492. {
  493. const char * curId = ids.item(i);
  494. StatsScopeId id(curId);
  495. switch (id.queryScopeType())
  496. {
  497. case SSTgraph:
  498. if (seenGraph)
  499. {
  500. if (singleGraph && !streq(singleGraph, curId))
  501. singleGraph.clear();
  502. }
  503. else
  504. {
  505. if (!id.isWildcard())
  506. singleGraph.set(curId);
  507. seenGraph = true;
  508. }
  509. break;
  510. case SSTsubgraph:
  511. if (seenSubGraph)
  512. {
  513. if (singleSubGraph && !streq(singleSubGraph, curId))
  514. singleSubGraph.clear();
  515. }
  516. else
  517. {
  518. if (!id.isWildcard())
  519. singleSubGraph.set(curId);
  520. seenSubGraph = true;
  521. }
  522. break;
  523. }
  524. }
  525. }
  526. }
  527. rootPath.append("/GraphProgress/").append(wuid).append('/');
  528. if (singleGraph)
  529. rootPath.append(singleGraph).append("/");
  530. //Don't lock the statistics while we iterate - any partial updates must not cause problems
  531. if (daliClientActive())
  532. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_NONE, SDS_LOCK_TIMEOUT));
  533. if (conn && !singleGraph)
  534. {
  535. graphIter.setown(conn->queryRoot()->getElements("*"));
  536. graphIter.setown(createSortedIterator(*graphIter, compareGraphNode));
  537. }
  538. valid = false;
  539. }
  540. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IConstWUScopeIterator>)
  541. virtual bool first()
  542. {
  543. valid = false;
  544. if (!conn)
  545. return false;
  546. if (graphIter && !graphIter->first())
  547. return false;
  548. if (!firstSubGraph())
  549. {
  550. if (!nextGraph())
  551. return false;
  552. }
  553. valid = true;
  554. return true;
  555. }
  556. virtual bool next()
  557. {
  558. if (!nextChildScope())
  559. {
  560. if (!nextSubGraph())
  561. {
  562. if (!nextGraph())
  563. {
  564. valid = false;
  565. return false;
  566. }
  567. }
  568. }
  569. return true;
  570. }
  571. virtual bool nextSibling() override
  572. {
  573. if (collections.ordinality() == 0)
  574. return false;
  575. assertex(childIterators.ordinality() < collections.ordinality());
  576. collections.pop();
  577. //next will call childIterator.next() - walking the next sibling
  578. return next();
  579. }
  580. virtual bool nextParent() override
  581. {
  582. if (collections.ordinality() == 0)
  583. return false;
  584. assertex(childIterators.ordinality() < collections.ordinality());
  585. collections.pop();
  586. if (collections.ordinality() == 0)
  587. return false;
  588. //Finish with this node - so next will move onto the sibling of the parent node.
  589. finishCollection();
  590. return next();
  591. }
  592. virtual bool isValid()
  593. {
  594. return valid;
  595. }
  596. protected:
  597. bool firstSubGraph()
  598. {
  599. IPropertyTree & graphNode = graphIter ? graphIter->query() : *conn->queryRoot();
  600. const char * xpath = "sg*";
  601. StringBuffer childXpath;
  602. if (singleSubGraph)
  603. {
  604. childXpath.append(singleSubGraph);
  605. xpath = childXpath.str();
  606. }
  607. subgraphIter.setown(graphNode.getElements(xpath));
  608. if (subgraphIter)
  609. {
  610. if (!singleSubGraph)
  611. subgraphIter.setown(createSortedIterator(*subgraphIter, compareSubGraphStatsNode));
  612. }
  613. else
  614. subgraphIter.setown(graphNode.getElements("sg0"));
  615. if (!subgraphIter->first())
  616. return false;
  617. if (firstStat())
  618. return true;
  619. return nextSubGraph();
  620. }
  621. bool nextSubGraph()
  622. {
  623. for (;;)
  624. {
  625. if (!subgraphIter->next())
  626. return false;
  627. if (firstStat())
  628. return true;
  629. }
  630. }
  631. bool nextGraph()
  632. {
  633. if (!graphIter)
  634. return false;
  635. for (;;)
  636. {
  637. if (!graphIter->next())
  638. return false;
  639. if (firstSubGraph())
  640. return true;
  641. }
  642. }
  643. bool firstStat()
  644. {
  645. IPropertyTree & curSubGraph = subgraphIter->query();
  646. if (!checkSubGraph())
  647. return false;
  648. curSubGraph.getPropBin("Stats", compressed.clear());
  649. //Don't crash on old format progress...
  650. if (compressed.length() == 0)
  651. return false;
  652. decompressToBuffer(serialized.clear(), compressed);
  653. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  654. statsIterator.timeStamp = collection->queryWhenCreated();
  655. if (!beginCollection(*collection))
  656. return false;
  657. // When workflow is root element, it is just a container. Ignore the workflow element here
  658. // as WorkUnitStatisticsScopeIterator will produce workflow scope - don't want duplicates.
  659. // (Note: workflow element never contains stats).
  660. if (collections.tos().queryScopeType() == SSTworkflow)
  661. {
  662. if (!next())
  663. return false;
  664. }
  665. //The root element of a collection is a graph - but it is only there to nest the subgraphs in.
  666. //Do not iterate it as a separate element - unless it has some stats.
  667. IStatisticCollection & curCollection = collections.tos();
  668. if ((curCollection.queryScopeType() != SSTgraph) || (curCollection.getNumStatistics() != 0))
  669. return true;
  670. return next();
  671. }
  672. bool beginCollection(IStatisticCollection & collection)
  673. {
  674. collections.append(OLINK(collection));
  675. curScopeType = collection.queryScopeType();
  676. collection.getFullScope(curScopeName.clear());
  677. ScopeCompare result = filter.compare(curScopeName);
  678. if (result & SCequal)
  679. return true;
  680. //If this scope cannot be the parent of a match then discard it.
  681. if (!(result & SCparent))
  682. collections.pop();
  683. //walk the next element
  684. return nextChildScope();
  685. }
  686. bool nextChildScope()
  687. {
  688. for (;;)
  689. {
  690. if (collections.ordinality() == 0)
  691. return false;
  692. IStatisticCollection * curCollection = &collections.tos();
  693. if (childIterators.ordinality() < collections.ordinality())
  694. {
  695. ScopeCompare result = filter.compare(curScopeName);
  696. //Do not walk children scopes if it is unrelated
  697. if (result & SCparent)
  698. {
  699. //Start iterating the children for the current collection
  700. childIterators.append(curCollection->getScopes(NULL, true));
  701. if (!childIterators.tos().first())
  702. {
  703. finishCollection();
  704. continue;
  705. }
  706. }
  707. else
  708. {
  709. //Don't walk the child scopes
  710. collections.pop();
  711. continue;
  712. }
  713. }
  714. else if (!childIterators.tos().next())
  715. {
  716. finishCollection();
  717. continue;
  718. }
  719. if (beginCollection(childIterators.tos().query()))
  720. return true;
  721. }
  722. }
  723. void finishCollection()
  724. {
  725. collections.pop();
  726. childIterators.pop();
  727. }
  728. bool checkSubGraph()
  729. {
  730. IPropertyTree & curSubGraph = subgraphIter->query();
  731. StatisticCreatorType creatorType = queryCreatorType(curSubGraph.queryProp("@c"), SCTnone);
  732. const char * creator = curSubGraph.queryProp("@creator");
  733. //MORE: Check minVersion and allow early filtering
  734. //MORE: Potentially filter by creator type??
  735. // if (!filter->matches(creatorType, creator, SSTall, NULL, SMeasureAll, StKindAll, AnyStatisticValue))
  736. // return false;
  737. statsIterator.creatorType = creatorType;
  738. statsIterator.creator.set(creator);
  739. return true;
  740. }
  741. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  742. {
  743. if ((whichProperties & PTstatistics))
  744. {
  745. /*
  746. MORE: Code from the statsIterator class should be inlined here - code will be much simpler
  747. but it currently needs an implementation of the IConstWUStatistic 3rd parameter
  748. IStatisticCollection & collection = collections.tos();
  749. ForEachItemIn(i, collection)
  750. {
  751. StatisticKind kind;
  752. unsigned __int64 value;
  753. collection->getStatistic(kind, value, i);
  754. visitor.noteStatistic(kind, value, *this);
  755. }
  756. */
  757. statsIterator.reset(curScopeName, curScopeType, collections.tos());
  758. ForEach(statsIterator)
  759. statsIterator.play(visitor);
  760. }
  761. }
  762. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  763. {
  764. return collections.tos().getStatistic(kind, value);
  765. }
  766. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  767. {
  768. return nullptr;
  769. }
  770. virtual const char * queryHint(const char * kind) const override
  771. {
  772. return nullptr;
  773. }
  774. virtual const char * queryScope() const override
  775. {
  776. return curScopeName;
  777. }
  778. virtual StatisticScopeType getScopeType() const override
  779. {
  780. return curScopeType;
  781. }
  782. private:
  783. class ScopeStatisticsIterator : public CInterfaceOf<IConstWUStatistic>
  784. {
  785. friend class CConstGraphProgressScopeIterator; // cleaner if this was removed + setScope() functions added.
  786. public:
  787. void reset(const char * _scopeName, StatisticScopeType _scopeType, IStatisticCollection & _collection)
  788. {
  789. scope.set(_scopeName);
  790. scopeType = _scopeType;
  791. collection = &_collection;
  792. numStats = collection->getNumStatistics();
  793. }
  794. // interface IConstWUStatisticIterator
  795. IConstWUStatistic & query()
  796. {
  797. return *this;
  798. }
  799. bool first()
  800. {
  801. curStatIndex = 0;
  802. if (curStatIndex >= numStats)
  803. return false;
  804. collection->getStatistic(kind, value, curStatIndex);
  805. //MORE: Allow filtering:
  806. /*
  807. * if (filter && !filter->matches(SCTall, NULL, SSTall, NULL, queryMeasure(kind), kind, value))
  808. continue;
  809. */
  810. return true;
  811. }
  812. bool next()
  813. {
  814. for (;;)
  815. {
  816. ++curStatIndex;
  817. if (curStatIndex >= numStats)
  818. return false;
  819. collection->getStatistic(kind, value, curStatIndex);
  820. //MORE: Allow stats filtering
  821. return true;
  822. }
  823. }
  824. bool isValid()
  825. {
  826. return curStatIndex < numStats;
  827. }
  828. //interface IConstWUStatistic
  829. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const override
  830. {
  831. if (createDefault)
  832. {
  833. StringBuffer description;
  834. createDefaultDescription(description, kind, scopeType, scope);
  835. str.set(description);
  836. }
  837. return str;
  838. }
  839. virtual IStringVal & getCreator(IStringVal & str) const override
  840. {
  841. str.set(creator);
  842. return str;
  843. }
  844. virtual const char * queryScope() const override
  845. {
  846. return scope;
  847. }
  848. virtual IStringVal & getFormattedValue(IStringVal & str) const override
  849. {
  850. StringBuffer formatted;
  851. formatStatistic(formatted, value, kind);
  852. str.set(formatted);
  853. return str;
  854. }
  855. virtual StatisticMeasure getMeasure() const override
  856. {
  857. return queryMeasure(kind);
  858. }
  859. virtual StatisticKind getKind() const override
  860. {
  861. return kind;
  862. }
  863. virtual StatisticCreatorType getCreatorType() const override
  864. {
  865. return creatorType;
  866. }
  867. virtual StatisticScopeType getScopeType() const override
  868. {
  869. return scopeType;
  870. }
  871. virtual unsigned __int64 getValue() const override
  872. {
  873. return value;
  874. }
  875. virtual unsigned __int64 getCount() const override
  876. {
  877. return 1;
  878. }
  879. virtual unsigned __int64 getMax() const override
  880. {
  881. return 0;
  882. }
  883. virtual unsigned __int64 getTimestamp() const override
  884. {
  885. return timeStamp;
  886. }
  887. void play(IWuScopeVisitor & visitor)
  888. {
  889. visitor.noteStatistic(kind, value, *this);
  890. }
  891. protected:
  892. IStatisticCollection * collection = nullptr;
  893. StringBuffer creator;
  894. StringBuffer scope;
  895. StatisticKind kind;
  896. StatisticCreatorType creatorType;
  897. StatisticScopeType scopeType;
  898. unsigned __int64 value = 0;
  899. unsigned __int64 timeStamp;
  900. unsigned curStatIndex = 0;
  901. unsigned numStats = 0;
  902. } statsIterator;
  903. Owned<IRemoteConnection> conn;
  904. StringBuffer curScopeName;
  905. StatisticScopeType curScopeType = SSTnone;
  906. __uint64 minVersion;
  907. const ScopeFilter & filter;
  908. StringBuffer rootPath;
  909. StringAttr singleSubGraph;
  910. Owned<IPropertyTreeIterator> graphIter;
  911. Owned<IPropertyTreeIterator> subgraphIter;
  912. IArrayOf<IStatisticCollection> collections;
  913. IArrayOf<IStatisticCollectionIterator> childIterators; // Iterator(n) through collections(n) - created once iterating children
  914. MemoryBuffer compressed;
  915. MemoryBuffer serialized;
  916. bool valid;
  917. };
  918. int compareNoteScopeOrder(IConstWUException & left, IConstWUException & right)
  919. {
  920. return compareScopeName(left.queryScope(), right.queryScope());
  921. }
  922. int compareNoteScopeOrder(IInterface * const * left, IInterface * const * right)
  923. {
  924. return compareNoteScopeOrder(*static_cast<IConstWUException *>(*left), *static_cast<IConstWUException *>(*right));
  925. }
  926. class NotesIterator : public CInterfaceOf<IConstWUScopeIterator>
  927. {
  928. public:
  929. NotesIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter)
  930. {
  931. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  932. ForEach(*exceptions)
  933. {
  934. IConstWUException & exception = exceptions->query();
  935. if (exception.queryScope()!=nullptr)
  936. notes.append(OLINK(exception));
  937. }
  938. notes.sort(compareNoteScopeOrder);
  939. }
  940. virtual bool first() override
  941. {
  942. baseIndex = 0;
  943. return updateCurrent();
  944. }
  945. virtual bool next() override
  946. {
  947. baseIndex += numCurrentScope;
  948. return updateCurrent();
  949. }
  950. virtual bool isValid() override
  951. {
  952. return notes.isItem(baseIndex);
  953. }
  954. virtual bool nextSibling() override
  955. {
  956. //Search until the current scope is not a child of the previous scope
  957. StringBuffer savedScope(queryScope());
  958. for (;;)
  959. {
  960. if (!next())
  961. return false;
  962. if (compareScopes(queryScope(), savedScope) != SCchild)
  963. return true;
  964. }
  965. }
  966. virtual bool nextParent() override
  967. {
  968. //Search until the current scope is not a child of the previous parent scope
  969. StringBuffer parentScope;
  970. if (getParentScope(parentScope, queryScope()))
  971. {
  972. for (;;)
  973. {
  974. if (!next())
  975. return false;
  976. if (compareScopes(queryScope(), parentScope) != SCchild)
  977. return true;
  978. }
  979. }
  980. else
  981. {
  982. finish();
  983. return false;
  984. }
  985. }
  986. virtual const char * queryScope() const override
  987. {
  988. const char * scope = notes.item(baseIndex).queryScope();
  989. return scope ? scope : "";
  990. }
  991. virtual StatisticScopeType getScopeType() const override
  992. {
  993. const char * tail = queryScopeTail(queryScope());
  994. StatsScopeId id(tail);
  995. return id.queryScopeType();
  996. }
  997. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties = PTall) override
  998. {
  999. if (whichProperties & PTnotes)
  1000. {
  1001. for (unsigned i=0; i < numCurrentScope; i++)
  1002. {
  1003. IConstWUException & cur = notes.item(baseIndex + i);
  1004. visitor.noteException(cur);
  1005. }
  1006. }
  1007. }
  1008. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1009. {
  1010. return false;
  1011. }
  1012. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1013. {
  1014. return nullptr;
  1015. }
  1016. virtual const char * queryHint(const char * kind) const override
  1017. {
  1018. return nullptr;
  1019. }
  1020. private:
  1021. bool updateCurrent()
  1022. {
  1023. if (!notes.isItem(baseIndex))
  1024. return false;
  1025. // set numCurrentScope to number of notes in the current scope
  1026. unsigned next = baseIndex+1;
  1027. while (next < notes.ordinality())
  1028. {
  1029. if (compareNoteScopeOrder(notes.item(baseIndex), notes.item(next)) != 0)
  1030. break;
  1031. next++;
  1032. }
  1033. numCurrentScope = (next - baseIndex);
  1034. return true;
  1035. }
  1036. void finish()
  1037. {
  1038. baseIndex = notes.ordinality();
  1039. }
  1040. unsigned baseIndex = 0;
  1041. unsigned numCurrentScope = 0;
  1042. IArrayOf<IConstWUException> notes;
  1043. };
  1044. int compareStatisticScopes(IConstWUStatistic & left, IConstWUStatistic & right)
  1045. {
  1046. return compareScopeName(left.queryScope(), right.queryScope());
  1047. }
  1048. int compareStatisticScopes(IInterface * const * left, IInterface * const * right)
  1049. {
  1050. return compareStatisticScopes(*static_cast<IConstWUStatistic *>(*left), *static_cast<IConstWUStatistic *>(*right));
  1051. }
  1052. /*
  1053. * An implementation of IConstWUScopeIterator for global workunit statistics.
  1054. */
  1055. class WorkUnitStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1056. {
  1057. public:
  1058. WorkUnitStatisticsScopeIterator(const IArrayOf<IConstWUStatistic> & _statistics, const ScopeFilter & _filter)
  1059. {
  1060. ForEachItemIn(i, _statistics)
  1061. {
  1062. IConstWUStatistic & cur = _statistics.item(i);
  1063. if (_filter.compare(cur.queryScope()) & SCequal)
  1064. statistics.append(OLINK(cur));
  1065. }
  1066. statistics.sort(compareStatisticScopes);
  1067. }
  1068. virtual bool first() override
  1069. {
  1070. curIndex = 0;
  1071. return initScope();
  1072. }
  1073. virtual bool next() override
  1074. {
  1075. curIndex += numStatistics;
  1076. return initScope();
  1077. }
  1078. virtual bool nextSibling() override
  1079. {
  1080. //Search until the current scope is not a child of the previous scope
  1081. StringBuffer savedScope(queryScope());
  1082. for (;;)
  1083. {
  1084. if (!next())
  1085. return false;
  1086. if (compareScopes(queryScope(), savedScope) != SCchild)
  1087. return true;
  1088. }
  1089. }
  1090. virtual bool nextParent() override
  1091. {
  1092. //Search until the current scope is not a child of the previous parent scope
  1093. StringBuffer parentScope;
  1094. if (getParentScope(parentScope, queryScope()))
  1095. {
  1096. for (;;)
  1097. {
  1098. if (!next())
  1099. return false;
  1100. if (compareScopes(queryScope(), parentScope) != SCchild)
  1101. return true;
  1102. }
  1103. }
  1104. else
  1105. {
  1106. finish();
  1107. return false;
  1108. }
  1109. }
  1110. virtual bool isValid() override
  1111. {
  1112. return statistics.isItem(curIndex);
  1113. }
  1114. virtual const char * queryScope() const override
  1115. {
  1116. return statistics.item(curIndex).queryScope();
  1117. }
  1118. virtual StatisticScopeType getScopeType() const override
  1119. {
  1120. return statistics.item(curIndex).getScopeType();
  1121. }
  1122. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1123. {
  1124. if (whichProperties & PTstatistics)
  1125. {
  1126. for (unsigned i=0; i < numStatistics; i++)
  1127. {
  1128. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1129. visitor.noteStatistic(cur.getKind(), cur.getValue(), cur);
  1130. }
  1131. }
  1132. }
  1133. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1134. {
  1135. for (unsigned i=0; i < numStatistics; i++)
  1136. {
  1137. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1138. if (cur.getKind() == kind)
  1139. {
  1140. value = cur.getValue();
  1141. return true;
  1142. }
  1143. }
  1144. return false;
  1145. }
  1146. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1147. {
  1148. return nullptr;
  1149. }
  1150. virtual const char * queryHint(const char * kind) const
  1151. {
  1152. return nullptr;
  1153. }
  1154. protected:
  1155. inline IConstWUStatistic & queryStatistic(unsigned i)
  1156. {
  1157. return statistics.item(curIndex + i);
  1158. }
  1159. bool initScope()
  1160. {
  1161. if (!statistics.isItem(curIndex))
  1162. return false;
  1163. unsigned next = curIndex+1;
  1164. while (next < statistics.ordinality())
  1165. {
  1166. if (compareStatisticScopes(statistics.item(curIndex), statistics.item(next)) != 0)
  1167. break;
  1168. next++;
  1169. }
  1170. numStatistics = (next - curIndex);
  1171. return true;
  1172. }
  1173. void finish()
  1174. {
  1175. curIndex = statistics.ordinality();
  1176. }
  1177. protected:
  1178. IArrayOf<IConstWUStatistic> statistics;
  1179. unsigned curIndex = 0;
  1180. unsigned numStatistics = 1;
  1181. };
  1182. /*
  1183. * An implementation of IConstWUScopeIterator for the query graphs.
  1184. */
  1185. class GraphScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1186. {
  1187. private:
  1188. //This uses a state machine - this enumeration contains the different states.
  1189. enum State
  1190. {
  1191. //Following are the states which represent valid scopes
  1192. SGraph,
  1193. SChildGraph,
  1194. SSubGraph,
  1195. SEdge,
  1196. SActivity,
  1197. //The following are internal states.
  1198. SGraphFirstEdge,
  1199. SGraphFirstSubGraph,
  1200. SGraphFirst,
  1201. SGraphEnd,
  1202. SGraphNext,
  1203. SSubGraphFirstEdge,
  1204. SSubGraphFirstActivity,
  1205. SSubGraphEnd,
  1206. SSubGraphNext,
  1207. SEdgeNext,
  1208. SEdgeEnd,
  1209. SActivityNext,
  1210. SActivityEnd,
  1211. SChildGraphFirstEdge,
  1212. SChildGraphFirstSubGraph,
  1213. SChildGraphFirst,
  1214. SChildGraphNext,
  1215. SChildGraphEnd,
  1216. SDone
  1217. };
  1218. State state = SDone;
  1219. State nextState = SDone;
  1220. public:
  1221. GraphScopeIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter) : graphIter(&wu->getGraphs(GraphTypeAny)), filter(_filter)
  1222. {
  1223. }
  1224. virtual bool first() override
  1225. {
  1226. state = SGraphFirst;
  1227. return nextScope();
  1228. }
  1229. virtual bool next() override
  1230. {
  1231. if (!selectNext())
  1232. return false;
  1233. return nextScope();
  1234. }
  1235. virtual bool nextSibling() override
  1236. {
  1237. if (!selectNextSibling())
  1238. return false;
  1239. return nextScope();
  1240. }
  1241. virtual bool nextParent() override
  1242. {
  1243. if (!selectNextParent())
  1244. return false;
  1245. return nextScope();
  1246. }
  1247. virtual bool isValid() override
  1248. {
  1249. return graphIter->isValid();
  1250. }
  1251. virtual const char * queryScope() const override
  1252. {
  1253. return curScopeName.str();
  1254. }
  1255. virtual StatisticScopeType getScopeType() const override
  1256. {
  1257. return scopeType;
  1258. }
  1259. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1260. {
  1261. switch (scopeType)
  1262. {
  1263. case SSTgraph:
  1264. return;
  1265. }
  1266. IPropertyTree & cur = treeIters.tos().query();
  1267. switch (scopeType)
  1268. {
  1269. case SSTgraph:
  1270. break;
  1271. case SSTsubgraph:
  1272. break;
  1273. case SSTactivity:
  1274. {
  1275. if (whichProperties & PTattributes)
  1276. {
  1277. playAttribute(visitor, WaLabel);
  1278. Owned<IPropertyTreeIterator> attrs = cur.getElements("att");
  1279. ForEach(*attrs)
  1280. {
  1281. IPropertyTree & cur = attrs->query();
  1282. WuAttr attr = queryGraphChildAttToWuAttr(cur.queryProp("@name"));
  1283. if (attr != WaNone)
  1284. visitor.noteAttribute(attr, cur.queryProp("@value"));
  1285. }
  1286. }
  1287. if (whichProperties & PThints)
  1288. {
  1289. Owned<IPropertyTreeIterator> hints = cur.getElements("hint");
  1290. ForEach(*hints)
  1291. {
  1292. IPropertyTree & cur = hints->query();
  1293. visitor.noteHint(cur.queryProp("@name"), cur.queryProp("@value"));
  1294. }
  1295. }
  1296. break;
  1297. }
  1298. case SSTedge:
  1299. if (whichProperties & PTattributes)
  1300. {
  1301. //MORE This will eventually need to walk the attributes and map the names.
  1302. //Need to be careful if they need to be mapped differently depending on the context.
  1303. playAttribute(visitor, WaLabel);
  1304. playAttribute(visitor, WaIdSource);
  1305. playAttribute(visitor, WaIdTarget);
  1306. playAttribute(visitor, WaSourceIndex);
  1307. playAttribute(visitor, WaTargetIndex);
  1308. playAttribute(visitor, WaIsDependency);
  1309. }
  1310. break;
  1311. }
  1312. }
  1313. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1314. {
  1315. return false;
  1316. }
  1317. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1318. {
  1319. if (!treeIters.ordinality())
  1320. return nullptr;
  1321. //MORE - check that the attribute is value for the current scope type (to prevent defaults being returned)
  1322. return queryAttributeValue(treeIters.tos().query(), attr, scratchpad);
  1323. }
  1324. virtual const char * queryHint(const char * kind) const override
  1325. {
  1326. //MORE: Needs to be implemented!
  1327. return nullptr;
  1328. }
  1329. private:
  1330. void playAttribute(IWuScopeVisitor & visitor, WuAttr kind)
  1331. {
  1332. StringBuffer scratchpad;
  1333. const char * value = queryAttributeValue(treeIters.tos().query(), kind, scratchpad);
  1334. if (value)
  1335. visitor.noteAttribute(kind, value);
  1336. }
  1337. void pushIterator(IPropertyTreeIterator * iter, State state)
  1338. {
  1339. treeIters.append(*LINK(iter));
  1340. stateStack.append(state);
  1341. }
  1342. State popIterator()
  1343. {
  1344. treeIters.pop();
  1345. return (State)stateStack.popGet();
  1346. }
  1347. void pushScope(const char * id)
  1348. {
  1349. scopeLengths.append(curScopeName.length());
  1350. curScopeName.append(":").append(id);
  1351. }
  1352. void popScope()
  1353. {
  1354. curScopeName.setLength(scopeLengths.popGet());
  1355. }
  1356. bool doNextScope()
  1357. {
  1358. for(;;)
  1359. {
  1360. switch (state)
  1361. {
  1362. case SGraph:
  1363. {
  1364. IConstWUGraph & graph = graphIter->query();
  1365. unsigned wfid = graph.getWfid();
  1366. curScopeName.clear();
  1367. if (wfid != 0)
  1368. curScopeName.append(WorkflowScopePrefix).append(wfid).append(':');
  1369. graph.getName(StringBufferAdaptor(curScopeName));
  1370. scopeType = SSTgraph;
  1371. return true;
  1372. }
  1373. case SSubGraph:
  1374. scopeId.set(SubGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1375. pushScope(scopeId);
  1376. scopeType = SSTsubgraph;
  1377. return true;
  1378. case SEdge:
  1379. scopeId.set(EdgeScopePrefix).append(treeIters.tos().query().queryProp("@id"));
  1380. pushScope(scopeId);
  1381. scopeType = SSTedge;
  1382. return true;
  1383. case SActivity:
  1384. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") == TAKsubgraph)
  1385. {
  1386. state = SActivityNext;
  1387. break;
  1388. }
  1389. scopeId.set(ActivityScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1390. pushScope(scopeId);
  1391. scopeType = SSTactivity;
  1392. return true;
  1393. case SChildGraph:
  1394. {
  1395. unsigned numIters = treeIters.ordinality();
  1396. //This should really be implemented by a filter on the node - but it would require _kind/_parentActivity to move to the node tag
  1397. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") != TAKsubgraph)
  1398. {
  1399. state = SChildGraphNext;
  1400. break;
  1401. }
  1402. unsigned parentActivityId = treeIters.item(numIters-2).query().getPropInt("@id");
  1403. unsigned parentId = treeIters.tos().query().getPropInt("att[@name='_parentActivity']/@value");
  1404. if (parentId != parentActivityId)
  1405. {
  1406. state = SChildGraphNext;
  1407. break;
  1408. }
  1409. scopeId.set(ChildGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1410. pushScope(scopeId);
  1411. scopeType = SSTchildgraph;
  1412. return true;
  1413. }
  1414. //Graph iteration
  1415. case SGraphFirst:
  1416. if (!graphIter->first())
  1417. state = SDone;
  1418. else
  1419. state = SGraph;
  1420. break;
  1421. case SGraphEnd:
  1422. state = SGraphNext;
  1423. break;
  1424. case SGraphNext:
  1425. if (!graphIter->next())
  1426. state = SDone;
  1427. else
  1428. state = SGraph;
  1429. break;
  1430. //Edge iteration
  1431. case SGraphFirstEdge:
  1432. {
  1433. //Walk dependencies - should possibly have a different SST e.g., SSTdependency since they do not
  1434. //share many characteristics with edges - e.g. no flowing records => few/no stats.
  1435. curGraph.setown(graphIter->query().getXGMMLTree(false));
  1436. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("edge");
  1437. if (treeIter && treeIter->first())
  1438. {
  1439. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1440. treeIter->first();
  1441. pushIterator(treeIter, SGraphFirstSubGraph);
  1442. state = SEdge;
  1443. }
  1444. else
  1445. state = SGraphFirstSubGraph;
  1446. break;
  1447. }
  1448. case SChildGraphFirstEdge:
  1449. {
  1450. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1451. if (treeIter && treeIter->first())
  1452. {
  1453. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1454. pushIterator(treeIter, SChildGraphFirstSubGraph);
  1455. state = SEdge;
  1456. }
  1457. else
  1458. state = SChildGraphFirstSubGraph;
  1459. break;
  1460. }
  1461. case SEdgeEnd:
  1462. popScope();
  1463. state = SEdgeNext;
  1464. break;
  1465. case SEdgeNext:
  1466. if (treeIters.tos().next())
  1467. state = SEdge;
  1468. else
  1469. state = popIterator();
  1470. break;
  1471. //Subgraph iteration
  1472. case SGraphFirstSubGraph:
  1473. {
  1474. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("node");
  1475. if (treeIter && treeIter->first())
  1476. {
  1477. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1478. treeIter->first();
  1479. pushIterator(treeIter, SGraphNext);
  1480. state = SSubGraph;
  1481. }
  1482. else
  1483. state = SGraphNext;
  1484. break;
  1485. }
  1486. case SChildGraphFirstSubGraph:
  1487. {
  1488. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1489. if (treeIter && treeIter->first())
  1490. {
  1491. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1492. pushIterator(treeIter, SChildGraphEnd);
  1493. state = SSubGraph;
  1494. }
  1495. else
  1496. state = SChildGraphEnd;
  1497. break;
  1498. }
  1499. case SSubGraphFirstEdge:
  1500. {
  1501. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1502. if (treeIter && treeIter->first())
  1503. {
  1504. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1505. pushIterator(treeIter, SSubGraphFirstActivity);
  1506. state = SEdge;
  1507. }
  1508. else
  1509. state = SSubGraphFirstActivity;
  1510. break;
  1511. }
  1512. case SSubGraphFirstActivity:
  1513. {
  1514. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1515. if (treeIter && treeIter->first())
  1516. {
  1517. treeIter.setown(createSortedIterator(*treeIter, compareActivityNode));
  1518. pushIterator(treeIter, SSubGraphEnd);
  1519. state = SActivity;
  1520. }
  1521. else
  1522. state = SSubGraphEnd;
  1523. break;
  1524. }
  1525. case SSubGraphEnd:
  1526. popScope();
  1527. state = SSubGraphNext;
  1528. break;
  1529. case SChildGraphEnd:
  1530. popScope();
  1531. state = SChildGraphNext;
  1532. break;
  1533. case SSubGraphNext:
  1534. if (treeIters.tos().next())
  1535. state = SSubGraph;
  1536. else
  1537. state = popIterator();
  1538. break;
  1539. case SActivityEnd:
  1540. popScope();
  1541. state = SActivityNext;
  1542. break;
  1543. case SActivityNext:
  1544. if (treeIters.tos().next())
  1545. state = SActivity;
  1546. else
  1547. state = popIterator();
  1548. break;
  1549. case SChildGraphNext:
  1550. if (treeIters.tos().next())
  1551. state = SChildGraph;
  1552. else
  1553. state = popIterator();
  1554. break;
  1555. case SChildGraphFirst:
  1556. {
  1557. unsigned numIters = treeIters.ordinality();
  1558. IPropertyTreeIterator & graphIter = treeIters.item(numIters-2);
  1559. Owned<IPropertyTreeIterator> treeIter = graphIter.query().getElements("att/graph/node");
  1560. //Really want to filter by <att name="_parentActivity" value="<parentid>">
  1561. if (treeIter && treeIter->first())
  1562. {
  1563. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1564. pushIterator(treeIter, SActivityEnd);
  1565. state = SChildGraph;
  1566. }
  1567. else
  1568. state = SActivityEnd;
  1569. break;
  1570. }
  1571. case SDone:
  1572. return false;
  1573. default:
  1574. throwUnexpected();
  1575. }
  1576. }
  1577. }
  1578. bool nextScope()
  1579. {
  1580. for(;;)
  1581. {
  1582. if (!doNextScope())
  1583. return false;
  1584. ScopeCompare cmp = filter.compare(curScopeName);
  1585. if (cmp & SCequal)
  1586. return true;
  1587. //MORE: Optimize next based on result of compare
  1588. if (!selectNext())
  1589. return false;
  1590. }
  1591. }
  1592. bool selectNext()
  1593. {
  1594. switch (state)
  1595. {
  1596. case SGraph:
  1597. state = SGraphFirstEdge;
  1598. break;
  1599. case SChildGraph:
  1600. state = SChildGraphFirstEdge;
  1601. break;
  1602. case SSubGraph:
  1603. state = SSubGraphFirstEdge;
  1604. break;
  1605. case SEdge:
  1606. state = SEdgeEnd;
  1607. break;
  1608. case SActivity:
  1609. state = SChildGraphFirst;
  1610. break;
  1611. case SDone:
  1612. return false;
  1613. default:
  1614. throwUnexpected();
  1615. }
  1616. return true;
  1617. }
  1618. bool selectNextSibling()
  1619. {
  1620. switch (state)
  1621. {
  1622. case SGraph:
  1623. state = SGraphEnd;
  1624. break;
  1625. case SChildGraph:
  1626. state = SChildGraphEnd;
  1627. break;
  1628. case SSubGraph:
  1629. state = SSubGraphEnd;
  1630. break;
  1631. case SEdge:
  1632. state = SEdgeEnd;
  1633. break;
  1634. case SActivity:
  1635. state = SActivityEnd;
  1636. break;
  1637. case SDone:
  1638. return false;
  1639. default:
  1640. throwUnexpected();
  1641. }
  1642. return true;
  1643. }
  1644. bool selectNextParent()
  1645. {
  1646. switch (state)
  1647. {
  1648. case SGraph:
  1649. state = SDone;
  1650. break;
  1651. case SChildGraph:
  1652. case SSubGraph:
  1653. case SEdge:
  1654. case SActivity:
  1655. popScope();
  1656. state = popIterator();
  1657. break;
  1658. case SDone:
  1659. return false;
  1660. default:
  1661. throwUnexpected();
  1662. }
  1663. return true;
  1664. }
  1665. protected:
  1666. const ScopeFilter & filter;
  1667. Owned<IConstWUGraphIterator> graphIter;
  1668. Owned<IPropertyTree> curGraph;
  1669. IArrayOf<IPropertyTreeIterator> treeIters;
  1670. UnsignedArray scopeLengths;
  1671. UnsignedArray stateStack;
  1672. StringBuffer curScopeName;
  1673. StringBuffer scopeId;
  1674. StatisticScopeType scopeType = SSTnone;
  1675. };
  1676. static int compareWorkflow(IInterface * const * pLeft, IInterface * const * pRight)
  1677. {
  1678. IConstWorkflowItem * left = static_cast<IConstWorkflowItem *>(*pLeft);
  1679. IConstWorkflowItem * right = static_cast<IConstWorkflowItem *>(*pRight);
  1680. return left->queryWfid() - right->queryWfid();
  1681. }
  1682. static const char * trueToStr(bool value) { return value ? "true" : nullptr; }
  1683. /*
  1684. * An implementation of IConstWUScopeIterator for the workflow information.
  1685. */
  1686. class WorkflowStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1687. {
  1688. public:
  1689. WorkflowStatisticsScopeIterator(IConstWorkflowItemIterator * wfIter)
  1690. {
  1691. ForEach(*wfIter)
  1692. workflow.append(*LINK(wfIter->query()));
  1693. workflow.sort(compareWorkflow);
  1694. }
  1695. virtual bool first() override
  1696. {
  1697. if (workflow.empty())
  1698. return false;
  1699. curWorkflow = 0;
  1700. return initWorkflowItem();
  1701. }
  1702. virtual bool next() override
  1703. {
  1704. if (!workflow.isItem(++curWorkflow))
  1705. return false;
  1706. return initWorkflowItem();
  1707. }
  1708. virtual bool nextSibling() override
  1709. {
  1710. return next();
  1711. }
  1712. virtual bool nextParent() override
  1713. {
  1714. curWorkflow = NotFound;
  1715. return false;
  1716. }
  1717. virtual bool isValid() override
  1718. {
  1719. return workflow.isItem(curWorkflow);
  1720. }
  1721. virtual const char * queryScope() const override
  1722. {
  1723. return curScope.str();
  1724. }
  1725. virtual StatisticScopeType getScopeType() const override
  1726. {
  1727. return SSTworkflow;
  1728. }
  1729. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1730. {
  1731. if (whichProperties & PTattributes)
  1732. {
  1733. {
  1734. StringBuffer scratchpad;
  1735. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1736. ForEach(*depends)
  1737. visitor.noteAttribute(WaIdDependency, getValueText(depends->query(), scratchpad, WorkflowScopePrefix));
  1738. }
  1739. play(visitor, { WaIsScheduled, WaIdSuccess, WaIdFailure, WaIdRecovery, WaIdPersist, WaIdScheduled,
  1740. WaPersistName, WaLabel, WaMode, WaType, WaState, WaCluster, WaCriticalSection });
  1741. }
  1742. }
  1743. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1744. {
  1745. return false;
  1746. }
  1747. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1748. {
  1749. auto wf = &workflow.item(curWorkflow);
  1750. StringBufferAdaptor adaptor(scratchpad);
  1751. switch (attr)
  1752. {
  1753. case WaIdDependencyList:
  1754. {
  1755. bool first = true;
  1756. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1757. ForEach(*depends)
  1758. {
  1759. if (first)
  1760. scratchpad.append("[");
  1761. else
  1762. scratchpad.append(",");
  1763. scratchpad.append('"').append(WorkflowScopePrefix).append(depends->query()).append('"');
  1764. first = false;
  1765. }
  1766. if (first)
  1767. return nullptr;
  1768. scratchpad.append("]");
  1769. return scratchpad.str();
  1770. }
  1771. case WaIsScheduled: return trueToStr(wf->isScheduled());
  1772. case WaIdSuccess: return getWfidText(wf->querySuccess(), scratchpad);
  1773. case WaIdFailure: return getWfidText(wf->queryFailure(), scratchpad);
  1774. case WaIdRecovery: return getWfidText(wf->queryRecovery(), scratchpad);
  1775. case WaIdPersist: return getWfidText(wf->queryPersistWfid(), scratchpad);
  1776. case WaIdScheduled: return getWfidText(wf->queryScheduledWfid(), scratchpad);
  1777. case WaPersistName: return queryOptString(wf->getPersistName(adaptor));
  1778. case WaLabel: return queryOptString(wf->getLabel(adaptor));
  1779. case WaMode: return wf->queryMode() != WFModeNormal ? queryWorkflowModeText(wf->queryMode()) : nullptr;
  1780. case WaType: return wf->queryType() != WFTypeNormal ? queryWorkflowTypeText(wf->queryType()) : nullptr;
  1781. case WaState: return queryWorkflowStateText(wf->queryState());
  1782. case WaCluster: return queryOptString(wf->queryCluster(adaptor));
  1783. case WaCriticalSection: return queryOptString(wf->getCriticalName(adaptor));
  1784. /*
  1785. The followng attributes are not generated - I'm not convinced they are very useful, but they could be added later.
  1786. virtual bool isScheduledNow() const = 0;
  1787. virtual IWorkflowEvent * getScheduleEvent() const = 0;
  1788. virtual unsigned querySchedulePriority() const = 0;
  1789. virtual bool hasScheduleCount() const = 0;
  1790. virtual unsigned queryScheduleCount() const = 0;
  1791. virtual unsigned queryRetriesAllowed() const = 0;
  1792. virtual int queryPersistCopies() const = 0; // 0 - unmangled name, < 0 - use default, > 0 - max number
  1793. virtual bool queryPersistRefresh() const = 0;
  1794. virtual unsigned queryScheduleCountRemaining() const = 0;
  1795. virtual unsigned queryRetriesRemaining() const = 0;
  1796. virtual int queryFailCode() const = 0;
  1797. virtual const char * queryFailMessage() const = 0;
  1798. virtual const char * queryEventName() const = 0;
  1799. virtual const char * queryEventExtra() const = 0;
  1800. */
  1801. }
  1802. return nullptr;
  1803. }
  1804. virtual const char * queryHint(const char * kind) const
  1805. {
  1806. return nullptr;
  1807. }
  1808. protected:
  1809. bool initWorkflowItem()
  1810. {
  1811. curScope.clear().append(WorkflowScopePrefix).append(workflow.item(curWorkflow).queryWfid());
  1812. return true;
  1813. }
  1814. const char * getValueText(unsigned value, StringBuffer & scratchpad, const char * prefix = nullptr) const
  1815. {
  1816. return scratchpad.clear().append(prefix).append(value).str();
  1817. }
  1818. const char * queryOptString(IStringVal & value) const
  1819. {
  1820. const char * text = value.str();
  1821. if (!text || !*text)
  1822. return nullptr;
  1823. return text;
  1824. }
  1825. const char * getWfidText(unsigned value, StringBuffer & scratchpad) const
  1826. {
  1827. if (!value)
  1828. return nullptr;
  1829. return scratchpad.clear().append(WorkflowScopePrefix).append(value).str();
  1830. }
  1831. void play(IWuScopeVisitor & visitor, const std::initializer_list<WuAttr> & attrs) const
  1832. {
  1833. StringBuffer scratchpad;
  1834. for (auto attr : attrs)
  1835. {
  1836. const char * value = queryAttribute(attr, scratchpad.clear());
  1837. if (value)
  1838. visitor.noteAttribute(attr, value);
  1839. }
  1840. }
  1841. protected:
  1842. IArrayOf<IConstWorkflowItem> workflow;
  1843. unsigned curWorkflow = 0;
  1844. StringBuffer curScope;
  1845. };
  1846. /*
  1847. * An implementation of IConstWUScopeIterator that combines results from multiple sources.
  1848. */
  1849. class CompoundStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1850. {
  1851. class VisitorMapper : implements IWuScopeVisitor
  1852. {
  1853. public:
  1854. VisitorMapper(const WuScopeFilter & _filter, IWuScopeVisitor & _visitor) :
  1855. filter(_filter), visitor(_visitor)
  1856. {}
  1857. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  1858. {
  1859. if (filter.includeStatistic(kind))
  1860. visitor.noteStatistic(kind, value, extra);
  1861. }
  1862. virtual void noteAttribute(WuAttr attr, const char * value) override
  1863. {
  1864. if (filter.includeAttribute(attr))
  1865. visitor.noteAttribute(attr, value);
  1866. }
  1867. virtual void noteHint(const char * kind, const char * value) override
  1868. {
  1869. if (filter.includeHint(kind))
  1870. visitor.noteHint(kind, value);
  1871. }
  1872. virtual void noteException(IConstWUException & exception) override
  1873. {
  1874. visitor.noteException(exception);
  1875. }
  1876. protected:
  1877. const WuScopeFilter & filter;
  1878. IWuScopeVisitor & visitor;
  1879. };
  1880. public:
  1881. CompoundStatisticsScopeIterator(const WuScopeFilter & _filter) : filter(_filter)
  1882. {
  1883. }
  1884. void addIter(IConstWUScopeIterator * iter)
  1885. {
  1886. if (iter)
  1887. {
  1888. iters.append(OLINK(*iter));
  1889. assertex(iters.ordinality() <= sizeof(activeIterMask)*8);
  1890. }
  1891. }
  1892. virtual bool first() override
  1893. {
  1894. activeIterMask = 0;
  1895. ForEachItemIn(i, iters)
  1896. {
  1897. if (iters.item(i).first())
  1898. activeIterMask |= (1U << i);
  1899. }
  1900. return findNextScope();
  1901. }
  1902. virtual bool next() override
  1903. {
  1904. selectNext();
  1905. return findNextScope();
  1906. }
  1907. virtual bool nextSibling() override
  1908. {
  1909. selectNextSibling();
  1910. return findNextScope();
  1911. }
  1912. virtual bool nextParent() override
  1913. {
  1914. selectNextParent();
  1915. return findNextScope();
  1916. }
  1917. virtual bool isValid() override
  1918. {
  1919. return (activeIterMask != 0);
  1920. }
  1921. virtual const char * queryScope() const override
  1922. {
  1923. return iters.item(firstMatchIter).queryScope();
  1924. }
  1925. virtual StatisticScopeType getScopeType() const override
  1926. {
  1927. return iters.item(firstMatchIter).getScopeType();
  1928. }
  1929. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1930. {
  1931. VisitorMapper mappedVisitor(filter, visitor);
  1932. whichProperties &= filter.properties;
  1933. ForEachItemIn(i, iters)
  1934. {
  1935. if (iterMatchesCurrentScope(i))
  1936. iters.item(i).playProperties(mappedVisitor, whichProperties);
  1937. }
  1938. }
  1939. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1940. {
  1941. ForEachItemIn(i, iters)
  1942. {
  1943. if (iterMatchesCurrentScope(i))
  1944. {
  1945. if (iters.item(i).getStat(kind, value))
  1946. return true;
  1947. }
  1948. }
  1949. return false;
  1950. }
  1951. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1952. {
  1953. ForEachItemIn(i, iters)
  1954. {
  1955. if (iterMatchesCurrentScope(i))
  1956. {
  1957. const char * value = iters.item(i).queryAttribute(attr, scratchpad);
  1958. if (value)
  1959. return value;
  1960. }
  1961. }
  1962. return nullptr;
  1963. }
  1964. virtual const char * queryHint(const char * kind) const override
  1965. {
  1966. ForEachItemIn(i, iters)
  1967. {
  1968. if (iterMatchesCurrentScope(i))
  1969. {
  1970. const char * value = iters.item(i).queryHint(kind);
  1971. if (value)
  1972. return value;
  1973. }
  1974. }
  1975. return nullptr;
  1976. }
  1977. inline bool iterMatchesCurrentScope(unsigned i) const { return ((1U << i) & matchIterMask) != 0; }
  1978. inline bool isAlive(unsigned i) const { return ((1U << i) & activeIterMask) != 0; }
  1979. protected:
  1980. //Calculate which iterators contain the scope that should come next
  1981. bool findNextScope()
  1982. {
  1983. for(;;)
  1984. {
  1985. if (activeIterMask == 0)
  1986. return false;
  1987. unsigned mask = 0;
  1988. const char * scope = nullptr;
  1989. ForEachItemIn(i, iters)
  1990. {
  1991. if (isAlive(i))
  1992. {
  1993. const char * iterScope = iters.item(i).queryScope();
  1994. if (mask)
  1995. {
  1996. int compare = compareScopeName(scope, iterScope);
  1997. if (compare == 0)
  1998. {
  1999. mask |= (1U << i);
  2000. }
  2001. else if (compare > 0)
  2002. {
  2003. scope = iterScope;
  2004. mask = (1U << i);
  2005. firstMatchIter = i;
  2006. }
  2007. }
  2008. else
  2009. {
  2010. scope = iterScope;
  2011. mask = (1U << i);
  2012. firstMatchIter = i;
  2013. }
  2014. }
  2015. }
  2016. matchIterMask = mask;
  2017. while (activeScopes)
  2018. {
  2019. const char * activeScope = activeScopes.tos();
  2020. //If the next scope if not a child of one of the active scopes then that active scope will no longer match.
  2021. if (compareScopes(scope, activeScope) & SCchild)
  2022. break;
  2023. activeScopes.pop();
  2024. }
  2025. //The top most scope will be the deepest. Check if the current scope is close enough to return as a match.
  2026. bool include = false;
  2027. if (activeScopes)
  2028. {
  2029. const char * activeScope = activeScopes.tos();
  2030. //code above has ensured that this scope must be a child of (and therefore deeper) than activeScope
  2031. unsigned nesting = queryScopeDepth(scope) - queryScopeDepth(activeScope);
  2032. if (nesting <= filter.include.nestedDepth)
  2033. include = true;
  2034. }
  2035. //Check to see if this is a new match
  2036. if (filter.compareMatchScopes(scope) & SCequal)
  2037. {
  2038. if (!include)
  2039. include = filter.include.matchedScope;
  2040. //Only add it to the list of active scopes if it can match child elements
  2041. if (filter.include.nestedDepth != 0)
  2042. activeScopes.append(scope);
  2043. }
  2044. if (include)
  2045. {
  2046. if (!filter.includeScope(scope))
  2047. include = false;
  2048. else if (filter.requiredStats.size())
  2049. {
  2050. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2051. for (unsigned iReq=0; iReq < filter.requiredStats.size(); iReq++)
  2052. {
  2053. const StatisticValueFilter & cur = filter.requiredStats[iReq];
  2054. unsigned __int64 value;
  2055. if (getStat(cur.queryKind(), value))
  2056. {
  2057. if (!cur.matches(value))
  2058. include = false;
  2059. }
  2060. else
  2061. include = false;
  2062. }
  2063. }
  2064. }
  2065. if (include)
  2066. return true;
  2067. //MORE: Optimize based on filter.compareScope()
  2068. selectNext();
  2069. }
  2070. }
  2071. void checkScopeOrder(unsigned input, const char * prevScope)
  2072. {
  2073. if (isAlive(input))
  2074. {
  2075. const char * curScope = iters.item(input).queryScope();
  2076. int compare = compareScopeName(prevScope, curScope);
  2077. if (compare >= 0)
  2078. throw MakeStringException(0, "Out of order (%u) scopes %s,%s = %d", input, prevScope, curScope, compare);
  2079. }
  2080. }
  2081. void selectNext()
  2082. {
  2083. ForEachItemIn(i, iters)
  2084. {
  2085. if (iterMatchesCurrentScope(i))
  2086. {
  2087. #ifdef _DEBUG
  2088. StringBuffer prevScope(iters.item(i).queryScope());
  2089. #endif
  2090. if (!iters.item(i).next())
  2091. activeIterMask &= ~(1U << i);
  2092. #ifdef _DEBUG
  2093. checkScopeOrder(i, prevScope);
  2094. #endif
  2095. }
  2096. }
  2097. }
  2098. void selectNextSibling()
  2099. {
  2100. ForEachItemIn(i, iters)
  2101. {
  2102. if (iterMatchesCurrentScope(i))
  2103. {
  2104. #ifdef _DEBUG
  2105. StringBuffer prevScope(iters.item(i).queryScope());
  2106. #endif
  2107. if (!iters.item(i).nextSibling())
  2108. activeIterMask &= ~(1U << i);
  2109. #ifdef _DEBUG
  2110. checkScopeOrder(i, prevScope);
  2111. #endif
  2112. }
  2113. }
  2114. }
  2115. void selectNextParent()
  2116. {
  2117. ForEachItemIn(i, iters)
  2118. {
  2119. if (iterMatchesCurrentScope(i))
  2120. {
  2121. #ifdef _DEBUG
  2122. StringBuffer prevScope(iters.item(i).queryScope());
  2123. #endif
  2124. if (!iters.item(i).nextParent())
  2125. activeIterMask &= ~(1U << i);
  2126. #ifdef _DEBUG
  2127. checkScopeOrder(i, prevScope);
  2128. #endif
  2129. }
  2130. }
  2131. }
  2132. protected:
  2133. const WuScopeFilter & filter;
  2134. IArrayOf<IConstWUScopeIterator> iters;
  2135. unsigned curIter = 0;
  2136. unsigned firstMatchIter = 0;
  2137. unsigned matchIterMask = 0; // bit set of iterators which have a valid entry for the current scope
  2138. unsigned activeIterMask = 0; // bit set of iterators which are still active
  2139. StringArray activeScopes;
  2140. };
  2141. //---------------------------------------------------------------------------------------------------------------------
  2142. class AggregateFilter
  2143. {
  2144. public:
  2145. AggregateFilter(StatisticKind _search) : search(_search) {}
  2146. inline bool matches(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) const
  2147. {
  2148. return (kind == search);
  2149. }
  2150. protected:
  2151. StatisticKind search;
  2152. //MORE: Allow filtering by scope?
  2153. };
  2154. class StatisticAggregator : public CInterfaceOf<IWuScopeVisitor>
  2155. {
  2156. public:
  2157. StatisticAggregator(StatisticKind _search) : filter(_search) {}
  2158. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2159. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2160. virtual void noteException(IConstWUException & exception) { throwUnexpected();}
  2161. protected:
  2162. AggregateFilter filter;
  2163. };
  2164. class SimpleAggregator : public StatisticAggregator
  2165. {
  2166. public:
  2167. SimpleAggregator(StatisticKind _search) : StatisticAggregator(_search) {}
  2168. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2169. {
  2170. if (filter.matches(kind, value, extra))
  2171. summary.noteValue(value);
  2172. }
  2173. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2174. //with a noteAggregate(value, variant, value, grouping)?
  2175. protected:
  2176. StatsAggregation summary;
  2177. };
  2178. class SimpleReferenceAggregator : public StatisticAggregator
  2179. {
  2180. public:
  2181. SimpleReferenceAggregator(StatisticKind _search, StatsAggregation & _summary) : StatisticAggregator(_search), summary(_summary) {}
  2182. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2183. {
  2184. if (filter.matches(kind, value, extra))
  2185. summary.noteValue(value);
  2186. }
  2187. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2188. //with a noteAggregate(value, variant, value, grouping)?
  2189. protected:
  2190. StatsAggregation & summary;
  2191. };
  2192. class GroupedAggregator : public StatisticAggregator
  2193. {
  2194. public:
  2195. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2196. {
  2197. if (filter.matches(kind, value, extra))
  2198. {
  2199. StatsAggregation & match = summary; // look up in hash table.
  2200. match.noteValue(value);
  2201. }
  2202. }
  2203. protected:
  2204. //HashTable of (possible groupings->summary)
  2205. StatsAggregation summary;
  2206. };
  2207. class CompoundAggregator : implements StatisticAggregator
  2208. {
  2209. public:
  2210. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra)
  2211. {
  2212. ForEachItemIn(i, aggregators)
  2213. aggregators.item(i).noteStatistic(kind, value, extra);
  2214. }
  2215. protected:
  2216. IArrayOf<StatisticAggregator> aggregators;
  2217. };
  2218. // Aggregate costs excluding all hThor costs
  2219. // Note: the only reason that this class is required is that it is not possible to determine the creator
  2220. // of a scope when iterating with IConstWUScopeIterator. (When this functionlity becomes available,
  2221. // consider filtering within aggregateCost and eliminating this class.)
  2222. class CostAggregatorExcludeHThor : public CInterfaceOf<IWuScopeVisitor>
  2223. {
  2224. public:
  2225. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2226. {
  2227. if (extra.getCreatorType() != SCThthor)
  2228. totalCost += value;
  2229. }
  2230. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2231. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2232. virtual void noteException(IConstWUException & exception) { throwUnexpected(); }
  2233. virtual cost_type getTotalCost() const { return totalCost; }
  2234. protected:
  2235. cost_type totalCost = 0;
  2236. };
  2237. // Aggregrate Thor or hThor costs
  2238. cost_type aggregateCost(const IConstWorkUnit * wu, const char *scope, bool excludeHThor)
  2239. {
  2240. // depth 1: workflow, depth 2: graph, depth 3: subgraph
  2241. WuScopeFilter filter;
  2242. if (scope && *scope) // All costs under specified scope (used to calculate all costs for a workflow)
  2243. {
  2244. filter.addScope(scope);
  2245. filter.setIncludeNesting(3);
  2246. filter.addOutputStatistic(StCostExecute);
  2247. filter.addRequiredStat(StCostExecute);
  2248. }
  2249. else
  2250. filter.addFilter("stat[CostExecute],depth[1..3],nested[0],where[CostExecute]");
  2251. filter.addSource("global");
  2252. filter.finishedFilter();
  2253. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  2254. // Note: use of CostAggregatorExcludeHThor will be a slower, so use only when necessary
  2255. if (excludeHThor)
  2256. {
  2257. CostAggregatorExcludeHThor aggregator;
  2258. for (it->first(); it->isValid(); )
  2259. {
  2260. it->playProperties(aggregator);
  2261. stat_type value;
  2262. if (it->getStat(StCostExecute, value))
  2263. it->nextSibling();
  2264. else
  2265. it->next();
  2266. }
  2267. return aggregator.getTotalCost();
  2268. }
  2269. else
  2270. {
  2271. cost_type totalCost = 0;
  2272. for (it->first(); it->isValid(); )
  2273. {
  2274. stat_type value = 0.0;
  2275. if (it->getStat(StCostExecute, value))
  2276. {
  2277. totalCost += value;
  2278. it->nextSibling();
  2279. }
  2280. else
  2281. it->next();
  2282. }
  2283. return totalCost;
  2284. }
  2285. }
  2286. //---------------------------------------------------------------------------------------------------------------------
  2287. //Extract an argument of the format abc[def[ghi...,]],... as (abc,def[...])
  2288. static bool extractOption(const char * & finger, StringBuffer & option, StringBuffer & arg)
  2289. {
  2290. const char * start = finger;
  2291. if (!*start)
  2292. return false;
  2293. const char * cur = start;
  2294. const char * bra = nullptr;
  2295. const char * end = nullptr;
  2296. unsigned braDepth = 0;
  2297. char next;
  2298. arg.clear();
  2299. for (;;)
  2300. {
  2301. next = *cur;
  2302. if (!next || ((next == ',') && (braDepth == 0)))
  2303. break;
  2304. switch (next)
  2305. {
  2306. case '[':
  2307. if (braDepth == 0)
  2308. {
  2309. if (bra)
  2310. throw makeStringExceptionV(0, "Multiple [ in filter : %s", bra);
  2311. bra = cur;
  2312. }
  2313. braDepth++;
  2314. break;
  2315. case ']':
  2316. if (braDepth > 0)
  2317. {
  2318. if (--braDepth == 0)
  2319. {
  2320. end = cur;
  2321. arg.append(cur - (bra+1), bra+1);
  2322. }
  2323. }
  2324. break;
  2325. }
  2326. cur++;
  2327. }
  2328. if (braDepth != 0)
  2329. throw makeStringExceptionV(0, "Mismatched ] in filter : %s", start);
  2330. option.clear();
  2331. if (bra)
  2332. {
  2333. if (cur != end+1)
  2334. throw makeStringExceptionV(0, "Text follows closing bracket: %s", end);
  2335. option.append(bra-start, start);
  2336. }
  2337. else
  2338. option.append(cur-start, start);
  2339. if (next)
  2340. finger = cur+1;
  2341. else
  2342. finger = cur;
  2343. return true;
  2344. }
  2345. static unsigned readOptValue(const char * start, const char * end, unsigned dft, const char * type)
  2346. {
  2347. if (start == end)
  2348. return dft;
  2349. char * next;
  2350. unsigned value = (unsigned)strtoll(start, &next, 10);
  2351. if (next != end)
  2352. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2353. return value;
  2354. }
  2355. static unsigned readValue(const char * start, const char * type)
  2356. {
  2357. if (*start == '\0')
  2358. throw makeStringExceptionV(0, "Expected a value for the %s option", type);
  2359. char * next;
  2360. unsigned value = (unsigned)strtoll(start, &next, 10);
  2361. if (*next != '\0')
  2362. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2363. return value;
  2364. }
  2365. /*
  2366. Scope service matching Syntax: * indicates
  2367. Which items are matched:
  2368. scope[<scope-id>]* | stype[<scope-type>]* | id[<id>]* - which scopes should be matched?
  2369. depth[n | low..high] - range of depths to search for a match
  2370. source[global|stats|graph|all]* - which sources to search within the workunit
  2371. where[<statistickind> | <statistickind> (=|<|<=|>|>=) value | <statistickind>=low..high] - a statistic filter
  2372. Which items are include in the results:
  2373. matched[true|false] - are the matched scopes returned?
  2374. nested[<depth>|all] - how deep within a scope should be matched (default = 0 if matched[true], all if matched[false])
  2375. includetype[<scope-type>] - which scope types should be included?
  2376. Which properties of the items are returned:
  2377. properties[statistics|hints|attributes|scope|all]
  2378. statistic[<statistic-kind>|none|all] - include statistic
  2379. attribute[<attribute-name>|none|all] - include attribute
  2380. hint[<hint-name>] - include hint
  2381. property[<statistic-kind>|<attribute-name>|<hint-name>] - include property
  2382. measure[<measure>] - all statistics with a particular measure
  2383. version[<version>] - minimum version to return
  2384. */
  2385. enum { FOscope, FOstype, FOid, FOdepth, FOsource, FOwhere, FOmatched, FOnested, FOinclude, FOproperties, FOstatistic, FOattribute, FOhint, FOproperty, FOmeasure, FOversion, FOunknown };
  2386. //Some of the following contains aliases for the same option e.g. stat and statistic
  2387. static constexpr EnumMapping filterOptions[] = {
  2388. { FOscope, "scope" }, { FOstype, "stype" }, { FOid, "id" },
  2389. { FOdepth, "depth" }, { FOsource, "source" }, { FOwhere, "where" },
  2390. { FOmatched, "matched" }, { FOnested, "nested" },
  2391. { FOinclude, "include" }, { FOinclude, "includetype" },
  2392. { FOproperties, "props" }, { FOproperties, "properties" }, // some aliases
  2393. { FOstatistic, "stat" }, { FOstatistic, "statistic" }, { FOattribute, "attr" }, { FOattribute, "attribute" }, { FOhint, "hint" },
  2394. { FOproperty, "prop" }, { FOproperty, "property" },
  2395. { FOmeasure, "measure" }, { FOversion, "version" }, { 0, nullptr} };
  2396. static constexpr EnumMapping sourceMappings[] = {
  2397. { SSFsearchGlobalStats, "global" }, { SSFsearchGraphStats, "stats" }, { SSFsearchGraphStats, "statistics" }, { SSFsearchGraph, "graph" }, { SSFsearchExceptions, "exception" }, { SSFsearchWorkflow, "workflow" },
  2398. { (int)SSFsearchAll, "all" }, { 0, nullptr } };
  2399. static constexpr EnumMapping propertyMappings[] = {
  2400. { PTstatistics, "stat" }, { PTstatistics, "statistic" }, { PTattributes, "attr" }, { PTattributes, "attribute" }, { PThints, "hint" },{ PTnotes, "note" },
  2401. { PTstatistics, "stats" }, { PTstatistics, "statistics" }, { PTattributes, "attrs" }, { PTattributes, "attributes" }, { PThints, "hints" }, { PTnotes, "notes" },
  2402. { PTnone, "none" }, { PTscope, "scope" }, { PTall, "all" }, { 0, nullptr } };
  2403. WuScopeSourceFlags querySource(const char * source) { return (WuScopeSourceFlags)getEnum(source, sourceMappings, SSFunknown); }
  2404. const char * querySourceText(WuScopeSourceFlags source) { return getEnumText(source, sourceMappings, nullptr); }
  2405. WuScopeFilter::WuScopeFilter(const char * filter)
  2406. {
  2407. addFilter(filter);
  2408. finishedFilter();
  2409. }
  2410. WuScopeFilter & WuScopeFilter::addFilter(const char * filter)
  2411. {
  2412. if (!filter)
  2413. return *this;
  2414. StringBuffer option;
  2415. StringBuffer arg;
  2416. while (extractOption(filter, option, arg))
  2417. {
  2418. switch (getEnum(option, filterOptions, FOunknown))
  2419. {
  2420. case FOscope:
  2421. addScope(arg);
  2422. break;
  2423. case FOstype:
  2424. addScopeType(arg);
  2425. break;
  2426. case FOid:
  2427. addId(arg);
  2428. break;
  2429. case FOdepth:
  2430. {
  2431. //Allow depth[n], depth[a,b] or depth[a..b]
  2432. const char * comma = strchr(arg, ',');
  2433. const char * dotdot = strstr(arg, "..");
  2434. if (comma)
  2435. {
  2436. unsigned low = readOptValue(arg, comma, 0, "depth");
  2437. if (comma[1])
  2438. {
  2439. scopeFilter.setDepth(low, readValue(comma+1, "depth"));
  2440. }
  2441. else
  2442. scopeFilter.setDepth(low, UINT_MAX);
  2443. }
  2444. else if (dotdot)
  2445. {
  2446. unsigned low = readOptValue(arg, dotdot, 0, "depth");
  2447. if (dotdot[2])
  2448. scopeFilter.setDepth(low, readValue(dotdot+2, "depth"));
  2449. else
  2450. scopeFilter.setDepth(low, UINT_MAX);
  2451. }
  2452. else
  2453. {
  2454. scopeFilter.setDepth(readValue(arg, "depth"));
  2455. }
  2456. break;
  2457. }
  2458. case FOsource:
  2459. addSource(arg);
  2460. break;
  2461. case FOwhere: // where[stat<op>value]
  2462. addRequiredStat(arg);
  2463. break;
  2464. case FOmatched:
  2465. setIncludeMatch(strToBool(arg));
  2466. break;
  2467. case FOnested:
  2468. if (strieq(arg, "all"))
  2469. setIncludeNesting(UINT_MAX);
  2470. else if (isdigit(*arg))
  2471. setIncludeNesting(atoi(arg));
  2472. else
  2473. throw makeStringExceptionV(0, "Expected a value for the nesting depth: %s", arg.str());
  2474. break;
  2475. case FOinclude:
  2476. setIncludeScopeType(arg);
  2477. break;
  2478. case FOproperties:
  2479. {
  2480. WuPropertyTypes prop = (WuPropertyTypes)getEnum(arg, propertyMappings, PTunknown);
  2481. if (prop == PTunknown)
  2482. throw makeStringExceptionV(0, "Unexpected properties '%s'", arg.str());
  2483. addOutputProperties(prop);
  2484. break;
  2485. }
  2486. case FOstatistic:
  2487. addOutputStatistic(arg);
  2488. break;
  2489. case FOattribute:
  2490. addOutputAttribute(arg);
  2491. break;
  2492. case FOhint:
  2493. addOutputHint(arg);
  2494. break;
  2495. case FOproperty:
  2496. addOutput(arg);
  2497. break;
  2498. case FOmeasure:
  2499. setMeasure(arg);
  2500. break;
  2501. case FOversion:
  2502. if (isdigit(*arg))
  2503. minVersion = atoi64(arg);
  2504. else
  2505. throw makeStringExceptionV(0, "Expected a value for the version: %s", arg.str());
  2506. break;
  2507. default:
  2508. throw makeStringExceptionV(0, "Unrecognised filter option: %s", option.str());
  2509. }
  2510. }
  2511. return *this;
  2512. }
  2513. WuScopeFilter & WuScopeFilter::addScope(const char * scope)
  2514. {
  2515. if (scope)
  2516. {
  2517. validateScope(scope);
  2518. scopeFilter.addScope(scope);
  2519. }
  2520. return *this;
  2521. }
  2522. WuScopeFilter & WuScopeFilter::addScopeType(const char * scopeType)
  2523. {
  2524. if (scopeType)
  2525. {
  2526. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2527. if (sst == SSTmax)
  2528. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2529. scopeFilter.addScopeType(sst);
  2530. }
  2531. return *this;
  2532. }
  2533. WuScopeFilter & WuScopeFilter::addId(const char * id)
  2534. {
  2535. validateScopeId(id);
  2536. scopeFilter.addId(id);
  2537. return *this;
  2538. }
  2539. WuScopeFilter & WuScopeFilter::addOutput(const char * prop)
  2540. {
  2541. WuAttr attr = queryWuAttribute(prop, WaNone);
  2542. if (attr != WaNone)
  2543. {
  2544. WuAttr singleKindAttr = getSingleKindOfListAttribute(attr);
  2545. if (singleKindAttr != WaNone)
  2546. addOutputAttribute(singleKindAttr);
  2547. else
  2548. addOutputAttribute(attr);
  2549. } else if (queryStatisticKind(prop, StMax) != StMax)
  2550. addOutputStatistic(prop);
  2551. else
  2552. addOutputHint(prop);
  2553. return *this;
  2554. }
  2555. WuScopeFilter & WuScopeFilter::addOutputStatistic(const char * prop)
  2556. {
  2557. if (!prop)
  2558. return *this;
  2559. StatisticKind kind = queryStatisticKind(prop, StMax);
  2560. if (kind == StMax)
  2561. throw makeStringExceptionV(0, "Unrecognised statistic '%s'", prop);
  2562. return addOutputStatistic(kind);
  2563. }
  2564. WuScopeFilter & WuScopeFilter::addOutputStatistic(StatisticKind stat)
  2565. {
  2566. if (stat != StKindNone)
  2567. {
  2568. if (stat != StKindAll)
  2569. desiredStats.append(stat);
  2570. else
  2571. desiredStats.kill();
  2572. properties |= PTstatistics;
  2573. }
  2574. else
  2575. properties &= ~PTstatistics;
  2576. return *this;
  2577. }
  2578. WuScopeFilter & WuScopeFilter::addOutputAttribute(const char * prop)
  2579. {
  2580. if (!prop)
  2581. return *this;
  2582. WuAttr attr = queryWuAttribute(prop, WaMax);
  2583. if (attr == WaMax)
  2584. throw makeStringExceptionV(0, "Unrecognised attribute '%s'", prop);
  2585. return addOutputAttribute(attr);
  2586. }
  2587. WuScopeFilter & WuScopeFilter::addOutputAttribute(WuAttr attr)
  2588. {
  2589. if (attr != WaNone)
  2590. {
  2591. if (attr != WaAll)
  2592. desiredAttrs.append(attr);
  2593. else
  2594. desiredAttrs.kill();
  2595. properties |= PTattributes;
  2596. }
  2597. else
  2598. properties &= ~PTattributes;
  2599. return *this;
  2600. }
  2601. WuScopeFilter & WuScopeFilter::addOutputHint(const char * prop)
  2602. {
  2603. if (strieq(prop, "none"))
  2604. {
  2605. desiredHints.kill();
  2606. properties &= ~PThints;
  2607. }
  2608. else
  2609. {
  2610. if (!strieq(prop, "all"))
  2611. desiredHints.append(prop);
  2612. else
  2613. desiredHints.kill();
  2614. properties |= PThints;
  2615. }
  2616. return *this;
  2617. }
  2618. WuScopeFilter & WuScopeFilter::setIncludeMatch(bool value)
  2619. {
  2620. include.matchedScope = value;
  2621. return *this;
  2622. }
  2623. WuScopeFilter & WuScopeFilter::setIncludeNesting(unsigned depth)
  2624. {
  2625. include.nestedDepth = depth;
  2626. return *this;
  2627. }
  2628. WuScopeFilter & WuScopeFilter::setIncludeScopeType(const char * scopeType)
  2629. {
  2630. if (scopeType)
  2631. {
  2632. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2633. if (sst == SSTmax)
  2634. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2635. include.scopeTypes.append(sst);
  2636. }
  2637. return *this;
  2638. }
  2639. WuScopeFilter & WuScopeFilter::setMeasure(const char * measure)
  2640. {
  2641. if (measure)
  2642. {
  2643. desiredMeasure = queryMeasure(measure, SMeasureNone);
  2644. if (desiredMeasure == SMeasureNone)
  2645. throw makeStringExceptionV(0, "Unrecognised measure '%s'", measure);
  2646. properties |= PTstatistics;
  2647. }
  2648. return *this;
  2649. }
  2650. WuScopeFilter & WuScopeFilter::addOutputProperties(WuPropertyTypes mask)
  2651. {
  2652. if (properties == PTnone)
  2653. properties = mask;
  2654. else
  2655. properties |= mask;
  2656. return *this;
  2657. }
  2658. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue)
  2659. {
  2660. requiredStats.emplace_back(statKind, lowValue, highValue);
  2661. return *this;
  2662. }
  2663. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind)
  2664. {
  2665. requiredStats.emplace_back(statKind, 0, MaxStatisticValue);
  2666. return *this;
  2667. }
  2668. //process a filter in one of the following forms:
  2669. // <statistic-name>
  2670. // <statistic-name> (=|<|<=|>|>=) <value>
  2671. // <statistic-name>=[<low>]..[<high>]
  2672. void WuScopeFilter::addRequiredStat(const char * filter)
  2673. {
  2674. const char * stat = filter;
  2675. const char * cur = stat;
  2676. while (isalpha(*cur))
  2677. cur++;
  2678. StringBuffer statisticName(cur-stat, stat);
  2679. StatisticKind statKind = queryStatisticKind(statisticName, StKindNone);
  2680. if (statKind == StKindNone)
  2681. throw makeStringExceptionV(0, "Unknown statistic name '%s'", statisticName.str());
  2682. //Skip any spaces before a comparison operator.
  2683. while (*cur && isspace(*cur))
  2684. cur++;
  2685. //Save the operator, and skip over any non digits.
  2686. const char * op = cur;
  2687. switch (*op)
  2688. {
  2689. case '=':
  2690. cur++;
  2691. break;
  2692. case '<':
  2693. case '>':
  2694. if (op[1] == '=')
  2695. cur += 2;
  2696. else
  2697. cur++;
  2698. break;
  2699. case '\0':
  2700. break;
  2701. default:
  2702. throw makeStringExceptionV(0, "Unknown comparison '%s'", op);
  2703. }
  2704. const char * next;
  2705. stat_type value = readStatisticValue(cur, &next, queryMeasure(statKind));
  2706. stat_type lowValue = 0;
  2707. stat_type highValue = MaxStatisticValue;
  2708. switch (op[0])
  2709. {
  2710. case '=':
  2711. {
  2712. //Allow a,b or a..b to specify a range - either bound may be omitted.
  2713. if (next[0] == ',')
  2714. {
  2715. lowValue = value;
  2716. next++;
  2717. if (*next != '\0')
  2718. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2719. }
  2720. else if (strncmp(next, "..", 2) == 0)
  2721. {
  2722. lowValue = value;
  2723. next += 2;
  2724. if (*next != '\0')
  2725. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2726. }
  2727. else
  2728. {
  2729. lowValue = value;
  2730. highValue = value;
  2731. }
  2732. break;
  2733. }
  2734. case '<':
  2735. if (op[1] == '=')
  2736. highValue = value;
  2737. else
  2738. highValue = value-1;
  2739. break;
  2740. case '>':
  2741. if (op[1] == '=')
  2742. lowValue = value;
  2743. else
  2744. lowValue = value+1;
  2745. break;
  2746. }
  2747. if (*next)
  2748. throw makeStringExceptionV(0, "Trailing characters in where '%s'", next);
  2749. requiredStats.emplace_back(statKind, lowValue, highValue);
  2750. }
  2751. WuScopeFilter & WuScopeFilter::addSource(const char * source)
  2752. {
  2753. WuScopeSourceFlags mask = querySource(source);
  2754. if (mask == SSFunknown)
  2755. throw makeStringExceptionV(0, "Unexpected source '%s'", source);
  2756. if (!mask)
  2757. sourceFlags = mask;
  2758. else
  2759. sourceFlags |= mask;
  2760. return *this;
  2761. }
  2762. WuScopeFilter & WuScopeFilter::setDepth(unsigned low, unsigned high)
  2763. {
  2764. scopeFilter.setDepth(low, high);
  2765. return *this;
  2766. }
  2767. bool WuScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2768. {
  2769. //If there is a post filter on the scopeType, then check if it matches
  2770. if (include.scopeTypes.ordinality() == 1)
  2771. return (include.scopeTypes.item(0) == scopeType);
  2772. //If filter doesn't match nested items, then check if the scope filter matches.
  2773. if (include.nestedDepth == 0)
  2774. {
  2775. if (scopeFilter.matchOnly(scopeType))
  2776. return true;
  2777. }
  2778. return false;
  2779. }
  2780. //Called once the filter has been updated to optimize the filter
  2781. void WuScopeFilter::finishedFilter()
  2782. {
  2783. scopeFilter.finishedFilter();
  2784. assertex(!optimized);
  2785. optimized = true;
  2786. if ((include.nestedDepth == 0) && !include.matchedScope)
  2787. include.nestedDepth = UINT_MAX;
  2788. preFilterScope = include.matchedScope && (include.nestedDepth == 0);
  2789. if (scopeFilter.canAlwaysPreFilter())
  2790. preFilterScope = true;
  2791. //If the source flags have not been explicitly set then calculate which sources will provide the results
  2792. if (!sourceFlags)
  2793. {
  2794. sourceFlags = SSFsearchAll;
  2795. //Use the other options to reduce the number of elements that are searched.
  2796. //If not interested in scopes on their own then...
  2797. if (!(properties & PTscope))
  2798. {
  2799. //Global stats and graph stats only contain stats => remove if not interested in them
  2800. if (!(properties & PTstatistics))
  2801. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchGraphStats);
  2802. //graph, workflow only contains attributes and hints => remove if not interested
  2803. if (!(properties & (PTattributes|PThints)))
  2804. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2805. }
  2806. if (!(properties & PTnotes))
  2807. sourceFlags &= ~SSFsearchExceptions;
  2808. }
  2809. //Optimize sources if they haven't been explicitly specified
  2810. //Most of the following are dependent on internal knowledge of the way that information is represented
  2811. if (matchOnly(SSTworkflow))
  2812. {
  2813. //Workflow is not nested within a graph
  2814. sourceFlags &= ~(SSFsearchGraph|SSFsearchGraphStats);
  2815. setDepth(1, 1);
  2816. }
  2817. else if (matchOnly(SSTgraph))
  2818. {
  2819. //Graph starts are stored globally, not in the graph stats.
  2820. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchWorkflow);
  2821. if (!(properties & (PTattributes|PThints)))
  2822. sourceFlags &= ~(SSFsearchGraph);
  2823. //This should really be setDepth(2,2) but workunits prior to 7.4 did not have graph ids prefixed by the wfid
  2824. //Remove once 7.2 is a distant memory (see HPCC-22887)
  2825. setDepth(1, 2);
  2826. }
  2827. else if (matchOnly(SSTsubgraph))
  2828. {
  2829. sourceFlags &= ~(SSFsearchWorkflow);
  2830. }
  2831. else if (matchOnly(SSTcompilestage))
  2832. {
  2833. //compile stages are not stored in the graph
  2834. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchGraph|SSFsearchWorkflow);
  2835. }
  2836. else if (matchOnly(SSTactivity))
  2837. {
  2838. //information about activities is not stored globally
  2839. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchWorkflow);
  2840. }
  2841. // Everything stored in the graphs stats has a depth of 3 or more - so ignore if there are not matches in that depth
  2842. if (include.nestedDepth == 0)
  2843. {
  2844. if (scopeFilter.compareDepth(3) > 0) // 3 is larger than any scope in the filter
  2845. sourceFlags &= ~(SSFsearchGraphStats);
  2846. else if (scopeFilter.compareDepth(3) == 0) // 3 matches the maximum scope in the filter
  2847. {
  2848. //Subgraph WhenStarted and TimeElapsed are stored globally. If that is all that is required
  2849. //then do not include the subgraph timings
  2850. if (desiredStats.ordinality())
  2851. {
  2852. bool needGraphStats = false;
  2853. ForEachItemIn(i, desiredStats)
  2854. {
  2855. unsigned stat = desiredStats.item(i);
  2856. if ((stat != StWhenStarted) && (stat != StTimeElapsed))
  2857. needGraphStats = true;
  2858. }
  2859. if (!needGraphStats)
  2860. {
  2861. sourceFlags &= ~(SSFsearchGraphStats);
  2862. if (matchOnly(SSTsubgraph))
  2863. sourceFlags &= SSFsearchGlobalStats;
  2864. }
  2865. }
  2866. }
  2867. }
  2868. if (scopeFilter.compareDepth(1) < 0)
  2869. {
  2870. //If minimum match depth is > 1 then it will never match workflow
  2871. sourceFlags &= ~(SSFsearchWorkflow);
  2872. }
  2873. //The xml graph is never updated, so do not check it if minVersion != 0
  2874. if (minVersion != 0)
  2875. {
  2876. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2877. }
  2878. }
  2879. bool WuScopeFilter::includeStatistic(StatisticKind kind) const
  2880. {
  2881. if (!(properties & PTstatistics))
  2882. return false;
  2883. if ((desiredMeasure != SMeasureAll) && (queryMeasure(kind) != desiredMeasure))
  2884. return false;
  2885. if (desiredStats.empty())
  2886. return true;
  2887. return desiredStats.contains(kind);
  2888. }
  2889. bool WuScopeFilter::includeAttribute(WuAttr attr) const
  2890. {
  2891. if (!(properties & PTattributes))
  2892. return false;
  2893. if (desiredAttrs.empty())
  2894. return true;
  2895. return desiredAttrs.contains(attr);
  2896. }
  2897. bool WuScopeFilter::includeHint(const char * kind) const
  2898. {
  2899. if (!(properties & PThints))
  2900. return false;
  2901. if (desiredHints.empty())
  2902. return true;
  2903. return desiredHints.contains(kind);
  2904. }
  2905. bool WuScopeFilter::includeScope(const char * scope) const
  2906. {
  2907. if (include.scopeTypes)
  2908. {
  2909. const char * tail = queryScopeTail(scope);
  2910. StatsScopeId id(tail);
  2911. if (!include.scopeTypes.contains(id.queryScopeType()))
  2912. return false;
  2913. }
  2914. return true;
  2915. }
  2916. const static ScopeFilter nullScopeFilter {};
  2917. const ScopeFilter & WuScopeFilter::queryIterFilter() const
  2918. {
  2919. if (preFilterScope)
  2920. return scopeFilter;
  2921. else
  2922. return nullScopeFilter;
  2923. }
  2924. ScopeCompare WuScopeFilter::compareMatchScopes(const char * scope) const
  2925. {
  2926. return scopeFilter.compare(scope);
  2927. }
  2928. StringBuffer & WuScopeFilter::describe(StringBuffer & out) const
  2929. {
  2930. scopeFilter.describe(out);
  2931. if (requiredStats.size())
  2932. {
  2933. out.append(",where[");
  2934. bool first = false;
  2935. for (const auto & stat : requiredStats)
  2936. {
  2937. if (!first)
  2938. out.append(",");
  2939. stat.describe(out);
  2940. first = false;
  2941. }
  2942. out.append("]");
  2943. }
  2944. {
  2945. StringBuffer sources;
  2946. for (unsigned mask=1; mask; mask *= 2)
  2947. {
  2948. if (sourceFlags & mask)
  2949. {
  2950. const char * source = querySourceText((WuScopeSourceFlags)mask);
  2951. if (source)
  2952. sources.append(",").append(source);
  2953. }
  2954. }
  2955. if (sources)
  2956. out.append(",source[").append(sources.str()+1).append("]");
  2957. }
  2958. if (include.nestedDepth != UINT_MAX)
  2959. out.appendf(",nested[%u]", include.nestedDepth);
  2960. if (include.scopeTypes)
  2961. {
  2962. out.append(",include[");
  2963. ForEachItemIn(i, include.scopeTypes)
  2964. {
  2965. if (i)
  2966. out.append(",");
  2967. out.append(queryScopeTypeName((StatisticScopeType)include.scopeTypes.item(i)));
  2968. }
  2969. out.append("]");
  2970. }
  2971. {
  2972. StringBuffer props;
  2973. if (properties == PTnone)
  2974. props.append(",none");
  2975. else if (properties == PTall)
  2976. props.append(",all");
  2977. else
  2978. {
  2979. if (properties & PTstatistics)
  2980. props.append(",stat");
  2981. if (properties & PTattributes)
  2982. props.append(",attr");
  2983. if (properties & PThints)
  2984. props.append(",hint");
  2985. if (properties & PTscope)
  2986. props.append(",scope");
  2987. if (properties & PTnotes)
  2988. props.append(",note");
  2989. }
  2990. out.append(",properties[").append(props.str()+1).append("]");
  2991. }
  2992. if (desiredStats)
  2993. {
  2994. out.append(",stat[");
  2995. ForEachItemIn(i, desiredStats)
  2996. {
  2997. if (i)
  2998. out.append(",");
  2999. out.append(queryStatisticName((StatisticKind)desiredStats.item(i)));
  3000. }
  3001. out.append("]");
  3002. }
  3003. if (desiredAttrs)
  3004. {
  3005. out.append(",attr[");
  3006. ForEachItemIn(i, desiredAttrs)
  3007. {
  3008. if (i)
  3009. out.append(",");
  3010. out.append(queryWuAttributeName((WuAttr)desiredAttrs.item(i)));
  3011. }
  3012. out.append("]");
  3013. }
  3014. if (desiredHints)
  3015. {
  3016. out.append(",hint[");
  3017. ForEachItemIn(i, desiredHints)
  3018. {
  3019. if (i)
  3020. out.append(",");
  3021. out.append(desiredHints.item(i));
  3022. }
  3023. out.append("]");
  3024. }
  3025. if (desiredMeasure != SMeasureAll)
  3026. out.append(",measure[").append(queryMeasureName(desiredMeasure)).append("]");
  3027. if (minVersion != 0)
  3028. out.appendf(",version(%" I64F "u)", minVersion);
  3029. return out;
  3030. }
  3031. //--------------------------------------------------------------------------------------------------------------------
  3032. EnumMapping states[] = {
  3033. { WUStateUnknown, "unknown" },
  3034. { WUStateCompiled, "compiled" },
  3035. { WUStateRunning, "running" },
  3036. { WUStateCompleted, "completed" },
  3037. { WUStateFailed, "failed" },
  3038. { WUStateArchived, "archived" },
  3039. { WUStateAborting, "aborting" },
  3040. { WUStateAborted, "aborted" },
  3041. { WUStateBlocked, "blocked" },
  3042. { WUStateSubmitted, "submitted" },
  3043. { WUStateScheduled, "scheduled" },
  3044. { WUStateCompiling, "compiling" },
  3045. { WUStateWait, "wait" },
  3046. { WUStateUploadingFiles, "uploading_files" },
  3047. { WUStateDebugPaused, "debugging" },
  3048. { WUStateDebugRunning, "debug_running" },
  3049. { WUStatePaused, "paused" },
  3050. { WUStateSize, NULL }
  3051. };
  3052. EnumMapping actions[] = {
  3053. { WUActionUnknown, "unknown" },
  3054. { WUActionCompile, "compile" },
  3055. { WUActionCheck, "check" },
  3056. { WUActionRun, "run" },
  3057. { WUActionExecuteExisting, "execute" },
  3058. { WUActionPause, "pause" },
  3059. { WUActionPauseNow, "pausenow" },
  3060. { WUActionResume, "resume" },
  3061. { WUActionSize, NULL },
  3062. };
  3063. EnumMapping priorityClasses[] = {
  3064. { PriorityClassUnknown, "unknown" },
  3065. { PriorityClassLow, "low" },
  3066. { PriorityClassNormal, "normal" },
  3067. { PriorityClassHigh, "high" },
  3068. { PriorityClassSize, NULL },
  3069. };
  3070. const char * getWorkunitStateStr(WUState state)
  3071. {
  3072. dbgassertex(state < WUStateSize);
  3073. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  3074. }
  3075. void setEnum(IPropertyTree *p, const char *propname, int value, const EnumMapping *map)
  3076. {
  3077. const char *defval = map->str;
  3078. while (map->str)
  3079. {
  3080. if (value==map->val)
  3081. {
  3082. p->setProp(propname, map->str);
  3083. return;
  3084. }
  3085. map++;
  3086. }
  3087. assertex(!"Unexpected value in setEnum");
  3088. p->setProp(propname, defval);
  3089. }
  3090. static int getEnum(const IPropertyTree *p, const char *propname, const EnumMapping *map)
  3091. {
  3092. return getEnum(p->queryProp(propname),map);
  3093. }
  3094. const char * getWorkunitActionStr(WUAction action)
  3095. {
  3096. return getEnumText(action, actions);
  3097. }
  3098. WUAction getWorkunitAction(const char *actionStr)
  3099. {
  3100. return (WUAction) getEnum(actionStr, actions);
  3101. }
  3102. //==========================================================================================
  3103. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  3104. {
  3105. public:
  3106. CLightweightWorkunitInfo(IPropertyTree &p)
  3107. {
  3108. wuid.set(p.queryName());
  3109. user.set(p.queryProp("@submitID"));
  3110. jobName.set(p.queryProp("@jobName"));
  3111. clusterName.set(p.queryProp("@clusterName"));
  3112. timeScheduled.set(p.queryProp("@timeScheduled"));
  3113. state = (WUState) getEnum(&p, "@state", states);
  3114. action = (WUAction) getEnum(&p, "Action", actions);
  3115. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  3116. priorityLevel = calcPriorityValue(&p);
  3117. wuscope.set(p.queryProp("@scope"));
  3118. appvalues.loadBranch(&p,"Application");
  3119. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  3120. _isProtected = p.getPropBool("@protected", false);
  3121. }
  3122. virtual const char *queryWuid() const { return wuid.str(); }
  3123. virtual const char *queryUser() const { return user.str(); }
  3124. virtual const char *queryJobName() const { return jobName.str(); }
  3125. virtual const char *queryClusterName() const { return clusterName.str(); }
  3126. virtual const char *queryWuScope() const { return wuscope.str(); }
  3127. virtual WUState getState() const { return state; }
  3128. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  3129. virtual WUAction getAction() const { return action; }
  3130. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  3131. virtual WUPriorityClass getPriority() const { return priority; }
  3132. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  3133. virtual int getPriorityLevel() const { return priorityLevel; }
  3134. virtual bool isProtected() const { return _isProtected; }
  3135. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  3136. {
  3137. if (timeScheduled.length())
  3138. val.setGmtString(timeScheduled.str());
  3139. return val;
  3140. }
  3141. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  3142. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  3143. protected:
  3144. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  3145. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  3146. unsigned totalThorTime;
  3147. WUState state;
  3148. WUAction action;
  3149. WUPriorityClass priority;
  3150. int priorityLevel;
  3151. bool _isProtected;
  3152. };
  3153. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  3154. {
  3155. return new CLightweightWorkunitInfo(p);
  3156. }
  3157. class CDaliWuGraphStats : public CWuGraphStats
  3158. {
  3159. public:
  3160. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, unsigned _wfid, const char * _rootScope, unsigned _id)
  3161. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _wfid, _rootScope, _id), conn(_conn)
  3162. {
  3163. }
  3164. protected:
  3165. Owned<IRemoteConnection> conn;
  3166. };
  3167. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  3168. {
  3169. abortId = 0;
  3170. stateId = 0;
  3171. actionId = 0;
  3172. assertex((flags & ~SubscribeOptionAbort) == 0);
  3173. if (flags & SubscribeOptionAbort)
  3174. {
  3175. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  3176. abortId = querySDS().subscribe(xpath.str(), *this, false, true);
  3177. }
  3178. }
  3179. CWorkUnitWatcher::~CWorkUnitWatcher()
  3180. {
  3181. assertex(abortId==0 && stateId==0 && actionId==0);
  3182. }
  3183. void CWorkUnitWatcher::unsubscribe()
  3184. {
  3185. CriticalBlock b(crit);
  3186. if (abortId)
  3187. querySDS().unsubscribe(abortId);
  3188. if (stateId)
  3189. querySDS().unsubscribe(stateId);
  3190. if (actionId)
  3191. querySDS().unsubscribe(actionId);
  3192. abortId = 0;
  3193. stateId = 0;
  3194. actionId = 0;
  3195. }
  3196. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  3197. {
  3198. CriticalBlock b(crit);
  3199. if (id==stateId)
  3200. subscriber->notify(SubscribeOptionState, valueLen, valueData);
  3201. else if (id==actionId)
  3202. subscriber->notify(SubscribeOptionAction, valueLen, valueData);
  3203. else if (id==abortId)
  3204. subscriber->notify(SubscribeOptionAbort, valueLen, valueData);
  3205. }
  3206. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  3207. {
  3208. public:
  3209. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  3210. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  3211. {
  3212. if (flags & SubscribeOptionState)
  3213. {
  3214. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  3215. stateId = querySDS().subscribe(xpath.str(), *this);
  3216. }
  3217. if (flags & SubscribeOptionAction)
  3218. {
  3219. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  3220. actionId = querySDS().subscribe(xpath.str(), *this);
  3221. }
  3222. }
  3223. };
  3224. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  3225. {
  3226. CriticalBlock block(crit);
  3227. assertex(options==SubscribeOptionAbort);
  3228. if (!abortWatcher)
  3229. {
  3230. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  3231. abortDirty = true;
  3232. }
  3233. }
  3234. void CPersistedWorkUnit::unsubscribe()
  3235. {
  3236. CriticalBlock block(crit);
  3237. if (abortWatcher)
  3238. {
  3239. abortWatcher->unsubscribe();
  3240. abortWatcher.clear();
  3241. }
  3242. }
  3243. bool CPersistedWorkUnit::aborting() const
  3244. {
  3245. CriticalBlock block(crit);
  3246. if (abortDirty)
  3247. {
  3248. StringBuffer apath;
  3249. apath.append("/WorkUnitAborts/").append(p->queryName());
  3250. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  3251. if (acon)
  3252. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  3253. else
  3254. abortState = false;
  3255. abortDirty = false;
  3256. }
  3257. return abortState;
  3258. }
  3259. class CDaliWorkUnit : public CPersistedWorkUnit
  3260. {
  3261. public:
  3262. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  3263. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  3264. {
  3265. loadPTree(connection->getRoot());
  3266. }
  3267. ~CDaliWorkUnit()
  3268. {
  3269. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  3270. // We use the beforeDispose() in base class to help ensure this
  3271. p.clear();
  3272. }
  3273. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  3274. {
  3275. Owned<IRemoteConnection> conn = getProgressConnection();
  3276. if (conn)
  3277. {
  3278. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3279. if (progress)
  3280. return new CConstGraphProgress(p->queryName(), graphName, progress);
  3281. }
  3282. return NULL;
  3283. }
  3284. virtual WUGraphState queryGraphState(const char *graphName) const
  3285. {
  3286. Owned<IRemoteConnection> conn = getProgressConnection();
  3287. if (conn)
  3288. {
  3289. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3290. if (progress)
  3291. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  3292. }
  3293. return WUGraphUnknown;
  3294. }
  3295. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3296. {
  3297. Owned<IRemoteConnection> conn = getProgressConnection();
  3298. if (conn)
  3299. {
  3300. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3301. if (progress)
  3302. {
  3303. StringBuffer path;
  3304. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3305. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  3306. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  3307. }
  3308. }
  3309. return WUGraphUnknown;
  3310. }
  3311. virtual void clearGraphProgress() const
  3312. {
  3313. CriticalBlock block(crit);
  3314. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3315. StringBuffer path("/GraphProgress/");
  3316. path.append(p->queryName());
  3317. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  3318. if (delconn)
  3319. delconn->close(true);
  3320. }
  3321. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3322. {
  3323. Owned<IRemoteConnection> conn = getProgressConnection();
  3324. if (!conn)
  3325. return false;
  3326. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  3327. if (name)
  3328. {
  3329. graphName.set(name);
  3330. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  3331. return true;
  3332. }
  3333. else
  3334. return false;
  3335. }
  3336. virtual void forceReload()
  3337. {
  3338. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  3339. CriticalBlock block(crit);
  3340. clearCached(true);
  3341. connection->reload();
  3342. progressConnection.clear();
  3343. abortDirty = true;
  3344. p.setown(connection->getRoot());
  3345. }
  3346. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3347. {
  3348. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  3349. clearGraphProgress();
  3350. connection->close(true);
  3351. connection.clear();
  3352. }
  3353. virtual void commit()
  3354. {
  3355. CPersistedWorkUnit::commit();
  3356. if (connection)
  3357. connection->commit();
  3358. }
  3359. virtual void _lockRemote()
  3360. {
  3361. StringBuffer wuRoot;
  3362. getXPath(wuRoot, p->queryName());
  3363. if (connection)
  3364. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  3365. else
  3366. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  3367. if (!connection)
  3368. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  3369. clearCached(true);
  3370. p.setown(connection->getRoot());
  3371. }
  3372. virtual void _unlockRemote()
  3373. {
  3374. if (connection)
  3375. {
  3376. try
  3377. {
  3378. try
  3379. {
  3380. connection->commit();
  3381. }
  3382. catch (IException *e)
  3383. {
  3384. EXCLOG(e, "Error during workunit commit");
  3385. connection->rollback();
  3386. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3387. throw;
  3388. }
  3389. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3390. }
  3391. catch (IException *E)
  3392. {
  3393. StringBuffer s;
  3394. IERRLOG("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  3395. throw;
  3396. }
  3397. }
  3398. }
  3399. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3400. {
  3401. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName, wfid);
  3402. conn->queryRoot()->setPropInt("@_state", state);
  3403. }
  3404. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3405. {
  3406. CriticalBlock block(crit);
  3407. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3408. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3409. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3410. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  3411. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3412. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  3413. IPropertyTree *node = progress->queryPropTree(path.str());
  3414. if (!node)
  3415. {
  3416. node = progress->addPropTree("node");
  3417. node->setPropInt64("@id", nodeId);
  3418. }
  3419. node->setPropInt("@_state", (unsigned)state);
  3420. switch (state)
  3421. {
  3422. case WUGraphRunning:
  3423. {
  3424. IPropertyTree *running = conn->queryRoot()->setPropTree("Running");
  3425. running->setProp("@graph", graphName);
  3426. running->setPropInt64("@subId", nodeId);
  3427. break;
  3428. }
  3429. case WUGraphComplete:
  3430. {
  3431. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  3432. break;
  3433. }
  3434. }
  3435. }
  3436. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3437. {
  3438. return new CDaliWuGraphStats(getWritableProgressConnection(graphName, _wfid), creatorType, creator, _wfid, graphName, subgraph);
  3439. }
  3440. protected:
  3441. IRemoteConnection *getProgressConnection() const
  3442. {
  3443. CriticalBlock block(crit);
  3444. if (!progressConnection)
  3445. {
  3446. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3447. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  3448. }
  3449. return progressConnection.getLink();
  3450. }
  3451. IRemoteConnection *getWritableProgressConnection(const char *graphName, unsigned wfid) const
  3452. {
  3453. CriticalBlock block(crit);
  3454. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  3455. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  3456. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3457. IPropertyTree * root = conn->queryRoot();
  3458. assertex(wfid);
  3459. if (!root->hasProp("@wfid"))
  3460. {
  3461. root->setPropInt("@wfid", wfid);
  3462. }
  3463. else
  3464. {
  3465. //Ideally the following code would check that the wfids are passed consistently.
  3466. //However there is an obscure problem with out of line functions being called from multiple workflow
  3467. //ids, and possibly library graphs.
  3468. //Stats for library graphs should be nested below the library call activity
  3469. //assertex(root->getPropInt("@wfid", 0) == wfid); // check that wfid is passed consistently
  3470. }
  3471. return conn.getClear();
  3472. }
  3473. IPropertyTree *getGraphProgressTree() const
  3474. {
  3475. Owned<IRemoteConnection> conn = getProgressConnection();
  3476. if (conn)
  3477. {
  3478. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  3479. mergePTree(tmp,conn->queryRoot());
  3480. return tmp.getClear();
  3481. }
  3482. return NULL;
  3483. }
  3484. Owned<IRemoteConnection> connection;
  3485. mutable Owned<IRemoteConnection> progressConnection;
  3486. };
  3487. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  3488. {
  3489. public:
  3490. Owned<CLocalWorkUnit> c;
  3491. IMPLEMENT_IINTERFACE;
  3492. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  3493. ~CLockedWorkUnit()
  3494. {
  3495. if (workUnitTraceLevel > 1)
  3496. DBGLOG("Releasing locked workunit %s", queryWuid());
  3497. if (c)
  3498. c->unlockRemote();
  3499. }
  3500. virtual IConstWorkUnit * unlock()
  3501. {
  3502. c->unlockRemote();
  3503. return c.getClear();
  3504. }
  3505. virtual bool aborting() const
  3506. { return c->aborting(); }
  3507. virtual void forceReload()
  3508. { }
  3509. virtual WUAction getAction() const
  3510. { return c->getAction(); }
  3511. virtual const char *queryActionDesc() const
  3512. { return c->queryActionDesc(); }
  3513. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  3514. { return c->getApplicationValue(application, propname, str); }
  3515. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  3516. { return c->getApplicationValueInt(application, propname, defVal); }
  3517. virtual IConstWUAppValueIterator & getApplicationValues() const
  3518. { return c->getApplicationValues(); }
  3519. virtual bool hasWorkflow() const
  3520. { return c->hasWorkflow(); }
  3521. virtual unsigned queryEventScheduledCount() const
  3522. { return c->queryEventScheduledCount(); }
  3523. virtual IPropertyTree * queryWorkflowTree() const
  3524. { return c->queryWorkflowTree(); }
  3525. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  3526. { return c->getWorkflowItems(); }
  3527. virtual IWorkflowItemArray * getWorkflowClone() const
  3528. { return c->getWorkflowClone(); }
  3529. virtual bool requiresLocalFileUpload() const
  3530. { return c->requiresLocalFileUpload(); }
  3531. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  3532. { return c->getLocalFileUploads(); }
  3533. virtual bool getIsQueryService() const
  3534. { return c->getIsQueryService(); }
  3535. virtual bool getCloneable() const
  3536. { return c->getCloneable(); }
  3537. virtual IUserDescriptor * queryUserDescriptor() const
  3538. { return c->queryUserDescriptor(); }
  3539. virtual const char *queryClusterName() const
  3540. { return c->queryClusterName(); }
  3541. virtual unsigned getCodeVersion() const
  3542. { return c->getCodeVersion(); }
  3543. virtual unsigned getWuidVersion() const
  3544. { return c->getWuidVersion(); }
  3545. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3546. { c->getBuildVersion(buildVersion, eclVersion); }
  3547. virtual bool hasDebugValue(const char * propname) const
  3548. { return c->hasDebugValue(propname); }
  3549. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  3550. { return c->getDebugValue(propname, str); }
  3551. virtual int getDebugValueInt(const char * propname, int defVal) const
  3552. { return c->getDebugValueInt(propname, defVal); }
  3553. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  3554. { return c->getDebugValueInt64(propname, defVal); }
  3555. virtual double getDebugValueReal(const char * propname, double defVal) const
  3556. { return c->getDebugValueReal(propname, defVal); }
  3557. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  3558. { return c->getDebugValueBool(propname, defVal); }
  3559. virtual IStringIterator & getDebugValues() const
  3560. { return c->getDebugValues(NULL); }
  3561. virtual IStringIterator & getDebugValues(const char *prop) const
  3562. { return c->getDebugValues(prop); }
  3563. virtual unsigned getExceptionCount() const
  3564. { return c->getExceptionCount(); }
  3565. virtual IConstWUExceptionIterator & getExceptions() const
  3566. { return c->getExceptions(); }
  3567. virtual unsigned getGraphCount() const
  3568. { return c->getGraphCount(); }
  3569. virtual unsigned getSourceFileCount() const
  3570. { return c->getSourceFileCount(); }
  3571. virtual unsigned getResultCount() const
  3572. { return c->getResultCount(); }
  3573. virtual unsigned getVariableCount() const
  3574. { return c->getVariableCount(); }
  3575. virtual unsigned getApplicationValueCount() const
  3576. { return c->getApplicationValueCount(); }
  3577. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  3578. { return c->getGraphs(type); }
  3579. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  3580. { return c->getGraphsMeta(type); }
  3581. virtual IConstWUGraph * getGraph(const char *name) const
  3582. { return c->getGraph(name); }
  3583. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  3584. { return c->getGraphProgress(name); }
  3585. virtual const char *queryJobName() const
  3586. { return c->queryJobName(); }
  3587. virtual IConstWUPlugin * getPluginByName(const char * name) const
  3588. { return c->getPluginByName(name); }
  3589. virtual IConstWUPluginIterator & getPlugins() const
  3590. { return c->getPlugins(); }
  3591. virtual IConstWULibrary* getLibraryByName(const char *name) const
  3592. { return c->getLibraryByName(name); }
  3593. virtual IConstWULibraryIterator & getLibraries() const
  3594. { return c->getLibraries(); }
  3595. virtual WUPriorityClass getPriority() const
  3596. { return c->getPriority(); }
  3597. virtual const char *queryPriorityDesc() const
  3598. { return c->queryPriorityDesc(); }
  3599. virtual int getPriorityLevel() const
  3600. { return c->getPriorityLevel(); }
  3601. virtual int getPriorityValue() const
  3602. { return c->getPriorityValue(); }
  3603. virtual IConstWUQuery * getQuery() const
  3604. { return c->getQuery(); }
  3605. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  3606. { return c->getWebServicesInfo(); }
  3607. virtual bool getRescheduleFlag() const
  3608. { return c->getRescheduleFlag(); }
  3609. virtual IConstWUResult * getResultByName(const char * name) const
  3610. { return c->getResultByName(name); }
  3611. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  3612. { return c->getResultBySequence(seq); }
  3613. virtual IConstWUResult * getQueryResultByName(const char * name) const
  3614. { return c->getQueryResultByName(name); }
  3615. virtual unsigned getResultLimit() const
  3616. { return c->getResultLimit(); }
  3617. virtual IConstWUResultIterator & getResults() const
  3618. { return c->getResults(); }
  3619. virtual IStringVal & getScope(IStringVal & str) const
  3620. { return c->getScope(str); }
  3621. virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & str) const
  3622. { return c->getWorkunitDistributedAccessToken(str); }
  3623. virtual WUState getState() const
  3624. { return c->getState(); }
  3625. virtual IStringVal & getStateEx(IStringVal & str) const
  3626. { return c->getStateEx(str); }
  3627. virtual __int64 getAgentSession() const
  3628. { return c->getAgentSession(); }
  3629. virtual unsigned getAgentPID() const
  3630. { return c->getAgentPID(); }
  3631. virtual const char *queryStateDesc() const
  3632. { return c->queryStateDesc(); }
  3633. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  3634. { return c->getRunningGraph(graphName, subId); }
  3635. virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const override
  3636. { return c->getScopeIterator(filter); }
  3637. virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const override
  3638. { return c->getStatistic(value, scope, kind); }
  3639. virtual IStringVal & getSnapshot(IStringVal & str) const
  3640. { return c->getSnapshot(str); }
  3641. virtual const char *queryUser() const
  3642. { return c->queryUser(); }
  3643. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  3644. { return c->getWarningSeverity(code, defaultSeverity); }
  3645. virtual const char *queryWuScope() const
  3646. { return c->queryWuScope(); }
  3647. virtual const char *queryWuid() const
  3648. { return c->queryWuid(); }
  3649. virtual IConstWUResult * getGlobalByName(const char * name) const
  3650. { return c->getGlobalByName(name); }
  3651. virtual IConstWUResult * getTemporaryByName(const char * name) const
  3652. { return c->getTemporaryByName(name); }
  3653. virtual IConstWUResultIterator & getTemporaries() const
  3654. { return c->getTemporaries(); }
  3655. virtual IConstWUResult * getVariableByName(const char * name) const
  3656. { return c->getVariableByName(name); }
  3657. virtual IConstWUResultIterator & getVariables() const
  3658. { return c->getVariables(); }
  3659. virtual bool isProtected() const
  3660. { return c->isProtected(); }
  3661. virtual bool isPausing() const
  3662. { return c->isPausing(); }
  3663. virtual IWorkUnit & lock()
  3664. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  3665. virtual bool reload()
  3666. { UNIMPLEMENTED; }
  3667. virtual void subscribe(WUSubscribeOptions options)
  3668. { c->subscribe(options); }
  3669. virtual void requestAbort()
  3670. { c->requestAbort(); }
  3671. virtual unsigned calculateHash(unsigned prevHash)
  3672. { return queryExtendedWU(c)->calculateHash(prevHash); }
  3673. virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  3674. { queryExtendedWU(c)->copyWorkUnit(cached, copyStats, all); }
  3675. virtual IPropertyTree *queryPTree() const
  3676. { return queryExtendedWU(c)->queryPTree(); }
  3677. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  3678. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  3679. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  3680. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  3681. virtual unsigned queryFileUsage(const char *filename) const
  3682. { return c->queryFileUsage(filename); }
  3683. virtual IConstWUFileUsageIterator * getFieldUsage() const
  3684. { return c->getFieldUsage(); }
  3685. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  3686. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  3687. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  3688. { return c->getTimeScheduled(val); }
  3689. virtual unsigned getDebugAgentListenerPort() const
  3690. { return c->getDebugAgentListenerPort(); }
  3691. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  3692. { return c->getDebugAgentListenerIP(ip); }
  3693. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  3694. { return c->getXmlParams(params, hidePasswords); }
  3695. virtual const IPropertyTree *getXmlParams() const
  3696. { return c->getXmlParams(); }
  3697. virtual unsigned __int64 getHash() const
  3698. { return c->getHash(); }
  3699. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  3700. { return c->getLogs(type, instance); }
  3701. virtual IStringIterator *getProcesses(const char *type) const
  3702. { return c->getProcesses(type); }
  3703. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  3704. { return c->getProcesses(type, instance); }
  3705. virtual unsigned getTotalThorTime() const
  3706. { return c->getTotalThorTime(); }
  3707. virtual WUGraphState queryGraphState(const char *graphName) const
  3708. { return c->queryGraphState(graphName); }
  3709. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3710. { return c->queryNodeState(graphName, nodeId); }
  3711. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3712. { c->setGraphState(graphName, wfid, state); }
  3713. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3714. { c->setNodeState(graphName, nodeId, state); }
  3715. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3716. { return c->updateStats(graphName, creatorType, creator, _wfid, subgraph); }
  3717. virtual void clearGraphProgress() const
  3718. { c->clearGraphProgress(); }
  3719. virtual IStringVal & getAbortBy(IStringVal & str) const
  3720. { return c->getAbortBy(str); }
  3721. virtual unsigned __int64 getAbortTimeStamp() const
  3722. { return c->getAbortTimeStamp(); }
  3723. virtual void clearExceptions(const char *source=nullptr)
  3724. { c->clearExceptions(source); }
  3725. virtual void commit()
  3726. { c->commit(); }
  3727. virtual IWUException * createException()
  3728. { return c->createException(); }
  3729. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  3730. { c->addProcess(type, instance, pid, log); }
  3731. virtual void protect(bool protectMode)
  3732. { c->protect(protectMode); }
  3733. virtual void setAction(WUAction action)
  3734. { c->setAction(action); }
  3735. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  3736. { c->setApplicationValue(application, propname, value, overwrite); }
  3737. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  3738. { c->setApplicationValueInt(application, propname, value, overwrite); }
  3739. virtual void incEventScheduledCount()
  3740. { c->incEventScheduledCount(); }
  3741. virtual void setIsQueryService(bool value)
  3742. { c->setIsQueryService(value); }
  3743. virtual void setCloneable(bool value)
  3744. { c->setCloneable(value); }
  3745. virtual void setIsClone(bool value)
  3746. { c->setIsClone(value); }
  3747. virtual void setClusterName(const char * value)
  3748. { c->setClusterName(value); }
  3749. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  3750. { c->setCodeVersion(version, buildVersion, eclVersion); }
  3751. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  3752. { c->setDebugValue(propname, value, overwrite); }
  3753. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  3754. { c->setDebugValueInt(propname, value, overwrite); }
  3755. virtual void setJobName(const char * value)
  3756. { c->setJobName(value); }
  3757. virtual void setPriority(WUPriorityClass cls)
  3758. { c->setPriority(cls); }
  3759. virtual void setPriorityLevel(int level)
  3760. { c->setPriorityLevel(level); }
  3761. virtual void setRescheduleFlag(bool value)
  3762. { c->setRescheduleFlag(value); }
  3763. virtual void setResultLimit(unsigned value)
  3764. { c->setResultLimit(value); }
  3765. virtual void setState(WUState state)
  3766. { c->setState(state); }
  3767. virtual void setStateEx(const char * text)
  3768. { c->setStateEx(text); }
  3769. virtual void setAgentSession(__int64 sessionId)
  3770. { c->setAgentSession(sessionId); }
  3771. virtual void setStatistic(StatisticCreatorType creatorType, const char * creator, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * optDescription, unsigned __int64 value, unsigned __int64 count, unsigned __int64 maxValue, StatsMergeAction mergeAction)
  3772. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  3773. virtual void setTracingValue(const char * propname, const char * value)
  3774. { c->setTracingValue(propname, value); }
  3775. virtual void setTracingValueInt(const char * propname, int value)
  3776. { c->setTracingValueInt(propname, value); }
  3777. virtual void setTracingValueInt64(const char * propname, __int64 value)
  3778. { c->setTracingValueInt64(propname, value); }
  3779. virtual void setUser(const char * value)
  3780. { c->setUser(value); }
  3781. virtual void setWuScope(const char * value)
  3782. { c->setWuScope(value); }
  3783. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  3784. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  3785. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  3786. { c->syncRuntimeWorkflow(array); }
  3787. virtual IWorkflowItemIterator * updateWorkflowItems()
  3788. { return c->updateWorkflowItems(); }
  3789. virtual void resetWorkflow()
  3790. { c->resetWorkflow(); }
  3791. virtual void schedule()
  3792. { c->schedule(); }
  3793. virtual void deschedule()
  3794. { c->deschedule(); }
  3795. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  3796. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  3797. virtual IWUResult * updateGlobalByName(const char * name)
  3798. { return c->updateGlobalByName(name); }
  3799. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  3800. { c->createGraph(name, label, type, xgmml, wfid); }
  3801. virtual IWUQuery * updateQuery()
  3802. { return c->updateQuery(); }
  3803. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  3804. { return c->updateWebServicesInfo(create); }
  3805. virtual IWUPlugin * updatePluginByName(const char * name)
  3806. { return c->updatePluginByName(name); }
  3807. virtual IWULibrary * updateLibraryByName(const char * name)
  3808. { return c->updateLibraryByName(name); }
  3809. virtual IWUResult * updateResultByName(const char * name)
  3810. { return c->updateResultByName(name); }
  3811. virtual IWUResult * updateResultBySequence(unsigned seq)
  3812. { return c->updateResultBySequence(seq); }
  3813. virtual IWUResult * updateTemporaryByName(const char * name)
  3814. { return c->updateTemporaryByName(name); }
  3815. virtual IWUResult * updateVariableByName(const char * name)
  3816. { return c->updateVariableByName(name); }
  3817. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  3818. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  3819. virtual void noteFileRead(IDistributedFile *file)
  3820. { c->noteFileRead(file); }
  3821. virtual void noteFieldUsage(IPropertyTree * usage)
  3822. { c->noteFieldUsage(usage); }
  3823. virtual void releaseFile(const char *fileName)
  3824. { c->releaseFile(fileName); }
  3825. virtual void resetBeforeGeneration()
  3826. { c->resetBeforeGeneration(); }
  3827. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  3828. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  3829. virtual void deleteTemporaries()
  3830. { c->deleteTemporaries(); }
  3831. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  3832. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  3833. virtual IPropertyTree * getDiskUsageStats()
  3834. { return c->getDiskUsageStats(); }
  3835. virtual IPropertyTreeIterator & getFileIterator() const
  3836. { return c->getFileIterator(); }
  3837. virtual IPropertyTreeIterator & getFilesReadIterator() const
  3838. { return c->getFilesReadIterator(); }
  3839. virtual void setSnapshot(const char * value)
  3840. { c->setSnapshot(value); }
  3841. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  3842. { c->setWarningSeverity(code, severity); }
  3843. virtual void setTimeScheduled(const IJlibDateTime &val)
  3844. { c->setTimeScheduled(val); }
  3845. virtual void setDebugAgentListenerPort(unsigned port)
  3846. { c->setDebugAgentListenerPort(port); }
  3847. virtual void setDebugAgentListenerIP(const char * ip)
  3848. { c->setDebugAgentListenerIP(ip); }
  3849. virtual void setXmlParams(const char *params)
  3850. { c->setXmlParams(params); }
  3851. virtual void setXmlParams(IPropertyTree *tree)
  3852. { c->setXmlParams(tree); }
  3853. virtual void setHash(unsigned __int64 hash)
  3854. { c->setHash(hash); }
  3855. // ILocalWorkUnit - used for debugging etc
  3856. virtual void serialize(MemoryBuffer &tgt)
  3857. { c->serialize(tgt); }
  3858. virtual void deserialize(MemoryBuffer &src)
  3859. { c->deserialize(src); }
  3860. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  3861. { return c->switchThorQueue(cluster,qs); }
  3862. virtual void setAllowedClusters(const char *value)
  3863. { c->setAllowedClusters(value); }
  3864. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  3865. { return c->getAllowedClusters(str); }
  3866. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3867. { c->remoteCheckAccess(user,writeaccess); }
  3868. virtual void setAllowAutoQueueSwitch(bool val)
  3869. { c->setAllowAutoQueueSwitch(val); }
  3870. virtual bool getAllowAutoQueueSwitch() const
  3871. { return c->getAllowAutoQueueSwitch(); }
  3872. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3873. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  3874. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  3875. { c->setResultInt(name, sequence, val); }
  3876. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  3877. { c->setResultUInt(name, sequence, val); }
  3878. virtual void setResultReal(const char *name, unsigned sequence, double val)
  3879. { c->setResultReal(name, sequence, val); }
  3880. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  3881. { c->setResultVarString(stepname, sequence, val); }
  3882. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  3883. { c->setResultVarUnicode(stepname, sequence, val); }
  3884. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  3885. { c->setResultString(stepname, sequence, len, val); }
  3886. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  3887. { c->setResultData(stepname, sequence, len, val); }
  3888. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  3889. { c->setResultRaw(name, sequence, len, val); }
  3890. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  3891. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  3892. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  3893. { c->setResultUnicode(name, sequence, len, val); }
  3894. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  3895. { c->setResultBool(name, sequence, val); }
  3896. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  3897. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  3898. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  3899. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  3900. };
  3901. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  3902. {
  3903. Owned<IPropertyTree> p;
  3904. public:
  3905. IMPLEMENT_IINTERFACE;
  3906. CLocalWUAssociated(IPropertyTree *p);
  3907. virtual WUFileType getType() const;
  3908. virtual IStringVal & getDescription(IStringVal & ret) const;
  3909. virtual IStringVal & getIp(IStringVal & ret) const;
  3910. virtual IStringVal & getName(IStringVal & ret) const;
  3911. virtual IStringVal & getNameTail(IStringVal & ret) const;
  3912. virtual unsigned getCrc() const;
  3913. virtual unsigned getMinActivityId() const;
  3914. virtual unsigned getMaxActivityId() const;
  3915. };
  3916. class CLocalWUQuery : implements IWUQuery, public CInterface
  3917. {
  3918. Owned<IPropertyTree> p;
  3919. mutable IArrayOf<IConstWUAssociatedFile> associated;
  3920. mutable CriticalSection crit;
  3921. mutable bool associatedCached;
  3922. private:
  3923. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  3924. void loadAssociated() const;
  3925. public:
  3926. IMPLEMENT_IINTERFACE;
  3927. CLocalWUQuery(IPropertyTree *p);
  3928. virtual WUQueryType getQueryType() const;
  3929. virtual IStringVal& getQueryText(IStringVal &str) const;
  3930. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  3931. virtual IStringVal& getQueryName(IStringVal &str) const;
  3932. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  3933. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  3934. virtual unsigned getQueryDllCrc() const;
  3935. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  3936. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  3937. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  3938. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  3939. virtual bool isArchive() const;
  3940. virtual bool hasArchive() const
  3941. {
  3942. return p->getPropBool("@hasArchive");
  3943. }
  3944. virtual void setQueryType(WUQueryType qt);
  3945. virtual void setQueryText(const char *pstr);
  3946. virtual void setQueryName(const char *);
  3947. virtual void setQueryMainDefinition(const char * str);
  3948. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  3949. virtual void removeAssociatedFiles();
  3950. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  3951. };
  3952. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  3953. {
  3954. Owned<IPropertyTree> p;
  3955. mutable CriticalSection crit;
  3956. private:
  3957. public:
  3958. IMPLEMENT_IINTERFACE;
  3959. CLocalWUWebServicesInfo(IPropertyTree *p);
  3960. virtual IStringVal& getModuleName(IStringVal &str) const;
  3961. virtual IStringVal& getAttributeName(IStringVal &str) const;
  3962. virtual IStringVal& getDefaultName(IStringVal &str) const;
  3963. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  3964. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  3965. virtual unsigned getWebServicesCRC() const;
  3966. virtual void setModuleName(const char *);
  3967. virtual void setAttributeName(const char *);
  3968. virtual void setDefaultName(const char *);
  3969. virtual void setInfo(const char *name, const char *info);
  3970. virtual void setText(const char *name, const char *info);
  3971. virtual void setWebServicesCRC(unsigned);
  3972. };
  3973. class CLocalWUResult : implements IWUResult, public CInterface
  3974. {
  3975. friend class CLocalWorkUnit;
  3976. mutable CriticalSection crit;
  3977. Owned<IPropertyTree> p;
  3978. Owned<IProperties> xmlns;
  3979. public:
  3980. IMPLEMENT_IINTERFACE;
  3981. CLocalWUResult(IPropertyTree *props);
  3982. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  3983. virtual WUResultStatus getResultStatus() const;
  3984. virtual IStringVal& getResultName(IStringVal &str) const;
  3985. virtual int getResultSequence() const;
  3986. virtual bool isResultScalar() const;
  3987. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  3988. virtual unsigned getResultFetchSize() const;
  3989. virtual __int64 getResultTotalRowCount() const;
  3990. virtual __int64 getResultRowCount() const;
  3991. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  3992. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  3993. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  3994. virtual unsigned getResultRequestedRows() const;
  3995. virtual __int64 getResultInt() const;
  3996. virtual bool getResultBool() const;
  3997. virtual double getResultReal() const;
  3998. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  3999. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4000. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  4001. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  4002. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  4003. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4004. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4005. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  4006. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  4007. virtual __int64 getResultRowLimit() const;
  4008. virtual IStringVal& getResultFilename(IStringVal & str) const;
  4009. virtual WUResultFormat getResultFormat() const;
  4010. virtual unsigned getResultHash() const;
  4011. virtual bool getResultIsAll() const;
  4012. virtual IProperties *queryResultXmlns();
  4013. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  4014. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  4015. virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const;
  4016. // interface IWUResult
  4017. virtual void setResultStatus(WUResultStatus status);
  4018. virtual void setResultName(const char *name);
  4019. virtual void setResultSequence(unsigned seq);
  4020. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  4021. virtual void setResultScalar(bool isScalar);
  4022. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  4023. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  4024. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  4025. virtual void setResultRowCount(__int64 rows);
  4026. virtual void setResultDataset(const char *ecl, const char *defs);
  4027. virtual void setResultLogicalName(const char *logicalName);
  4028. virtual void setResultKeyField(const char * name);
  4029. virtual void setResultRequestedRows(unsigned req);
  4030. virtual void setResultRecordSizeEntry(const char * val);
  4031. virtual void setResultTransformerEntry(const char * val);
  4032. virtual void setResultInt(__int64 val);
  4033. virtual void setResultReal(double val);
  4034. virtual void setResultBool(bool val);
  4035. virtual void setResultString(const char * val, unsigned length);
  4036. virtual void setResultUnicode(const void * val, unsigned length);
  4037. virtual void setResultData(const void * val, unsigned length);
  4038. virtual void setResultDecimal(const void * val, unsigned length);
  4039. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  4040. virtual void setResultRowLimit(__int64 value);
  4041. virtual void setResultFilename(const char * name);
  4042. virtual void setResultUInt(unsigned __int64 val);
  4043. virtual void setResultIsAll(bool value);
  4044. virtual void setResultFormat(WUResultFormat format);
  4045. virtual void setResultXML(const char *val);
  4046. virtual void setResultRow(unsigned len, const void * data);
  4047. virtual void setResultXmlns(const char *prefix, const char *uri);
  4048. virtual void setResultFieldOpt(const char *name, const char *value);
  4049. virtual void setResultWriteLocation(const char * _graph, unsigned _activityId);
  4050. virtual IPropertyTree *queryPTree() { return p; }
  4051. };
  4052. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  4053. {
  4054. Owned<IPropertyTree> p;
  4055. public:
  4056. IMPLEMENT_IINTERFACE;
  4057. CLocalWUPlugin(IPropertyTree *p);
  4058. virtual IStringVal& getPluginName(IStringVal &str) const;
  4059. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  4060. virtual void setPluginName(const char *str);
  4061. virtual void setPluginVersion(const char *str);
  4062. };
  4063. class CLocalWULibrary : implements IWULibrary, public CInterface
  4064. {
  4065. Owned<IPropertyTree> p;
  4066. public:
  4067. IMPLEMENT_IINTERFACE;
  4068. CLocalWULibrary(IPropertyTree *p);
  4069. virtual IStringVal & getName(IStringVal & str) const;
  4070. virtual void setName(const char * str);
  4071. };
  4072. class CLocalWUException : implements IWUException, public CInterface
  4073. {
  4074. Owned<IPropertyTree> p;
  4075. public:
  4076. IMPLEMENT_IINTERFACE;
  4077. CLocalWUException(IPropertyTree *p);
  4078. virtual IStringVal& getExceptionSource(IStringVal &str) const override;
  4079. virtual IStringVal& getExceptionMessage(IStringVal &str) const override;
  4080. virtual unsigned getExceptionCode() const override;
  4081. virtual ErrorSeverity getSeverity() const override;
  4082. virtual IStringVal & getTimeStamp(IStringVal & dt) const override;
  4083. virtual IStringVal & getExceptionFileName(IStringVal & str) const override;
  4084. virtual unsigned getExceptionLineNo() const override;
  4085. virtual unsigned getExceptionColumn() const override;
  4086. virtual unsigned getActivityId() const override;
  4087. virtual unsigned getSequence() const override;
  4088. virtual const char * queryScope() const override;
  4089. virtual unsigned getPriority() const override;
  4090. virtual void setExceptionSource(const char *str) override;
  4091. virtual void setExceptionMessage(const char *str) override;
  4092. virtual void setExceptionCode(unsigned code) override;
  4093. virtual void setSeverity(ErrorSeverity level) override;
  4094. virtual void setTimeStamp(const char * dt) override;
  4095. virtual void setExceptionFileName(const char *str) override;
  4096. virtual void setExceptionLineNo(unsigned r) override;
  4097. virtual void setExceptionColumn(unsigned c) override;
  4098. virtual void setActivityId(unsigned _id) override;
  4099. virtual void setScope(const char * _scope) override;
  4100. virtual void setPriority(unsigned _priority) override;
  4101. };
  4102. //==========================================================================================
  4103. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  4104. {
  4105. switch ((int) sequence)
  4106. {
  4107. case ResultSequenceInternal:
  4108. case ResultSequenceOnce:
  4109. case ResultSequencePersist:
  4110. case ResultSequenceStored:
  4111. return true;
  4112. default:
  4113. assertex(sequence <= INT_MAX);
  4114. if ((int) sequence >= LibraryBaseSequence)
  4115. return true;
  4116. return false;
  4117. }
  4118. }
  4119. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  4120. {
  4121. unsigned curTreeNum;
  4122. IArrayOf<IPropertyTree> trees;
  4123. Owned<IConstWorkUnitInfo> cur;
  4124. void setCurrent()
  4125. {
  4126. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  4127. }
  4128. public:
  4129. IMPLEMENT_IINTERFACE;
  4130. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  4131. {
  4132. ForEachItemIn(t, _trees)
  4133. trees.append(*LINK(&_trees.item(t)));
  4134. curTreeNum = 0;
  4135. }
  4136. bool first()
  4137. {
  4138. curTreeNum = 0;
  4139. return next();
  4140. }
  4141. bool isValid()
  4142. {
  4143. return (NULL != cur.get());
  4144. }
  4145. bool next()
  4146. {
  4147. if (curTreeNum >= trees.ordinality())
  4148. {
  4149. cur.clear();
  4150. return false;
  4151. }
  4152. setCurrent();
  4153. ++curTreeNum;
  4154. return true;
  4155. }
  4156. IConstWorkUnitInfo & query() { return *cur; }
  4157. };
  4158. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  4159. {
  4160. Owned<IPropertyTree> p;
  4161. public:
  4162. IMPLEMENT_IINTERFACE;
  4163. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  4164. virtual const char * queryName() const { return p->queryProp("@name"); }
  4165. };
  4166. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  4167. {
  4168. public:
  4169. IMPLEMENT_IINTERFACE;
  4170. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4171. bool first() override { return iter->first(); }
  4172. bool isValid() override { return iter->isValid(); }
  4173. bool next() override { return iter->next(); }
  4174. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  4175. private:
  4176. Owned<IPropertyTreeIterator> iter;
  4177. };
  4178. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  4179. {
  4180. Owned<IPropertyTree> p;
  4181. public:
  4182. IMPLEMENT_IINTERFACE;
  4183. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  4184. virtual const char * queryName() const { return p->queryProp("@name"); }
  4185. virtual const char * queryType() const { return p->queryProp("@type"); }
  4186. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  4187. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  4188. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  4189. };
  4190. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  4191. {
  4192. public:
  4193. IMPLEMENT_IINTERFACE;
  4194. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4195. bool first() override { return iter->first(); }
  4196. bool isValid() override { return iter->isValid(); }
  4197. bool next() override { return iter->next(); }
  4198. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  4199. private:
  4200. Owned<IPropertyTreeIterator> iter;
  4201. };
  4202. //==========================================================================================
  4203. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  4204. {
  4205. Owned<IPropertyTreeIterator> it;
  4206. public:
  4207. IMPLEMENT_IINTERFACE;
  4208. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  4209. virtual bool first() { return it->first(); }
  4210. virtual bool next() { return it->next(); }
  4211. virtual bool isValid() { return it->isValid(); }
  4212. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  4213. };
  4214. EnumMapping workunitSortFields[] =
  4215. {
  4216. { WUSFuser, "@submitID" },
  4217. { WUSFcluster, "@clusterName" },
  4218. { WUSFjob, "@jobName" },
  4219. { WUSFstate, "@state" },
  4220. { WUSFpriority, "@priorityClass" },
  4221. { WUSFprotected, "@protected" },
  4222. { WUSFwuid, "@" },
  4223. { WUSFecl, "Query/ShortText" },
  4224. { WUSFfileread, "FilesRead/File/@name" },
  4225. { WUSFtotalthortime, "@totalThorTime|"
  4226. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  4227. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  4228. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  4229. "Statistics/Statistic[@desc='Total thor time']/@value|"
  4230. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  4231. },
  4232. { WUSFwuidhigh, "@" },
  4233. { WUSFwildwuid, "@" },
  4234. { WUSFappvalue, "Application" },
  4235. { WUSFfilewritten, "Files/File/@name" },
  4236. { WUSFterm, NULL }
  4237. };
  4238. extern const char *queryFilterXPath(WUSortField field)
  4239. {
  4240. return getEnumText(field, workunitSortFields);
  4241. }
  4242. EnumMapping querySortFields[] =
  4243. {
  4244. { WUQSFId, "@id" },
  4245. { WUQSFwuid, "@wuid" },
  4246. { WUQSFname, "@name" },
  4247. { WUQSFdll, "@dll" },
  4248. { WUQSFmemoryLimit, "@memoryLimit" },
  4249. { WUQSFmemoryLimitHi, "@memoryLimit" },
  4250. { WUQSFtimeLimit, "@timeLimit" },
  4251. { WUQSFtimeLimitHi, "@timeLimit" },
  4252. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  4253. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  4254. { WUQSFpriority, "@priority" },
  4255. { WUQSFpriorityHi, "@priority" },
  4256. { WUQSFQuerySet, "@querySetId" },
  4257. { WUQSFActivited, "@activated" },
  4258. { WUQSFSuspendedByUser, "@suspended" },
  4259. { WUQSFLibrary, "Library"},
  4260. { WUQSFPublishedBy, "@publishedBy" },
  4261. { WUQSFterm, NULL }
  4262. };
  4263. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  4264. {
  4265. StringAttr name;
  4266. public:
  4267. IMPLEMENT_IINTERFACE;
  4268. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  4269. {
  4270. }
  4271. void execute()
  4272. {
  4273. PROGLOG("WU removeDll %s", name.get());
  4274. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  4275. }
  4276. };
  4277. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  4278. {
  4279. RemoteFilename name;
  4280. public:
  4281. IMPLEMENT_IINTERFACE;
  4282. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  4283. {
  4284. SocketEndpoint ep(_ip);
  4285. name.setPath(ep, _name);
  4286. }
  4287. void execute()
  4288. {
  4289. Owned<IFile> file = createIFile(name);
  4290. PROGLOG("WU removeDll %s",file->queryFilename());
  4291. file->remove();
  4292. }
  4293. };
  4294. //==========================================================================================
  4295. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  4296. {
  4297. unsigned index;
  4298. IArrayOf<IPropertyTree> trees;
  4299. public:
  4300. IMPLEMENT_IINTERFACE;
  4301. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  4302. {
  4303. ForEachItemIn(t, _trees)
  4304. trees.append(*LINK(&_trees.item(t)));
  4305. index = 0;
  4306. }
  4307. ~CConstQuerySetQueryIterator()
  4308. {
  4309. trees.kill();
  4310. }
  4311. bool first()
  4312. {
  4313. index = 0;
  4314. return (trees.ordinality()!=0);
  4315. }
  4316. bool next()
  4317. {
  4318. index++;
  4319. return (index<trees.ordinality());
  4320. }
  4321. bool isValid()
  4322. {
  4323. return (index<trees.ordinality());
  4324. }
  4325. IPropertyTree &query()
  4326. {
  4327. return trees.item(index);
  4328. }
  4329. };
  4330. class CSecurityCache
  4331. {
  4332. };
  4333. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  4334. {
  4335. public:
  4336. IMPLEMENT_IINTERFACE;
  4337. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  4338. : ptreeIter(_ptreeIter)
  4339. {
  4340. }
  4341. bool first()
  4342. {
  4343. if (!ptreeIter->first())
  4344. {
  4345. cur.clear();
  4346. return false;
  4347. }
  4348. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4349. return true;
  4350. }
  4351. bool isValid()
  4352. {
  4353. return (NULL != cur.get());
  4354. }
  4355. bool next()
  4356. {
  4357. if (!ptreeIter->next())
  4358. {
  4359. cur.clear();
  4360. return false;
  4361. }
  4362. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4363. return true;
  4364. }
  4365. IConstWorkUnitInfo & query() { return *cur; }
  4366. private:
  4367. Owned<IConstWorkUnitInfo> cur;
  4368. Owned<IPropertyTreeIterator> ptreeIter;
  4369. };
  4370. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  4371. {
  4372. public:
  4373. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  4374. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  4375. {
  4376. assertex(_secuser && _secmgr);
  4377. }
  4378. bool first()
  4379. {
  4380. if (!parent->first())
  4381. return false;
  4382. return getNext();
  4383. }
  4384. bool next()
  4385. {
  4386. if (!parent->next())
  4387. return false;
  4388. return getNext();
  4389. }
  4390. virtual bool isValid()
  4391. {
  4392. return parent->isValid();
  4393. }
  4394. virtual IConstWorkUnitInfo &query()
  4395. {
  4396. return parent->query();
  4397. }
  4398. private:
  4399. Owned<IConstWorkUnitIterator> parent;
  4400. MapStringTo<int> scopePermissions;
  4401. Linked<ISecManager> secmgr;
  4402. Linked<ISecUser> secuser;
  4403. bool getNext() // scan for a workunit with permissions
  4404. {
  4405. do
  4406. {
  4407. const char *scopeName = parent->query().queryWuScope();
  4408. if (!scopeName || !*scopeName || checkScope(scopeName))
  4409. return true;
  4410. } while (parent->next());
  4411. return false;
  4412. }
  4413. bool checkScope(const char *scopeName)
  4414. {
  4415. int *perms = scopePermissions.getValue(scopeName);
  4416. SecAccessFlags perm;
  4417. if (!perms)
  4418. {
  4419. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  4420. scopePermissions.setValue(scopeName, perm);
  4421. }
  4422. else
  4423. perm = (SecAccessFlags)*perms;
  4424. return perm >= SecAccess_Read;
  4425. }
  4426. };
  4427. CWorkUnitFactory::CWorkUnitFactory()
  4428. {
  4429. }
  4430. CWorkUnitFactory::~CWorkUnitFactory()
  4431. {
  4432. }
  4433. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4434. {
  4435. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  4436. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  4437. if (scope)
  4438. cw->setWuScope(scope); // Note - this may check access rights and throw exception. Is that correct? We might prefer to only check access once, and this will check on the lock too...
  4439. cw->setDistributedAccessToken(secuser ? secuser->getName() : "");//create and sign the workunit distributed access token
  4440. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  4441. ret->setDebugValue("CREATED_BY", app, true);
  4442. ret->setDebugValue("CREATED_FOR", scope, true);
  4443. return ret;
  4444. }
  4445. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4446. {
  4447. StringBuffer wuid("W");
  4448. char result[32];
  4449. time_t ltime;
  4450. time( &ltime );
  4451. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  4452. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  4453. wuid.append(result);
  4454. if (workUnitTraceLevel > 1)
  4455. DBGLOG("createWorkUnit created %s", wuid.str());
  4456. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  4457. if (workUnitTraceLevel > 1)
  4458. DBGLOG("createWorkUnit created %s", ret->queryWuid());
  4459. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  4460. return ret;
  4461. }
  4462. bool CWorkUnitFactory::deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secmgr, ISecUser *secuser)
  4463. {
  4464. if (workUnitTraceLevel > 1)
  4465. DBGLOG("deleteWorkUnit %s", wuid);
  4466. StringBuffer wuRoot;
  4467. getXPath(wuRoot, wuid);
  4468. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  4469. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  4470. return false;
  4471. if (throwException)
  4472. cw->cleanupAndDelete(true, true);
  4473. else
  4474. {
  4475. try
  4476. {
  4477. cw->cleanupAndDelete(true, true);
  4478. }
  4479. catch (IException *E)
  4480. {
  4481. StringBuffer s;
  4482. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  4483. E->Release();
  4484. return false;
  4485. }
  4486. }
  4487. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  4488. return true;
  4489. }
  4490. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  4491. {
  4492. return deleteWorkUnitEx(wuid, false, secmgr, secuser);
  4493. }
  4494. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4495. {
  4496. StringBuffer wuidStr(wuid);
  4497. wuidStr.trim();
  4498. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  4499. wuidStr.setCharAt(0, 'W');
  4500. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  4501. {
  4502. if (workUnitTraceLevel > 1)
  4503. DBGLOG("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  4504. return NULL;
  4505. }
  4506. if (workUnitTraceLevel > 1)
  4507. DBGLOG("openWorkUnit %s", wuidStr.str());
  4508. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  4509. if (wu)
  4510. {
  4511. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  4512. return NULL; // Actually throws exception on failure, so won't reach here
  4513. return wu.getClear();
  4514. }
  4515. else
  4516. {
  4517. if (workUnitTraceLevel > 0)
  4518. IERRLOG("openWorkUnit %s not found", wuidStr.str());
  4519. return NULL;
  4520. }
  4521. }
  4522. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4523. {
  4524. if (workUnitTraceLevel > 1)
  4525. DBGLOG("updateWorkUnit %s", wuid);
  4526. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  4527. if (wu)
  4528. {
  4529. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  4530. return NULL;
  4531. return &wu->lockRemote(false);
  4532. }
  4533. else
  4534. {
  4535. if (workUnitTraceLevel > 0)
  4536. IERRLOG("updateWorkUnit %s not found", wuid);
  4537. return NULL;
  4538. }
  4539. }
  4540. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  4541. {
  4542. Owned<IPropertyTree> ret;
  4543. IPropertyTree * branch = from->queryPropTree(xpath);
  4544. if(branch)
  4545. {
  4546. ret.setown(createPTreeFromIPT(branch));
  4547. from->removeTree(branch);
  4548. }
  4549. return ret.getClear();
  4550. }
  4551. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  4552. {
  4553. StringBuffer path(base);
  4554. addPathSepChar(path).append(wuid).append(".xml");
  4555. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  4556. if (!pt)
  4557. return false;
  4558. CDateTime dt;
  4559. dt.setNow();
  4560. StringBuffer dts;
  4561. dt.getString(dts);
  4562. pt->setProp("@restoredDate", dts.str());
  4563. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  4564. Owned<IPropertyTree> associatedFiles;
  4565. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  4566. if (srcAssociated)
  4567. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  4568. // The updating of the repo is implementation specific...
  4569. if (!_restoreWorkUnit(pt.getClear(), wuid))
  4570. return false;
  4571. // now kludge back GeneratedDlls
  4572. if (generatedDlls)
  4573. {
  4574. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  4575. for(dlls->first(); dlls->isValid(); dlls->next())
  4576. {
  4577. IPropertyTree & dll = dlls->query();
  4578. char const * name = dll.queryProp("@name");
  4579. char const * kind = dll.queryProp("@kind");
  4580. char const * location = dll.queryProp("@location");
  4581. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  4582. if (!got)
  4583. {
  4584. RemoteFilename dstRfn;
  4585. dstRfn.setRemotePath(location);
  4586. StringBuffer srcPath(base);
  4587. addPathSepChar(srcPath);
  4588. dstRfn.getTail(srcPath);
  4589. OwnedIFile srcFile = createIFile(srcPath);
  4590. OwnedIFile dstFile = createIFile(dstRfn);
  4591. copyFile(dstFile, srcFile);
  4592. queryDllServer().registerDll(name, kind, location);
  4593. }
  4594. }
  4595. }
  4596. if (associatedFiles)
  4597. {
  4598. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  4599. ForEach(*associated)
  4600. {
  4601. IPropertyTree &file = associated->query();
  4602. const char *filename = file.queryProp("@filename");
  4603. SocketEndpoint ep(file.queryProp("@ip"));
  4604. RemoteFilename rfn;
  4605. rfn.setPath(ep, filename);
  4606. OwnedIFile dstFile = createIFile(rfn);
  4607. StringBuffer srcPath(base), name;
  4608. addPathSepChar(srcPath);
  4609. rfn.getTail(name);
  4610. srcPath.append(name);
  4611. if (generatedDlls)
  4612. {
  4613. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  4614. if (generatedDlls->hasProp(gDllPath))
  4615. continue; // generated dlls handled separately - see above
  4616. }
  4617. OwnedIFile srcFile = createIFile(srcPath);
  4618. if (srcFile->exists())
  4619. {
  4620. try
  4621. {
  4622. copyFile(dstFile, srcFile);
  4623. }
  4624. catch (IException *e)
  4625. {
  4626. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  4627. EXCLOG(e, msg.str());
  4628. e->Release();
  4629. }
  4630. }
  4631. }
  4632. }
  4633. return true;
  4634. }
  4635. int CWorkUnitFactory::setTracingLevel(int newLevel)
  4636. {
  4637. if (newLevel)
  4638. DBGLOG("Setting workunit trace level to %d", newLevel);
  4639. int level = workUnitTraceLevel;
  4640. workUnitTraceLevel = newLevel;
  4641. return level;
  4642. }
  4643. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4644. {
  4645. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4646. if(!conn) return;
  4647. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  4648. KeptAtomTable entries;
  4649. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  4650. StringBuffer wuid;
  4651. for(iter->first(); iter->isValid(); iter->next())
  4652. {
  4653. char const * entry = iter->query().queryName();
  4654. if(!entries.find(entry))
  4655. {
  4656. entries.addAtom(entry);
  4657. ncnameUnescape(entry, wuid.clear());
  4658. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  4659. if(wu && (wu->getState() == WUStateWait))
  4660. wu->setState(WUStateCompleted);
  4661. }
  4662. }
  4663. bool more;
  4664. do more = root->removeProp("*"); while(more);
  4665. }
  4666. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  4667. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4668. const void *filterbuf, // (appended) string values for filters
  4669. unsigned startoffset,
  4670. unsigned maxnum,
  4671. __int64 *cachehint,
  4672. unsigned *total,
  4673. const MapStringTo<bool> *_subset)
  4674. {
  4675. struct PostFilters
  4676. {
  4677. WUQueryFilterBoolean activatedFilter;
  4678. WUQueryFilterBoolean suspendedByUserFilter;
  4679. PostFilters()
  4680. {
  4681. activatedFilter = WUQFSAll;
  4682. suspendedByUserFilter = WUQFSAll;
  4683. };
  4684. } postFilters;
  4685. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  4686. {
  4687. StringAttr querySet;
  4688. StringAttr xPath;
  4689. StringAttr sortOrder;
  4690. PostFilters postFilters;
  4691. StringArray unknownAttributes;
  4692. const MapStringTo<bool> *subset;
  4693. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  4694. {
  4695. const char* querySetId = querySetTree->queryProp("@id");
  4696. std::unordered_set<std::string> aliasSet;
  4697. Owned<IPropertyTreeIterator> aliasIter = querySetTree->getElements("Alias");
  4698. ForEach(*aliasIter)
  4699. {
  4700. const char *id = aliasIter->query().queryProp("@id");
  4701. if (!isEmptyString(id))
  4702. aliasSet.insert(id);
  4703. }
  4704. VStringBuffer path("Query%s", xPath.get());
  4705. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  4706. ForEach(*iter)
  4707. {
  4708. IPropertyTree &query = iter->query();
  4709. bool activated = false;
  4710. const char* queryId = query.queryProp("@id");
  4711. if (queryId && *queryId)
  4712. {
  4713. if (subset)
  4714. {
  4715. VStringBuffer match("%s/%s", querySetId, queryId);
  4716. if (!subset->getValue(match))
  4717. continue;
  4718. }
  4719. if (aliasSet.find(queryId) != aliasSet.end())
  4720. activated = true;
  4721. }
  4722. if (activated && (postFilters.activatedFilter == WUQFSNo))
  4723. continue;
  4724. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  4725. continue;
  4726. if ((postFilters.suspendedByUserFilter == WUQFSNo) && query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4727. continue;
  4728. if ((postFilters.suspendedByUserFilter == WUQFSYes) && !query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4729. continue;
  4730. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  4731. queryWithSetId->setProp("@querySetId", querySetId);
  4732. queryWithSetId->setPropBool("@activated", activated);
  4733. }
  4734. }
  4735. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  4736. {
  4737. StringBuffer querySetXPath("QuerySets");
  4738. if (!querySet.isEmpty())
  4739. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  4740. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4741. if (!conn)
  4742. return NULL;
  4743. IPropertyTree *root = conn->queryRoot()->queryBranch(nullptr);
  4744. if (querySet.isEmpty())
  4745. {
  4746. Owned<IPropertyTreeIterator> querySetIter = root->getElements("*");
  4747. ForEach(*querySetIter)
  4748. populateQueryTree(&querySetIter->query(), queryTree);
  4749. }
  4750. else
  4751. populateQueryTree(root, queryTree);
  4752. return conn.getClear();
  4753. }
  4754. public:
  4755. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  4756. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters, StringArray& _unknownAttributes, const MapStringTo<bool> *_subset)
  4757. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset)
  4758. {
  4759. postFilters.activatedFilter = _postFilters.activatedFilter;
  4760. postFilters.suspendedByUserFilter = _postFilters.suspendedByUserFilter;
  4761. ForEachItemIn(x, _unknownAttributes)
  4762. unknownAttributes.append(_unknownAttributes.item(x));
  4763. }
  4764. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  4765. {
  4766. Owned<IPropertyTree> elementTree = createPTree("Queries");
  4767. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  4768. if (!conn)
  4769. return NULL;
  4770. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  4771. if (!iter)
  4772. return NULL;
  4773. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  4774. return conn.getClear();
  4775. }
  4776. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  4777. };
  4778. StringAttr querySet;
  4779. StringBuffer xPath;
  4780. StringBuffer so;
  4781. StringArray unknownAttributes;
  4782. if (filters)
  4783. {
  4784. const char *fv = (const char *)filterbuf;
  4785. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  4786. int fmt = filters[i];
  4787. int subfmt = (fmt&0xff);
  4788. if (subfmt==WUQSFQuerySet)
  4789. querySet.set(fv);
  4790. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  4791. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  4792. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  4793. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  4794. else if (subfmt==WUQSFActivited)
  4795. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  4796. else if (subfmt==WUQSFSuspendedByUser)
  4797. postFilters.suspendedByUserFilter = (WUQueryFilterBoolean) atoi(fv);
  4798. else if (!fv || !*fv)
  4799. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  4800. else {
  4801. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  4802. if (fmt&WUQSFnocase)
  4803. xPath.append('?');
  4804. if (fmt&WUQSFnumeric)
  4805. xPath.append('#');
  4806. if (fmt&WUQSFwild)
  4807. xPath.append('~');
  4808. xPath.append('"').append(fv).append("\"]");
  4809. }
  4810. fv = fv + strlen(fv)+1;
  4811. }
  4812. }
  4813. if (sortorder) {
  4814. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  4815. if (so.length())
  4816. so.append(',');
  4817. int fmt = sortorder[i];
  4818. if (fmt&WUQSFreverse)
  4819. so.append('-');
  4820. if (fmt&WUQSFnocase)
  4821. so.append('?');
  4822. if (fmt&WUQSFnumeric)
  4823. so.append('#');
  4824. so.append(getEnumText(fmt&0xff,querySortFields));
  4825. }
  4826. }
  4827. IArrayOf<IPropertyTree> results;
  4828. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL, postFilters, unknownAttributes, _subset);
  4829. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  4830. return new CConstQuerySetQueryIterator(results);
  4831. }
  4832. bool CWorkUnitFactory::isAborting(const char *wuid) const
  4833. {
  4834. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4835. try
  4836. {
  4837. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4838. if (acon)
  4839. return acon->queryRoot()->getPropInt(NULL) != 0;
  4840. }
  4841. catch (IException *E)
  4842. {
  4843. EXCLOG(E);
  4844. E->Release();
  4845. }
  4846. return false;
  4847. }
  4848. void CWorkUnitFactory::clearAborting(const char *wuid)
  4849. {
  4850. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4851. try
  4852. {
  4853. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4854. if (acon)
  4855. acon->close(true);
  4856. }
  4857. catch (IException *E)
  4858. {
  4859. EXCLOG(E);
  4860. E->Release();
  4861. }
  4862. }
  4863. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  4864. {
  4865. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  4866. bool isEcl = false;
  4867. switch (state)
  4868. {
  4869. case WUStateAborting:
  4870. state = WUStateAborted;
  4871. break;
  4872. case WUStateCompiling:
  4873. isEcl = true;
  4874. // drop into
  4875. default:
  4876. state = WUStateFailed;
  4877. }
  4878. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  4879. wu->setState(state);
  4880. Owned<IWUException> e = wu->createException();
  4881. e->setExceptionCode(isEcl ? 1001 : 1000);
  4882. e->setExceptionMessage(isEcl ? "EclCC terminated unexpectedly" : "Workunit terminated unexpectedly");
  4883. }
  4884. static CriticalSection deleteDllLock;
  4885. static IWorkQueueThread *deleteDllWorkQ = nullptr;
  4886. MODULE_INIT(INIT_PRIORITY_STANDARD)
  4887. {
  4888. return true;
  4889. }
  4890. MODULE_EXIT()
  4891. {
  4892. CriticalBlock b(deleteDllLock);
  4893. if (deleteDllWorkQ)
  4894. ::Release(deleteDllWorkQ);
  4895. deleteDllWorkQ = nullptr;
  4896. }
  4897. static void asyncRemoveDll(const char * name)
  4898. {
  4899. CriticalBlock b(deleteDllLock);
  4900. if (!deleteDllWorkQ)
  4901. deleteDllWorkQ = createWorkQueueThread();
  4902. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  4903. }
  4904. static void asyncRemoveFile(const char * ip, const char * name)
  4905. {
  4906. CriticalBlock b(deleteDllLock);
  4907. if (!deleteDllWorkQ)
  4908. deleteDllWorkQ = createWorkQueueThread();
  4909. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  4910. }
  4911. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  4912. {
  4913. public:
  4914. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  4915. CDaliWorkUnitFactory()
  4916. {
  4917. // Assumes dali client configuration has already been done
  4918. sdsManager = &querySDS();
  4919. session = myProcessSession();
  4920. addShutdownHook(*this);
  4921. }
  4922. ~CDaliWorkUnitFactory()
  4923. {
  4924. removeShutdownHook(*this);
  4925. }
  4926. virtual bool initializeStore()
  4927. {
  4928. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  4929. }
  4930. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  4931. {
  4932. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  4933. }
  4934. virtual unsigned validateRepository(bool fixErrors)
  4935. {
  4936. return 0;
  4937. }
  4938. virtual void deleteRepository(bool recreate)
  4939. {
  4940. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4941. if (conn)
  4942. conn->close(true);
  4943. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  4944. if (conn)
  4945. conn->close(true);
  4946. }
  4947. virtual void createRepository()
  4948. {
  4949. // Nothing to do
  4950. }
  4951. virtual const char *queryStoreType() const
  4952. {
  4953. return "Dali";
  4954. }
  4955. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4956. {
  4957. StringBuffer wuRoot;
  4958. getXPath(wuRoot, wuid);
  4959. IRemoteConnection *conn;
  4960. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  4961. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4962. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  4963. conn->queryRoot()->setProp("@totalThorTime", "");
  4964. return new CDaliWorkUnit(conn, secmgr, secuser);
  4965. }
  4966. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4967. {
  4968. StringBuffer wuRoot;
  4969. getXPath(wuRoot, wuid);
  4970. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  4971. if (conn)
  4972. return new CDaliWorkUnit(conn, secmgr, secuser);
  4973. else
  4974. return NULL;
  4975. }
  4976. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  4977. {
  4978. Owned<IPTree> pt(_pt);
  4979. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  4980. StringBuffer wuRoot;
  4981. getXPath(wuRoot, wuid);
  4982. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4983. if (!conn)
  4984. {
  4985. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  4986. return false;
  4987. }
  4988. IPropertyTree *root = conn->queryRoot();
  4989. if (root->hasChildren())
  4990. {
  4991. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  4992. return false;
  4993. }
  4994. root->setPropTree(NULL, pt.getClear());
  4995. conn.clear();
  4996. // now kludge back GraphProgress
  4997. if (gprogress)
  4998. {
  4999. VStringBuffer xpath("/GraphProgress/%s", wuid);
  5000. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  5001. if (conn)
  5002. {
  5003. IPropertyTree *groot = conn->queryRoot();
  5004. if (groot->hasChildren())
  5005. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  5006. groot->setPropTree(NULL, gprogress.getClear());
  5007. }
  5008. }
  5009. return true;
  5010. }
  5011. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5012. {
  5013. StringBuffer wuRoot;
  5014. getXPath(wuRoot, wuid);
  5015. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  5016. if (conn)
  5017. return new CDaliWorkUnit(conn, secmgr, secuser);
  5018. else
  5019. return NULL;
  5020. }
  5021. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5022. {
  5023. // MORE - should it check security?
  5024. StringBuffer wuRoot;
  5025. getXPath(wuRoot, GLOBAL_WORKUNIT);
  5026. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  5027. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  5028. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  5029. return &cw->lockRemote(false);
  5030. }
  5031. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  5032. {
  5033. StringBuffer path("*");
  5034. if (owner && *owner)
  5035. path.append("[@submitID=?~\"").append(owner).append("\"]");
  5036. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5037. }
  5038. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  5039. {
  5040. StringBuffer path("*");
  5041. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  5042. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5043. }
  5044. virtual void clientShutdown();
  5045. virtual unsigned numWorkUnits()
  5046. {
  5047. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5048. if (!conn)
  5049. return 0;
  5050. IPropertyTree *root = conn->queryRoot();
  5051. return root->numChildren();
  5052. }
  5053. /**
  5054. * Add a filter to an xpath query, with the appropriate filter flags
  5055. */
  5056. static void appendFilterToQueryString(StringBuffer& query, int flags, const char* name, const char* value)
  5057. {
  5058. query.append('[').append(name).append('=');
  5059. if (flags & WUSFnocase)
  5060. query.append('?');
  5061. if (flags & WUSFwild)
  5062. query.append('~');
  5063. query.append('"').append(value).append("\"]");
  5064. };
  5065. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  5066. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5067. const void *filterbuf, // (appended) string values for filters
  5068. unsigned startoffset,
  5069. unsigned maxnum,
  5070. __int64 *cachehint,
  5071. unsigned *total,
  5072. ISecManager *secmgr,
  5073. ISecUser *secuser)
  5074. {
  5075. class CQueryOrFilter : public CInterface
  5076. {
  5077. unsigned flags;
  5078. StringAttr name;
  5079. StringArray values;
  5080. public:
  5081. IMPLEMENT_IINTERFACE;
  5082. CQueryOrFilter(unsigned _flags, const char *_name, const char *_value)
  5083. : flags(_flags), name(_name)
  5084. {
  5085. values.appendListUniq(_value, "|");
  5086. };
  5087. const char* queryName() { return name.get(); };
  5088. unsigned querySearchFlags() { return flags; };
  5089. const StringArray& queryValues() const { return values; };
  5090. };
  5091. class CMultiPTreeIterator : public CInterfaceOf<IPropertyTreeIterator>
  5092. {
  5093. public:
  5094. virtual bool first() override
  5095. {
  5096. curSource = 0;
  5097. while (sources.isItem(curSource))
  5098. {
  5099. if (sources.item(curSource).first())
  5100. return true;
  5101. curSource++;
  5102. }
  5103. return false;
  5104. }
  5105. virtual bool next() override
  5106. {
  5107. if (sources.isItem(curSource))
  5108. {
  5109. if (sources.item(curSource).next())
  5110. return true;
  5111. curSource++;
  5112. while (sources.isItem(curSource))
  5113. {
  5114. if (sources.item(curSource).first())
  5115. return true;
  5116. curSource++;
  5117. }
  5118. }
  5119. return false;
  5120. }
  5121. virtual bool isValid() override
  5122. {
  5123. return sources.isItem(curSource);
  5124. }
  5125. virtual IPropertyTree & query() override
  5126. {
  5127. return sources.item(curSource).query();
  5128. }
  5129. void addSource(IPropertyTreeIterator &source)
  5130. {
  5131. sources.append(source);
  5132. }
  5133. private:
  5134. IArrayOf<IPropertyTreeIterator> sources;
  5135. unsigned curSource = 0;
  5136. };
  5137. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  5138. {
  5139. StringAttr xPath;
  5140. StringAttr sortOrder;
  5141. StringAttr nameFilterLo;
  5142. StringAttr nameFilterHi;
  5143. StringArray unknownAttributes;
  5144. Owned<CQueryOrFilter> orFilter;
  5145. public:
  5146. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5147. CWorkUnitsPager(const char* _xPath, CQueryOrFilter* _orFilter, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  5148. : xPath(_xPath), orFilter(_orFilter), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  5149. {
  5150. ForEachItemIn(x, _unknownAttributes)
  5151. unknownAttributes.append(_unknownAttributes.item(x));
  5152. }
  5153. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5154. {
  5155. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5156. if (!conn)
  5157. return NULL;
  5158. Owned<IPropertyTreeIterator> iter;
  5159. if (!orFilter)
  5160. {
  5161. iter.setown(conn->getElements(xPath.get()));
  5162. }
  5163. else
  5164. {
  5165. Owned <CMultiPTreeIterator> multi = new CMultiPTreeIterator;
  5166. bool added = false;
  5167. const char* fieldName = orFilter->queryName();
  5168. unsigned flags = orFilter->querySearchFlags();
  5169. const StringArray& values = orFilter->queryValues();
  5170. ForEachItemIn(i, values)
  5171. {
  5172. StringBuffer path(xPath.get());
  5173. const char* value = values.item(i);
  5174. if (!isEmptyString(value))
  5175. {
  5176. appendFilterToQueryString(path, flags, fieldName, value);
  5177. IPropertyTreeIterator *itr = conn->getElements(path.str());
  5178. if (itr)
  5179. {
  5180. multi->addSource(*itr);
  5181. added = true;
  5182. }
  5183. }
  5184. }
  5185. if (added)
  5186. iter.setown(multi.getClear());
  5187. }
  5188. if (!iter)
  5189. return NULL;
  5190. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  5191. return conn.getClear();
  5192. }
  5193. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  5194. };
  5195. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  5196. {
  5197. UniqueScopes done;
  5198. ISecManager *secmgr;
  5199. ISecUser *secuser;
  5200. CriticalSection crit;
  5201. public:
  5202. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5203. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  5204. {
  5205. secmgr = _secmgr;
  5206. secuser = _secuser;
  5207. }
  5208. bool isOK(IPropertyTree &tree)
  5209. {
  5210. const char *scopename = tree.queryProp("@scope");
  5211. if (!scopename||!*scopename)
  5212. return true;
  5213. {
  5214. CriticalBlock block(crit);
  5215. const bool *b = done.getValue(scopename);
  5216. if (b)
  5217. return *b;
  5218. }
  5219. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  5220. {
  5221. // conceivably could have already been checked and added, but ok.
  5222. CriticalBlock block(crit);
  5223. done.setValue(scopename,ret);
  5224. }
  5225. return ret;
  5226. }
  5227. };
  5228. Owned<CQueryOrFilter> orFilter;
  5229. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  5230. StringBuffer query;
  5231. StringBuffer so;
  5232. StringAttr namefilter("*");
  5233. StringAttr namefilterlo;
  5234. StringAttr namefilterhi;
  5235. StringArray unknownAttributes;
  5236. if (filters)
  5237. {
  5238. const char *fv = (const char *) filterbuf;
  5239. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  5240. {
  5241. assertex(fv);
  5242. int fmt = filters[i];
  5243. int subfmt = (fmt&0xff);
  5244. if (subfmt==WUSFwuid)
  5245. namefilterlo.set(fv);
  5246. else if (subfmt==WUSFwuidhigh)
  5247. namefilterhi.set(fv);
  5248. else if (subfmt==WUSFwildwuid)
  5249. namefilter.set(fv);
  5250. else if (subfmt==WUSFappvalue)
  5251. {
  5252. const char *app = fv;
  5253. fv = fv + strlen(fv)+1;
  5254. query.append("[Application/").append(app);
  5255. if (*fv)
  5256. query.append("=?~\"").append(fv).append('\"');
  5257. query.append("]");
  5258. }
  5259. else if (subfmt==WUSFtotalthortime)
  5260. {
  5261. query.append("[@totalThorTime>=\"");
  5262. formatTimeCollatable(query, milliToNano(atoi(fv)), false);
  5263. query.append("\"]");
  5264. }
  5265. else if (!*fv)
  5266. {
  5267. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  5268. if (subfmt==WUSFtotalthortime)
  5269. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5270. }
  5271. else
  5272. {
  5273. const char* fieldName = getEnumText(subfmt,workunitSortFields);
  5274. if (!strchr(fv, '|'))
  5275. appendFilterToQueryString(query, fmt, fieldName, fv);
  5276. else if (orFilter)
  5277. throw MakeStringException(WUERR_InvalidUserInput, "Multiple OR filters not allowed");
  5278. else
  5279. {
  5280. if (!strieq(fieldName, getEnumText(WUSFstate,workunitSortFields)) &&
  5281. !strieq(fieldName, getEnumText(WUSFuser,workunitSortFields)) &&
  5282. !strieq(fieldName, getEnumText(WUSFcluster,workunitSortFields)))
  5283. throw MakeStringException(WUERR_InvalidUserInput, "OR filters not allowed for %s", fieldName);
  5284. orFilter.setown(new CQueryOrFilter(fmt, fieldName, fv));
  5285. }
  5286. }
  5287. fv = fv + strlen(fv)+1;
  5288. }
  5289. }
  5290. if ((sortorder&0xff)==WUSFtotalthortime)
  5291. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5292. query.insert(0, namefilter.get());
  5293. if (sortorder)
  5294. {
  5295. if (so.length())
  5296. so.append(',');
  5297. if (sortorder & WUSFreverse)
  5298. so.append('-');
  5299. if (sortorder & WUSFnocase)
  5300. so.append('?');
  5301. if (sortorder & WUSFnumeric)
  5302. so.append('#');
  5303. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  5304. }
  5305. IArrayOf<IPropertyTree> results;
  5306. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), orFilter.getClear(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  5307. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  5308. return new CConstWUArrayIterator(results);
  5309. }
  5310. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5311. {
  5312. WUState ret = WUStateUnknown;
  5313. StringBuffer wuRoot;
  5314. getXPath(wuRoot, wuid);
  5315. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5316. if (timeout == 0) //no need to subscribe
  5317. {
  5318. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5319. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5320. if (it != expectedStates.end())
  5321. return ret;
  5322. switch (ret)
  5323. {
  5324. case WUStateCompiled:
  5325. case WUStateUploadingFiles:
  5326. if (!compiled)
  5327. break;
  5328. //fall through
  5329. case WUStateCompleted:
  5330. case WUStateFailed:
  5331. case WUStateAborted:
  5332. return ret;
  5333. default:
  5334. break;
  5335. }
  5336. return WUStateUnknown;
  5337. }
  5338. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  5339. LocalIAbortHandler abortHandler(*waiter);
  5340. if (conn)
  5341. {
  5342. SessionId agent = -1;
  5343. bool agentSessionStopped = false;
  5344. unsigned start = msTick();
  5345. for (;;)
  5346. {
  5347. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5348. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5349. if (it != expectedStates.end())
  5350. return ret;
  5351. switch (ret)
  5352. {
  5353. case WUStateCompiled:
  5354. case WUStateUploadingFiles:
  5355. if (!compiled)
  5356. break;
  5357. // fall into
  5358. case WUStateCompleted:
  5359. case WUStateFailed:
  5360. case WUStateAborted:
  5361. return ret;
  5362. case WUStateWait:
  5363. break;
  5364. case WUStateCompiling:
  5365. case WUStateRunning:
  5366. case WUStateDebugPaused:
  5367. case WUStateDebugRunning:
  5368. case WUStateBlocked:
  5369. case WUStateAborting:
  5370. if (agentSessionStopped)
  5371. {
  5372. reportAbnormalTermination(wuid, ret, agent);
  5373. return ret;
  5374. }
  5375. if (queryDaliServerVersion().compare("2.1")>=0)
  5376. {
  5377. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  5378. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  5379. {
  5380. agentSessionStopped = true;
  5381. conn->reload();
  5382. continue;
  5383. }
  5384. }
  5385. break;
  5386. }
  5387. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  5388. unsigned waited = msTick() - start;
  5389. if (timeout==-1 || waited + 20000 < timeout)
  5390. {
  5391. waiter->wait(20000); // recheck state every 20 seconds, in case eclagent has crashed.
  5392. if (waiter->isAborted())
  5393. {
  5394. ret = WUStateUnknown; // MORE - throw an exception?
  5395. break;
  5396. }
  5397. }
  5398. else if (waited > timeout || !waiter->wait(timeout-waited))
  5399. {
  5400. ret = WUStateUnknown; // MORE - throw an exception?
  5401. break;
  5402. }
  5403. conn->reload();
  5404. }
  5405. }
  5406. return ret;
  5407. }
  5408. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5409. {
  5410. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  5411. LocalIAbortHandler abortHandler(*waiter);
  5412. WUAction ret = WUActionUnknown;
  5413. StringBuffer wuRoot;
  5414. getXPath(wuRoot, wuid);
  5415. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5416. if (conn)
  5417. {
  5418. unsigned start = msTick();
  5419. for (;;)
  5420. {
  5421. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  5422. if (ret != original)
  5423. break;
  5424. unsigned waited = msTick() - start;
  5425. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  5426. if (waiter->isAborted())
  5427. {
  5428. ret = WUActionUnknown; // MORE - throw an exception?
  5429. break;
  5430. }
  5431. conn->reload();
  5432. }
  5433. }
  5434. waiter->unsubscribe();
  5435. return ret;
  5436. }
  5437. protected:
  5438. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  5439. {
  5440. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5441. if (conn)
  5442. {
  5443. CDaliVersion serverVersionNeeded("3.2");
  5444. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  5445. conn->queryRoot()->getElements(xpath) :
  5446. conn->getElements(xpath));
  5447. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  5448. }
  5449. else
  5450. return NULL;
  5451. }
  5452. ISDSManager *sdsManager;
  5453. SessionId session;
  5454. };
  5455. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5456. {
  5457. if (secmgr)
  5458. return new CSecureConstWUIterator(iter, secmgr, secuser);
  5459. else
  5460. return iter;
  5461. }
  5462. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5463. {
  5464. if (secmgr)
  5465. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  5466. else
  5467. return new CConstWUIterator(iter);
  5468. }
  5469. static CriticalSection factoryCrit;
  5470. static Owned<IWorkUnitFactory> factory;
  5471. void CDaliWorkUnitFactory::clientShutdown()
  5472. {
  5473. CriticalBlock b(factoryCrit);
  5474. factory.clear();
  5475. }
  5476. void clientShutdownWorkUnit()
  5477. {
  5478. CriticalBlock b(factoryCrit);
  5479. factory.clear();
  5480. }
  5481. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  5482. {
  5483. CriticalBlock b(factoryCrit);
  5484. factory.setown(_factory);
  5485. }
  5486. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  5487. {
  5488. if (!factory)
  5489. {
  5490. CriticalBlock b(factoryCrit);
  5491. if (!factory) // NOTE - this "double test" paradigm is not guaranteed threadsafe on modern systems/compilers - I think in this instance that is harmless even in the (extremely) unlikely event that it resulted in the setown being called twice.
  5492. {
  5493. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  5494. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  5495. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5496. IPropertyTree *pluginInfo = NULL;
  5497. if (env)
  5498. {
  5499. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  5500. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  5501. if (daliInfo)
  5502. {
  5503. const char *daliName = daliInfo->queryProp("@name");
  5504. if (daliName)
  5505. {
  5506. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  5507. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  5508. }
  5509. if (!pluginInfo)
  5510. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  5511. }
  5512. }
  5513. if (pluginInfo && !forceDali)
  5514. factory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  5515. else
  5516. factory.setown(new CDaliWorkUnitFactory());
  5517. }
  5518. }
  5519. return factory.getLink();
  5520. }
  5521. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  5522. {
  5523. if (!factory)
  5524. {
  5525. CriticalBlock b(factoryCrit);
  5526. if (!factory) // NOTE - this "double test" paradigm is not guaranteed threadsafe on modern systems/compilers - I think in this instance that is harmless even in the (extremely) unlikely event that it resulted in the setown being called twice.
  5527. factory.setown(new CDaliWorkUnitFactory());
  5528. }
  5529. return factory.getLink();
  5530. }
  5531. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  5532. // They can still be supplied if you want...
  5533. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  5534. {
  5535. public:
  5536. IMPLEMENT_IINTERFACE;
  5537. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  5538. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  5539. {
  5540. }
  5541. virtual bool initializeStore()
  5542. {
  5543. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5544. }
  5545. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5546. {
  5547. return baseFactory->getWatcher(subscriber, options, wuid);
  5548. }
  5549. virtual unsigned validateRepository(bool fix)
  5550. {
  5551. return baseFactory->validateRepository(fix);
  5552. }
  5553. virtual void deleteRepository(bool recreate)
  5554. {
  5555. return baseFactory->deleteRepository(recreate);
  5556. }
  5557. virtual void createRepository()
  5558. {
  5559. return baseFactory->createRepository();
  5560. }
  5561. virtual const char *queryStoreType() const
  5562. {
  5563. return baseFactory->queryStoreType();
  5564. }
  5565. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  5566. {
  5567. return baseFactory->getUniqueValues(field, prefix, result);
  5568. }
  5569. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5570. {
  5571. if (!secMgr) secMgr = defaultSecMgr.get();
  5572. if (!secUser) secUser = defaultSecUser.get();
  5573. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  5574. }
  5575. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5576. {
  5577. if (!secMgr) secMgr = defaultSecMgr.get();
  5578. if (!secUser) secUser = defaultSecUser.get();
  5579. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  5580. }
  5581. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  5582. {
  5583. if (!secMgr) secMgr = defaultSecMgr.get();
  5584. if (!secUser) secUser = defaultSecUser.get();
  5585. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  5586. }
  5587. virtual bool deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secMgr, ISecUser *secUser)
  5588. {
  5589. if (!secMgr) secMgr = defaultSecMgr.get();
  5590. if (!secUser) secUser = defaultSecUser.get();
  5591. return baseFactory->deleteWorkUnitEx(wuid, throwException, secMgr, secUser);
  5592. }
  5593. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5594. {
  5595. if (!secMgr) secMgr = defaultSecMgr.get();
  5596. if (!secUser) secUser = defaultSecUser.get();
  5597. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  5598. }
  5599. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5600. {
  5601. if (!secMgr) secMgr = defaultSecMgr.get();
  5602. if (!secUser) secUser = defaultSecUser.get();
  5603. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  5604. }
  5605. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  5606. {
  5607. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  5608. }
  5609. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  5610. {
  5611. if (!secMgr) secMgr = defaultSecMgr.get();
  5612. if (!secUser) secUser = defaultSecUser.get();
  5613. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  5614. }
  5615. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  5616. {
  5617. if (!secMgr) secMgr = defaultSecMgr.get();
  5618. if (!secUser) secUser = defaultSecUser.get();
  5619. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  5620. }
  5621. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5622. {
  5623. if (!secMgr) secMgr = defaultSecMgr.get();
  5624. if (!secUser) secUser = defaultSecUser.get();
  5625. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  5626. }
  5627. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5628. {
  5629. if (!secMgr) secMgr = defaultSecMgr.get();
  5630. if (!secUser) secUser = defaultSecUser.get();
  5631. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  5632. }
  5633. virtual int setTracingLevel(int newLevel)
  5634. {
  5635. return baseFactory->setTracingLevel(newLevel);
  5636. }
  5637. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  5638. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5639. const void *filterbuf, // (appended) string values for filters
  5640. unsigned startoffset,
  5641. unsigned maxnum,
  5642. __int64 *cachehint,
  5643. unsigned *total,
  5644. ISecManager *secMgr, ISecUser *secUser)
  5645. {
  5646. if (!secMgr) secMgr = defaultSecMgr.get();
  5647. if (!secUser) secUser = defaultSecUser.get();
  5648. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  5649. }
  5650. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  5651. WUQuerySortField *filters,
  5652. const void *filterbuf,
  5653. unsigned startoffset,
  5654. unsigned maxnum,
  5655. __int64 *cachehint,
  5656. unsigned *total,
  5657. const MapStringTo<bool> *subset)
  5658. {
  5659. // MORE - why no security?
  5660. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset);
  5661. }
  5662. virtual unsigned numWorkUnits()
  5663. {
  5664. return baseFactory->numWorkUnits();
  5665. }
  5666. virtual bool isAborting(const char *wuid) const
  5667. {
  5668. return baseFactory->isAborting(wuid);
  5669. }
  5670. virtual void clearAborting(const char *wuid)
  5671. {
  5672. baseFactory->clearAborting(wuid);
  5673. }
  5674. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5675. {
  5676. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, expectedStates);
  5677. }
  5678. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5679. {
  5680. return baseFactory->waitForWorkUnitAction(wuid, original);
  5681. }
  5682. private:
  5683. Owned<IWorkUnitFactory> baseFactory;
  5684. Linked<ISecManager> defaultSecMgr;
  5685. Linked<ISecUser> defaultSecUser;
  5686. };
  5687. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  5688. {
  5689. if (secmgr && secuser)
  5690. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  5691. else
  5692. return getWorkUnitFactory();
  5693. }
  5694. //==========================================================================================
  5695. class CStringPTreeIterator : implements IStringIterator, public CInterface
  5696. {
  5697. Owned<IPropertyTreeIterator> it;
  5698. public:
  5699. IMPLEMENT_IINTERFACE;
  5700. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  5701. virtual bool first() { return it->first(); }
  5702. virtual bool next() { return it->next(); }
  5703. virtual bool isValid() { return it->isValid(); }
  5704. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  5705. };
  5706. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  5707. {
  5708. Owned<IPropertyTreeIterator> it;
  5709. public:
  5710. IMPLEMENT_IINTERFACE;
  5711. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  5712. virtual bool first() { return it->first(); }
  5713. virtual bool next() { return it->next(); }
  5714. virtual bool isValid() { return it->isValid(); }
  5715. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  5716. };
  5717. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  5718. {
  5719. Owned<IPropertyTreeIterator> it;
  5720. StringAttr name;
  5721. public:
  5722. IMPLEMENT_IINTERFACE;
  5723. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  5724. virtual bool first() { return it->first(); }
  5725. virtual bool next() { return it->next(); }
  5726. virtual bool isValid() { return it->isValid(); }
  5727. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  5728. };
  5729. //==========================================================================================
  5730. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5731. {
  5732. clearCached(false);
  5733. secMgr.set(secmgr);
  5734. secUser.set(secuser);
  5735. workflowIteratorCached = false;
  5736. resultsCached = false;
  5737. graphsCached = false;
  5738. temporariesCached = false;
  5739. variablesCached = false;
  5740. exceptionsCached = false;
  5741. pluginsCached = false;
  5742. librariesCached = false;
  5743. activitiesCached = false;
  5744. webServicesInfoCached = false;
  5745. roxieQueryInfoCached = false;
  5746. }
  5747. void CLocalWorkUnit::clearCached(bool clearTree)
  5748. {
  5749. query.clear();
  5750. webServicesInfo.clear();
  5751. workflowIterator.clear();
  5752. graphs.kill();
  5753. results.kill();
  5754. variables.kill();
  5755. plugins.kill();
  5756. libraries.kill();
  5757. exceptions.kill();
  5758. temporaries.kill();
  5759. statistics.kill();
  5760. appvalues.kill();
  5761. if (clearTree)
  5762. p.clear();
  5763. workflowIteratorCached = false;
  5764. resultsCached = false;
  5765. graphsCached = false;
  5766. temporariesCached = false;
  5767. variablesCached = false;
  5768. exceptionsCached = false;
  5769. pluginsCached = false;
  5770. librariesCached = false;
  5771. activitiesCached = false;
  5772. webServicesInfoCached = false;
  5773. roxieQueryInfoCached = false;
  5774. }
  5775. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  5776. {
  5777. clearCached(false);
  5778. p.setown(ptree);
  5779. }
  5780. void CLocalWorkUnit::beforeDispose()
  5781. {
  5782. try
  5783. {
  5784. unsubscribe();
  5785. clearCached(true);
  5786. userDesc.clear();
  5787. secMgr.clear();
  5788. secUser.clear();
  5789. }
  5790. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  5791. }
  5792. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  5793. {
  5794. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  5795. // Delete any related things in SDS etc that might otherwise be forgotten
  5796. if (p->getPropBool("@protected", false))
  5797. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  5798. switch (getState())
  5799. {
  5800. case WUStateAborted:
  5801. case WUStateCompleted:
  5802. case WUStateFailed:
  5803. case WUStateArchived:
  5804. break;
  5805. case WUStateCompiled:
  5806. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  5807. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5808. break;
  5809. case WUStateWait:
  5810. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  5811. default:
  5812. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5813. break;
  5814. }
  5815. if (getIsQueryService())
  5816. {
  5817. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  5818. if (registry)
  5819. {
  5820. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  5821. if (registry->hasProp(xpath.str()))
  5822. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  5823. }
  5824. }
  5825. try
  5826. {
  5827. if (deldll && !p->getPropBool("@isClone", false))
  5828. {
  5829. Owned<IConstWUQuery> q = getQuery();
  5830. if (q)
  5831. {
  5832. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5833. SCMStringBuffer name;
  5834. ForEach(*iter)
  5835. {
  5836. IConstWUAssociatedFile & cur = iter->query();
  5837. cur.getNameTail(name);
  5838. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  5839. {
  5840. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5841. if (entry.get())
  5842. asyncRemoveDll(name.str());
  5843. else
  5844. {
  5845. SCMStringBuffer ip, localPath;
  5846. cur.getName(localPath);
  5847. cur.getIp(ip);
  5848. asyncRemoveFile(ip.str(), localPath.str());
  5849. }
  5850. }
  5851. }
  5852. }
  5853. }
  5854. factory->clearAborting(queryWuid());
  5855. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  5856. }
  5857. catch(IException *E)
  5858. {
  5859. StringBuffer s;
  5860. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  5861. E->Release();
  5862. }
  5863. catch (...)
  5864. {
  5865. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  5866. }
  5867. }
  5868. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  5869. {
  5870. SCMStringBuffer strval;
  5871. val.getGmtString(strval);
  5872. p->setProp("@timescheduled",strval.str());
  5873. }
  5874. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  5875. {
  5876. StringBuffer str;
  5877. p->getProp("@timescheduled",str);
  5878. if(str.length())
  5879. val.setGmtString(str.str());
  5880. return val;
  5881. }
  5882. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  5883. {
  5884. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  5885. if (extra.length())
  5886. {
  5887. const char *bufStart = buf.str();
  5888. const char *bufPtr = bufStart+buf.length();
  5889. while (bufStart != bufPtr)
  5890. {
  5891. --bufPtr;
  5892. if (!isspace(*bufPtr))
  5893. break;
  5894. }
  5895. assertex('>' == *bufPtr);
  5896. size_t l = strlen(wuid);
  5897. assertex((size_t)(bufPtr-bufStart) > l+2); // e.g. at least </W20171111-111111>
  5898. bufPtr -= l+2; // skip back over </wuid
  5899. assertex(0 == memcmp(bufPtr, "</", 2) );
  5900. assertex(0 == memcmp(bufPtr+2, wuid, l));
  5901. buf.insert(bufPtr-bufStart, extra);
  5902. }
  5903. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  5904. }
  5905. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  5906. {
  5907. CriticalBlock block(crit);
  5908. StringBuffer path(base);
  5909. if (!p)
  5910. return false;
  5911. const char *wuid = p->queryName();
  5912. if (!wuid||!*wuid)
  5913. return false;
  5914. addPathSepChar(path).append(wuid).append(".xml");
  5915. Owned<IFile> file = createIFile(path.str());
  5916. if (!file)
  5917. return false;
  5918. Owned<IFileIO> fileio = file->open(IFOcreate);
  5919. if (!fileio)
  5920. return false;
  5921. StringBuffer buf;
  5922. exportWorkUnitToXML(this, buf, false, false, true);
  5923. StringBuffer extraWorkUnitXML;
  5924. Owned<IPTree> graphProgress = getGraphProgressTree();
  5925. if (graphProgress)
  5926. {
  5927. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  5928. graphProgress.clear();
  5929. }
  5930. Owned<IConstWUQuery> q = getQuery();
  5931. if (!q)
  5932. {
  5933. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5934. return false;
  5935. if (del)
  5936. {
  5937. if (getState()==WUStateUnknown)
  5938. setState(WUStateArchived); // to allow delete
  5939. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  5940. }
  5941. return false;
  5942. }
  5943. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  5944. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5945. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  5946. ForEach(*iter)
  5947. {
  5948. IConstWUAssociatedFile & cur = iter->query();
  5949. SCMStringBuffer name;
  5950. cur.getNameTail(name);
  5951. if (name.length())
  5952. {
  5953. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5954. SCMStringBuffer curPath, curIp;
  5955. cur.getName(curPath);
  5956. cur.getIp(curIp);
  5957. SocketEndpoint curEp(curIp.str());
  5958. RemoteFilename curRfn;
  5959. curRfn.setPath(curEp, curPath.str());
  5960. StringBuffer dst(base);
  5961. addPathSepChar(dst);
  5962. curRfn.getTail(dst);
  5963. Owned<IFile> dstFile = createIFile(dst.str());
  5964. if (entry.get())
  5965. {
  5966. Owned<IException> exception;
  5967. Owned<IDllLocation> loc;
  5968. Owned<IPropertyTree> generatedDllBranch = createPTree();
  5969. generatedDllBranch->setProp("@name", entry->queryName());
  5970. generatedDllBranch->setProp("@kind", entry->queryKind());
  5971. if (exportAssociatedFiles)
  5972. {
  5973. try
  5974. {
  5975. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  5976. }
  5977. catch(IException * e)
  5978. {
  5979. exception.setown(e);
  5980. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  5981. }
  5982. RemoteFilename filename;
  5983. loc->getDllFilename(filename);
  5984. if (!exception)
  5985. {
  5986. Owned<IFile> srcfile = createIFile(filename);
  5987. try
  5988. {
  5989. if (dstFile->exists())
  5990. {
  5991. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  5992. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  5993. // still want to delete if already archived but there are source file copies
  5994. }
  5995. else
  5996. copyFile(dstFile, srcfile);
  5997. }
  5998. catch(IException * e)
  5999. {
  6000. exception.setown(e);
  6001. }
  6002. }
  6003. if (exception)
  6004. {
  6005. if (ignoredllerrors)
  6006. {
  6007. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  6008. //copy failed, so don't delete the registered dll files
  6009. deleteExclusions.append(name.str());
  6010. }
  6011. else
  6012. throw exception.getClear();
  6013. }
  6014. }
  6015. // Record Associated path to restore back to
  6016. StringBuffer restorePath;
  6017. curRfn.getRemotePath(restorePath);
  6018. generatedDllBranch->setProp("@location", restorePath.str());
  6019. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  6020. }
  6021. else if (exportAssociatedFiles) // no generated dll entry
  6022. {
  6023. Owned<IFile> srcFile = createIFile(curRfn);
  6024. try
  6025. {
  6026. copyFile(dstFile, srcFile);
  6027. }
  6028. catch (IException *e)
  6029. {
  6030. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  6031. EXCLOG(e, msg.str());
  6032. e->Release();
  6033. deleteExclusions.append(name.str());
  6034. }
  6035. }
  6036. }
  6037. }
  6038. iter.clear();
  6039. if (generatedDlls->numChildren())
  6040. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  6041. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  6042. return false;
  6043. if (del)
  6044. {
  6045. //setState(WUStateArchived); // this isn't useful as about to delete it!
  6046. q.clear();
  6047. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  6048. }
  6049. return true;
  6050. }
  6051. void CLocalWorkUnit::loadXML(const char *xml)
  6052. {
  6053. CriticalBlock block(crit);
  6054. clearCached(true);
  6055. assertex(xml);
  6056. p.setown(createPTreeFromXMLString(xml,ipt_lowmem));
  6057. }
  6058. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  6059. {
  6060. CriticalBlock block(crit);
  6061. StringBuffer x;
  6062. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  6063. }
  6064. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  6065. {
  6066. CriticalBlock block(crit);
  6067. StringAttr value;
  6068. src.read(value);
  6069. loadXML(value);
  6070. }
  6071. void CLocalWorkUnit::requestAbort()
  6072. {
  6073. CriticalBlock block(crit);
  6074. abortWorkUnit(p->queryName());
  6075. }
  6076. void CLocalWorkUnit::unlockRemote()
  6077. {
  6078. CriticalBlock block(crit);
  6079. locked.unlock();
  6080. _unlockRemote();
  6081. }
  6082. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  6083. {
  6084. if (secMgr)
  6085. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  6086. locked.lock();
  6087. CriticalBlock block(crit);
  6088. if (commit)
  6089. {
  6090. try
  6091. {
  6092. _lockRemote();
  6093. }
  6094. catch (IException *E)
  6095. {
  6096. StringBuffer s;
  6097. IERRLOG("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  6098. locked.unlock();
  6099. throw;
  6100. }
  6101. }
  6102. return *new CLockedWorkUnit(LINK(this));
  6103. }
  6104. void CLocalWorkUnit::commit()
  6105. {
  6106. // Nothing to do if not backed by a persistent store
  6107. }
  6108. IWorkUnit& CLocalWorkUnit::lock()
  6109. {
  6110. return lockRemote(true);
  6111. }
  6112. const char *CLocalWorkUnit::queryWuid() const
  6113. {
  6114. CriticalBlock block(crit);
  6115. return p->queryName();
  6116. }
  6117. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  6118. {
  6119. CriticalBlock block(crit);
  6120. return p->getPropInt("@DebugListenerPort", 0);
  6121. }
  6122. unsigned CLocalWorkUnit::getTotalThorTime() const
  6123. {
  6124. CriticalBlock block(crit);
  6125. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  6126. }
  6127. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  6128. {
  6129. CriticalBlock block(crit);
  6130. p->setPropInt("@DebugListenerPort", port);
  6131. }
  6132. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  6133. {
  6134. CriticalBlock block(crit);
  6135. ip.set(p->queryProp("@DebugListenerIP"));
  6136. return ip;
  6137. }
  6138. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  6139. {
  6140. CriticalBlock block(crit);
  6141. p->setProp("@DebugListenerIP", ip);
  6142. }
  6143. IStringVal & CLocalWorkUnit::getWorkunitDistributedAccessToken(IStringVal & datoken) const
  6144. {
  6145. CriticalBlock block(crit);
  6146. datoken.set(p->queryProp("@distributedAccessToken"));
  6147. return datoken;
  6148. }
  6149. bool CLocalWorkUnit::setDistributedAccessToken(const char * user)
  6150. {
  6151. CriticalBlock block(crit);
  6152. //If this format changes, you must update the isWorkunitDAToken() and extractFromWorkunitDAToken() methods
  6153. VStringBuffer datoken("HPCC[u=%s,w=%s]", user, queryWuid());
  6154. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6155. if (pDSM && pDSM->isDigiSignerConfigured())
  6156. {
  6157. datoken.append(pDSM->queryKeyName()).append(';');
  6158. StringBuffer b64Signature;
  6159. if (pDSM->digiSign(b64Signature, datoken))
  6160. {
  6161. datoken.append(b64Signature.str());
  6162. }
  6163. else
  6164. {
  6165. ERRLOG("Cannot create workunit Distributed Access Token, digisign failed");
  6166. return false;
  6167. }
  6168. }
  6169. else
  6170. {
  6171. WARNLOG("Cannot sign Distributed Access Token, digisign signing not configured");
  6172. datoken.append(";");
  6173. }
  6174. p->setProp("@distributedAccessToken", datoken);
  6175. return true;
  6176. }
  6177. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  6178. {
  6179. // Only implemented in derived classes
  6180. return false;
  6181. }
  6182. void CLocalWorkUnit::setJobName(const char *value)
  6183. {
  6184. CriticalBlock block(crit);
  6185. p->setProp("@jobName", value);
  6186. }
  6187. const char *CLocalWorkUnit::queryJobName() const
  6188. {
  6189. CriticalBlock block(crit);
  6190. const char *ret = p->queryProp("@jobName");
  6191. if (!ret)
  6192. ret = "";
  6193. return ret;
  6194. }
  6195. void CLocalWorkUnit::setClusterName(const char *value)
  6196. {
  6197. CriticalBlock block(crit);
  6198. p->setProp("@clusterName", value);
  6199. }
  6200. const char *CLocalWorkUnit::queryClusterName() const
  6201. {
  6202. CriticalBlock block(crit);
  6203. const char *ret = p->queryProp("@clusterName");
  6204. if (!ret)
  6205. ret = "";
  6206. return ret;
  6207. }
  6208. void CLocalWorkUnit::setAllowedClusters(const char *value)
  6209. {
  6210. setDebugValue("allowedclusters",value, true);
  6211. }
  6212. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  6213. {
  6214. CriticalBlock block(crit);
  6215. getDebugValue("allowedclusters",str);
  6216. if (str.length()!=0)
  6217. return str;
  6218. str.set(p->queryProp("@clusterName"));
  6219. return str;
  6220. }
  6221. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  6222. {
  6223. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  6224. }
  6225. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  6226. {
  6227. CriticalBlock block(crit);
  6228. return getDebugValueBool("allowautoqueueswitch",false);
  6229. }
  6230. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  6231. {
  6232. StringBuffer suffix;
  6233. if (name && *name)
  6234. setApplicationValue("LibraryModule", "name", name, true);
  6235. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  6236. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  6237. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  6238. }
  6239. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  6240. {
  6241. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  6242. if (writeaccess)
  6243. auditflags |= DALI_LDAP_WRITE_WANTED;
  6244. SecAccessFlags perm = SecAccess_Full;
  6245. const char *scopename = p->queryProp("@scope");
  6246. if (scopename&&*scopename) {
  6247. if (!user)
  6248. user = queryUserDescriptor();
  6249. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  6250. if (perm<0) {
  6251. if (perm == SecAccess_Unavailable)
  6252. perm = SecAccess_Full;
  6253. else
  6254. perm = SecAccess_None;
  6255. }
  6256. }
  6257. if (!HASREADPERMISSION(perm))
  6258. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  6259. if (writeaccess && !HASWRITEPERMISSION(perm))
  6260. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  6261. }
  6262. void CLocalWorkUnit::setUser(const char * value)
  6263. {
  6264. CriticalBlock block(crit);
  6265. p->setProp("@submitID", value);
  6266. }
  6267. const char *CLocalWorkUnit::queryUser() const
  6268. {
  6269. CriticalBlock block(crit);
  6270. const char *ret = p->queryProp("@submitID");
  6271. if (!ret)
  6272. ret = "";
  6273. return ret;
  6274. }
  6275. void CLocalWorkUnit::setWuScope(const char * value)
  6276. {
  6277. if (value && *value)
  6278. {
  6279. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  6280. {
  6281. CriticalBlock block(crit);
  6282. p->setProp("@scope", value);
  6283. }
  6284. }
  6285. }
  6286. const char *CLocalWorkUnit::queryWuScope() const
  6287. {
  6288. CriticalBlock block(crit);
  6289. const char *ret = p->queryProp("@scope");
  6290. if (!ret)
  6291. ret = "";
  6292. return ret;
  6293. }
  6294. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  6295. {
  6296. CriticalBlock block(crit);
  6297. setEnum(p, "@priorityClass", cls, priorityClasses);
  6298. }
  6299. WUPriorityClass CLocalWorkUnit::getPriority() const
  6300. {
  6301. CriticalBlock block(crit);
  6302. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  6303. }
  6304. const char *CLocalWorkUnit::queryPriorityDesc() const
  6305. {
  6306. return getEnumText(getPriority(), priorityClasses);
  6307. }
  6308. void CLocalWorkUnit::setState(WUState value)
  6309. {
  6310. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  6311. {
  6312. if (factory)
  6313. factory->clearAborting(queryWuid());
  6314. }
  6315. CriticalBlock block(crit);
  6316. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  6317. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  6318. if (getDebugValueBool("monitorWorkunit", false))
  6319. {
  6320. switch(value)
  6321. {
  6322. case WUStateAborted:
  6323. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  6324. break;
  6325. case WUStateCompleted:
  6326. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  6327. break;
  6328. case WUStateFailed:
  6329. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  6330. break;
  6331. }
  6332. }
  6333. p->removeProp("@stateEx");
  6334. }
  6335. void CLocalWorkUnit::setStateEx(const char * text)
  6336. {
  6337. CriticalBlock block(crit);
  6338. p->setProp("@stateEx", text);
  6339. }
  6340. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  6341. {
  6342. CriticalBlock block(crit);
  6343. p->setPropInt64("@agentSession", sessionId);
  6344. }
  6345. bool CLocalWorkUnit::getIsQueryService() const
  6346. {
  6347. CriticalBlock block(crit);
  6348. return p->getPropBool("@isQueryService", false);
  6349. }
  6350. void CLocalWorkUnit::setIsQueryService(bool value)
  6351. {
  6352. CriticalBlock block(crit);
  6353. p->setPropBool("@isQueryService", value);
  6354. }
  6355. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  6356. {
  6357. if (queryDaliServerVersion().compare("2.1")<0)
  6358. return;
  6359. switch(state)
  6360. {
  6361. case WUStateRunning:
  6362. case WUStateDebugPaused:
  6363. case WUStateDebugRunning:
  6364. case WUStateBlocked:
  6365. case WUStateAborting:
  6366. case WUStateCompiling:
  6367. case WUStatePaused:
  6368. {
  6369. SessionId agent = getAgentSession();
  6370. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  6371. {
  6372. forceReload();
  6373. state = (WUState) getEnum(p, "@state", states);
  6374. bool isecl=state==WUStateCompiling;
  6375. if (aborting())
  6376. state = WUStateAborted;
  6377. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  6378. state = WUStateFailed;
  6379. else
  6380. return;
  6381. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  6382. Owned<IWorkUnit> w = &lock();
  6383. w->setState(state);
  6384. Owned<IWUException> e = w->createException();
  6385. WUAction action = w->getAction();
  6386. switch (action)
  6387. {
  6388. case WUActionPause:
  6389. case WUActionPauseNow:
  6390. case WUActionResume:
  6391. w->setAction(WUActionUnknown);
  6392. }
  6393. if(isecl)
  6394. {
  6395. e->setExceptionCode(1001);
  6396. e->setExceptionMessage("EclServer terminated unexpectedly");
  6397. }
  6398. else
  6399. {
  6400. e->setExceptionCode(1000);
  6401. e->setExceptionMessage("Workunit terminated unexpectedly");
  6402. }
  6403. }
  6404. }
  6405. }
  6406. }
  6407. WUState CLocalWorkUnit::getState() const
  6408. {
  6409. CriticalBlock block(crit);
  6410. WUState state = (WUState) getEnum(p, "@state", states);
  6411. switch (state)
  6412. {
  6413. case WUStateRunning:
  6414. case WUStateDebugPaused:
  6415. case WUStateDebugRunning:
  6416. case WUStateBlocked:
  6417. case WUStateCompiling:
  6418. if (aborting())
  6419. state = WUStateAborting;
  6420. break;
  6421. case WUStateSubmitted:
  6422. if (aborting())
  6423. state = WUStateAborted;
  6424. break;
  6425. }
  6426. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  6427. return state;
  6428. }
  6429. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  6430. {
  6431. CriticalBlock block(crit);
  6432. str.set(p->queryProp("@stateEx"));
  6433. return str;
  6434. }
  6435. __int64 CLocalWorkUnit::getAgentSession() const
  6436. {
  6437. CriticalBlock block(crit);
  6438. return p->getPropInt64("@agentSession", -1);
  6439. }
  6440. unsigned CLocalWorkUnit::getAgentPID() const
  6441. {
  6442. CriticalBlock block(crit);
  6443. return p->getPropInt("@agentPID", -1);
  6444. }
  6445. const char * CLocalWorkUnit::queryStateDesc() const
  6446. {
  6447. // MORE - not sure about this - may prefer a separate interface
  6448. CriticalBlock block(crit);
  6449. try
  6450. {
  6451. return getEnumText(getState(), states);
  6452. }
  6453. catch (...)
  6454. {
  6455. return "???";
  6456. }
  6457. }
  6458. void CLocalWorkUnit::setAction(WUAction value)
  6459. {
  6460. CriticalBlock block(crit);
  6461. setEnum(p, "Action", value, actions);
  6462. }
  6463. WUAction CLocalWorkUnit::getAction() const
  6464. {
  6465. CriticalBlock block(crit);
  6466. return (WUAction) getEnum(p, "Action", actions);
  6467. }
  6468. const char *CLocalWorkUnit::queryActionDesc() const
  6469. {
  6470. CriticalBlock block(crit);
  6471. return p->queryProp("Action");
  6472. }
  6473. bool CLocalWorkUnit::hasApplicationValue(const char *app, const char *propname) const
  6474. {
  6475. StringBuffer prop("Application/");
  6476. prop.append(app).append('/').append(propname);
  6477. CriticalBlock block(crit);
  6478. return p->hasProp(prop);
  6479. }
  6480. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  6481. {
  6482. StringBuffer prop("Application/");
  6483. prop.append(app).append('/').append(propname);
  6484. CriticalBlock block(crit);
  6485. str.set(p->queryProp(prop.str()));
  6486. return str;
  6487. }
  6488. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  6489. {
  6490. StringBuffer prop("Application/");
  6491. prop.append(app).append('/').append(propname);
  6492. CriticalBlock block(crit);
  6493. return p->getPropInt(prop.str(), defVal);
  6494. }
  6495. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  6496. {
  6497. CriticalBlock block(crit);
  6498. appvalues.load(p,"Application/*");
  6499. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  6500. }
  6501. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  6502. {
  6503. CriticalBlock block(crit);
  6504. StringBuffer prop("Application/");
  6505. prop.append(app).append('/').append(propname);
  6506. if (overwrite || !p->hasProp(prop.str()))
  6507. {
  6508. StringBuffer sp;
  6509. p->setProp(sp.append("Application").str(), "");
  6510. p->setProp(sp.append('/').append(app).str(), "");
  6511. p->setProp(prop.str(), value);
  6512. }
  6513. }
  6514. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  6515. {
  6516. VStringBuffer s("%d", value);
  6517. setApplicationValue(app, propname, s, overwrite);
  6518. }
  6519. void CLocalWorkUnit::setPriorityLevel(int level)
  6520. {
  6521. CriticalBlock block(crit);
  6522. p->setPropInt("PriorityFlag", level);
  6523. }
  6524. int CLocalWorkUnit::getPriorityLevel() const
  6525. {
  6526. CriticalBlock block(crit);
  6527. return p->getPropInt("PriorityFlag");
  6528. }
  6529. int calcPriorityValue(const IPropertyTree * p)
  6530. {
  6531. int priority = p->getPropInt("PriorityFlag");
  6532. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  6533. {
  6534. case PriorityClassLow:
  6535. priority -= 100;
  6536. break;
  6537. case PriorityClassHigh:
  6538. priority += 100;
  6539. break;
  6540. }
  6541. return priority;
  6542. }
  6543. int CLocalWorkUnit::getPriorityValue() const
  6544. {
  6545. CriticalBlock block(crit);
  6546. return calcPriorityValue(p);
  6547. }
  6548. void CLocalWorkUnit::setRescheduleFlag(bool value)
  6549. {
  6550. CriticalBlock block(crit);
  6551. p->setPropInt("RescheduleFlag", (int) value);
  6552. }
  6553. bool CLocalWorkUnit::getRescheduleFlag() const
  6554. {
  6555. CriticalBlock block(crit);
  6556. return p->getPropInt("RescheduleFlag") != 0;
  6557. }
  6558. class NullIStringIterator : implements IStringIterator, public CInterface
  6559. {
  6560. public:
  6561. IMPLEMENT_IINTERFACE;
  6562. bool first() { return false; }
  6563. bool next() { return false; }
  6564. bool isValid() { return false; }
  6565. IStringVal & str(IStringVal & str) { return str; }
  6566. };
  6567. ClusterType getClusterType(const char * platform, ClusterType dft)
  6568. {
  6569. if (stricmp(platform, "thor") == 0)
  6570. return ThorLCRCluster;
  6571. if (stricmp(platform, "thorlcr") == 0)
  6572. return ThorLCRCluster;
  6573. if (stricmp(platform, "hthor") == 0)
  6574. return HThorCluster;
  6575. if (stricmp(platform, "roxie") == 0)
  6576. return RoxieCluster;
  6577. return dft;
  6578. }
  6579. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  6580. {
  6581. switch (clusterType)
  6582. {
  6583. case ThorLCRCluster:
  6584. if (lcrSensitive)
  6585. return "thorlcr";
  6586. return "thor";
  6587. case RoxieCluster:
  6588. return "roxie";
  6589. case HThorCluster:
  6590. return "hthor";
  6591. }
  6592. throwUnexpected();
  6593. }
  6594. bool extractFromWorkunitDAToken(const char * distributedAccessToken, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey)
  6595. {
  6596. if (!isWorkunitDAToken(distributedAccessToken))
  6597. {
  6598. DBGLOG("Not a valid workunit distributed access token");
  6599. return false;
  6600. }
  6601. //Extract the string between [ and ]
  6602. const char * pEndBracket = strchr(distributedAccessToken + 5, ']');
  6603. StringBuffer tokenValues;
  6604. tokenValues.append(pEndBracket - distributedAccessToken - 5, distributedAccessToken + 5);
  6605. StringArray nameValues;
  6606. nameValues.appendList(tokenValues.str(), ",",true);
  6607. if (user || wuid)
  6608. {
  6609. for (int x = 0; x < nameValues.ordinality(); x++)
  6610. {
  6611. if (user && 0==strncmp(nameValues[x],"u=",2))//Extract user
  6612. user->append(nameValues[x] + 2);
  6613. if (wuid && 0==strncmp(nameValues[x],"w=",2))//Extract wuid
  6614. wuid->append(nameValues[x] + 2);
  6615. }
  6616. }
  6617. if (privKey)
  6618. {
  6619. const char * finger = pEndBracket;
  6620. ++finger;
  6621. while (*finger && *finger != ';')
  6622. privKey->append(1, finger++);
  6623. }
  6624. return true;
  6625. }
  6626. //Verifies the given signed workunit distributed access token was created
  6627. //and signed by the given wuid and user, and that the workunit is still active
  6628. //Returns:
  6629. // 0 : Success, token is valid and workunit is active
  6630. // 1 : Signature does not verify (wuid/username don't match, or signature does not verify)
  6631. // 2 : Workunit not active
  6632. // Throws if unable to open workunit
  6633. wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken)
  6634. {
  6635. if (isEmptyString(daToken))
  6636. {
  6637. ERRLOG("verifyWorkunitDAToken : Token must be provided");
  6638. return wuTokenInvalid;
  6639. }
  6640. StringBuffer tokWuid;
  6641. StringBuffer tokUser;
  6642. if (!extractFromWorkunitDAToken(daToken, &tokWuid, &tokUser, nullptr))//get the wuid and user
  6643. {
  6644. //Not a valid workunit distributed access token
  6645. return wuTokenInvalid;
  6646. }
  6647. //Validate signature
  6648. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6649. if (pDSM && pDSM->isDigiVerifierConfigured())
  6650. {
  6651. const char * finger;
  6652. StringBuffer token;//receives copy of everything up until signature
  6653. for (finger = daToken; *finger && *finger != ';'; finger++)
  6654. token.append(1, finger);
  6655. token.append(1, finger);//append ;
  6656. StringBuffer sig(++finger);
  6657. if (!pDSM->digiVerify(sig, token))
  6658. {
  6659. ERRLOG("verifyWorkunitDAToken : workunit distributed access token does not verify");
  6660. return wuTokenInvalid;
  6661. }
  6662. }
  6663. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6664. Owned<IConstWorkUnit> cw = factory->openWorkUnit(tokWuid.str());
  6665. if(!cw)
  6666. {
  6667. throw MakeStringException(WUERR_WorkunitAccessDenied,"verifyWorkunitDAToken : Cannot open workunit %s",tokWuid.str());
  6668. }
  6669. //Verify user matches
  6670. bool wuUserExist = !isEmptyString(cw->queryUser());
  6671. bool tokUserExist = !isEmptyString(tokUser.str());
  6672. bool ctxUserExist = !isEmptyString(ctxUser);
  6673. if (wuUserExist && tokUserExist)
  6674. {
  6675. //if both users are found, they must match
  6676. if (!streq(tokUser.str(), cw->queryUser()))
  6677. {
  6678. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match WU user (%s)", tokUser.str(), cw->queryUser());
  6679. return wuTokenInvalid;//Possible Internal error
  6680. }
  6681. else if (ctxUserExist && !streq(tokUser.str(), ctxUser))//ctxUser will be empty if security not enabled
  6682. {
  6683. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match Context user (%s)", cw->queryUser(), ctxUser);
  6684. return wuTokenInvalid;
  6685. }
  6686. }
  6687. else if (!wuUserExist && !tokUserExist)//both users will be empty if no security enabled
  6688. {
  6689. if (ctxUserExist)
  6690. {
  6691. ERRLOG("verifyWorkunitDAToken : Security enabled but WU user and Token user not specified");
  6692. return wuTokenInvalid;
  6693. }
  6694. //both users empty and no context user means if no security enabled
  6695. }
  6696. else
  6697. {
  6698. //one user found, but not the other, treat as an error
  6699. ERRLOG("verifyWorkunitDAToken : WU user %s and Token user %s must be provided", wuUserExist ? cw->queryUser() : "(NULL)", tokUserExist ? tokUser.str() : "(NULL)");
  6700. return wuTokenInvalid;
  6701. }
  6702. // no need to compare tokWuid with workunit wuid, because it will always match
  6703. bool wuActive;
  6704. switch (cw->getState())
  6705. {
  6706. case WUStateRunning:
  6707. case WUStateDebugRunning:
  6708. case WUStateBlocked:
  6709. case WUStateAborting:
  6710. case WUStateUploadingFiles:
  6711. #ifdef _DEBUG
  6712. DBGLOG("verifyWorkunitDAToken : Workunit token validated for %s %s, state is '%s'", cw->queryWuid(), cw->queryUser(), getWorkunitStateStr(cw->getState()));
  6713. #endif
  6714. wuActive = true;
  6715. break;
  6716. default:
  6717. ERRLOG("verifyWorkunitDAToken : Workunit %s not active, state is '%s'", cw->queryWuid(), getWorkunitStateStr(cw->getState()));
  6718. wuActive = false;
  6719. break;
  6720. }
  6721. return wuActive ? wuTokenValid : wuTokenWorkunitInactive;
  6722. }
  6723. bool CLocalWorkUnit::resolveFilePrefix(StringBuffer & prefix, const char * queue) const
  6724. {
  6725. if (hasApplicationValue("prefix", queue))
  6726. {
  6727. getApplicationValue("prefix", queue, StringBufferAdaptor(prefix));
  6728. return true;
  6729. }
  6730. #ifndef _CONTAINERIZED
  6731. Owned<IConstWUClusterInfo> ci = getTargetClusterInfo(queue);
  6732. if (ci)
  6733. {
  6734. ci->getScope(StringBufferAdaptor(prefix));
  6735. return true;
  6736. }
  6737. #endif
  6738. return false;
  6739. }
  6740. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  6741. {
  6742. StringBuffer prefix;
  6743. CriticalBlock block(crit);
  6744. if (p->hasProp("Debug/ForceScope"))
  6745. {
  6746. prefix.append(p->queryProp("Debug/ForceScope")).toLowerCase();
  6747. }
  6748. else
  6749. {
  6750. resolveFilePrefix(prefix, p->queryProp("@clusterName"));
  6751. }
  6752. str.set(prefix.str());
  6753. return str;
  6754. }
  6755. //Queries
  6756. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  6757. {
  6758. CriticalBlock block(crit);
  6759. p->setPropInt("@codeVersion", codeVersion);
  6760. p->setProp("@buildVersion", buildVersion);
  6761. p->setProp("@eclVersion", eclVersion);
  6762. }
  6763. unsigned CLocalWorkUnit::getCodeVersion() const
  6764. {
  6765. CriticalBlock block(crit);
  6766. return p->getPropInt("@codeVersion");
  6767. }
  6768. unsigned CLocalWorkUnit::getWuidVersion() const
  6769. {
  6770. CriticalBlock block(crit);
  6771. return p->getPropInt("@wuidVersion");
  6772. }
  6773. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  6774. {
  6775. CriticalBlock block(crit);
  6776. buildVersion.set(p->queryProp("@buildVersion"));
  6777. eclVersion.set(p->queryProp("@eclVersion"));
  6778. }
  6779. void CLocalWorkUnit::setCloneable(bool value)
  6780. {
  6781. CriticalBlock block(crit);
  6782. p->setPropInt("@cloneable", value);
  6783. }
  6784. void CLocalWorkUnit::setIsClone(bool value)
  6785. {
  6786. CriticalBlock block(crit);
  6787. p->setPropInt("@isClone", value);
  6788. }
  6789. bool CLocalWorkUnit::getCloneable() const
  6790. {
  6791. CriticalBlock block(crit);
  6792. return p->getPropBool("@cloneable", false);
  6793. }
  6794. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  6795. {
  6796. CriticalBlock block(crit);
  6797. if (!userDesc)
  6798. {
  6799. userDesc.setown(createUserDescriptor());
  6800. SCMStringBuffer token;
  6801. getWorkunitDistributedAccessToken(token);
  6802. userDesc->set(queryUser(), token.str());//use token as password
  6803. }
  6804. return userDesc;
  6805. }
  6806. bool CLocalWorkUnit::isProtected() const
  6807. {
  6808. CriticalBlock block(crit);
  6809. return p->getPropBool("@protected", false);
  6810. }
  6811. bool CLocalWorkUnit::isPausing() const
  6812. {
  6813. CriticalBlock block(crit);
  6814. if (WUActionPause == getAction())
  6815. {
  6816. switch (getState())
  6817. {
  6818. case WUStateRunning:
  6819. case WUStateAborting:
  6820. return true;
  6821. }
  6822. }
  6823. return false;
  6824. }
  6825. void CLocalWorkUnit::protect(bool protectMode)
  6826. {
  6827. CriticalBlock block(crit);
  6828. p->setPropBool("@protected", protectMode);
  6829. }
  6830. void CLocalWorkUnit::setResultLimit(unsigned value)
  6831. {
  6832. CriticalBlock block(crit);
  6833. p->setPropInt("resultLimit", value);
  6834. }
  6835. unsigned CLocalWorkUnit::getResultLimit() const
  6836. {
  6837. CriticalBlock block(crit);
  6838. return p->getPropInt("resultLimit");
  6839. }
  6840. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  6841. {
  6842. CriticalBlock block(crit);
  6843. str.set(p->queryProp("SNAPSHOT"));
  6844. return str;
  6845. }
  6846. void CLocalWorkUnit::setSnapshot(const char * val)
  6847. {
  6848. CriticalBlock block(crit);
  6849. p->setProp("SNAPSHOT", val);
  6850. }
  6851. const static EnumMapping warningSeverityMap[] =
  6852. {
  6853. { SeverityInformation, "info" },
  6854. { SeverityWarning, "warning" },
  6855. { SeverityError, "error" },
  6856. { SeverityAlert, "alert" },
  6857. { SeverityIgnore, "ignore" },
  6858. { SeverityFatal, "fatal" },
  6859. { SeverityUnknown, NULL }
  6860. };
  6861. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  6862. {
  6863. StringBuffer xpath;
  6864. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  6865. CriticalBlock block(crit);
  6866. IPropertyTree * mapping = p->queryPropTree(xpath);
  6867. if (mapping)
  6868. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  6869. return defaultSeverity;
  6870. }
  6871. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  6872. {
  6873. StringBuffer xpath;
  6874. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  6875. CriticalBlock block(crit);
  6876. IPropertyTree * mapping = p->queryPropTree(xpath);
  6877. if (!mapping)
  6878. {
  6879. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  6880. mapping = onWarnings->addPropTree("OnWarning");
  6881. mapping->setPropInt("@code", code);
  6882. }
  6883. setEnum(mapping, "@severity", severity, warningSeverityMap);
  6884. }
  6885. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  6886. {
  6887. IPropertyTree *l = (IPropertyTree *) *ll;
  6888. IPropertyTree *r = (IPropertyTree *) *rr;
  6889. return stricmp(l->queryName(), r->queryName());
  6890. };
  6891. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  6892. {
  6893. // Any other values in the WU that could affect generated code should be crc'ed here
  6894. IPropertyTree *tree = p->queryBranch("Debug");
  6895. if (tree)
  6896. {
  6897. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  6898. ICopyArrayOf<IPropertyTree> subs;
  6899. for(sub->first(); sub->isValid(); sub->next())
  6900. subs.append(sub->query());
  6901. subs.sort(comparePropTrees);
  6902. ForEachItemIn(idx, subs)
  6903. {
  6904. const char *name = subs.item(idx).queryName();
  6905. const char *val = subs.item(idx).queryProp(NULL);
  6906. crc = crc32(name, (size32_t)strlen(name), crc);
  6907. if (val)
  6908. crc = crc32(val, (size32_t)strlen(val), crc);
  6909. }
  6910. }
  6911. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  6912. for (plugins->first();plugins->isValid();plugins->next())
  6913. {
  6914. IConstWUPlugin &thisplugin = plugins->query();
  6915. SCMStringBuffer version;
  6916. thisplugin.getPluginVersion(version);
  6917. crc = crc32(version.str(), version.length(), crc);
  6918. }
  6919. return crc;
  6920. }
  6921. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6922. {
  6923. if (!to->hasProp(xpath) && from->hasProp(xpath))
  6924. to->setProp(xpath, from->queryProp(xpath));
  6925. }
  6926. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6927. {
  6928. if (from->hasProp(xpath))
  6929. to->setProp(xpath, from->queryProp(xpath));
  6930. }
  6931. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6932. {
  6933. IPropertyTree * match = from->getBranch(xpath);
  6934. if (match)
  6935. to->setPropTree(xpath, match);
  6936. }
  6937. IPropertyTree *CLocalWorkUnit::queryPTree() const
  6938. {
  6939. return p;
  6940. }
  6941. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  6942. {
  6943. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  6944. if (!from)
  6945. {
  6946. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  6947. if (!fl)
  6948. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  6949. from = fl->c;
  6950. }
  6951. // Need to copy the query, the results, and the graphs from the cached query.
  6952. // The cache is made before the query is executed so there is no need to clear them.
  6953. if (!cached->getCloneable())
  6954. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  6955. const IPropertyTree * fromP = from->p;
  6956. IPropertyTree *pt;
  6957. CriticalBlock block(crit);
  6958. clearCached(false);
  6959. query.clear();
  6960. updateProp(p, fromP, "@jobName");
  6961. copyTree(p, fromP, "Query");
  6962. pt = fromP->getBranch("Application/LibraryModule");
  6963. if (pt)
  6964. {
  6965. ensurePTree(p, "Application");
  6966. p->setPropTree("Application/LibraryModule", pt);
  6967. }
  6968. pt = fromP->getBranch("Application/prefix");
  6969. if (pt)
  6970. {
  6971. ensurePTree(p, "Application");
  6972. p->setPropTree("Application/prefix", pt);
  6973. }
  6974. pt = fromP->queryBranch("Debug");
  6975. if (pt)
  6976. {
  6977. IPropertyTree *curDebug = p->queryPropTree("Debug");
  6978. if (curDebug)
  6979. {
  6980. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  6981. ForEach(*elems)
  6982. {
  6983. IPropertyTree *elem = &elems->query();
  6984. if (!curDebug->hasProp(elem->queryName()))
  6985. curDebug->setPropTree(elem->queryName(),LINK(elem));
  6986. }
  6987. }
  6988. else
  6989. p->setPropTree("Debug", LINK(pt));
  6990. }
  6991. copyTree(p, fromP, "OnWarnings");
  6992. copyTree(p, fromP, "Plugins");
  6993. copyTree(p, fromP, "Libraries");
  6994. copyTree(p, fromP, "Results");
  6995. copyTree(p, fromP, "Graphs");
  6996. copyTree(p, fromP, "Workflow");
  6997. copyTree(p, fromP, "WebServicesInfo");
  6998. if (copyStats)
  6999. {
  7000. // Merge timing info from both branches
  7001. pt = fromP->getBranch("Statistics");
  7002. if (pt)
  7003. {
  7004. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  7005. mergePTree(tgtStatistics, pt);
  7006. pt->Release();
  7007. }
  7008. }
  7009. updateProp(p, fromP, "@clusterName");
  7010. updateProp(p, fromP, "allowedclusters");
  7011. updateProp(p, fromP, "@submitID");
  7012. updateProp(p, fromP, "SNAPSHOT");
  7013. setProp(p, fromP, "@eventScheduledCount");
  7014. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  7015. if (all)
  7016. {
  7017. setProp(p, fromP, "PriorityFlag");
  7018. setProp(p, fromP, "@priorityClass");
  7019. setProp(p, fromP, "@protected");
  7020. setProp(p, fromP, "@clusterName");
  7021. updateProp(p, fromP, "@scope");
  7022. }
  7023. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  7024. pt = fromP->getBranch("Variables");
  7025. if (pt)
  7026. {
  7027. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  7028. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  7029. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  7030. {
  7031. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  7032. const char *name = ptSrcVariable->queryProp("@name");
  7033. assertex(name);
  7034. StringBuffer xpath;
  7035. xpath.append("Variable[@name='").append(name).append("']");
  7036. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  7037. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  7038. merged->removeProp("Value"); // except value and status
  7039. merged->setProp("@status", "undefined");
  7040. if (!merged->getPropBool("@isScalar"))
  7041. merged->removeProp("totalRowCount");
  7042. merged->removeProp("rowCount");
  7043. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  7044. if (ptTgtVariable)
  7045. {
  7046. // copy status and Value from what is already set in target
  7047. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  7048. MemoryBuffer value;
  7049. if (ptTgtVariable->getPropBin("Value", value))
  7050. merged->setPropBin("Value", value.length(), value.toByteArray());
  7051. ptTgtVariable->removeProp(xpath.str());
  7052. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  7053. }
  7054. ptTgtVariables->addPropTree("Variable", merged);
  7055. }
  7056. pt->Release();
  7057. }
  7058. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  7059. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  7060. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  7061. p->setProp("@totalThorTime", fromP->queryProp("@totalThorTime"));
  7062. p->setProp("@hash", fromP->queryProp("@hash"));
  7063. p->setPropBool("@cloneable", true);
  7064. p->setPropBool("@isClone", true);
  7065. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  7066. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  7067. ForEach(*results)
  7068. {
  7069. CLocalWUResult result(LINK(&results->query()));
  7070. result.setResultStatus(ResultStatusUndefined);
  7071. }
  7072. copyTree(p, fromP, "usedsources"); // field usage
  7073. }
  7074. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  7075. {
  7076. StringBuffer lower;
  7077. lower.append(propname).toLowerCase();
  7078. CriticalBlock block(crit);
  7079. StringBuffer prop("Debug/");
  7080. return p->hasProp(prop.append(lower));
  7081. }
  7082. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  7083. {
  7084. StringBuffer lower;
  7085. lower.append(propname).toLowerCase();
  7086. CriticalBlock block(crit);
  7087. StringBuffer prop("Debug/");
  7088. str.set(p->queryProp(prop.append(lower).str()));
  7089. return str;
  7090. }
  7091. IStringIterator& CLocalWorkUnit::getDebugValues() const
  7092. {
  7093. return getDebugValues(NULL);
  7094. }
  7095. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  7096. {
  7097. CriticalBlock block(crit);
  7098. StringBuffer path("Debug/");
  7099. if (prop)
  7100. {
  7101. StringBuffer lower;
  7102. lower.append(prop).toLowerCase();
  7103. path.append(lower);
  7104. }
  7105. else
  7106. path.append("*");
  7107. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  7108. }
  7109. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  7110. {
  7111. StringBuffer lower;
  7112. lower.append(propname).toLowerCase();
  7113. CriticalBlock block(crit);
  7114. StringBuffer prop("Debug/");
  7115. prop.append(lower);
  7116. return p->getPropInt(prop.str(), defVal);
  7117. }
  7118. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  7119. {
  7120. StringBuffer lower;
  7121. lower.append(propname).toLowerCase();
  7122. CriticalBlock block(crit);
  7123. StringBuffer prop("Debug/");
  7124. prop.append(lower);
  7125. return p->getPropInt64(prop.str(), defVal);
  7126. }
  7127. double CLocalWorkUnit::getDebugValueReal(const char *propname, double defVal) const
  7128. {
  7129. StringBuffer lower;
  7130. lower.append(propname).toLowerCase();
  7131. CriticalBlock block(crit);
  7132. StringBuffer prop("Debug/");
  7133. prop.append(lower);
  7134. return p->getPropReal(prop.str(), defVal);
  7135. }
  7136. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  7137. {
  7138. StringBuffer lower;
  7139. lower.append(propname).toLowerCase();
  7140. CriticalBlock block(crit);
  7141. StringBuffer prop("Debug/");
  7142. prop.append(lower);
  7143. return p->getPropBool(prop.str(), defVal);
  7144. }
  7145. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  7146. {
  7147. VStringBuffer xpath("Process/%s/", type);
  7148. if (instance)
  7149. xpath.append(instance);
  7150. else
  7151. xpath.append("*");
  7152. CriticalBlock block(crit);
  7153. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  7154. {
  7155. // NB: instance unused
  7156. if (streq("EclAgent", type))
  7157. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  7158. else if (streq("Thor", type))
  7159. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  7160. VStringBuffer xpath("Debug/%s", type);
  7161. return new CStringPTreeIterator(p->getElements(xpath.str()));
  7162. }
  7163. else
  7164. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  7165. }
  7166. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  7167. {
  7168. VStringBuffer xpath("Process/%s/", type);
  7169. if (instance)
  7170. xpath.append(instance);
  7171. else
  7172. xpath.append("*");
  7173. CriticalBlock block(crit);
  7174. return p->getElements(xpath.str());
  7175. }
  7176. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  7177. {
  7178. VStringBuffer xpath("Process/%s/*", type);
  7179. CriticalBlock block(crit);
  7180. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  7181. }
  7182. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  7183. {
  7184. VStringBuffer processType("Process/%s", type);
  7185. VStringBuffer xpath("%s/%s", processType.str(), instance);
  7186. if (log)
  7187. xpath.appendf("[@log=\"%s\"]", log);
  7188. CriticalBlock block(crit);
  7189. if (!p->hasProp(xpath))
  7190. {
  7191. IPropertyTree *node = ensurePTree(p, processType.str());
  7192. node = node->addPropTree(instance);
  7193. node->setProp("@log", log);
  7194. node->setPropInt("@pid", pid);
  7195. }
  7196. }
  7197. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  7198. {
  7199. StringBuffer lower;
  7200. lower.append(propname).toLowerCase();
  7201. CriticalBlock block(crit);
  7202. StringBuffer prop("Debug/");
  7203. prop.append(lower);
  7204. if (overwrite || !p->hasProp(prop.str()))
  7205. {
  7206. // MORE - not sure this line should be needed....
  7207. p->setProp("Debug", "");
  7208. p->setProp(prop.str(), value);
  7209. }
  7210. }
  7211. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  7212. {
  7213. StringBuffer lower;
  7214. lower.append(propname).toLowerCase();
  7215. CriticalBlock block(crit);
  7216. StringBuffer prop("Debug/");
  7217. prop.append(lower);
  7218. if (overwrite || !p->hasProp(prop.str()))
  7219. {
  7220. // MORE - not sure this line should be needed....
  7221. p->setProp("Debug", "");
  7222. p->setPropInt(prop.str(), value);
  7223. }
  7224. }
  7225. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  7226. {
  7227. CriticalBlock block(crit);
  7228. // MORE - not sure this line should be needed....
  7229. p->setProp("Tracing", "");
  7230. StringBuffer prop("Tracing/");
  7231. p->setProp(prop.append(propname).str(), value);
  7232. }
  7233. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  7234. {
  7235. CriticalBlock block(crit);
  7236. StringBuffer prop("Tracing/");
  7237. p->setPropInt(prop.append(propname).str(), value);
  7238. }
  7239. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  7240. {
  7241. CriticalBlock block(crit);
  7242. VStringBuffer prop("Tracing/%s", propname);
  7243. p->setPropInt64(prop.str(), value);
  7244. }
  7245. IConstWUQuery* CLocalWorkUnit::getQuery() const
  7246. {
  7247. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7248. CriticalBlock block(crit);
  7249. if (!query)
  7250. {
  7251. IPropertyTree *s = p->getPropTree("Query");
  7252. if (s)
  7253. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  7254. }
  7255. return query.getLink();
  7256. }
  7257. IWUQuery* CLocalWorkUnit::updateQuery()
  7258. {
  7259. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7260. CriticalBlock block(crit);
  7261. if (!query)
  7262. {
  7263. IPropertyTree *s = p->queryPropTree("Query");
  7264. if (!s)
  7265. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  7266. s->Link();
  7267. query.setown(new CLocalWUQuery(s));
  7268. }
  7269. return query.getLink();
  7270. }
  7271. void CLocalWorkUnit::loadPlugins() const
  7272. {
  7273. CriticalBlock block(crit);
  7274. if (!pluginsCached)
  7275. {
  7276. assertex(plugins.length() == 0);
  7277. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  7278. for (r->first(); r->isValid(); r->next())
  7279. {
  7280. IPropertyTree *rp = &r->query();
  7281. rp->Link();
  7282. plugins.append(*new CLocalWUPlugin(rp));
  7283. }
  7284. pluginsCached = true;
  7285. }
  7286. }
  7287. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  7288. {
  7289. CriticalBlock block(crit);
  7290. loadPlugins();
  7291. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  7292. }
  7293. void CLocalWorkUnit::loadLibraries() const
  7294. {
  7295. CriticalBlock block(crit);
  7296. if (!librariesCached)
  7297. {
  7298. assertex(libraries.length() == 0);
  7299. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  7300. ForEach(*r)
  7301. {
  7302. IPropertyTree *rp = &r->query();
  7303. rp->Link();
  7304. libraries.append(*new CLocalWULibrary(rp));
  7305. }
  7306. librariesCached = true;
  7307. }
  7308. }
  7309. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  7310. {
  7311. CriticalBlock block(crit);
  7312. loadLibraries();
  7313. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  7314. }
  7315. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  7316. {
  7317. CriticalBlock block(crit);
  7318. loadLibraries();
  7319. ForEachItemIn(idx, libraries)
  7320. {
  7321. SCMStringBuffer name;
  7322. IConstWULibrary &cur = libraries.item(idx);
  7323. cur.getName(name);
  7324. if (stricmp(name.str(), search)==0)
  7325. return &OLINK(cur);
  7326. }
  7327. return NULL;
  7328. }
  7329. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7330. {
  7331. str.append("Graph ").append(graphName);
  7332. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  7333. else if (subId) str.append(" - id(").append(subId).append(")");
  7334. return str;
  7335. }
  7336. StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7337. {
  7338. if (wfid)
  7339. str.append(WorkflowScopePrefix).append(wfid).append(":");
  7340. str.append(graphName);
  7341. if (subId) str.append(":sg").append(subId);
  7342. return str;
  7343. }
  7344. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  7345. {
  7346. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  7347. unsigned len = (size32_t)strlen(label);
  7348. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  7349. return false;
  7350. graphNum = 0;
  7351. subGraphNum = 0;
  7352. subId = 0;
  7353. const char *finger = label+6;
  7354. const char *finger2 = strchr(finger, '-');
  7355. if (NULL == finger2) // just graphName
  7356. graphName.set(finger);
  7357. else
  7358. {
  7359. graphName.set(finger, (size32_t)((finger2-1)-finger));
  7360. finger = finger2+2; // skip '-' and space
  7361. finger2 = strchr(finger, ' ');
  7362. if (finger2)
  7363. {
  7364. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  7365. finger = finger2+2; // skip space and '('
  7366. finger2 = strchr(finger, ')');
  7367. if (finger2)
  7368. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7369. }
  7370. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  7371. {
  7372. finger += 3;
  7373. finger2 = strchr(finger, ')');
  7374. if (finger2)
  7375. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7376. }
  7377. }
  7378. if (graphName && !memicmp(graphName, "graph", 5))
  7379. graphNum = atoi(graphName + 5);
  7380. return true;
  7381. }
  7382. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  7383. {
  7384. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  7385. return false;
  7386. graphNum = atoi(scope + strlen(GraphScopePrefix));
  7387. subGraphId = 0;
  7388. const char * colon = strchr(scope, ':');
  7389. if (!colon)
  7390. {
  7391. graphName.set(scope);
  7392. return true;
  7393. }
  7394. const char * subgraph = colon+1;
  7395. graphName.set(scope, (size32_t)(colon - scope));
  7396. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  7397. subGraphId = atoi(subgraph+strlen(SubGraphScopePrefix));
  7398. return true;
  7399. }
  7400. void CLocalWorkUnit::setStatistic(StatisticCreatorType creatorType, const char * creator, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * optDescription, unsigned __int64 value, unsigned __int64 count, unsigned __int64 maxValue, StatsMergeAction mergeAction)
  7401. {
  7402. if (!scope) scope = GLOBAL_SCOPE;
  7403. const char * kindName = queryStatisticName(kind);
  7404. StatisticMeasure measure = queryMeasure(kind);
  7405. //creator. scope and name must all be present, and must not contain semi colons.
  7406. assertex(creator && scope);
  7407. CriticalBlock block(crit);
  7408. IPropertyTree * stats = p->queryPropTree("Statistics");
  7409. if (!stats)
  7410. stats = p->addPropTree("Statistics");
  7411. IPropertyTree * statTree = NULL;
  7412. if (mergeAction != StatsMergeAppend)
  7413. {
  7414. StringBuffer xpath;
  7415. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  7416. statTree = stats->queryPropTree(xpath.str());
  7417. }
  7418. if (!statTree)
  7419. {
  7420. statTree = stats->addPropTree("Statistic");
  7421. statTree->setProp("@creator", creator);
  7422. statTree->setProp("@scope", scope);
  7423. statTree->setProp("@kind", kindName);
  7424. //These items are primarily here to facilitate filtering.
  7425. statTree->setProp("@unit", queryMeasureName(measure));
  7426. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  7427. statTree->setProp("@s", queryScopeTypeName(scopeType));
  7428. statTree->setPropInt64("@ts", getTimeStampNowValue());
  7429. if (optDescription)
  7430. statTree->setProp("@desc", optDescription);
  7431. if (statistics.cached)
  7432. statistics.append(LINK(statTree));
  7433. mergeAction = StatsMergeAppend;
  7434. }
  7435. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  7436. {
  7437. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  7438. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  7439. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  7440. if (oldMax < oldValue)
  7441. oldMax = oldValue;
  7442. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  7443. statTree->setPropInt64("@count", count + oldCount);
  7444. if (maxValue > oldMax)
  7445. statTree->setPropInt64("@max", maxValue);
  7446. }
  7447. else
  7448. {
  7449. statTree->setPropInt64("@value", value);
  7450. statTree->setPropInt64("@count", count);
  7451. if (maxValue)
  7452. statTree->setPropInt64("@max", maxValue);
  7453. else
  7454. statTree->removeProp("@max");
  7455. }
  7456. //Whenever a graph time is updated recalculate the total time spent in thor, and save it
  7457. if ((scopeType == SSTgraph) && (kind == StTimeElapsed))
  7458. {
  7459. _loadStatistics();
  7460. stat_type totalTime = 0;
  7461. ForEachItemIn(i, statistics)
  7462. {
  7463. IConstWUStatistic & cur = statistics.item(i);
  7464. if ((cur.getScopeType() == SSTgraph) && (cur.getKind() == StTimeElapsed))
  7465. totalTime += cur.getValue();
  7466. }
  7467. StringBuffer t;
  7468. formatTimeCollatable(t, totalTime, false);
  7469. p->setProp("@totalThorTime", t);
  7470. }
  7471. }
  7472. void CLocalWorkUnit::_loadStatistics() const
  7473. {
  7474. statistics.load(p,"Statistics/*");
  7475. }
  7476. bool CLocalWorkUnit::getStatistic(stat_type & value, const char * scope, StatisticKind kind) const
  7477. {
  7478. //MORE: Optimize this....
  7479. WuScopeFilter filter;
  7480. filter.addScope(scope).setIncludeNesting(0).addRequiredStat(kind).addOutputStatistic(kind).finishedFilter();
  7481. Owned<IConstWUScopeIterator> stats = &getScopeIterator(filter);
  7482. if (stats->first())
  7483. return stats->getStat(kind, value);
  7484. return false;
  7485. }
  7486. IConstWUScopeIterator & CLocalWorkUnit::getScopeIterator(const WuScopeFilter & filter) const
  7487. {
  7488. assertex(filter.isOptimized());
  7489. WuScopeSourceFlags sources = filter.sourceFlags;
  7490. Owned<CompoundStatisticsScopeIterator> compoundIter = new CompoundStatisticsScopeIterator(filter);
  7491. if (sources & SSFsearchGlobalStats)
  7492. {
  7493. {
  7494. CriticalBlock block(crit);
  7495. statistics.loadBranch(p,"Statistics");
  7496. }
  7497. Owned<IConstWUScopeIterator> localStats(new WorkUnitStatisticsScopeIterator(statistics, filter.queryIterFilter()));
  7498. compoundIter->addIter(localStats);
  7499. }
  7500. if (sources & SSFsearchGraphStats)
  7501. {
  7502. const char * wuid = p->queryName();
  7503. Owned<IConstWUScopeIterator> scopeIter(new CConstGraphProgressScopeIterator(wuid, filter.queryIterFilter(), filter.minVersion));
  7504. compoundIter->addIter(scopeIter);
  7505. }
  7506. if (sources & SSFsearchGraph)
  7507. {
  7508. Owned<IConstWUScopeIterator> graphIter(new GraphScopeIterator(this, filter.queryIterFilter()));
  7509. compoundIter->addIter(graphIter);
  7510. }
  7511. if (sources & SSFsearchWorkflow)
  7512. {
  7513. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  7514. if (iter)
  7515. {
  7516. Owned<IConstWUScopeIterator> workflowIter(new WorkflowStatisticsScopeIterator(iter));
  7517. compoundIter->addIter(workflowIter);
  7518. }
  7519. }
  7520. if (sources & SSFsearchExceptions)
  7521. {
  7522. Owned<IConstWUScopeIterator> notesIter(new NotesIterator(this,filter.queryIterFilter()));
  7523. compoundIter->addIter(notesIter);
  7524. }
  7525. return *compoundIter.getClear();
  7526. }
  7527. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  7528. {
  7529. CriticalBlock block(crit);
  7530. IConstWUPlugin *existing = getPluginByName(qname);
  7531. if (existing)
  7532. return (IWUPlugin *) existing;
  7533. if (!plugins.length())
  7534. p->addPropTree("Plugins");
  7535. IPropertyTree *pl = p->queryPropTree("Plugins");
  7536. IPropertyTree *s = pl->addPropTree("Plugin");
  7537. s->Link();
  7538. IWUPlugin* q = new CLocalWUPlugin(s);
  7539. q->Link();
  7540. plugins.append(*q);
  7541. q->setPluginName(qname);
  7542. return q;
  7543. }
  7544. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  7545. {
  7546. CriticalBlock block(crit);
  7547. loadPlugins();
  7548. ForEachItemIn(idx, plugins)
  7549. {
  7550. SCMStringBuffer name;
  7551. IConstWUPlugin &cur = plugins.item(idx);
  7552. cur.getPluginName(name);
  7553. if (stricmp(name.str(), qname)==0)
  7554. {
  7555. cur.Link();
  7556. return &cur;
  7557. }
  7558. }
  7559. return NULL;
  7560. }
  7561. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  7562. {
  7563. CriticalBlock block(crit);
  7564. IConstWULibrary *existing = getLibraryByName(qname);
  7565. if (existing)
  7566. return (IWULibrary *) existing;
  7567. if (!libraries.length())
  7568. p->addPropTree("Libraries");
  7569. IPropertyTree *pl = p->queryPropTree("Libraries");
  7570. IPropertyTree *s = pl->addPropTree("Library");
  7571. s->Link();
  7572. IWULibrary* q = new CLocalWULibrary(s);
  7573. q->Link();
  7574. libraries.append(*q);
  7575. q->setName(qname);
  7576. return q;
  7577. }
  7578. void CLocalWorkUnit::_loadExceptions() const
  7579. {
  7580. assertex(exceptions.length() == 0);
  7581. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  7582. for (r->first(); r->isValid(); r->next())
  7583. {
  7584. IPropertyTree *rp = &r->query();
  7585. rp->Link();
  7586. exceptions.append(*new CLocalWUException(rp));
  7587. }
  7588. }
  7589. void CLocalWorkUnit::loadExceptions() const
  7590. {
  7591. CriticalBlock block(crit);
  7592. if (!exceptionsCached)
  7593. {
  7594. _loadExceptions();
  7595. exceptionsCached = true;
  7596. }
  7597. }
  7598. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  7599. {
  7600. CriticalBlock block(crit);
  7601. loadExceptions();
  7602. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  7603. }
  7604. unsigned CLocalWorkUnit::getExceptionCount() const
  7605. {
  7606. CriticalBlock block(crit);
  7607. loadExceptions();
  7608. return exceptions.length();
  7609. }
  7610. void CLocalWorkUnit::clearExceptions(const char *source)
  7611. {
  7612. CriticalBlock block(crit);
  7613. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7614. loadExceptions();
  7615. ForEachItemInRev(idx, exceptions)
  7616. {
  7617. IWUException &e = exceptions.item(idx);
  7618. SCMStringBuffer s;
  7619. e.getExceptionSource(s);
  7620. if (source)
  7621. {
  7622. if (!strieq(s.s, source))
  7623. continue;
  7624. }
  7625. else
  7626. {
  7627. if (strieq(s.s, "eclcc") || strieq(s.s, "eclccserver") || strieq(s.s, "eclserver") )
  7628. break;
  7629. }
  7630. VStringBuffer xpath("Exceptions/Exception[@sequence='%d']", e.getSequence());
  7631. p->removeProp(xpath);
  7632. exceptions.remove(idx);
  7633. }
  7634. if (exceptions.length() == 0)
  7635. p->removeProp("Exceptions");
  7636. }
  7637. IWUException* CLocalWorkUnit::createException()
  7638. {
  7639. CriticalBlock block(crit);
  7640. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7641. loadExceptions();
  7642. if (!exceptions.length())
  7643. p->addPropTree("Exceptions");
  7644. IPropertyTree *r = p->queryPropTree("Exceptions");
  7645. IPropertyTree *s = r->addPropTree("Exception");
  7646. s->setPropInt("@sequence", exceptions.ordinality());
  7647. IWUException* q = new CLocalWUException(LINK(s));
  7648. exceptions.append(*LINK(q));
  7649. Owned<IJlibDateTime> now = createDateTimeNow();
  7650. SCMStringBuffer temp;
  7651. now->getString(temp);
  7652. q->setTimeStamp(temp.str());
  7653. return q;
  7654. }
  7655. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  7656. {
  7657. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7658. CriticalBlock block(crit);
  7659. if (!webServicesInfoCached)
  7660. {
  7661. assertex(!webServicesInfo);
  7662. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  7663. if (s)
  7664. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  7665. webServicesInfoCached = true;
  7666. }
  7667. return webServicesInfo.getLink();
  7668. }
  7669. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  7670. {
  7671. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7672. CriticalBlock block(crit);
  7673. if (!webServicesInfoCached)
  7674. {
  7675. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  7676. if (!s)
  7677. {
  7678. if (create)
  7679. s = p->addPropTree("WebServicesInfo");
  7680. else
  7681. return NULL;
  7682. }
  7683. s->Link();
  7684. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  7685. webServicesInfoCached = true;
  7686. }
  7687. return webServicesInfo.getLink();
  7688. }
  7689. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  7690. {
  7691. CLocalWUResult *l = (CLocalWUResult *) *ll;
  7692. CLocalWUResult *r = (CLocalWUResult *) *rr;
  7693. return l->getResultSequence() - r->getResultSequence();
  7694. }
  7695. void CLocalWorkUnit::_loadResults() const
  7696. {
  7697. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  7698. for (r->first(); r->isValid(); r->next())
  7699. {
  7700. IPropertyTree *rp = &r->query();
  7701. rp->Link();
  7702. results.append(*new CLocalWUResult(rp));
  7703. }
  7704. }
  7705. void CLocalWorkUnit::loadResults() const
  7706. {
  7707. if (!resultsCached)
  7708. {
  7709. assertex(results.length() == 0);
  7710. _loadResults();
  7711. results.sort(compareResults);
  7712. resultsCached = true;
  7713. }
  7714. }
  7715. void CLocalWorkUnit::_loadVariables() const
  7716. {
  7717. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  7718. for (r->first(); r->isValid(); r->next())
  7719. {
  7720. IPropertyTree *rp = &r->query();
  7721. rp->Link();
  7722. variables.append(*new CLocalWUResult(rp));
  7723. }
  7724. }
  7725. void CLocalWorkUnit::loadVariables() const
  7726. {
  7727. if (!variablesCached)
  7728. {
  7729. assertex(variables.length() == 0);
  7730. _loadVariables();
  7731. variablesCached = true;
  7732. }
  7733. }
  7734. void CLocalWorkUnit::_loadTemporaries() const
  7735. {
  7736. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  7737. for (r->first(); r->isValid(); r->next())
  7738. {
  7739. IPropertyTree *rp = &r->query();
  7740. rp->Link();
  7741. temporaries.append(*new CLocalWUResult(rp));
  7742. }
  7743. }
  7744. void CLocalWorkUnit::loadTemporaries() const
  7745. {
  7746. if (!temporariesCached)
  7747. {
  7748. assertex(temporaries.length() == 0);
  7749. _loadTemporaries();
  7750. temporariesCached = true;
  7751. }
  7752. }
  7753. void CLocalWorkUnit::deleteTemporaries()
  7754. {
  7755. CriticalBlock block(crit);
  7756. if (temporariesCached)
  7757. {
  7758. temporaries.kill();
  7759. temporariesCached = false;
  7760. }
  7761. p->removeProp("Temporaries");
  7762. }
  7763. IWUResult* CLocalWorkUnit::createResult()
  7764. {
  7765. CriticalBlock block(crit);
  7766. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7767. loadResults();
  7768. if (!results.length())
  7769. p->addPropTree("Results");
  7770. IPropertyTree *r = p->queryPropTree("Results");
  7771. IPropertyTree *s = r->addPropTree("Result");
  7772. s->Link();
  7773. IWUResult* q = new CLocalWUResult(s);
  7774. q->Link();
  7775. results.append(*q);
  7776. return q;
  7777. }
  7778. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  7779. {
  7780. CriticalBlock block(crit);
  7781. IConstWUResult *existing = getResultByName(qname);
  7782. if (existing)
  7783. return (IWUResult *) existing;
  7784. IWUResult* q = createResult();
  7785. q->setResultName(qname);
  7786. return q;
  7787. }
  7788. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  7789. {
  7790. CriticalBlock block(crit);
  7791. IConstWUResult *existing = getResultBySequence(seq);
  7792. if (existing)
  7793. return (IWUResult *) existing;
  7794. IWUResult* q = createResult();
  7795. q->setResultSequence(seq);
  7796. return q;
  7797. }
  7798. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  7799. {
  7800. CriticalBlock block(crit);
  7801. loadResults();
  7802. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  7803. }
  7804. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  7805. {
  7806. CriticalBlock block(crit);
  7807. loadResults();
  7808. ForEachItemIn(idx, results)
  7809. {
  7810. SCMStringBuffer name;
  7811. IConstWUResult &cur = results.item(idx);
  7812. cur.getResultName(name);
  7813. if (stricmp(name.str(), qname)==0)
  7814. {
  7815. cur.Link();
  7816. return &cur;
  7817. }
  7818. }
  7819. return NULL;
  7820. }
  7821. IConstWUResult* CLocalWorkUnit::getQueryResultByName(const char *qname) const
  7822. {
  7823. CriticalBlock block(crit);
  7824. loadResults();
  7825. ForEachItemIn(idx, results)
  7826. {
  7827. IConstWUResult &cur = results.item(idx);
  7828. if (!isSpecialResultSequence(cur.getResultSequence()))
  7829. {
  7830. SCMStringBuffer name;
  7831. cur.getResultName(name);
  7832. if (stricmp(name.str(), qname)==0)
  7833. {
  7834. cur.Link();
  7835. return &cur;
  7836. }
  7837. }
  7838. }
  7839. return NULL;
  7840. }
  7841. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  7842. {
  7843. CriticalBlock block(crit);
  7844. loadResults();
  7845. ForEachItemIn(idx, results)
  7846. {
  7847. IConstWUResult &cur = results.item(idx);
  7848. if (cur.getResultSequence() == seq)
  7849. {
  7850. cur.Link();
  7851. return &cur;
  7852. }
  7853. }
  7854. return NULL;
  7855. }
  7856. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  7857. {
  7858. CriticalBlock block(crit);
  7859. loadVariables();
  7860. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  7861. }
  7862. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  7863. {
  7864. CriticalBlock block(crit);
  7865. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  7866. return getVariableByName(qname);
  7867. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  7868. return global->getVariableByName(qname);
  7869. }
  7870. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  7871. {
  7872. CriticalBlock block(crit);
  7873. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  7874. return updateVariableByName(qname);
  7875. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  7876. return global->updateVariableByName(qname);
  7877. }
  7878. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  7879. {
  7880. CriticalBlock block(crit);
  7881. loadVariables();
  7882. ForEachItemIn(idx, variables)
  7883. {
  7884. SCMStringBuffer name;
  7885. IConstWUResult &cur = variables.item(idx);
  7886. cur.getResultName(name);
  7887. if (stricmp(name.str(), qname)==0)
  7888. {
  7889. cur.Link();
  7890. return &cur;
  7891. }
  7892. }
  7893. return NULL;
  7894. }
  7895. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  7896. {
  7897. CriticalBlock block(crit);
  7898. loadTemporaries();
  7899. ForEachItemIn(idx, temporaries)
  7900. {
  7901. SCMStringBuffer name;
  7902. IConstWUResult &cur = temporaries.item(idx);
  7903. cur.getResultName(name);
  7904. if (stricmp(name.str(), qname)==0)
  7905. {
  7906. cur.Link();
  7907. return &cur;
  7908. }
  7909. }
  7910. return NULL;
  7911. }
  7912. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  7913. {
  7914. CriticalBlock block(crit);
  7915. loadTemporaries();
  7916. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  7917. }
  7918. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  7919. {
  7920. CriticalBlock block(crit);
  7921. IConstWUResult *existing = getTemporaryByName(qname);
  7922. if (existing)
  7923. return (IWUResult *) existing;
  7924. IPropertyTree *vars = (temporaries.length()) ? p->queryPropTree("Temporaries") : p->addPropTree("Temporaries");
  7925. IPropertyTree *s = vars->addPropTree("Variable");
  7926. s->Link();
  7927. IWUResult* q = new CLocalWUResult(s);
  7928. q->Link();
  7929. temporaries.append(*q);
  7930. q->setResultName(qname);
  7931. q->setResultSequence(ResultSequenceInternal);
  7932. return q;
  7933. }
  7934. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  7935. {
  7936. CriticalBlock block(crit);
  7937. IConstWUResult *existing = getVariableByName(qname);
  7938. if (existing)
  7939. return (IWUResult *) existing;
  7940. if (!variables.length())
  7941. p->addPropTree("Variables");
  7942. IPropertyTree *vars = p->queryPropTree("Variables");
  7943. IPropertyTree *s = vars->addPropTree("Variable");
  7944. s->Link();
  7945. IWUResult* q = new CLocalWUResult(s);
  7946. q->Link();
  7947. variables.append(*q);
  7948. q->setResultName(qname);
  7949. q->setResultSequence(ResultSequenceStored);
  7950. return q;
  7951. }
  7952. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  7953. {
  7954. CriticalBlock block(crit);
  7955. IPropertyTree *files = p->queryPropTree("Files");
  7956. if (!files) return;
  7957. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  7958. ICopyArrayOf<IPropertyTree> toRemove;
  7959. ForEach (*iter)
  7960. {
  7961. IPropertyTree &file = iter->query();
  7962. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  7963. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  7964. bool needDelete;
  7965. switch(fileKind)
  7966. {
  7967. case WUFileTemporary:
  7968. if(graph==NULL)
  7969. needDelete = true;
  7970. else
  7971. {
  7972. const char *graphOwner = file.queryProp("@graph");
  7973. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  7974. }
  7975. break;
  7976. case WUFileJobOwned:
  7977. needDelete = ((graph==NULL) && deleteJobOwned);
  7978. break;
  7979. case WUFileOwned:
  7980. needDelete = ((graph==NULL) && deleteOwned);
  7981. break;
  7982. default:
  7983. needDelete = false;
  7984. }
  7985. if(needDelete)
  7986. {
  7987. const char *name = file.queryProp("@name");
  7988. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  7989. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  7990. toRemove.append(file);
  7991. }
  7992. }
  7993. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  7994. }
  7995. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  7996. {
  7997. IDistributedSuperFile *super = file->querySuperFile();
  7998. StringBuffer fname;
  7999. file->getLogicalName(fname);
  8000. if (fname.length())
  8001. {
  8002. StringBuffer path("File[@name=\"");
  8003. path.append(fname).append("\"]");
  8004. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  8005. if (fileTree)
  8006. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  8007. else
  8008. {
  8009. StringBuffer cluster;
  8010. file->getClusterName(0,cluster);
  8011. fileTree = createPTree();
  8012. fileTree->setProp("@name", fname.str());
  8013. fileTree->setProp("@cluster", cluster.str());
  8014. fileTree->setPropInt("@useCount", 1);
  8015. fileTree = filesRead->addPropTree("File", fileTree);
  8016. }
  8017. if (super)
  8018. {
  8019. fileTree->setPropBool("@super", true);
  8020. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  8021. ForEach (*iter)
  8022. {
  8023. IDistributedFile &file = iter->query();
  8024. StringBuffer fname;
  8025. file.getLogicalName(fname);
  8026. fileTree->addPropTree("Subfile")->setProp("@name", fname.str());
  8027. _noteFileRead(&file, filesRead);
  8028. }
  8029. }
  8030. }
  8031. }
  8032. void CLocalWorkUnit::_loadFilesRead() const
  8033. {
  8034. // Nothing to do
  8035. }
  8036. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  8037. {
  8038. if (file)
  8039. {
  8040. CriticalBlock block(crit);
  8041. IPropertyTree *files = p->queryPropTree("FilesRead");
  8042. if (!files)
  8043. files = p->addPropTree("FilesRead");
  8044. _noteFileRead(file, files);
  8045. }
  8046. }
  8047. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  8048. {
  8049. if (fieldUsage)
  8050. {
  8051. CriticalBlock block(crit);
  8052. p->addPropTree("usedsources", fieldUsage);
  8053. }
  8054. }
  8055. void CLocalWorkUnit::_loadFilesWritten() const
  8056. {
  8057. // Nothing to do
  8058. }
  8059. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8060. {
  8061. StringBuffer path("File[@name=\"");
  8062. path.append(fileName).append("\"]");
  8063. if (cluster)
  8064. path.append("[@cluster=\"").append(cluster).append("\"]");
  8065. IPropertyTree *file = files->queryPropTree(path.str());
  8066. if (file) files->removeTree(file);
  8067. file = createPTree();
  8068. file->setProp("@name", fileName);
  8069. if (cluster)
  8070. file->setProp("@cluster", cluster);
  8071. if (graphOwner)
  8072. file->setProp("@graph", graphOwner);
  8073. file->setPropInt("@kind", (unsigned)fileKind);
  8074. if (WUFileTemporary == fileKind)
  8075. file->setPropInt("@usageCount", usageCount);
  8076. files->addPropTree("File", file);
  8077. }
  8078. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8079. {
  8080. CriticalBlock block(crit);
  8081. IPropertyTree *files = p->queryPropTree("Files");
  8082. if (!files)
  8083. files = p->addPropTree("Files");
  8084. if (!clusters)
  8085. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  8086. else
  8087. {
  8088. ForEachItemIn(c, *clusters)
  8089. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  8090. }
  8091. }
  8092. void CLocalWorkUnit::releaseFile(const char *fileName)
  8093. {
  8094. StringBuffer path("File[@name=\"");
  8095. path.append(fileName).append("\"]");
  8096. CriticalBlock block(crit);
  8097. IPropertyTree *files = p->queryPropTree("Files");
  8098. if (!files) return;
  8099. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  8100. ForEach (*fiter)
  8101. {
  8102. IPropertyTree *file = &fiter->query();
  8103. unsigned usageCount = file->getPropInt("@usageCount");
  8104. if (usageCount > 1)
  8105. file->setPropInt("@usageCount", usageCount-1);
  8106. else
  8107. {
  8108. StringAttr name(file->queryProp("@name"));
  8109. files->removeTree(file);
  8110. if (!name.isEmpty()&&(1 == usageCount))
  8111. {
  8112. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  8113. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  8114. }
  8115. }
  8116. }
  8117. }
  8118. void CLocalWorkUnit::clearGraphProgress() const
  8119. {
  8120. }
  8121. void CLocalWorkUnit::resetBeforeGeneration()
  8122. {
  8123. CriticalBlock block(crit);
  8124. //Remove all associated files
  8125. Owned<IWUQuery> q = updateQuery();
  8126. q->removeAssociatedFiles();
  8127. //Remove any pre-existing workflow information
  8128. workflowIterator.clear();
  8129. p->removeProp("Workflow");
  8130. }
  8131. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  8132. {
  8133. StringBuffer path("Files/File[@name=\"");
  8134. path.append(fileName).append("\"]/@usageCount");
  8135. CriticalBlock block(crit);
  8136. return p->getPropInt(path.str());
  8137. }
  8138. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  8139. {
  8140. CriticalBlock block(crit);
  8141. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  8142. if (!fieldUsageTree)
  8143. return NULL;
  8144. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  8145. return new CConstWUFileUsageIterator(iter);
  8146. }
  8147. bool isFilenameResolved(StringBuffer& filename)
  8148. {
  8149. size32_t length = filename.length();
  8150. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  8151. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  8152. return true;
  8153. else
  8154. return false;
  8155. }
  8156. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  8157. {
  8158. bool scopeLoaded = false;
  8159. StringBuffer defaultScope;
  8160. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  8161. if (!files)
  8162. return false; // this query was not compiled with recordFieldUsage option.
  8163. ForEach(*files)
  8164. {
  8165. Owned<IConstWUFileUsage> file = files->get();
  8166. StringBuffer filename(file->queryName());
  8167. size32_t length = filename.length();
  8168. if (length == 0)
  8169. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8170. StringBuffer normalizedFilename;
  8171. // Two cases to handle:
  8172. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  8173. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  8174. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  8175. if (isFilenameResolved(filename))
  8176. {
  8177. // filename cannot be empty (i.e. empty single quotes '')
  8178. if (length == 2)
  8179. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8180. // Remove surrounding single quotes
  8181. StringAttr cleanFilename(filename.str()+1, length-2);
  8182. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  8183. // We need to load a default scope from config and prefix the filename with it.
  8184. if (cleanFilename.str()[0] != '~')
  8185. {
  8186. // loading a default scope from config is expensive, and should be only done once and be reused later.
  8187. if (!scopeLoaded)
  8188. {
  8189. //MORE: This should actually depend on the cluster that was active when the file was read!
  8190. if (!resolveFilePrefix(defaultScope, clusterName))
  8191. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  8192. scopeLoaded = true;
  8193. }
  8194. normalizedFilename.append(defaultScope.str());
  8195. normalizedFilename.append(cleanFilename.str());
  8196. }
  8197. else
  8198. {
  8199. normalizedFilename.append(cleanFilename);
  8200. }
  8201. }
  8202. else
  8203. {
  8204. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  8205. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  8206. normalizedFilename.append(filename.str());
  8207. }
  8208. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  8209. ForEach(*fields)
  8210. {
  8211. Owned<IConstWUFieldUsage> field = fields->get();
  8212. filenames.append(normalizedFilename.str());
  8213. columnnames.append(field->queryName());
  8214. }
  8215. }
  8216. return true;
  8217. }
  8218. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  8219. {
  8220. return p->getPropTree("DiskUsageStats");
  8221. }
  8222. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  8223. {
  8224. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  8225. offset_t maxNodeUsage;
  8226. if (stats)
  8227. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  8228. else
  8229. {
  8230. stats = p->addPropTree("DiskUsageStats");
  8231. maxNodeUsage = 0;
  8232. }
  8233. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  8234. {
  8235. // record all details at time of max node usage.
  8236. stats->setPropInt("@minNode", _minNode);
  8237. stats->setPropInt("@maxNode", _maxNode);
  8238. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  8239. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  8240. stats->setPropInt64("@graphId", _graphId);
  8241. if (_avgNodeUsage)
  8242. {
  8243. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  8244. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  8245. stats->setPropInt("@skewHi", _skewHi);
  8246. stats->setPropInt("@skewLo", _skewLo);
  8247. }
  8248. }
  8249. }
  8250. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  8251. {
  8252. CriticalBlock block(crit);
  8253. _loadFilesWritten();
  8254. return * p->getElements("Files/File");
  8255. }
  8256. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  8257. {
  8258. CriticalBlock block(crit);
  8259. _loadFilesRead();
  8260. return * p->getElements("FilesRead/File");
  8261. }
  8262. //=================================================================================================
  8263. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  8264. {
  8265. CriticalBlock block(crit);
  8266. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  8267. return false;
  8268. const char * currentcluster = queryClusterName();
  8269. const char *wuid = p->queryName();
  8270. StringBuffer curqname;
  8271. getClusterThorQueueName(curqname, currentcluster);
  8272. void *qi = qs->getQ(curqname.str(),wuid);
  8273. if (!qi)
  8274. return false;
  8275. setClusterName(cluster);
  8276. StringBuffer newqname;
  8277. getClusterThorQueueName(newqname, cluster);
  8278. qs->putQ(newqname.str(),wuid,qi);
  8279. return true;
  8280. }
  8281. //=================================================================================================
  8282. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  8283. {
  8284. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  8285. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  8286. ForEach(*graphIter)
  8287. {
  8288. IConstWUGraph &graph = graphIter->query();
  8289. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  8290. SCMStringBuffer gName;
  8291. graph.getName(gName);
  8292. StringBuffer xpath("Graphs/Graph[@name=\"");
  8293. xpath.append(gName.s).append("\"]/xgmml");
  8294. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  8295. if (xgmml) // don't know of any reason it shouldn't exist
  8296. {
  8297. xgmml->removeProp("graphBin");
  8298. xgmml->setPropTree("graph", graphTree.getClear());
  8299. }
  8300. }
  8301. return ret.getClear();
  8302. }
  8303. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  8304. {
  8305. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  8306. ForEach(*iter)
  8307. {
  8308. IPropertyTree &graph = iter->query();
  8309. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  8310. }
  8311. }
  8312. void CLocalWorkUnit::loadGraphs(bool heavy) const
  8313. {
  8314. if (graphsCached < (heavy ? 2 : 1))
  8315. {
  8316. graphs.kill();
  8317. _loadGraphs(heavy);
  8318. graphsCached = (heavy ? 2 : 1);
  8319. }
  8320. }
  8321. EnumMapping graphTypes[] = {
  8322. { GraphTypeAny, "unknown" },
  8323. { GraphTypeProgress, "progress" },
  8324. { GraphTypeEcl, "ECL" },
  8325. { GraphTypeActivities, "activities" },
  8326. { GraphTypeSubProgress, "subgraph" },
  8327. { GraphTypeSize, NULL },
  8328. };
  8329. WUGraphType getGraphTypeFromString(const char* type)
  8330. {
  8331. return (WUGraphType) getEnum(type, graphTypes);
  8332. }
  8333. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  8334. {
  8335. wuidVersion = owner.getWuidVersion();
  8336. }
  8337. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  8338. {
  8339. str.set(p->queryProp("@name"));
  8340. return str;
  8341. }
  8342. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  8343. {
  8344. if (wuidVersion >= 2)
  8345. {
  8346. str.set(p->queryProp("@label"));
  8347. return str;
  8348. }
  8349. else
  8350. {
  8351. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  8352. str.set(xgmml->queryProp("@label"));
  8353. return str;
  8354. }
  8355. }
  8356. WUGraphState CLocalWUGraph::getState() const
  8357. {
  8358. return owner.queryGraphState(p->queryProp("@name"));
  8359. }
  8360. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  8361. {
  8362. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  8363. if (xgmml)
  8364. {
  8365. StringBuffer x;
  8366. toXML(xgmml, x);
  8367. str.set(x.str());
  8368. }
  8369. return str;
  8370. }
  8371. unsigned CLocalWorkUnit::getGraphCount() const
  8372. {
  8373. CriticalBlock block(crit);
  8374. if (p->hasProp("Graphs"))
  8375. {
  8376. return p->queryPropTree("Graphs")->numChildren();
  8377. }
  8378. return 0;
  8379. }
  8380. unsigned CLocalWorkUnit::getSourceFileCount() const
  8381. {
  8382. CriticalBlock block(crit);
  8383. _loadFilesRead();
  8384. if (p->hasProp("FilesRead"))
  8385. {
  8386. return p->queryPropTree("FilesRead")->numChildren();
  8387. }
  8388. return 0;
  8389. }
  8390. unsigned CLocalWorkUnit::getResultCount() const
  8391. {
  8392. CriticalBlock block(crit);
  8393. if (p->hasProp("Results"))
  8394. {
  8395. return p->queryPropTree("Results")->numChildren();
  8396. }
  8397. return 0;
  8398. }
  8399. unsigned CLocalWorkUnit::getVariableCount() const
  8400. {
  8401. CriticalBlock block(crit);
  8402. if (p->hasProp("Variables"))
  8403. {
  8404. return p->queryPropTree("Variables")->numChildren();
  8405. }
  8406. return 0;
  8407. }
  8408. unsigned CLocalWorkUnit::getApplicationValueCount() const
  8409. {
  8410. CriticalBlock block(crit);
  8411. if (p->hasProp("Application"))
  8412. {
  8413. return p->queryPropTree("Application")->numChildren();
  8414. }
  8415. return 0;
  8416. }
  8417. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent, bool hidePasswords)
  8418. {
  8419. appendXMLOpenTag(s, name, NULL, false);
  8420. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  8421. if (attrs->first())
  8422. {
  8423. unsigned attributeindent = indent + (size32_t) strlen(name);
  8424. unsigned count = attrs->count();
  8425. bool doindent = false;
  8426. ForEach(*attrs)
  8427. {
  8428. if (hidePasswords && streq(attrs->queryName(), "@token"))
  8429. continue;
  8430. #ifndef _DEBUG
  8431. if (hidePasswords && streq(attrs->queryName(), "@distributedAccessToken"))
  8432. continue;
  8433. #endif
  8434. if (doindent)
  8435. s.append('\n').appendN(attributeindent, ' ');
  8436. else if (count > 3)
  8437. doindent = true;
  8438. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  8439. }
  8440. }
  8441. s.append('>');
  8442. return s;
  8443. }
  8444. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  8445. {
  8446. CriticalBlock block(crit);
  8447. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  8448. if (!paramTree)
  8449. return str;
  8450. StringBuffer xml;
  8451. if (!hidePasswords)
  8452. toXML(paramTree, xml);
  8453. else
  8454. {
  8455. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0, false).append('\n');
  8456. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  8457. ForEach(*elems)
  8458. {
  8459. const char *paramname = elems->query().queryName();
  8460. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8461. if (p->getPropBool(xpath))
  8462. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  8463. else
  8464. toXML(&elems->query(), xml, 2);
  8465. }
  8466. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  8467. }
  8468. str.set(xml);
  8469. return str;
  8470. }
  8471. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  8472. {
  8473. CriticalBlock block(crit);
  8474. return p->getPropTree("Parameters");
  8475. }
  8476. void CLocalWorkUnit::setXmlParams(const char *params)
  8477. {
  8478. CriticalBlock block(crit);
  8479. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  8480. }
  8481. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  8482. {
  8483. CriticalBlock block(crit);
  8484. p->setPropTree("Parameters", tree);
  8485. }
  8486. unsigned __int64 CLocalWorkUnit::getHash() const
  8487. {
  8488. CriticalBlock block(crit);
  8489. return p->getPropInt64("@hash");
  8490. }
  8491. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  8492. {
  8493. CriticalBlock block(crit);
  8494. p->setPropInt64("@hash", hash);
  8495. }
  8496. // getGraphs / getGraphsMeta
  8497. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  8498. // If a type other than any is requested, a postfilter is needed.
  8499. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  8500. {
  8501. WUGraphType type;
  8502. Owned<T> base;
  8503. bool match()
  8504. {
  8505. return base->query().getType()==type;
  8506. }
  8507. public:
  8508. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  8509. : base(_base), type(_type)
  8510. {
  8511. }
  8512. bool first()
  8513. {
  8514. if (!base->first())
  8515. return false;
  8516. if (match())
  8517. return true;
  8518. return next();
  8519. }
  8520. bool next()
  8521. {
  8522. while (base->next())
  8523. if (match())
  8524. return true;
  8525. return false;
  8526. }
  8527. virtual bool isValid()
  8528. {
  8529. return base->isValid();
  8530. }
  8531. U & query()
  8532. {
  8533. return base->query();
  8534. }
  8535. };
  8536. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  8537. {
  8538. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  8539. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  8540. */
  8541. CriticalBlock block(crit);
  8542. loadGraphs(false);
  8543. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  8544. if (type!=GraphTypeAny)
  8545. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  8546. return *giter;
  8547. }
  8548. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  8549. {
  8550. CriticalBlock block(crit);
  8551. loadGraphs(true);
  8552. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  8553. if (type!=GraphTypeAny)
  8554. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  8555. return *giter;
  8556. }
  8557. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  8558. {
  8559. CriticalBlock block(crit);
  8560. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  8561. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  8562. IPTree *graph = p->queryPropTree(xpath);
  8563. if (graph)
  8564. return new CLocalWUGraph(*this, LINK(graph));
  8565. return NULL;
  8566. }
  8567. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  8568. {
  8569. CriticalBlock block(crit);
  8570. if (!graphs.length())
  8571. p->addPropTree("Graphs");
  8572. IPropertyTree *r = p->queryPropTree("Graphs");
  8573. IPropertyTree *s = r->addPropTree("Graph");
  8574. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  8575. q->setName(name);
  8576. q->setLabel(label);
  8577. q->setType(type);
  8578. q->setWfid(wfid);
  8579. q->setXGMMLTree(xgmml);
  8580. graphs.append(*q);
  8581. }
  8582. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  8583. {
  8584. /* Owned<IRemoteConnection> conn = getProgressConnection();
  8585. if (conn)
  8586. {
  8587. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  8588. if (progress)
  8589. return new CConstGraphProgress(p->queryName(), graphName, progress);
  8590. }
  8591. */
  8592. return NULL;
  8593. }
  8594. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  8595. {
  8596. throwUnexpected(); // Should only be used for persisted workunits
  8597. }
  8598. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  8599. {
  8600. throwUnexpected(); // Should only be used for persisted workunits
  8601. }
  8602. void CLocalWorkUnit::setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  8603. {
  8604. throwUnexpected(); // Should only be used for persisted workunits
  8605. }
  8606. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  8607. {
  8608. throwUnexpected(); // Should only be used for persisted workunits
  8609. }
  8610. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const
  8611. {
  8612. return new CWuGraphStats(LINK(p), creatorType, creator, _wfid, graphName, subgraph);
  8613. }
  8614. void CLocalWUGraph::setName(const char *str)
  8615. {
  8616. p->setProp("@name", str);
  8617. }
  8618. void CLocalWUGraph::setLabel(const char *str)
  8619. {
  8620. p->setProp("@label", str);
  8621. }
  8622. void CLocalWUGraph::setWfid(unsigned wfid)
  8623. {
  8624. p->setPropInt("@wfid", wfid);
  8625. }
  8626. void CLocalWUGraph::setXGMML(const char *str)
  8627. {
  8628. setXGMMLTree(createPTreeFromXMLString(str,ipt_lowmem));
  8629. }
  8630. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  8631. {
  8632. assertex(strcmp(_graph->queryName(), "graph")==0);
  8633. IPropertyTree *xgmml = p->setPropTree("xgmml");
  8634. MemoryBuffer mb;
  8635. _graph->serialize(mb);
  8636. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  8637. // Cassandra workunit code actually lzw compresses the parent anyway
  8638. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  8639. graph.setown(_graph);
  8640. }
  8641. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  8642. {
  8643. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  8644. ForEach (*aIter)
  8645. {
  8646. const char *aName = aIter->queryName()+1;
  8647. if (0 != stricmp("id", aName)) // "id" reserved.
  8648. {
  8649. IPropertyTree *att = targetNode.addPropTree("att");
  8650. att->setProp("@name", aName);
  8651. att->setProp("@value", aIter->queryValue());
  8652. }
  8653. }
  8654. }
  8655. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  8656. {
  8657. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  8658. if (!graphNode) return;
  8659. unsigned nodeId = rootNode.getPropInt("@id");
  8660. StringBuffer progressNodePath("node[@id=\"");
  8661. progressNodePath.append(nodeId).append("\"]");
  8662. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  8663. if (progressNode)
  8664. {
  8665. expandAttributes(*graphNode, *progressNode);
  8666. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  8667. ForEach (*edges)
  8668. {
  8669. IPropertyTree &edge = edges->query();
  8670. StringBuffer edgePath("edge[@id=\"");
  8671. edgePath.append(edge.queryProp("@id")).append("\"]");
  8672. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  8673. if (graphEdge)
  8674. {
  8675. if (progressV < 1)
  8676. mergePTree(graphEdge, &edge);
  8677. else
  8678. { // must translate to XGMML format
  8679. expandAttributes(*graphEdge, edge);
  8680. // This is really only here, so that our progress format can use non-attribute values, which have different efficiency qualifies (e.g. can be external by dali)
  8681. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  8682. ForEach (*iter)
  8683. {
  8684. IPropertyTree &t = iter->query();
  8685. IPropertyTree *att = graphEdge->addPropTree("att");
  8686. att->setProp("@name", t.queryName());
  8687. att->setProp("@value", t.queryProp(NULL));
  8688. }
  8689. }
  8690. }
  8691. }
  8692. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  8693. ForEach (*nodes)
  8694. {
  8695. IPropertyTree &node = nodes->query();
  8696. StringBuffer nodePath("node[@id=\"");
  8697. nodePath.append(node.queryProp("@id")).append("\"]");
  8698. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  8699. if (_node)
  8700. {
  8701. if (progressV < 1)
  8702. mergePTree(_node, &node);
  8703. else
  8704. { // must translate to XGMML format
  8705. expandAttributes(*_node, node);
  8706. }
  8707. }
  8708. }
  8709. }
  8710. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  8711. ForEach (*iter)
  8712. mergeProgress(iter->query(), progressTree, progressV);
  8713. }
  8714. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  8715. {
  8716. return p->getPropTree("xgmml");
  8717. }
  8718. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  8719. {
  8720. if (!graph)
  8721. {
  8722. // NB: although graphBin introduced in wuidVersion==2,
  8723. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  8724. MemoryBuffer mb;
  8725. if (p->getPropBin("xgmml/graphBin", mb))
  8726. graph.setown(createPTree(mb, ipt_lowmem));
  8727. else
  8728. graph.setown(p->getBranch("xgmml/graph"));
  8729. if (!graph)
  8730. return NULL;
  8731. }
  8732. if (!doMergeProgress)
  8733. return graph.getLink();
  8734. else
  8735. {
  8736. Owned<IPropertyTree> copy = createPTreeFromIPT(graph, ipt_lowmem);
  8737. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  8738. if (progress)
  8739. {
  8740. //MORE: Eventually this should directly access the new stats structure
  8741. unsigned progressV = progress->queryFormatVersion();
  8742. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  8743. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  8744. ForEach (*nodeIterator)
  8745. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  8746. }
  8747. return copy.getClear();
  8748. }
  8749. }
  8750. WUGraphType CLocalWUGraph::getType() const
  8751. {
  8752. return (WUGraphType) getEnum(p, "@type", graphTypes);
  8753. }
  8754. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  8755. {
  8756. str.set(p->queryProp("@type"));
  8757. if (!str.length())
  8758. str.set("unknown");
  8759. return str;
  8760. }
  8761. unsigned CLocalWUGraph::getWfid() const
  8762. {
  8763. return p->getPropInt("@wfid", 0);
  8764. }
  8765. void CLocalWUGraph::setType(WUGraphType _type)
  8766. {
  8767. setEnum(p, "@type", _type, graphTypes);
  8768. }
  8769. //=================================================================================================
  8770. EnumMapping queryFileTypes[] = {
  8771. { FileTypeCpp, "cpp" },
  8772. { FileTypeDll, "dll" },
  8773. { FileTypeResText, "res" },
  8774. { FileTypeHintXml, "hint" },
  8775. { FileTypeXml, "xml" },
  8776. { FileTypeLog, "log" },
  8777. { FileTypeSize, NULL },
  8778. };
  8779. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  8780. {
  8781. }
  8782. WUFileType CLocalWUAssociated::getType() const
  8783. {
  8784. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  8785. }
  8786. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  8787. {
  8788. str.set(p->queryProp("@desc"));
  8789. return str;
  8790. }
  8791. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  8792. {
  8793. str.set(p->queryProp("@ip"));
  8794. return str;
  8795. }
  8796. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  8797. {
  8798. str.set(p->queryProp("@filename"));
  8799. return str;
  8800. }
  8801. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  8802. {
  8803. str.set(pathTail(p->queryProp("@filename")));
  8804. return str;
  8805. }
  8806. unsigned CLocalWUAssociated::getCrc() const
  8807. {
  8808. return p->getPropInt("@crc", 0);
  8809. }
  8810. unsigned CLocalWUAssociated::getMinActivityId() const
  8811. {
  8812. return p->getPropInt("@minActivity", 0);
  8813. }
  8814. unsigned CLocalWUAssociated::getMaxActivityId() const
  8815. {
  8816. return p->getPropInt("@maxActivity", 0);
  8817. }
  8818. //=================================================================================================
  8819. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  8820. {
  8821. associatedCached = false;
  8822. }
  8823. EnumMapping queryTypes[] = {
  8824. { QueryTypeUnknown, "unknown" },
  8825. { QueryTypeEcl, "ECL" },
  8826. { QueryTypeSql, "SQL" },
  8827. { QueryTypeXml, "XML" },
  8828. { QueryTypeAttribute, "Attribute" },
  8829. { QueryTypeSize, NULL },
  8830. };
  8831. WUQueryType CLocalWUQuery::getQueryType() const
  8832. {
  8833. return (WUQueryType) getEnum(p, "@type", queryTypes);
  8834. }
  8835. void CLocalWUQuery::setQueryType(WUQueryType qt)
  8836. {
  8837. setEnum(p, "@type", qt, queryTypes);
  8838. }
  8839. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  8840. {
  8841. const char *text = p->queryProp("Text");
  8842. if (!text)
  8843. text = p->queryProp("ShortText");
  8844. str.set(text);
  8845. return str;
  8846. }
  8847. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  8848. {
  8849. const char * text = p->queryProp("ShortText");
  8850. if (text)
  8851. str.set(text);
  8852. else
  8853. {
  8854. text = p->queryProp("Text");
  8855. if (isArchiveQuery(text))
  8856. {
  8857. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  8858. const char * path = xml->queryProp("Query/@attributePath");
  8859. if (path)
  8860. {
  8861. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  8862. if (resolved)
  8863. str.set(resolved->queryProp(NULL));
  8864. }
  8865. else
  8866. str.set(xml->queryProp("Query"));
  8867. }
  8868. else
  8869. str.set(text);
  8870. }
  8871. return str;
  8872. }
  8873. bool CLocalWUQuery::isArchive() const
  8874. {
  8875. if (p->hasProp("@isArchive"))
  8876. return p->getPropBool("@isArchive");
  8877. const char *text = p->queryProp("Text");
  8878. return isArchiveQuery(text);
  8879. }
  8880. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  8881. {
  8882. str.set(p->queryProp("@name"));
  8883. return str;
  8884. }
  8885. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  8886. {
  8887. str.set(p->queryProp("@main"));
  8888. return str;
  8889. }
  8890. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  8891. {
  8892. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  8893. if (entry)
  8894. entry->getNameTail(str);
  8895. return str;
  8896. }
  8897. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  8898. {
  8899. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  8900. if (entry)
  8901. entry->getName(str);
  8902. return str;
  8903. }
  8904. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  8905. {
  8906. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  8907. if (entry)
  8908. entry->getName(str);
  8909. return str;
  8910. }
  8911. unsigned CLocalWUQuery::getQueryDllCrc() const
  8912. {
  8913. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  8914. if (entry)
  8915. return entry->getCrc();
  8916. return 0;
  8917. }
  8918. void CLocalWUQuery::setQueryText(const char *text)
  8919. {
  8920. bool isArchive = isArchiveQuery(text);
  8921. if (isArchive)
  8922. {
  8923. p->setProp("Text", text);
  8924. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  8925. const char * path = xml->queryProp("Query/@attributePath");
  8926. if (path)
  8927. {
  8928. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  8929. if (resolved)
  8930. p->setProp("ShortText", resolved->queryProp(NULL));
  8931. }
  8932. else
  8933. p->setProp("ShortText", xml->queryProp("Query"));
  8934. }
  8935. else
  8936. {
  8937. p->setProp("Text", text); // At some point in the future we may be able to remove this,
  8938. // but as long as there may be new workunits compiled by old systems, we can't
  8939. p->setProp("ShortText", text);
  8940. }
  8941. p->setPropBool("@isArchive", isArchive);
  8942. if (isArchive)
  8943. p->setPropBool("@hasArchive", true); //preserved if setQueryText is called multiple times. Should setting this be more explicit?
  8944. }
  8945. void CLocalWUQuery::setQueryName(const char *qname)
  8946. {
  8947. p->setProp("@name", qname);
  8948. }
  8949. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  8950. {
  8951. p->setProp("@main", str);
  8952. }
  8953. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  8954. {
  8955. CriticalBlock block(crit);
  8956. loadAssociated();
  8957. StringBuffer xpath;
  8958. xpath.append("Associated/File[@filename=\"").append(name).append("\"]");
  8959. if (p->hasProp(xpath))
  8960. return;
  8961. if (!associated.length())
  8962. p->addPropTree("Associated");
  8963. IPropertyTree *pl = p->queryPropTree("Associated");
  8964. IPropertyTree *s = pl->addPropTree("File");
  8965. setEnum(s, "@type", type, queryFileTypes);
  8966. s->setProp("@filename", name);
  8967. s->setProp("@ip", ip);
  8968. s->setProp("@desc", desc);
  8969. if (crc)
  8970. s->setPropInt("@crc", crc);
  8971. if (minActivity)
  8972. s->setPropInt("@minActivity", minActivity);
  8973. if (maxActivity)
  8974. s->setPropInt("@maxActivity", maxActivity);
  8975. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  8976. associated.append(*q);
  8977. }
  8978. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  8979. {
  8980. CriticalBlock block(crit);
  8981. associatedCached = false;
  8982. associated.kill();
  8983. StringBuffer xpath;
  8984. xpath.append("Associated/File");
  8985. if (type)
  8986. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  8987. if (name)
  8988. xpath.append("[@filename=\"").append(name).append("\"]");
  8989. if (desc)
  8990. xpath.append("[@desc=\"").append(desc).append("\"]");
  8991. p->removeProp(xpath.str());
  8992. }
  8993. void CLocalWUQuery::removeAssociatedFiles()
  8994. {
  8995. associatedCached = false;
  8996. associated.kill();
  8997. p->removeProp("Associated");
  8998. }
  8999. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  9000. {
  9001. CriticalBlock block(crit);
  9002. loadAssociated();
  9003. ForEachItemIn(idx, associated)
  9004. {
  9005. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  9006. if (cur.getType() == type)
  9007. {
  9008. if (index-- == 0)
  9009. return &OLINK(cur);
  9010. }
  9011. }
  9012. return NULL;
  9013. }
  9014. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  9015. {
  9016. const char * name = p->queryProp(propname);
  9017. if (name)
  9018. {
  9019. IPropertyTree *s = createPTree("File");
  9020. setEnum(s, "@type", type, queryFileTypes);
  9021. s->setProp("@filename", name);
  9022. if (crc)
  9023. s->setPropInt("@crc", crc);
  9024. associated.append(*new CLocalWUAssociated(s));
  9025. }
  9026. }
  9027. void CLocalWUQuery::loadAssociated() const
  9028. {
  9029. CriticalBlock block(crit);
  9030. if (!associatedCached)
  9031. {
  9032. assertex(associated.length() == 0);
  9033. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  9034. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  9035. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  9036. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  9037. for (r->first(); r->isValid(); r->next())
  9038. {
  9039. IPropertyTree *rp = &r->query();
  9040. rp->Link();
  9041. associated.append(*new CLocalWUAssociated(rp));
  9042. }
  9043. associatedCached = true;
  9044. }
  9045. }
  9046. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  9047. {
  9048. CriticalBlock block(crit);
  9049. loadAssociated();
  9050. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  9051. }
  9052. //========================================================================================
  9053. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  9054. {
  9055. }
  9056. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  9057. {
  9058. str.set(p->queryProp("@module"));
  9059. return str;
  9060. }
  9061. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  9062. {
  9063. str.set(p->queryProp("@attribute"));
  9064. return str;
  9065. }
  9066. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  9067. {
  9068. str.set(p->queryProp("@defaultName"));
  9069. return str;
  9070. }
  9071. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  9072. {
  9073. return (unsigned) p->getPropInt("@crc");
  9074. }
  9075. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  9076. {
  9077. if (!name)
  9078. {
  9079. StringBuffer ws_info;
  9080. ws_info.appendf("<%s ", p->queryName());
  9081. Owned<IAttributeIterator> attrs = p->getAttributes();
  9082. for(attrs->first(); attrs->isValid(); attrs->next())
  9083. {
  9084. const char *name = attrs->queryName()+1;
  9085. const char *value = attrs->queryValue();
  9086. ws_info.appendf("%s='%s' ", name, value);
  9087. }
  9088. ws_info.append("> \n");
  9089. Owned<IPropertyTreeIterator> info = p->getElements("*");
  9090. ForEach(*info)
  9091. {
  9092. IPropertyTree &item = info->query();
  9093. const char *name = item.queryName();
  9094. if (name)
  9095. {
  9096. MemoryBuffer mb;
  9097. bool isbin = p->isBinary(name);
  9098. if (isbin)
  9099. {
  9100. p->getPropBin(name,mb);
  9101. if (mb.length())
  9102. {
  9103. unsigned len = 0;
  9104. mb.read(len);
  9105. StringBuffer encodedString;
  9106. StringBuffer val(len, (const char *) mb.readDirect(len));
  9107. encodeXML(val, encodedString);
  9108. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  9109. }
  9110. }
  9111. else
  9112. {
  9113. StringBuffer tmp;
  9114. toXML(&item, tmp);
  9115. ws_info.append(tmp.str());
  9116. }
  9117. }
  9118. }
  9119. ws_info.appendf("</%s>", p->queryName());
  9120. str.setLen(ws_info.str(), ws_info.length());
  9121. }
  9122. else
  9123. {
  9124. MemoryBuffer mb;
  9125. p->getPropBin(name,mb);
  9126. if (mb.length())
  9127. {
  9128. unsigned len;
  9129. mb.read(len);
  9130. str.setLen((const char *) mb.readDirect(len), len);
  9131. }
  9132. }
  9133. return str;
  9134. }
  9135. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  9136. {
  9137. str.set(p->queryProp(name));
  9138. return str;
  9139. }
  9140. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  9141. {
  9142. p->setProp("@module", mname);
  9143. }
  9144. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  9145. {
  9146. p->setProp("@attribute", aname);
  9147. }
  9148. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  9149. {
  9150. p->setProp("@defaultName", dname);
  9151. }
  9152. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  9153. {
  9154. p->setPropInt("@crc", crc);
  9155. }
  9156. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  9157. {
  9158. MemoryBuffer m;
  9159. unsigned len = (size32_t)strlen(info);
  9160. serializeLPString(len, info, m);
  9161. p->setPropBin(name, m.length(), m.toByteArray());
  9162. }
  9163. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  9164. {
  9165. p->setProp(name, info);
  9166. }
  9167. //========================================================================================
  9168. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  9169. {
  9170. }
  9171. EnumMapping resultStatuses[] = {
  9172. { ResultStatusUndefined, "undefined" },
  9173. { ResultStatusCalculated, "calculated" },
  9174. { ResultStatusSupplied, "supplied" },
  9175. { ResultStatusFailed, "failed" },
  9176. { ResultStatusPartial, "partial" },
  9177. { ResultStatusSize, NULL }
  9178. };
  9179. WUResultStatus CLocalWUResult::getResultStatus() const
  9180. {
  9181. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  9182. }
  9183. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  9184. {
  9185. str.set(p->queryProp("@name"));
  9186. return str;
  9187. }
  9188. int CLocalWUResult::getResultSequence() const
  9189. {
  9190. return p->getPropInt("@sequence", -1);
  9191. }
  9192. bool CLocalWUResult::isResultScalar() const
  9193. {
  9194. return p->getPropInt("@isScalar", 1) != 0;
  9195. }
  9196. bool findSize(int size, IntArray &sizes)
  9197. {
  9198. ForEachItemIn(idx, sizes)
  9199. {
  9200. if (sizes.item(idx)==size)
  9201. return true;
  9202. }
  9203. return false;
  9204. }
  9205. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  9206. {
  9207. MemoryBuffer schema;
  9208. p->getPropBin("SchemaRaw", schema);
  9209. if (schema.length())
  9210. {
  9211. for (;;)
  9212. {
  9213. StringAttr name;
  9214. schema.read(name);
  9215. if (*schema.readDirect(0)==type_void)
  9216. break;
  9217. names.append(*new StringAttrItem(name));
  9218. types.append(*deserializeType(schema)); // MORE - nested records!
  9219. }
  9220. schema.skip(1);
  9221. if (schema.length() != schema.getPos())
  9222. {
  9223. unsigned eclLen;
  9224. schema.read(eclLen);
  9225. const char * schemaData = (const char *)schema.readDirect(eclLen);
  9226. if (eclText)
  9227. {
  9228. eclText->setLen(schemaData, eclLen);
  9229. if ((eclLen == 0) && names.ordinality())
  9230. {
  9231. const char * firstName = names.item(0).text;
  9232. StringBuffer temp;
  9233. temp.append("RECORD ");
  9234. types.item(0).getECLType(temp);
  9235. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  9236. eclText->set(temp.str());
  9237. }
  9238. }
  9239. }
  9240. }
  9241. }
  9242. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  9243. {
  9244. ForEachItemIn(idx, types)
  9245. {
  9246. StringAttrItem &name = names.item(idx);
  9247. ITypeInfo &type = types.item(idx);
  9248. unsigned size = type.getSize();
  9249. switch(type.getTypeCode())
  9250. {
  9251. case type_data:
  9252. if (size==UNKNOWN_LENGTH)
  9253. {
  9254. if (in.remaining() < sizeof(int))
  9255. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9256. in.read(size);
  9257. }
  9258. outputXmlData(size, in.readDirect(size), name.text, out);
  9259. break;
  9260. case type_string:
  9261. if (size==UNKNOWN_LENGTH)
  9262. {
  9263. if (in.remaining() < sizeof(int))
  9264. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9265. in.read(size);
  9266. }
  9267. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  9268. break;
  9269. case type_varstring:
  9270. {
  9271. if (size == UNKNOWN_LENGTH)
  9272. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  9273. const char * text = (const char *) in.readDirect(size);
  9274. outputXmlString((size32_t)strlen(text), text, name.text, out);
  9275. break;
  9276. }
  9277. case type_unicode:
  9278. {
  9279. unsigned len = type.getStringLen();
  9280. if (size==UNKNOWN_LENGTH)
  9281. in.read(len);
  9282. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  9283. }
  9284. break;
  9285. case type_utf8:
  9286. {
  9287. unsigned len = type.getStringLen();
  9288. if (size==UNKNOWN_LENGTH)
  9289. {
  9290. in.read(len);
  9291. size = rtlUtf8Size(len, in.readDirect(0));
  9292. }
  9293. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  9294. }
  9295. break;
  9296. case type_qstring:
  9297. {
  9298. unsigned len = type.getStringLen();
  9299. if (size==UNKNOWN_LENGTH)
  9300. in.read(len);
  9301. unsigned outlen;
  9302. char *outstr;
  9303. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  9304. outputXmlString(outlen, outstr, name.text, out);
  9305. free(outstr);
  9306. break;
  9307. }
  9308. case type_int:
  9309. case type_swapint:
  9310. if (type.isSigned())
  9311. {
  9312. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9313. unsigned __int64 cval8 = 0;
  9314. //MORE: I think this is wrong - swapped doesn't mean little/big/
  9315. if (type.isSwappedEndian())
  9316. {
  9317. unsigned idx = 0;
  9318. if (raw[idx] & 0x80)
  9319. cval8 = (__int64)-1;
  9320. while (size--)
  9321. cval8 = (cval8 << 8) | raw[idx++];
  9322. }
  9323. else
  9324. {
  9325. if (raw[size-1] & 0x80)
  9326. cval8 = (__int64)-1;
  9327. while (size--)
  9328. cval8 = (cval8 << 8) | raw[size];
  9329. }
  9330. outputXmlInt((__int64) cval8, name.text, out);
  9331. }
  9332. else
  9333. {
  9334. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9335. unsigned __int64 cval8 = 0;
  9336. if (type.isSwappedEndian())
  9337. {
  9338. unsigned idx = 0;
  9339. while (size--)
  9340. cval8 = (cval8 << 8) | raw[idx++];
  9341. }
  9342. else
  9343. {
  9344. while (size--)
  9345. cval8 = (cval8 << 8) | raw[size];
  9346. }
  9347. outputXmlUInt(cval8, name.text, out);
  9348. }
  9349. break;
  9350. case type_boolean:
  9351. bool cvalb;
  9352. in.read(cvalb);
  9353. outputXmlBool(cvalb, name.text, out);
  9354. break;
  9355. case type_decimal:
  9356. if (type.isSigned())
  9357. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9358. else
  9359. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9360. break;
  9361. case type_real:
  9362. double cvald;
  9363. switch(size)
  9364. {
  9365. case 4:
  9366. float cvalf;
  9367. in.read(cvalf);
  9368. cvald = cvalf;
  9369. break;
  9370. case 8:
  9371. in.read(cvald);
  9372. break;
  9373. default:
  9374. throwUnexpected();
  9375. }
  9376. outputXmlReal(cvald, name.text, out);
  9377. break;
  9378. default:
  9379. assertex(!"unexpected type in raw record");
  9380. break;
  9381. }
  9382. }
  9383. }
  9384. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  9385. {
  9386. TypeInfoArray types;
  9387. StringAttrArray names;
  9388. getSchema(types, names);
  9389. StringBuffer xml;
  9390. const char * name = p->queryProp("@name");
  9391. if (name)
  9392. xml.appendf("<Dataset name=\'%s\'>\n", name);
  9393. else
  9394. xml.append("<Dataset>\n");
  9395. if (hidePassword && p->getPropBool("Format/@password"))
  9396. {
  9397. xml.append(" <Row>");
  9398. appendXMLTag(xml, name, "****");
  9399. xml.append("</Row>\n");
  9400. }
  9401. else if (p->hasProp("Value"))
  9402. {
  9403. MemoryBuffer raw;
  9404. p->getPropBin("Value", raw);
  9405. unsigned __int64 numrows = getResultRowCount();
  9406. while (numrows--)
  9407. {
  9408. xml.append(" <Row>");
  9409. readRow(xml, raw, types, names);
  9410. xml.append("</Row>\n");
  9411. }
  9412. }
  9413. else if (p->hasProp("xmlValue"))
  9414. {
  9415. xml.append(" <Row>");
  9416. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  9417. xml.append("</Row>\n");
  9418. }
  9419. xml.append("</Dataset>\n");
  9420. str.set(xml.str());
  9421. return str;
  9422. }
  9423. IProperties *CLocalWUResult::queryResultXmlns()
  9424. {
  9425. CriticalBlock block(crit);
  9426. if (xmlns)
  9427. return xmlns;
  9428. xmlns.setown(createProperties());
  9429. Owned<IAttributeIterator> it = p->getAttributes();
  9430. unsigned prefixLen = strlen("@xmlns");
  9431. ForEach(*it)
  9432. {
  9433. const char *name = it->queryName();
  9434. if (!strncmp("@xmlns", name, prefixLen))
  9435. {
  9436. if (name[prefixLen]==':') //normal case
  9437. xmlns->setProp(name+prefixLen+1, it->queryValue());
  9438. else if (!name[prefixLen]) //special case, unprefixed namespace
  9439. xmlns->setProp("xmlns", it->queryValue());
  9440. }
  9441. }
  9442. return xmlns;
  9443. }
  9444. unsigned CLocalWUResult::getResultFetchSize() const
  9445. {
  9446. return p->getPropInt("fetchSize", 100);
  9447. }
  9448. __int64 CLocalWUResult::getResultTotalRowCount() const
  9449. {
  9450. return p->getPropInt64("totalRowCount", -1);
  9451. }
  9452. __int64 CLocalWUResult::getResultRowCount() const
  9453. {
  9454. return p->getPropInt64("rowCount", 0);
  9455. }
  9456. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  9457. {
  9458. ecl.set(p->queryProp("datasetEcl"));
  9459. defs.set(p->queryProp("datasetEclDefs"));
  9460. }
  9461. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  9462. {
  9463. val.set(p->queryProp("logicalName"));
  9464. return val;
  9465. }
  9466. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  9467. {
  9468. ecl.set(p->queryProp("keyField"));
  9469. return ecl;
  9470. }
  9471. unsigned CLocalWUResult::getResultRequestedRows() const
  9472. {
  9473. return p->getPropInt("requestedRows", 1);
  9474. }
  9475. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  9476. {
  9477. TypeInfoArray types;
  9478. StringAttrArray names;
  9479. getSchema(types, names, &str);
  9480. return str;
  9481. }
  9482. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  9483. {
  9484. str.set(p->queryProp("@recordSizeEntry"));
  9485. return str;
  9486. }
  9487. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  9488. {
  9489. str.set(p->queryProp("@transformerEntry"));
  9490. return str;
  9491. }
  9492. __int64 CLocalWUResult::getResultRowLimit() const
  9493. {
  9494. return p->getPropInt64("@rowLimit");
  9495. }
  9496. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  9497. {
  9498. str.set(p->queryProp("@tempFilename"));
  9499. return str;
  9500. }
  9501. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  9502. {
  9503. str.clear();
  9504. if (!name || !*name)
  9505. return str;
  9506. IPropertyTree *format = p->queryPropTree("Format");
  9507. if (!format)
  9508. return str;
  9509. VStringBuffer xpath("@%s", name);
  9510. str.set(format->queryProp(xpath));
  9511. return str;
  9512. }
  9513. void CLocalWUResult::getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const
  9514. {
  9515. _graph.set(p->queryProp("@graph"));
  9516. _activityId = p->getPropInt("@activity", 0);
  9517. }
  9518. void CLocalWUResult::setResultStatus(WUResultStatus status)
  9519. {
  9520. setEnum(p, "@status", status, resultStatuses);
  9521. if (status==ResultStatusUndefined)
  9522. {
  9523. p->removeProp("Value");
  9524. p->removeProp("totalRowCount");
  9525. p->removeProp("rowCount");
  9526. p->removeProp("@format");
  9527. p->removeProp("@tempFileNmae");
  9528. p->removeProp("logicalName");
  9529. }
  9530. }
  9531. void CLocalWUResult::setResultName(const char *s)
  9532. {
  9533. p->setProp("@name", s);
  9534. }
  9535. void CLocalWUResult::setResultSequence(unsigned seq)
  9536. {
  9537. p->setPropInt("@sequence", seq);
  9538. }
  9539. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  9540. {
  9541. p->setPropBin("SchemaRaw", size, schema);
  9542. }
  9543. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  9544. {
  9545. StringBuffer xpath("@xmlns");
  9546. if (prefix && *prefix)
  9547. xpath.append(':').append(prefix);
  9548. p->setProp(xpath, uri);
  9549. }
  9550. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  9551. {
  9552. if (!name || !*name)
  9553. return;
  9554. IPropertyTree *format = ensurePTree(p, "Format");
  9555. VStringBuffer xpath("@%s", name);
  9556. format->setProp(xpath, value);
  9557. }
  9558. void CLocalWUResult::setResultWriteLocation(const char * _graph, unsigned _activityId)
  9559. {
  9560. p->setProp("@graph", _graph);
  9561. p->setPropInt("@activity", _activityId);
  9562. }
  9563. void CLocalWUResult::setResultScalar(bool isScalar)
  9564. {
  9565. p->setPropInt("@isScalar", (int) isScalar);
  9566. if (isScalar)
  9567. setResultTotalRowCount(1);
  9568. }
  9569. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  9570. {
  9571. p->setPropBin("Value", len, data);
  9572. setResultStatus(ResultStatusSupplied);
  9573. setResultFormat(format);
  9574. }
  9575. void CLocalWUResult::setResultFormat(WUResultFormat format)
  9576. {
  9577. switch (format)
  9578. {
  9579. case ResultFormatXml:
  9580. p->setProp("@format","xml");
  9581. break;
  9582. case ResultFormatXmlSet:
  9583. p->setProp("@format","xmlSet");
  9584. break;
  9585. case ResultFormatCsv:
  9586. p->setProp("@format","csv");
  9587. break;
  9588. default:
  9589. p->removeProp("@format");
  9590. break;
  9591. }
  9592. }
  9593. void CLocalWUResult::setResultXML(const char *val)
  9594. {
  9595. p->setProp("xmlValue", val);
  9596. }
  9597. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  9598. {
  9599. p->appendPropBin("Value", len, data);
  9600. setResultStatus(ResultStatusPartial);
  9601. const char *existingFormat = p->queryProp("@format");
  9602. const char *formatStr = NULL;
  9603. switch (format)
  9604. {
  9605. case ResultFormatXml:
  9606. formatStr = "xml";
  9607. break;
  9608. case ResultFormatXmlSet:
  9609. formatStr = "xmlSet";
  9610. break;
  9611. case ResultFormatCsv:
  9612. formatStr = "csv";
  9613. break;
  9614. default:
  9615. existingFormat = nullptr;
  9616. p->removeProp("@format");
  9617. break;
  9618. }
  9619. if (format)
  9620. {
  9621. if (existingFormat)
  9622. {
  9623. if (0 != stricmp(formatStr, existingFormat))
  9624. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  9625. }
  9626. else
  9627. p->setProp("@format", formatStr);
  9628. }
  9629. }
  9630. void CLocalWUResult::setResultFetchSize(unsigned rows)
  9631. {
  9632. p->setPropInt("fetchSize", rows);
  9633. }
  9634. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  9635. {
  9636. p->setPropInt64("totalRowCount", rows);
  9637. }
  9638. void CLocalWUResult::setResultRowCount(__int64 rows)
  9639. {
  9640. p->setPropInt64("rowCount", rows);
  9641. }
  9642. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  9643. {
  9644. p->setProp("datasetEcl", ecl);
  9645. p->setProp("datasetEclDefs", defs);
  9646. }
  9647. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  9648. {
  9649. p->setProp("logicalName", logicalName);
  9650. }
  9651. void CLocalWUResult::setResultKeyField(const char *ecl)
  9652. {
  9653. p->setProp("keyField", ecl);
  9654. }
  9655. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  9656. {
  9657. p->setPropInt("requestedRows", rows);
  9658. }
  9659. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  9660. {
  9661. p->setProp("@recordSizeEntry", entry);
  9662. }
  9663. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  9664. {
  9665. p->setProp("@transformerEntry", entry);
  9666. }
  9667. void CLocalWUResult::setResultRowLimit(__int64 value)
  9668. {
  9669. p->setPropInt64("@rowLimit", value);
  9670. }
  9671. void CLocalWUResult::setResultFilename(const char * name)
  9672. {
  9673. p->setProp("@tempFilename", name);
  9674. }
  9675. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  9676. __int64 CLocalWUResult::getResultInt() const
  9677. {
  9678. __int64 result = 0;
  9679. MemoryBuffer s;
  9680. p->getPropBin("Value", s);
  9681. if (s.length())
  9682. s.read(result);
  9683. else
  9684. {
  9685. // NOTE - we use this rather than getPropInt64 since it handles uint64 values up to MAX_UINT better (for our purposes)
  9686. const char *val = p->queryProp("xmlValue");
  9687. if (val)
  9688. result = rtlStrToInt8(strlen(val), val);
  9689. }
  9690. return result;
  9691. }
  9692. bool CLocalWUResult::getResultBool() const
  9693. {
  9694. bool result = false;
  9695. MemoryBuffer s;
  9696. p->getPropBin("Value", s);
  9697. if (s.length())
  9698. s.read(result);
  9699. else
  9700. result = p->getPropBool("xmlValue");
  9701. return result;
  9702. }
  9703. double CLocalWUResult::getResultReal() const
  9704. {
  9705. double result = 0;
  9706. MemoryBuffer s;
  9707. p->getPropBin("Value", s);
  9708. if (s.length())
  9709. s.read(result);
  9710. else
  9711. {
  9712. const char *xmlVal = p->queryProp("xmlValue");
  9713. if (xmlVal)
  9714. result = atof(xmlVal);
  9715. }
  9716. return result;
  9717. }
  9718. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  9719. {
  9720. MemoryBuffer s;
  9721. p->getPropBin("Value", s);
  9722. if (s.length())
  9723. {
  9724. assertex(s.length() == len);
  9725. s.read(len, val);
  9726. }
  9727. else
  9728. {
  9729. const char *xmlVal = p->queryProp("xmlValue");
  9730. if (xmlVal)
  9731. {
  9732. Decimal d;
  9733. d.setString(strlen(xmlVal), xmlVal);
  9734. if (isSigned)
  9735. d.getDecimal(len, precision, val);
  9736. else
  9737. d.getUDecimal(len, precision, val);
  9738. }
  9739. else
  9740. memset(val, 0, len);
  9741. }
  9742. }
  9743. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  9744. {
  9745. if (hidePassword && p->getPropBool("@password"))
  9746. {
  9747. str.set("****");
  9748. return str;
  9749. }
  9750. MemoryBuffer s;
  9751. p->getPropBin("Value", s);
  9752. if (s.length())
  9753. {
  9754. unsigned len;
  9755. s.read(len);
  9756. str.setLen((const char *) s.readDirect(len), len);
  9757. }
  9758. else
  9759. {
  9760. p->getPropBin("xmlValue", s);
  9761. if (p->isBinary("xmlValue"))
  9762. str.setLen(s.toByteArray(), s.length());
  9763. else
  9764. {
  9765. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  9766. str.set(ascii);
  9767. rtlFree(ascii);
  9768. }
  9769. }
  9770. return str;
  9771. }
  9772. WUResultFormat CLocalWUResult::getResultFormat() const
  9773. {
  9774. const char * format = p->queryProp("@format");
  9775. if (!format)
  9776. return ResultFormatRaw;
  9777. else if (strcmp(format, "xml") == 0)
  9778. return ResultFormatXml;
  9779. else if (strcmp(format, "xmlSet") == 0)
  9780. return ResultFormatXmlSet;
  9781. else if (strcmp(format, "csv") == 0)
  9782. return ResultFormatCsv;
  9783. else
  9784. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  9785. }
  9786. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9787. {
  9788. MemoryBuffer s;
  9789. p->getPropBin("Value", s);
  9790. unsigned len = s.length();
  9791. if (len)
  9792. {
  9793. WUResultFormat format = getResultFormat();
  9794. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  9795. {
  9796. if (!xmlTransformer)
  9797. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  9798. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  9799. }
  9800. else if (format == ResultFormatCsv)
  9801. {
  9802. if (!csvTransformer)
  9803. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  9804. csvTransformer->transform(data, len, s.readDirect(len), true);
  9805. }
  9806. else
  9807. data.setLen(s.readDirect(len), len);
  9808. }
  9809. else
  9810. data.clear();
  9811. return data;
  9812. }
  9813. unsigned CLocalWUResult::getResultHash() const
  9814. {
  9815. MemoryBuffer s;
  9816. p->getPropBin("Value", s);
  9817. unsigned len = s.length();
  9818. const byte * data = (const byte *)s.toByteArray();
  9819. return ~hashc(data, len, ~0);
  9820. }
  9821. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  9822. {
  9823. MemoryBuffer s;
  9824. p->getPropBin("Value", s);
  9825. if (s.length())
  9826. {
  9827. unsigned len;
  9828. s.read(len);
  9829. data.setLen(s.readDirect(len*2), len*2);
  9830. }
  9831. else
  9832. {
  9833. StringBuffer utf8;
  9834. if (p->getProp("xmlValue", utf8))
  9835. {
  9836. unsigned outlen;
  9837. UChar *out;
  9838. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  9839. data.setLen(out, outlen*2);
  9840. rtlFree(out);
  9841. }
  9842. else
  9843. data.clear();
  9844. }
  9845. return data;
  9846. }
  9847. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9848. {
  9849. WUResultFormat format = getResultFormat();
  9850. if (format == ResultFormatRaw)
  9851. {
  9852. //MORE: This should not load the whole property...
  9853. MemoryBuffer s;
  9854. p->getPropBin("Value", s);
  9855. return s.length();
  9856. }
  9857. else
  9858. {
  9859. MemoryBuffer temp;
  9860. MemoryBuffer2IDataVal adaptor(temp);
  9861. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  9862. return temp.length();
  9863. }
  9864. }
  9865. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9866. {
  9867. WUResultFormat format = getResultFormat();
  9868. if (format != ResultFormatRaw)
  9869. {
  9870. MemoryBuffer temp;
  9871. MemoryBuffer2IDataVal adaptor(temp);
  9872. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  9873. unsigned len = temp.length();
  9874. if (from > len) from = len;
  9875. if (from + length > len) length = len - from;
  9876. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  9877. return data;
  9878. }
  9879. else
  9880. {
  9881. //MORE: This should not load the whole property, and should be different from the code above...
  9882. MemoryBuffer s;
  9883. p->getPropBin("Value", s);
  9884. unsigned len = s.length();
  9885. if (from > len) from = len;
  9886. if (from + length > len) length = len - from;
  9887. data.setLen(s.readDirect(len) + from, (size32_t)length);
  9888. return data;
  9889. }
  9890. }
  9891. bool CLocalWUResult::getResultIsAll() const
  9892. {
  9893. return p->getPropBool("@isAll", false);
  9894. }
  9895. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  9896. void CLocalWUResult::setResultInt(__int64 val)
  9897. {
  9898. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  9899. MemoryBuffer m;
  9900. serializeInt8(val, m);
  9901. p->setPropBin("Value", m.length(), m.toByteArray());
  9902. setResultRowCount(1);
  9903. setResultTotalRowCount(1);
  9904. }
  9905. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  9906. {
  9907. setResultInt((__int64) val);
  9908. }
  9909. void CLocalWUResult::setResultReal(double val)
  9910. {
  9911. // Note: we always serialize scalar real results as real8, and schema must reflect this
  9912. MemoryBuffer m;
  9913. serializeReal8(val, m);
  9914. p->setPropBin("Value", m.length(), m.toByteArray());
  9915. setResultRowCount(1);
  9916. setResultTotalRowCount(1);
  9917. }
  9918. void CLocalWUResult::setResultBool(bool val)
  9919. {
  9920. MemoryBuffer m;
  9921. serializeBool(val, m);
  9922. p->setPropBin("Value", m.length(), m.toByteArray());
  9923. setResultRowCount(1);
  9924. setResultTotalRowCount(1);
  9925. }
  9926. void CLocalWUResult::setResultString(const char *val, unsigned len)
  9927. {
  9928. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  9929. MemoryBuffer m;
  9930. serializeLPString(len, val, m);
  9931. p->setPropBin("Value", m.length(), m.toByteArray());
  9932. setResultRowCount(1);
  9933. setResultTotalRowCount(1);
  9934. }
  9935. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  9936. {
  9937. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  9938. MemoryBuffer m;
  9939. m.append(len).append(len*2, val);
  9940. p->setPropBin("Value", m.length(), m.toByteArray());
  9941. setResultRowCount(1);
  9942. setResultTotalRowCount(1);
  9943. }
  9944. void CLocalWUResult::setResultData(const void *val, unsigned len)
  9945. {
  9946. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  9947. MemoryBuffer m;
  9948. serializeLPString(len, (const char *)val, m);
  9949. p->setPropBin("Value", m.length(), m.toByteArray());
  9950. setResultRowCount(1);
  9951. setResultTotalRowCount(1);
  9952. }
  9953. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  9954. {
  9955. // Note: serialized as data but with length known from schema
  9956. MemoryBuffer m;
  9957. serializeFixedData(len, val, m);
  9958. p->setPropBin("Value", m.length(), m.toByteArray());
  9959. setResultRowCount(1);
  9960. setResultTotalRowCount(1);
  9961. }
  9962. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  9963. {
  9964. p->setPropBin("Value", len, data);
  9965. setResultRowCount(1);
  9966. setResultTotalRowCount(1);
  9967. setResultFormat(ResultFormatRaw);
  9968. }
  9969. void CLocalWUResult::setResultIsAll(bool value)
  9970. {
  9971. p->setPropBool("@isAll", value);
  9972. }
  9973. //==========================================================================================
  9974. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  9975. {
  9976. }
  9977. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  9978. {
  9979. str.set(p->queryProp("@dllname"));
  9980. return str;
  9981. }
  9982. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  9983. {
  9984. str.set(p->queryProp("@version"));
  9985. return str;
  9986. }
  9987. void CLocalWUPlugin::setPluginName(const char *str)
  9988. {
  9989. p->setProp("@dllname", str);
  9990. }
  9991. void CLocalWUPlugin::setPluginVersion(const char *str)
  9992. {
  9993. p->setProp("@version", str);
  9994. }
  9995. //==========================================================================================
  9996. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  9997. {
  9998. }
  9999. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  10000. {
  10001. str.set(p->queryProp("@name"));
  10002. return str;
  10003. }
  10004. void CLocalWULibrary::setName(const char *str)
  10005. {
  10006. p->setProp("@name", str);
  10007. }
  10008. //==========================================================================================
  10009. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  10010. {
  10011. }
  10012. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  10013. {
  10014. str.set(p->queryProp("@source"));
  10015. return str;
  10016. }
  10017. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  10018. {
  10019. str.set(p->queryProp(NULL));
  10020. return str;
  10021. }
  10022. unsigned CLocalWUException::getExceptionCode() const
  10023. {
  10024. return p->getPropInt("@code", 0);
  10025. }
  10026. ErrorSeverity CLocalWUException::getSeverity() const
  10027. {
  10028. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  10029. }
  10030. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  10031. {
  10032. dt.set(p->queryProp("@time"));
  10033. return dt;
  10034. }
  10035. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  10036. {
  10037. str.set(p->queryProp("@filename"));
  10038. return str;
  10039. }
  10040. unsigned CLocalWUException::getExceptionLineNo() const
  10041. {
  10042. return p->getPropInt("@row", 0);
  10043. }
  10044. unsigned CLocalWUException::getExceptionColumn() const
  10045. {
  10046. return p->getPropInt("@col", 0);
  10047. }
  10048. unsigned CLocalWUException::getActivityId() const
  10049. {
  10050. const char * scope = queryScope();
  10051. if (scope)
  10052. {
  10053. const char * colon = strrchr(scope, ':');
  10054. if (colon && hasPrefix(colon+1, ActivityScopePrefix, true))
  10055. return atoi(colon+1+strlen(ActivityScopePrefix));
  10056. }
  10057. return p->getPropInt("@activity", 0);
  10058. }
  10059. unsigned CLocalWUException::getSequence() const
  10060. {
  10061. return p->getPropInt("@sequence", 0);
  10062. }
  10063. const char * CLocalWUException::queryScope() const
  10064. {
  10065. return p->queryProp("@scope");
  10066. }
  10067. unsigned CLocalWUException::getPriority() const
  10068. {
  10069. return p->getPropInt("@prio", 0);
  10070. }
  10071. void CLocalWUException::setExceptionSource(const char *str)
  10072. {
  10073. p->setProp("@source", str);
  10074. }
  10075. void CLocalWUException::setExceptionMessage(const char *str)
  10076. {
  10077. p->setProp(NULL, str);
  10078. }
  10079. void CLocalWUException::setExceptionCode(unsigned code)
  10080. {
  10081. p->setPropInt("@code", code);
  10082. }
  10083. void CLocalWUException::setSeverity(ErrorSeverity level)
  10084. {
  10085. p->setPropInt("@severity", level);
  10086. }
  10087. void CLocalWUException::setTimeStamp(const char *str)
  10088. {
  10089. p->setProp("@time", str);
  10090. }
  10091. void CLocalWUException::setExceptionFileName(const char *str)
  10092. {
  10093. p->setProp("@filename", str);
  10094. }
  10095. void CLocalWUException::setExceptionLineNo(unsigned r)
  10096. {
  10097. p->setPropInt("@row", r);
  10098. }
  10099. void CLocalWUException::setExceptionColumn(unsigned c)
  10100. {
  10101. p->setPropInt("@col", c);
  10102. }
  10103. void CLocalWUException::setActivityId(unsigned _id)
  10104. {
  10105. p->setPropInt("@activity", _id);
  10106. }
  10107. void CLocalWUException::setScope(const char * _scope)
  10108. {
  10109. p->setProp("@scope", _scope);
  10110. }
  10111. void CLocalWUException::setPriority(unsigned _priority)
  10112. {
  10113. p->setPropInt("@prio", _priority);
  10114. }
  10115. //==========================================================================================
  10116. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  10117. {
  10118. StringAttrBuilder propPath(prop);
  10119. propPath.append("*[").append(child).append("]");
  10120. }
  10121. const char * CLocalWUAppValue::queryApplication() const
  10122. {
  10123. return p->queryName();
  10124. }
  10125. const char * CLocalWUAppValue::queryName() const
  10126. {
  10127. IPropertyTree* val=p->queryPropTree(prop.str());
  10128. if(val)
  10129. return val->queryName();
  10130. return ""; // Should not happen in normal usage
  10131. }
  10132. const char * CLocalWUAppValue::queryValue() const
  10133. {
  10134. return p->queryProp(prop.str());
  10135. }
  10136. //==========================================================================================
  10137. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  10138. {
  10139. }
  10140. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  10141. {
  10142. const char * creator = p->queryProp("@creator");
  10143. str.set(creator);
  10144. return str;
  10145. }
  10146. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  10147. {
  10148. const char * desc = p->queryProp("@desc");
  10149. if (desc)
  10150. {
  10151. str.set(desc); // legacy and in case it is overridden
  10152. }
  10153. else if (createDefault)
  10154. {
  10155. StatisticKind kind = getKind();
  10156. assertex(kind != StKindNone);
  10157. const char * scope = p->queryProp("@scope");
  10158. assertex(scope);
  10159. //Clean up the format of the scope when converting it to a description
  10160. StringBuffer descriptionText;
  10161. if (isGlobalScope(scope))
  10162. {
  10163. const char * creator = p->queryProp("@creator");
  10164. descriptionText.append(creator).append(":");
  10165. queryLongStatisticName(descriptionText, kind);
  10166. }
  10167. else
  10168. {
  10169. for (;;)
  10170. {
  10171. char c = *scope++;
  10172. if (!c)
  10173. break;
  10174. if (c == ':')
  10175. descriptionText.append(": ");
  10176. else
  10177. descriptionText.append(c);
  10178. }
  10179. if (kind != StTimeElapsed)
  10180. queryLongStatisticName(descriptionText.append(": "), kind);
  10181. }
  10182. str.set(descriptionText);
  10183. }
  10184. else
  10185. str.clear();
  10186. return str;
  10187. }
  10188. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  10189. {
  10190. StringBuffer formatted;
  10191. formatStatistic(formatted, getValue(), getMeasure());
  10192. str.set(formatted);
  10193. return str;
  10194. }
  10195. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  10196. {
  10197. return queryCreatorType(p->queryProp("@c"), SCTnone);
  10198. }
  10199. StatisticScopeType CLocalWUStatistic::getScopeType() const
  10200. {
  10201. return queryScopeType(p->queryProp("@s"), SSTnone);
  10202. }
  10203. StatisticKind CLocalWUStatistic::getKind() const
  10204. {
  10205. return queryStatisticKind(p->queryProp("@kind"), StKindNone);
  10206. }
  10207. const char * CLocalWUStatistic::queryScope() const
  10208. {
  10209. const char * scope = p->queryProp("@scope");
  10210. if (!scope || streq(scope, LEGACY_GLOBAL_SCOPE))
  10211. scope = GLOBAL_SCOPE;
  10212. return scope;
  10213. }
  10214. StatisticMeasure CLocalWUStatistic::getMeasure() const
  10215. {
  10216. return queryMeasure(p->queryProp("@unit"), SMeasureNone);
  10217. }
  10218. unsigned __int64 CLocalWUStatistic::getValue() const
  10219. {
  10220. return p->getPropInt64("@value", 0);
  10221. }
  10222. unsigned __int64 CLocalWUStatistic::getCount() const
  10223. {
  10224. return p->getPropInt64("@count", 0);
  10225. }
  10226. unsigned __int64 CLocalWUStatistic::getMax() const
  10227. {
  10228. return p->getPropInt64("@max", 0);
  10229. }
  10230. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  10231. {
  10232. return p->getPropInt64("@ts", 0);
  10233. }
  10234. //==========================================================================================
  10235. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  10236. {
  10237. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  10238. if (xml)
  10239. cw->loadPTree(createPTreeFromXMLString(xml, ipt_lowmem));
  10240. else
  10241. {
  10242. Owned<IPropertyTree> p = createPTree("W_LOCAL", ipt_lowmem);
  10243. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  10244. cw->loadPTree(p.getClear());
  10245. }
  10246. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  10247. return ret;
  10248. }
  10249. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  10250. {
  10251. const char *name = p->queryName();
  10252. if (!name)
  10253. name = "__unnamed__";
  10254. StringBuffer temp;
  10255. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1, true));
  10256. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  10257. ForEach(*elems)
  10258. {
  10259. IPropertyTree &elem = elems->query();
  10260. if (streq(elem.queryName(), "Parameters"))
  10261. {
  10262. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2, false).append('\n'));
  10263. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  10264. ForEach(*params)
  10265. {
  10266. IPropertyTree &param = params->query();
  10267. const char *paramname = param.queryName();
  10268. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  10269. if (p->getPropBool(xpath))
  10270. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  10271. else
  10272. {
  10273. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10274. }
  10275. }
  10276. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  10277. }
  10278. else if (streq(elem.queryName(), "Variables"))
  10279. {
  10280. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2, false).append('\n'));
  10281. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  10282. ForEach(*vars)
  10283. {
  10284. Owned<IPropertyTree> var = LINK(&vars->query());
  10285. if (var->getPropBool("Format/@password"))
  10286. {
  10287. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  10288. var->removeProp("Value");
  10289. var->removeProp("xmlValue");
  10290. }
  10291. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10292. }
  10293. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  10294. }
  10295. else
  10296. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  10297. }
  10298. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  10299. }
  10300. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  10301. {
  10302. class CAdapter : public CInterface, implements IIOStream
  10303. {
  10304. StringBuffer &out;
  10305. public:
  10306. IMPLEMENT_IINTERFACE;
  10307. CAdapter(StringBuffer &_out) : out(_out) { }
  10308. virtual void flush() { }
  10309. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  10310. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  10311. } adapter(str);
  10312. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  10313. return str;
  10314. }
  10315. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  10316. {
  10317. OwnedIFile ifile = createIFile(filename);
  10318. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  10319. Owned<IIOStream> stream = createIOStream(ifileio);
  10320. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  10321. }
  10322. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  10323. {
  10324. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  10325. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10326. if (ewu)
  10327. {
  10328. Linked<IPropertyTree> p;
  10329. if (unpack||includeProgress)
  10330. p.setown(ewu->getUnpackedTree(includeProgress));
  10331. else
  10332. p.set(ewu->queryPTree());
  10333. if (hidePasswords)
  10334. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  10335. else
  10336. return toXML(p, str, 0, XML_Format|XML_SortTags);
  10337. }
  10338. else
  10339. return str.append("Unrecognized workunit format");
  10340. }
  10341. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool regressionTest)
  10342. {
  10343. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10344. if (ewu)
  10345. {
  10346. Linked<IPropertyTree> p;
  10347. if (unpack||includeProgress)
  10348. p.setown(ewu->getUnpackedTree(includeProgress));
  10349. else if (regressionTest)
  10350. p.setown(createPTreeFromIPT(ewu->queryPTree()));
  10351. else
  10352. p.set(ewu->queryPTree());
  10353. if (hidePasswords)
  10354. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  10355. if (regressionTest)
  10356. {
  10357. //This removes any items from the xml that will vary from run to run, so they can be binary compared from run to run
  10358. //The following attributes change with the build. Simpler to remove rather than needing to updated each build
  10359. p->removeProp("@buildVersion");
  10360. p->removeProp("@eclVersion");
  10361. p->removeProp("@hash");
  10362. //Remove statistics, and extract them to a separate file
  10363. IPropertyTree * stats = p->queryPropTree("Statistics");
  10364. if (stats)
  10365. {
  10366. StringBuffer statsFilename;
  10367. statsFilename.append(filename).append(".stats");
  10368. saveXML(statsFilename, stats, 0, (XML_Format|XML_SortTags|extraXmlFlags) & ~XML_LineBreakAttributes);
  10369. p->removeProp("Statistics");
  10370. }
  10371. //Now remove timestamps from exceptions
  10372. Owned<IPropertyTreeIterator> elems = p->getElements("Exceptions/Exception", iptiter_sort);
  10373. ForEach(*elems)
  10374. {
  10375. IPropertyTree &elem = elems->query();
  10376. elem.removeProp("@time");
  10377. }
  10378. }
  10379. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  10380. }
  10381. else
  10382. throw makeStringException(0, "Unrecognized workunit format");
  10383. }
  10384. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  10385. {
  10386. MemoryBuffer buffer;
  10387. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  10388. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  10389. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  10390. assertex(workunit);
  10391. StringAttr clusterName(workunit->queryClusterName());
  10392. if (!clusterName.length())
  10393. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  10394. workunit->commit();
  10395. workunit.clear();
  10396. StringBuffer serverQueue;
  10397. getClusterEclCCServerQueueName(serverQueue, clusterName);
  10398. assertex(serverQueue.length());
  10399. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  10400. if (!queue.get())
  10401. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  10402. IJobQueueItem *item = createJobQueueItem(wuid);
  10403. queue->enqueue(item);
  10404. }
  10405. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  10406. {
  10407. StringBuffer xpath("/WorkUnitAborts/");
  10408. xpath.append(wuid);
  10409. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  10410. acon->queryRoot()->setPropInt(NULL, 1);
  10411. }
  10412. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10413. {
  10414. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10415. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  10416. }
  10417. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10418. {
  10419. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10420. return;
  10421. abortWorkUnit(wuid);
  10422. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  10423. if(!cw)
  10424. return;
  10425. WorkunitUpdate wu(&cw->lock());
  10426. const char *abortBy = secuser.getName();
  10427. if (abortBy && *abortBy)
  10428. wu->setTracingValue("AbortBy", abortBy);
  10429. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  10430. }
  10431. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10432. {
  10433. if (secmgr && secuser)
  10434. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  10435. if (secuser)
  10436. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  10437. submitWorkUnit(wuid, "", "");
  10438. }
  10439. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10440. {
  10441. if (secmgr && secuser)
  10442. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  10443. abortWorkUnit(wuid);
  10444. }
  10445. bool CLocalWorkUnit::hasWorkflow() const
  10446. {
  10447. return p->hasProp("Workflow");
  10448. }
  10449. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  10450. {
  10451. CriticalBlock block(crit);
  10452. if (p->hasProp("@eventScheduledCount"))
  10453. return p->getPropInt("@eventScheduledCount", 0);
  10454. else
  10455. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  10456. }
  10457. void CLocalWorkUnit::incEventScheduledCount()
  10458. {
  10459. CriticalBlock block(crit);
  10460. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  10461. }
  10462. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  10463. {
  10464. CriticalBlock block(crit);
  10465. return p->queryPropTree("Workflow");
  10466. }
  10467. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  10468. {
  10469. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10470. CriticalBlock block(crit);
  10471. if(!workflowIteratorCached)
  10472. {
  10473. assertex(!workflowIterator);
  10474. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  10475. if(s)
  10476. workflowIterator.setown(createWorkflowItemIterator(s));
  10477. workflowIteratorCached = true;
  10478. }
  10479. return workflowIterator.getLink();
  10480. }
  10481. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  10482. {
  10483. unsigned count = 0;
  10484. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10485. for(iter->first(); iter->isValid(); iter->next())
  10486. count++;
  10487. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  10488. for(iter->first(); iter->isValid(); iter->next())
  10489. array->addClone(iter->query());
  10490. return array.getLink();
  10491. }
  10492. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  10493. {
  10494. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10495. CriticalBlock block(crit);
  10496. workflowIterator.clear();
  10497. workflowIteratorCached = false;
  10498. IPropertyTree * s = p->queryPropTree("Workflow");
  10499. if(!s)
  10500. s = p->addPropTree("Workflow");
  10501. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  10502. }
  10503. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  10504. {
  10505. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10506. CriticalBlock block(crit);
  10507. if(!workflowIterator)
  10508. {
  10509. IPropertyTree * s = p->queryPropTree("Workflow");
  10510. if(!s)
  10511. s = p->addPropTree("Workflow");
  10512. workflowIterator.setown(createWorkflowItemIterator(s));
  10513. workflowIteratorCached = true;
  10514. }
  10515. return workflowIterator.getLink();
  10516. }
  10517. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  10518. {
  10519. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10520. Owned<IWorkflowItem> item;
  10521. for(iter->first(); iter->isValid(); iter->next())
  10522. {
  10523. item.setown(iter->get());
  10524. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  10525. }
  10526. workflowIterator.clear();
  10527. workflowIteratorCached = false;
  10528. }
  10529. void CLocalWorkUnit::resetWorkflow()
  10530. {
  10531. if (hasWorkflow())
  10532. {
  10533. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10534. Owned<IWorkflowItem> wf;
  10535. for(iter->first(); iter->isValid(); iter->next())
  10536. {
  10537. wf.setown(iter->get());
  10538. wf->reset();
  10539. }
  10540. workflowIterator.clear();
  10541. workflowIteratorCached = false;
  10542. }
  10543. }
  10544. void CLocalWorkUnit::schedule()
  10545. {
  10546. CriticalBlock block(crit);
  10547. if(queryEventScheduledCount() == 0) return;
  10548. switch(getState())
  10549. {
  10550. case WUStateCompleted:
  10551. setState(WUStateWait);
  10552. break;
  10553. case WUStateFailed:
  10554. case WUStateArchived:
  10555. case WUStateAborting:
  10556. case WUStateAborted:
  10557. case WUStateScheduled:
  10558. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  10559. }
  10560. StringBuffer rootPath;
  10561. rootPath.append("/Schedule/").append(queryClusterName());
  10562. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10563. Owned<IPropertyTree> root = conn->getRoot();
  10564. if(!root->hasChildren())
  10565. {
  10566. StringBuffer addPath;
  10567. addPath.append("/Schedulers/").append(queryClusterName());
  10568. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10569. }
  10570. char const * wuid = p->queryName();
  10571. StringBuffer xpath("*/*/");
  10572. ncnameEscape(wuid, xpath);
  10573. bool more;
  10574. do more = root->removeProp(xpath.str()); while(more);
  10575. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10576. Owned<IWorkflowEvent> event;
  10577. Owned<IPropertyTree> branch1, branch2;
  10578. for(iter->first(); iter->isValid(); iter->next())
  10579. {
  10580. event.setown(iter->query()->getScheduleEvent());
  10581. if(!event) continue;
  10582. ncnameEscape(event->queryName(), xpath.clear());
  10583. ensurePTree(root, xpath.str());
  10584. branch1.setown(root->getPropTree(xpath.str()));
  10585. ncnameEscape(event->queryText(), xpath.clear());
  10586. ensurePTree(branch1, xpath.str());
  10587. branch2.setown(branch1->getPropTree(xpath.str()));
  10588. ncnameEscape(wuid, xpath.clear());
  10589. ensurePTree(branch2, xpath.str());
  10590. }
  10591. }
  10592. void CLocalWorkUnit::deschedule()
  10593. {
  10594. if(queryEventScheduledCount() == 0) return;
  10595. if(getState() == WUStateWait)
  10596. setState(WUStateCompleted);
  10597. doDescheduleWorkkunit(p->queryName());
  10598. }
  10599. EnumMapping localFileUploadTypes[] = {
  10600. { UploadTypeFileSpray, "FileSpray" },
  10601. { UploadTypeWUResult, "WUResult" },
  10602. { UploadTypeWUResultCsv, "WUResultCsv" },
  10603. { UploadTypeWUResultXml, "WUResultXml" },
  10604. { UploadTypeSize, NULL }
  10605. };
  10606. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  10607. {
  10608. public:
  10609. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  10610. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10611. {
  10612. tree.setown(createPTree());
  10613. tree->setPropInt("@id", id);
  10614. setEnum(tree, "@type", type, localFileUploadTypes);
  10615. tree->setProp("@source", source);
  10616. tree->setProp("@destination", destination);
  10617. if (eventTag)
  10618. tree->setProp("@eventTag", eventTag);
  10619. }
  10620. IMPLEMENT_IINTERFACE;
  10621. IPropertyTree * getTree() { return tree.getLink(); }
  10622. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  10623. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  10624. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  10625. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  10626. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  10627. private:
  10628. Owned<IPropertyTree> tree;
  10629. };
  10630. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  10631. {
  10632. public:
  10633. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  10634. IMPLEMENT_IINTERFACE;
  10635. bool first() { return iter->first(); }
  10636. bool isValid() { return iter->isValid(); }
  10637. bool next() { return iter->next(); }
  10638. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  10639. private:
  10640. Owned<IPropertyTree> tree;
  10641. Owned<IPropertyTreeIterator> iter;
  10642. };
  10643. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  10644. {
  10645. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10646. CriticalBlock block(crit);
  10647. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  10648. if(s)
  10649. return new CLocalFileUploadIterator(s.getClear());
  10650. else
  10651. return NULL;
  10652. }
  10653. bool CLocalWorkUnit::requiresLocalFileUpload() const
  10654. {
  10655. SCMStringBuffer dest;
  10656. Owned<IConstWUResult> result;
  10657. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  10658. if(!iter)
  10659. return false;
  10660. for(iter->first(); iter->isValid(); iter->next())
  10661. {
  10662. Owned<IConstLocalFileUpload> upload(iter->get());
  10663. switch(upload->queryType())
  10664. {
  10665. case UploadTypeWUResult:
  10666. case UploadTypeWUResultCsv:
  10667. case UploadTypeWUResultXml:
  10668. upload->getDestination(dest);
  10669. result.setown(getResultByName(dest.str()));
  10670. if(!result)
  10671. return true;
  10672. break;
  10673. default:
  10674. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  10675. }
  10676. }
  10677. return false;
  10678. }
  10679. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10680. {
  10681. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10682. CriticalBlock block(crit);
  10683. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  10684. if(!s)
  10685. s = p->addPropTree("LocalFileUploads");
  10686. unsigned id = s->numChildren();
  10687. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  10688. s->addPropTree("LocalFileUpload", upload->getTree());
  10689. return id;
  10690. }
  10691. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  10692. {
  10693. CriticalBlock block(crit);
  10694. str.set(p->queryProp("Tracing/AbortBy"));
  10695. return str;
  10696. }
  10697. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  10698. {
  10699. CriticalBlock block(crit);
  10700. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  10701. }
  10702. #if 0
  10703. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  10704. {
  10705. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  10706. unsigned deps = 0;
  10707. Owned<IWorkflowDependencyIterator> diter;
  10708. switch(cwf->queryWfid())
  10709. {
  10710. case 1:
  10711. assertex(!cwf->isScheduled());
  10712. assertex(cwf->queryType() == WFTypeNormal);
  10713. assertex(cwf->queryState() == WFStateNull);
  10714. diter.setown(cwf->getDependencies());
  10715. for(diter->first(); diter->isValid(); diter->next())
  10716. deps++;
  10717. assertex(deps==0);
  10718. okay[0] = true;
  10719. break;
  10720. case 2:
  10721. assertex(!cwf->isScheduled());
  10722. assertex(cwf->queryType() == WFTypeRecovery);
  10723. assertex(cwf->queryState() == WFStateSkip);
  10724. okay[1] = true;
  10725. break;
  10726. case 3:
  10727. assertex(cwf->queryContingencyFor() == 4);
  10728. okay[2] = true;
  10729. break;
  10730. case 4:
  10731. assertex(cwf->isScheduled());
  10732. assertex(cwf->queryType() == WFTypeNormal);
  10733. assertex(cwf->queryState() == WFStateReqd);
  10734. assertex(cwf->querySuccess() == 0);
  10735. assertex(cwf->queryFailure() == 3);
  10736. assertex(cwf->queryRecovery() == 2);
  10737. assertex(cwf->queryRetriesAllowed() == 10);
  10738. assertex(cwf->queryRetriesRemaining() == 10);
  10739. diter.setown(cwf->getDependencies());
  10740. for(diter->first(); diter->isValid(); diter->next())
  10741. {
  10742. dep[diter->query()-1] = true;
  10743. deps++;
  10744. }
  10745. assertex(deps==2);
  10746. assertex(dep[0]);
  10747. assertex(dep[1]);
  10748. okay[3] = true;
  10749. break;
  10750. case 5:
  10751. assertex(cwf->isScheduled());
  10752. assertex(!cwf->isScheduledNow());
  10753. assertex(cwf->querySchedulePriority() == 75);
  10754. assertex(cwf->queryScheduleCount() == 5);
  10755. assertex(cwf->queryScheduleCountRemaining() == 5);
  10756. okay[4] = true;
  10757. break;
  10758. case 6:
  10759. assertex(cwf->isScheduled());
  10760. assertex(!cwf->isScheduledNow());
  10761. assertex(cwf->querySchedulePriority() == 25);
  10762. assertex(!cwf->hasScheduleCount());
  10763. okay[5] = true;
  10764. break;
  10765. default:
  10766. assertex(!"unknown wfid in test");
  10767. }
  10768. }
  10769. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  10770. {
  10771. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  10772. switch(rwf->queryWfid())
  10773. {
  10774. case 1:
  10775. case 2:
  10776. case 3:
  10777. okay[rwf->queryWfid()-1] = true;
  10778. break;
  10779. case 4:
  10780. {
  10781. unsigned tries = 0;
  10782. while(rwf->testAndDecRetries())
  10783. tries++;
  10784. assertex(tries == 10);
  10785. assertex(rwf->queryRetriesRemaining() == 0);
  10786. rwf->setState(WFStateFail);
  10787. assertex(rwf->queryState() == WFStateFail);
  10788. rwf->reset();
  10789. assertex(rwf->queryRetriesRemaining() == 10);
  10790. assertex(rwf->queryState() == WFStateReqd);
  10791. }
  10792. okay[3] = true;
  10793. break;
  10794. case 5:
  10795. {
  10796. assertex(rwf->queryScheduleCountRemaining() == 5);
  10797. unsigned count = 0;
  10798. do count++; while(rwf->decAndTestScheduleCountRemaining());
  10799. assertex(count == 5);
  10800. assertex(rwf->queryScheduleCountRemaining() == 0);
  10801. rwf->reset();
  10802. assertex(rwf->queryScheduleCountRemaining() == 5);
  10803. }
  10804. okay[4] = true;
  10805. break;
  10806. case 6:
  10807. {
  10808. assertex(!rwf->hasScheduleCount());
  10809. unsigned count;
  10810. for(count=0; count<20; count++)
  10811. assertex(rwf->decAndTestScheduleCountRemaining());
  10812. }
  10813. okay[5] = true;
  10814. break;
  10815. default:
  10816. assertex(!"unknown wfid in test");
  10817. }
  10818. }
  10819. void testWorkflow()
  10820. {
  10821. DBGLOG("workunit.cpp : testWorkflow");
  10822. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  10823. Owned<IWorkflowItem> wf;
  10824. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  10825. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  10826. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  10827. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  10828. wf->setScheduledNow();
  10829. wf->addDependency(1);
  10830. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  10831. wf->setScheduledOn("test", "foo*");
  10832. wf->setSchedulePriority(75);
  10833. wf->setScheduleCount(5);
  10834. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  10835. wf->setScheduledOn("test", "bar*");
  10836. wf->setSchedulePriority(25);
  10837. unsigned const n = 6;
  10838. bool okay[n];
  10839. bool dep[n];
  10840. unsigned i;
  10841. for(i=0; i<n; i++)
  10842. okay[i] = dep[i] = 0;
  10843. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  10844. for(citer->first(); citer->isValid(); citer->next())
  10845. testConstWorkflow(citer->query(), okay, dep);
  10846. for(i=0; i<n; i++)
  10847. {
  10848. assertex(okay[i]);
  10849. okay[i] = false;
  10850. }
  10851. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  10852. for(miter->first(); miter->isValid(); miter->next())
  10853. {
  10854. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  10855. testRuntimeWorkflow(rwf, okay);
  10856. }
  10857. for(i=0; i<n; i++)
  10858. {
  10859. assertex(okay[i]);
  10860. okay[i] = dep[i] = false;
  10861. }
  10862. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  10863. unsigned wfid;
  10864. for(wfid = 1; array->isValid(wfid); wfid++)
  10865. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  10866. for(i=0; i<n; i++)
  10867. {
  10868. assertex(okay[i]);
  10869. okay[i] = false;
  10870. }
  10871. for(wfid = 1; array->isValid(wfid); wfid++)
  10872. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  10873. for(i=0; i<n; i++)
  10874. {
  10875. assertex(okay[i]);
  10876. okay[i] = false;
  10877. }
  10878. }
  10879. #endif
  10880. //------------------------------------------------------------------------------------------
  10881. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, std::list<WUState> expectedStates)
  10882. {
  10883. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, expectedStates);
  10884. }
  10885. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, std::list<WUState> expectedStates)
  10886. {
  10887. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  10888. return waitForWorkUnitToComplete(wuid, timeout, expectedStates);
  10889. return WUStateUnknown;
  10890. }
  10891. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  10892. {
  10893. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, { WUStateWait }))
  10894. {
  10895. case WUStateCompiled:
  10896. case WUStateCompleted:
  10897. case WUStateWait:
  10898. case WUStateUploadingFiles:
  10899. return true;
  10900. default:
  10901. return false;
  10902. }
  10903. }
  10904. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  10905. {
  10906. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  10907. return waitForWorkUnitToCompile(wuid, timeout);
  10908. return false;
  10909. }
  10910. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  10911. {
  10912. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  10913. {
  10914. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  10915. SCMStringBuffer ip;
  10916. unsigned port;
  10917. try
  10918. {
  10919. port = wu->getDebugAgentListenerPort();
  10920. wu->getDebugAgentListenerIP(ip);
  10921. SocketEndpoint debugEP(ip.str(), port);
  10922. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  10923. unsigned len = (size32_t)strlen(command);
  10924. unsigned revlen = len;
  10925. _WINREV(revlen);
  10926. socket->write(&revlen, sizeof(revlen));
  10927. socket->write(command, len);
  10928. for (;;)
  10929. {
  10930. socket->read(&len, sizeof(len));
  10931. _WINREV(len);
  10932. if (len == 0)
  10933. break;
  10934. if (len & 0x80000000)
  10935. {
  10936. throwUnexpected();
  10937. }
  10938. char * mem = (char*) response.reserve(len);
  10939. socket->read(mem, len);
  10940. }
  10941. return true;
  10942. }
  10943. catch (IException *E)
  10944. {
  10945. VStringBuffer msg("In secDebugWorkunit wuid %s port %d ip %s command %s", wuid, port, ip.str(), command);
  10946. EXCLOG(E, msg.str());
  10947. throw;
  10948. }
  10949. }
  10950. return false;
  10951. }
  10952. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  10953. {
  10954. TypeInfoArray types;
  10955. StringAttrArray names;
  10956. r->getSchema(types, names, NULL);
  10957. if (types.ordinality()==1)
  10958. type.set(&types.item(0));
  10959. }
  10960. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  10961. {
  10962. if (!r->isResultScalar())
  10963. return false;
  10964. if (!curVal.hasChildren())
  10965. return true;
  10966. getSimpleResultType(r, type);
  10967. return type && type->isScalar();
  10968. }
  10969. void updateSuppliedXmlParams(IWorkUnit * w)
  10970. {
  10971. Owned<const IPropertyTree> params = w->getXmlParams();
  10972. if (!params)
  10973. return;
  10974. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  10975. ForEach(*elems)
  10976. {
  10977. IPropertyTree & curVal = elems->query();
  10978. const char *name = curVal.queryName();
  10979. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  10980. if (r)
  10981. {
  10982. Owned<ITypeInfo> type;
  10983. StringBuffer s;
  10984. if (isSuppliedParamScalar(r, curVal, type))
  10985. {
  10986. curVal.getProp(".", s);
  10987. r->setResultXML(s);
  10988. r->setResultStatus(ResultStatusSupplied);
  10989. }
  10990. else
  10991. {
  10992. toXML(&curVal, s);
  10993. if (!type)
  10994. getSimpleResultType(r, type);
  10995. bool isSet = (type && type->getTypeCode()==type_set);
  10996. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  10997. }
  10998. }
  10999. else
  11000. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  11001. }
  11002. }
  11003. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  11004. {
  11005. switch ((int)sequence)
  11006. {
  11007. case ResultSequenceStored:
  11008. return w->updateVariableByName(name);
  11009. case ResultSequencePersist:
  11010. return w->updateGlobalByName(name);
  11011. case ResultSequenceInternal:
  11012. case ResultSequenceOnce:
  11013. return w->updateTemporaryByName(name);
  11014. default:
  11015. return w->updateResultBySequence(sequence);
  11016. }
  11017. }
  11018. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  11019. {
  11020. switch ((int)sequence)
  11021. {
  11022. case ResultSequenceStored:
  11023. return w->getVariableByName(name);
  11024. case ResultSequencePersist:
  11025. return w->getGlobalByName(name);
  11026. case ResultSequenceInternal:
  11027. case ResultSequenceOnce:
  11028. return w->getTemporaryByName(name);
  11029. default:
  11030. if (name && name[0])
  11031. return w->getResultByName(name);//name takes precedence over sequence
  11032. else
  11033. return w->getResultBySequence(sequence);
  11034. }
  11035. }
  11036. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  11037. {
  11038. if (wuid) {
  11039. char prefchar;
  11040. unsigned year,month,day,hour,min,sec;
  11041. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  11042. time.set(year, month, day, hour, min, sec, 0, true);
  11043. // time.setDate(year, month, day);
  11044. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  11045. return true;
  11046. }
  11047. }
  11048. return false;
  11049. }
  11050. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  11051. {
  11052. return (WUState) getEnum(state, states);
  11053. }
  11054. constexpr LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  11055. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  11056. {
  11057. public:
  11058. CWorkflowScheduleConnection(char const * wuid)
  11059. {
  11060. basexpath.append("/WorkflowSchedule/").append(wuid);
  11061. flagxpath.append(basexpath.str()).append("/Active");
  11062. }
  11063. IMPLEMENT_IINTERFACE;
  11064. virtual void lock()
  11065. {
  11066. LOG(MCschedconn, "Locking base schedule connection");
  11067. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  11068. if(!baseconn)
  11069. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  11070. }
  11071. virtual void unlock()
  11072. {
  11073. LOG(MCschedconn, "Unlocking base schedule connection");
  11074. baseconn.clear();
  11075. }
  11076. virtual void setActive()
  11077. {
  11078. LOG(MCschedconn, "Setting active flag in schedule connection");
  11079. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  11080. if(!flagconn)
  11081. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  11082. }
  11083. virtual void resetActive()
  11084. {
  11085. LOG(MCschedconn, "Resetting active flag in schedule connection");
  11086. flagconn.clear();
  11087. }
  11088. virtual bool queryActive()
  11089. {
  11090. return baseconn->queryRoot()->hasProp("Active");
  11091. }
  11092. virtual bool pull(IWorkflowItemArray * workflow)
  11093. {
  11094. assertex(baseconn);
  11095. Owned<IPropertyTree> root = baseconn->getRoot();
  11096. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  11097. if(!eventQueue) return false;
  11098. if(!eventQueue->hasProp("Item")) return false;
  11099. {
  11100. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  11101. Owned<IPropertyTree> eventItem;
  11102. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  11103. Owned<IRuntimeWorkflowItem> wfItem;
  11104. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  11105. {
  11106. eventItem.setown(&eventItems->get());
  11107. const char * eventName = eventItem->queryProp("@name");
  11108. const char * eventText = eventItem->queryProp("@text");
  11109. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  11110. {
  11111. wfItem.setown(wfItems->get());
  11112. if(wfItem->queryState() != WFStateWait)
  11113. continue;
  11114. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  11115. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  11116. continue;
  11117. wfItem->setEvent(eventName, eventText);
  11118. wfItem->setState(WFStateReqd);
  11119. resetDependentsState(workflow, *wfItem);
  11120. }
  11121. }
  11122. }
  11123. bool more;
  11124. do
  11125. more = eventQueue->removeProp("Item");
  11126. while(more);
  11127. return true;
  11128. }
  11129. virtual void push(char const * name, char const * text)
  11130. {
  11131. assertex(baseconn);
  11132. Owned<IPropertyTree> root = baseconn->getRoot();
  11133. IPropertyTree *eventQueue = ensurePTree(root, "EventQueue");
  11134. IPropertyTree *eventItem = eventQueue->addPropTree("Item");
  11135. eventItem->setProp("@name", name);
  11136. eventItem->setProp("@text", text);
  11137. }
  11138. virtual void remove()
  11139. {
  11140. if (baseconn)
  11141. {
  11142. baseconn->close(true);
  11143. baseconn.clear();
  11144. }
  11145. }
  11146. private:
  11147. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  11148. {
  11149. if (wfid)
  11150. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  11151. }
  11152. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11153. {
  11154. switch(item.queryState())
  11155. {
  11156. case WFStateDone:
  11157. case WFStateFail:
  11158. {
  11159. item.setState(WFStateNull);
  11160. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  11161. resetDependentsState(workflow, item);
  11162. break;
  11163. }
  11164. }
  11165. }
  11166. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11167. {
  11168. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  11169. for(iter->first(); iter->isValid(); iter->next())
  11170. {
  11171. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  11172. resetItemStateAndDependents(workflow, dep);
  11173. }
  11174. }
  11175. private:
  11176. StringBuffer basexpath;
  11177. StringBuffer flagxpath;
  11178. Owned<IRemoteConnection> baseconn;
  11179. Owned<IRemoteConnection> flagconn;
  11180. };
  11181. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  11182. {
  11183. return new CWorkflowScheduleConnection(wuid);
  11184. }
  11185. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  11186. {
  11187. return QUERYINTERFACE(wu, IExtendedWUInterface);
  11188. }
  11189. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  11190. {
  11191. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  11192. }
  11193. extern WORKUNIT_API void addExceptionToWorkunit(IWorkUnit * wu, ErrorSeverity severity, const char * source, unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column, unsigned activity)
  11194. {
  11195. Owned<IWUException> we = wu->createException();
  11196. we->setSeverity(severity);
  11197. we->setExceptionMessage(text);
  11198. if (source)
  11199. we->setExceptionSource(source);
  11200. if (code)
  11201. we->setExceptionCode(code);
  11202. if (filename)
  11203. we->setExceptionFileName(filename);
  11204. if (lineno)
  11205. {
  11206. we->setExceptionLineNo(lineno);
  11207. if (column)
  11208. we->setExceptionColumn(lineno);
  11209. }
  11210. if (activity)
  11211. we->setActivityId(activity);
  11212. }
  11213. const char * skipLeadingXml(const char * text)
  11214. {
  11215. if (!text)
  11216. return NULL;
  11217. //skip utf8 BOM, probably excessive
  11218. if (memcmp(text, UTF8_BOM, 3) == 0)
  11219. text += 3;
  11220. for (;;)
  11221. {
  11222. if (isspace(*text))
  11223. text++;
  11224. else if (text[0] == '<' && text[1] == '?')
  11225. {
  11226. text += 2;
  11227. for (;;)
  11228. {
  11229. if (!*text) break;
  11230. if (text[0] == '?' && text[1] == '>')
  11231. {
  11232. text += 2;
  11233. break;
  11234. }
  11235. text++;
  11236. }
  11237. }
  11238. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  11239. {
  11240. text += 4;
  11241. for (;;)
  11242. {
  11243. if (!*text) break;
  11244. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  11245. {
  11246. text += 3;
  11247. break;
  11248. }
  11249. text++;
  11250. }
  11251. }
  11252. else
  11253. break;
  11254. }
  11255. return text;
  11256. }
  11257. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  11258. {
  11259. text = skipLeadingXml(text);
  11260. if (!text)
  11261. return false;
  11262. const char * archivePrefix = "<Archive";
  11263. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  11264. }
  11265. extern WORKUNIT_API bool isQueryManifest(const char * text)
  11266. {
  11267. text = skipLeadingXml(text);
  11268. if (!text)
  11269. return false;
  11270. const char * manifestPrefix = "<Manifest";
  11271. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  11272. }
  11273. //------------------------------------------------------------------------------
  11274. // Named Alias helper function
  11275. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  11276. {
  11277. StringBuffer xpath;
  11278. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  11279. return queryRegistry->getPropTree(xpath);
  11280. }
  11281. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  11282. {
  11283. StringBuffer xpath;
  11284. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  11285. return queryRegistry->getPropTree(xpath);
  11286. }
  11287. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  11288. {
  11289. StringBuffer lcId(id);
  11290. lcId.toLowerCase();
  11291. StringBuffer xpath;
  11292. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  11293. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11294. ForEach(*iter)
  11295. {
  11296. queryRegistry->removeProp(xpath.str());
  11297. }
  11298. }
  11299. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  11300. {
  11301. StringBuffer lcName(name);
  11302. lcName.toLowerCase();
  11303. StringBuffer xpath;
  11304. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  11305. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11306. unsigned seq = 1;
  11307. ForEach(*iter)
  11308. {
  11309. IPropertyTree &item = iter->query();
  11310. const char *thisWuid = item.queryProp("@wuid");
  11311. if (strieq(wuid, thisWuid))
  11312. return &item;
  11313. unsigned thisSeq = item.getPropInt("@seq");
  11314. if (thisSeq >= seq)
  11315. seq = thisSeq + 1;
  11316. }
  11317. StringBuffer id;
  11318. id.append(lcName).append(".").append(seq);
  11319. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive|ipt_lowmem);
  11320. newEntry->setProp("@name", lcName);
  11321. newEntry->setProp("@wuid", wuid);
  11322. newEntry->setProp("@dll", dll);
  11323. newEntry->setProp("@id", id);
  11324. newEntry->setPropInt("@seq", seq);
  11325. if (library)
  11326. newEntry->setPropBool("@isLibrary", true);
  11327. if (userid && *userid)
  11328. newEntry->setProp("@publishedBy", userid);
  11329. if (snapshot && *snapshot)
  11330. newEntry->setProp("@snapshot", snapshot);
  11331. return queryRegistry->addPropTree("Query", newEntry);
  11332. }
  11333. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11334. {
  11335. StringBuffer lcId(id);
  11336. lcId.toLowerCase();
  11337. clearAliases(queryRegistry, lcId);
  11338. StringBuffer xpath;
  11339. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11340. queryRegistry->removeProp(xpath);
  11341. }
  11342. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  11343. {
  11344. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  11345. if (!match)
  11346. return;
  11347. clearAliases(queryRegistry, match->queryProp("@id"));
  11348. queryRegistry->removeTree(match);
  11349. }
  11350. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  11351. {
  11352. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  11353. if (!match)
  11354. return;
  11355. clearAliases(queryRegistry, match->queryProp("@id"));
  11356. queryRegistry->removeTree(match);
  11357. }
  11358. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11359. {
  11360. clearAliases(queryRegistry, id);
  11361. }
  11362. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  11363. {
  11364. StringBuffer lcName(name);
  11365. lcName.toLowerCase();
  11366. StringBuffer xpath;
  11367. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  11368. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  11369. if (!match)
  11370. {
  11371. match = queryRegistry->addPropTree("Alias");
  11372. match->setProp("@name", lcName);
  11373. }
  11374. match->setProp("@id", value);
  11375. }
  11376. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  11377. {
  11378. if (!queryRegistry || !queryid)
  11379. return NULL;
  11380. StringBuffer xpath;
  11381. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  11382. return queryRegistry->getPropTree(xpath);
  11383. }
  11384. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  11385. {
  11386. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11387. return getQueryById(queryRegistry, queryid);
  11388. }
  11389. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  11390. {
  11391. if (!queryRegistry || !alias)
  11392. return NULL;
  11393. StringBuffer xpath;
  11394. unsigned cnt = 0;
  11395. StringBuffer lc(alias);
  11396. const char * search = lc.toLowerCase().str();
  11397. for (;;)
  11398. {
  11399. xpath.set("Alias[@name='").append(search).append("']/@id");
  11400. const char * queryId = queryRegistry->queryProp(xpath);
  11401. if (!queryId)
  11402. break;
  11403. //Check for too many alias indirections.
  11404. if (cnt++ > 10)
  11405. return NULL;
  11406. search = lc.set(queryId).toLowerCase().str();
  11407. }
  11408. return getQueryById(queryRegistry, search);
  11409. }
  11410. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  11411. {
  11412. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11413. return resolveQueryAlias(queryRegistry, alias);
  11414. }
  11415. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  11416. {
  11417. StringBuffer lcId(id);
  11418. lcId.toLowerCase();
  11419. StringBuffer xpath;
  11420. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11421. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11422. if (tree)
  11423. {
  11424. if (tree->getPropBool("@suspended", false) == suspend)
  11425. return;
  11426. if (suspend)
  11427. {
  11428. tree->addPropBool("@suspended", true);
  11429. if (userid && *userid)
  11430. tree->addProp("@suspendedBy", userid);
  11431. }
  11432. else
  11433. {
  11434. tree->removeProp("@suspended");
  11435. tree->removeProp("@suspendedBy");
  11436. }
  11437. }
  11438. else
  11439. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  11440. }
  11441. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  11442. {
  11443. if (queryComment)
  11444. {
  11445. StringBuffer lcId(id);
  11446. lcId.toLowerCase();
  11447. StringBuffer xpath;
  11448. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11449. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11450. if (tree)
  11451. tree->setProp("@queryComment", queryComment);
  11452. else
  11453. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  11454. }
  11455. }
  11456. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  11457. {
  11458. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  11459. if (conn)
  11460. return conn->getRoot();
  11461. else
  11462. return NULL;
  11463. }
  11464. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  11465. {
  11466. if (!queryTree || !libraries)
  11467. return;
  11468. if (queryTree->hasProp("@libCount")) //already added
  11469. return;
  11470. unsigned libCount=0;
  11471. ForEach(*libraries)
  11472. {
  11473. IConstWULibrary &library = libraries->query();
  11474. SCMStringBuffer libname;
  11475. if (!library.getName(libname).length())
  11476. continue;
  11477. queryTree->addProp("Library", libname.str());
  11478. libCount++;
  11479. }
  11480. queryTree->setPropInt("@libCount", libCount);
  11481. }
  11482. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  11483. {
  11484. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  11485. checkAddLibrariesToQueryEntry(queryTree, libraries);
  11486. }
  11487. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  11488. {
  11489. //Only lock the branch for the target we're interested in.
  11490. StringBuffer xpath;
  11491. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  11492. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11493. if (conn)
  11494. return conn->getRoot();
  11495. if (readonly)
  11496. return NULL;
  11497. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  11498. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11499. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  11500. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11501. if (conn)
  11502. return conn->getRoot();
  11503. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11504. if (!conn)
  11505. throwUnexpected();
  11506. IPropertyTree * root = conn->queryRoot();
  11507. root->setProp("@id",wsEclId);
  11508. conn->commit();
  11509. return LINK(root);
  11510. }
  11511. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  11512. {
  11513. StringBuffer xpath;
  11514. StringBuffer lcName(name);
  11515. lcName.toLowerCase();
  11516. // see if "name" already exists
  11517. xpath.append("Package[@id='").append(name).append("']");
  11518. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  11519. if (pkgTree)
  11520. {
  11521. if (overWrite)
  11522. packageRegistry->removeTree(pkgTree);
  11523. else
  11524. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  11525. }
  11526. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  11527. tree->setProp("@id", lcName);
  11528. return tree;
  11529. }
  11530. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  11531. {
  11532. StringBuffer lcId(id);
  11533. lcId.toLowerCase();
  11534. StringBuffer xpath;
  11535. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  11536. packageRegistry->removeProp(xpath);
  11537. }
  11538. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  11539. {
  11540. //Only lock the branch for the target we're interested in.
  11541. StringBuffer xpath;
  11542. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  11543. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11544. if (conn)
  11545. return conn->getRoot();
  11546. if (readonly)
  11547. return NULL;
  11548. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  11549. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11550. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  11551. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11552. if (conn)
  11553. return conn->getRoot();
  11554. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11555. if (!conn)
  11556. throwUnexpected();
  11557. IPropertyTree* root = conn->queryRoot();
  11558. root->setProp("@id",wsEclId);
  11559. conn->commit();
  11560. return LINK(root);
  11561. }
  11562. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11563. {
  11564. StringBuffer cleanQueryName;
  11565. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11566. SCMStringBuffer dllName;
  11567. Owned<IConstWUQuery> q = workunit->getQuery();
  11568. q->getQueryDllName(dllName);
  11569. if (!dllName.length())
  11570. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  11571. StringBuffer currentTargetClusterType;
  11572. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  11573. SCMStringBuffer targetClusterType;
  11574. workunit->getDebugValue("targetclustertype", targetClusterType);
  11575. SCMStringBuffer snapshot;
  11576. workunit->getSnapshot(snapshot);
  11577. if (currentTargetClusterType.length() < 1)
  11578. {
  11579. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  11580. }
  11581. else
  11582. {
  11583. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  11584. {
  11585. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  11586. }
  11587. }
  11588. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  11589. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  11590. checkAddLibrariesToQueryEntry(newEntry, libraries);
  11591. newQueryId.append(newEntry->queryProp("@id"));
  11592. workunit->setIsQueryService(true); //will check querysets before delete
  11593. workunit->commit();
  11594. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  11595. }
  11596. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  11597. {
  11598. StringBuffer cleanQueryName;
  11599. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11600. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  11601. {
  11602. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  11603. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11604. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  11605. {
  11606. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  11607. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  11608. else
  11609. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  11610. }
  11611. }
  11612. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  11613. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11614. }
  11615. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11616. {
  11617. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11618. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  11619. }
  11620. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  11621. {
  11622. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11623. StringBuffer xpath;
  11624. xpath.appendf("Alias[@name='%s']", alias);
  11625. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  11626. return queryRegistry->removeTree(t);
  11627. }
  11628. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  11629. {
  11630. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11631. setQueryAlias(queryRegistry, alias, id);
  11632. }
  11633. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  11634. {
  11635. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11636. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  11637. }
  11638. void deleteQuerySetQuery(const char *querySetName, const char *id)
  11639. {
  11640. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11641. removeNamedQuery(queryRegistry, id);
  11642. }
  11643. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  11644. {
  11645. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11646. clearAliases(queryRegistry, id);
  11647. }
  11648. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  11649. {
  11650. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11651. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  11652. }
  11653. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  11654. {
  11655. if (!queryRegistry)
  11656. return NULL;
  11657. StringBuffer xpath;
  11658. xpath.appendf("Query[@wuid='%s']", wuid);
  11659. if (queryName && *queryName)
  11660. xpath.appendf("[@name='%s']", queryName);
  11661. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  11662. if (q)
  11663. {
  11664. id.set(q->queryProp("@id"));
  11665. }
  11666. return id.str();
  11667. }
  11668. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  11669. {
  11670. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11671. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  11672. }
  11673. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  11674. {
  11675. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  11676. ForEach(*wulibraries)
  11677. {
  11678. SCMStringBuffer libname;
  11679. IConstWULibrary &wulibrary = wulibraries->query();
  11680. wulibrary.getName(libname);
  11681. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  11682. continue;
  11683. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  11684. if (query && query->getPropBool("@isLibrary"))
  11685. {
  11686. const char *wuid = query->queryProp("@wuid");
  11687. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  11688. if (libcw)
  11689. {
  11690. names.appendUniq(libname.str());
  11691. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  11692. continue;
  11693. }
  11694. }
  11695. unresolved.appendUniq(libname.str());
  11696. }
  11697. }
  11698. bool looksLikeAWuid(const char * wuid, const char firstChar)
  11699. {
  11700. if (!wuid)
  11701. return false;
  11702. if (wuid[0] != firstChar)
  11703. return false;
  11704. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  11705. return false;
  11706. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  11707. return false;
  11708. return (wuid[9]=='-');
  11709. }
  11710. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  11711. {
  11712. IPropertyTree * module = archive;
  11713. const char * dot = strrchr(path, '.');
  11714. StringBuffer xpath;
  11715. if (dot)
  11716. {
  11717. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  11718. module = archive->queryPropTree(xpath);
  11719. path = dot+1;
  11720. }
  11721. else
  11722. module = archive->queryPropTree("Module[@key='']");
  11723. if (!module)
  11724. return NULL;
  11725. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  11726. return module->queryPropTree(xpath);
  11727. }
  11728. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  11729. {
  11730. StringBuffer fullPathName;
  11731. makeAbsolutePath(name, fullPathName);
  11732. if (isContainerized())
  11733. {
  11734. const char *dllserver_root = getenv("HPCC_DLLSERVER_PATH");
  11735. assertex(dllserver_root != nullptr);
  11736. StringBuffer destPathName(dllserver_root);
  11737. addNonEmptyPathSepChar(destPathName);
  11738. splitFilename(fullPathName.str(), nullptr, nullptr, &destPathName, &destPathName);
  11739. OwnedIFile source = createIFile(fullPathName);
  11740. OwnedIFile target = createIFile(destPathName);
  11741. if (!target->exists())
  11742. {
  11743. source->copyTo(target, 0, NULL, true);
  11744. }
  11745. query->addAssociatedFile(type, destPathName, "localhost", description, crc, minActivity, maxActivity);
  11746. // Should we delete the local files? May not matter...
  11747. }
  11748. else
  11749. {
  11750. StringBuffer hostname;
  11751. queryHostIP().getIpText(hostname);
  11752. query->addAssociatedFile(type, fullPathName, hostname, description, crc, minActivity, maxActivity);
  11753. }
  11754. }
  11755. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  11756. {
  11757. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  11758. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  11759. if(workunit)
  11760. workunit->deschedule();
  11761. else
  11762. doDescheduleWorkkunit(wuid);
  11763. }
  11764. extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid)
  11765. {
  11766. StringBuffer scopestr;
  11767. if (wfid && scope && *scope)
  11768. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  11769. else
  11770. scopestr.set(scope);
  11771. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, description, value, 1, 0, StatsMergeReplace);
  11772. }
  11773. class WuTimingUpdater : implements ITimeReportInfo
  11774. {
  11775. public:
  11776. WuTimingUpdater(IWorkUnit * _wu, StatisticScopeType _scopeType, StatisticKind _kind)
  11777. : wu(_wu), scopeType(_scopeType), kind(_kind)
  11778. { }
  11779. virtual void report(const char * scope, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  11780. {
  11781. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, nullptr, totaltime, count, maxtime, StatsMergeReplace);
  11782. }
  11783. protected:
  11784. IWorkUnit * wu;
  11785. StatisticScopeType scopeType;
  11786. StatisticKind kind;
  11787. };
  11788. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  11789. {
  11790. WuTimingUpdater target(wu, SSTsection, StTimeTotalExecute);
  11791. timer->report(target);
  11792. }
  11793. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer)
  11794. {
  11795. WuTimingUpdater target(wu, scopeType, kind);
  11796. timer->report(target);
  11797. }
  11798. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid)
  11799. {
  11800. StringBuffer scopestr;
  11801. if (wfid && scope && *scope)
  11802. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  11803. else
  11804. scopestr.set(scope);
  11805. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  11806. }
  11807. extern WORKUNIT_API cost_type calculateThorCost(unsigned __int64 ms, unsigned clusterWidth)
  11808. {
  11809. IPropertyTree *costs = queryCostsConfiguration();
  11810. if (costs)
  11811. {
  11812. cost_type thor_master_rate = money2cost_type(costs->getPropReal("thor/@master"));
  11813. cost_type thor_slave_rate = money2cost_type(costs->getPropReal("thor/@slave"));
  11814. return calcCost(thor_master_rate, ms) + calcCost(thor_slave_rate, ms) * clusterWidth;
  11815. }
  11816. return 0;
  11817. }
  11818. void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search)
  11819. {
  11820. SimpleReferenceAggregator aggregator(search, result);
  11821. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  11822. ForEach(*it)
  11823. it->playProperties(aggregator);
  11824. }
  11825. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  11826. {
  11827. public:
  11828. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  11829. virtual void beginScope(const StatsScopeId & id)
  11830. {
  11831. prevLenStack.append(scope.length());
  11832. if (scope.length())
  11833. scope.append(":");
  11834. id.getScopeText(scope);
  11835. scopeTypeStack.append(id.queryScopeType());
  11836. }
  11837. virtual void beginSubGraphScope(unsigned id)
  11838. {
  11839. StatsScopeId scopeId(SSTsubgraph, id);
  11840. beginScope(scopeId);
  11841. }
  11842. virtual void beginActivityScope(unsigned id)
  11843. {
  11844. StatsScopeId scopeId(SSTactivity, id);
  11845. beginScope(scopeId);
  11846. }
  11847. virtual void beginEdgeScope(unsigned id, unsigned oid)
  11848. {
  11849. StatsScopeId scopeId(SSTedge, id, oid);
  11850. beginScope(scopeId);
  11851. }
  11852. virtual void beginChildGraphScope(unsigned id)
  11853. {
  11854. StatsScopeId scopeId(SSTchildgraph, id);
  11855. beginScope(scopeId);
  11856. }
  11857. virtual void endScope()
  11858. {
  11859. scope.setLength(prevLenStack.popGet());
  11860. scopeTypeStack.pop();
  11861. }
  11862. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  11863. {
  11864. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  11865. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  11866. }
  11867. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  11868. {
  11869. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  11870. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  11871. }
  11872. virtual IStatisticCollection * getResult()
  11873. {
  11874. return NULL;
  11875. }
  11876. protected:
  11877. Linked<IWorkUnit> wu;
  11878. StringBuffer scope;
  11879. UnsignedArray prevLenStack;
  11880. UnsignedArray scopeTypeStack;
  11881. };
  11882. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  11883. {
  11884. return new GlobalStatisticGatherer(wu);
  11885. }
  11886. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  11887. {
  11888. if (!wuid || !*wuid)
  11889. return NULL;
  11890. VStringBuffer path("/GraphProgress/%s", wuid);
  11891. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11892. if (conn)
  11893. return conn->getRoot();
  11894. else
  11895. return NULL;
  11896. }
  11897. void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp)
  11898. {
  11899. ErrorSeverity wuSeverity = SeverityInformation;
  11900. ErrorSeverity severity = error->getSeverity();
  11901. switch (severity)
  11902. {
  11903. case SeverityIgnore:
  11904. return;
  11905. case SeverityInformation:
  11906. break;
  11907. case SeverityWarning:
  11908. wuSeverity = SeverityWarning;
  11909. break;
  11910. case SeverityError:
  11911. case SeverityFatal:
  11912. wuSeverity = SeverityError;
  11913. break;
  11914. }
  11915. Owned<IWUException> exception = wu->createException();
  11916. exception->setSeverity(wuSeverity);
  11917. StringBuffer msg;
  11918. exception->setExceptionCode(error->errorCode());
  11919. exception->setExceptionMessage(error->errorMessage(msg).str());
  11920. const char * source = queryCreatorTypeName(queryStatisticsComponentType());
  11921. exception->setExceptionSource(source);
  11922. exception->setExceptionFileName(error->getFilename());
  11923. exception->setExceptionLineNo(error->getLine());
  11924. exception->setExceptionColumn(error->getColumn());
  11925. if (removeTimeStamp)
  11926. exception->setTimeStamp(nullptr);
  11927. if (error->getActivity())
  11928. exception->setActivityId(error->getActivity());
  11929. if (error->queryScope())
  11930. exception->setScope(error->queryScope());
  11931. }
  11932. IError * WorkUnitErrorReceiver::mapError(IError * error)
  11933. {
  11934. return LINK(error);
  11935. }
  11936. void WorkUnitErrorReceiver::report(IError* eclError)
  11937. {
  11938. addWorkunitException(wu, eclError, removeTimeStamp);
  11939. }
  11940. size32_t WorkUnitErrorReceiver::errCount()
  11941. {
  11942. unsigned count = 0;
  11943. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  11944. ForEach(*exceptions)
  11945. if (exceptions->query().getSeverity() == SeverityError)
  11946. count++;
  11947. return count;
  11948. }
  11949. size32_t WorkUnitErrorReceiver::warnCount()
  11950. {
  11951. unsigned count = 0;
  11952. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  11953. ForEach(*exceptions)
  11954. if (exceptions->query().getSeverity() == SeverityWarning)
  11955. count++;
  11956. return count;
  11957. }
  11958. bool isValidPriorityValue(const char *priority)
  11959. {
  11960. if (isEmptyString(priority))
  11961. return false;
  11962. if (strieq("SLA", priority) || strieq("LOW", priority) || strieq("HIGH", priority) || strieq("NONE", priority))
  11963. return true;
  11964. return false;
  11965. }
  11966. bool isValidMemoryValue(const char *memoryUnit)
  11967. {
  11968. if (isEmptyString(memoryUnit) || !isdigit(*memoryUnit))
  11969. return false;
  11970. while (isdigit(*++memoryUnit));
  11971. if (!*memoryUnit)
  11972. return true;
  11973. switch (toupper(*memoryUnit++))
  11974. {
  11975. case 'E':
  11976. case 'P':
  11977. case 'T':
  11978. case 'G':
  11979. case 'M':
  11980. case 'K':
  11981. if (!*memoryUnit || strieq("B", memoryUnit))
  11982. return true;
  11983. break;
  11984. case 'B':
  11985. if (!*memoryUnit)
  11986. return true;
  11987. break;
  11988. }
  11989. return false;
  11990. }
  11991. // used by eclagent and roxie
  11992. #define ABORT_POLL_PERIOD (5*1000)
  11993. void executeThorGraph(const char * graphName, IConstWorkUnit &workunit, const IPropertyTree &config)
  11994. {
  11995. unsigned timelimit = workunit.getDebugValueInt("thorConnectTimeout", config.getPropInt("@thorConnectTimeout", 60));
  11996. StringAttr wuid(workunit.queryWuid());
  11997. #ifdef _CONTAINERIZED
  11998. // NB: If a single agent were to want to launch >1 Thor, then the threading could be in the workflow above this call.
  11999. {
  12000. Owned<IWorkUnit> w = &workunit.lock();
  12001. w->setState(WUStateBlocked);
  12002. }
  12003. WUState state = WUStateUnknown;
  12004. if (config.hasProp("@queue"))
  12005. {
  12006. bool multiJobLinger = config.getPropBool("@multiJobLinger");
  12007. if (executeGraphOnLingeringThor(workunit, graphName, multiJobLinger ? config.queryProp("@queue") : nullptr))
  12008. PROGLOG("Existing lingering Thor handled graph: %s", graphName);
  12009. else
  12010. {
  12011. VStringBuffer queueName("%s.thor", config.queryProp("@queue"));
  12012. DBGLOG("Queueing wuid=%s, graph=%s, on queue=%s, timelimit=%u seconds", wuid.str(), graphName, queueName.str(), timelimit);
  12013. Owned<IJobQueue> queue = createJobQueue(queueName);
  12014. VStringBuffer jobName("%s/%s", wuid.get(), graphName);
  12015. IJobQueueItem *item = createJobQueueItem(jobName);
  12016. queue->enqueue(item);
  12017. }
  12018. // NB: overall max runtime if guillotine set handled by abortmonitor
  12019. unsigned runningTimeLimit = workunit.getDebugValueInt("maxRunTime", 0);
  12020. runningTimeLimit = runningTimeLimit ? runningTimeLimit : INFINITE;
  12021. std::list<WUState> expectedStates = { WUStateRunning, WUStateWait };
  12022. for (unsigned i=0; i<2; i++)
  12023. {
  12024. WUState state = waitForWorkUnitToComplete(wuid, timelimit*1000, expectedStates);
  12025. DBGLOG("Got state: %s", getWorkunitStateStr(state));
  12026. if (WUStateWait == state) // already finished
  12027. break;
  12028. else if ((INFINITE != timelimit) && (WUStateUnknown == state))
  12029. throw makeStringExceptionV(0, "Query %s failed to start within specified timelimit (%u) seconds", wuid.str(), timelimit);
  12030. else
  12031. {
  12032. auto it = std::find(expectedStates.begin(), expectedStates.end(), state);
  12033. if (it == expectedStates.end())
  12034. throw makeStringExceptionV(0, "Query %s failed, state: %s", wuid.str(), getWorkunitStateStr(state));
  12035. }
  12036. timelimit = runningTimeLimit;
  12037. expectedStates = { WUStateWait };
  12038. }
  12039. }
  12040. else
  12041. {
  12042. VStringBuffer job("%s-%s", wuid.str(), graphName);
  12043. runK8sJob("thormaster", wuid, job, queryComponentConfig().getPropBool("@deleteJobs", true), { { "graphName", graphName} });
  12044. }
  12045. /* In k8s, Thor feeds back the terminating exception via the workunit.
  12046. * (in bare-metal it is returned via a socket the agent connect to Thor with)
  12047. */
  12048. workunit.forceReload();
  12049. if (workunit.getExceptionCount())
  12050. {
  12051. Owned<IConstWUExceptionIterator> iter = &workunit.getExceptions();
  12052. ForEach(*iter)
  12053. {
  12054. IConstWUException &e = iter->query();
  12055. SCMStringBuffer str;
  12056. e.getExceptionSource(str);
  12057. if (streq("thormasterexception", str.s))
  12058. {
  12059. str.clear();
  12060. e.getExceptionMessage(str);
  12061. unsigned errCode = e.getExceptionCode();
  12062. {
  12063. /* Clear the feedback exception (consume it),
  12064. * so that any future re-submissions of this workunit (e.g. due to workflow)
  12065. * don't see it again.
  12066. */
  12067. Owned<IWorkUnit> w = &workunit.lock();
  12068. w->clearExceptions("thormasterexception");
  12069. }
  12070. throw makeStringException(errCode, str.str());
  12071. }
  12072. }
  12073. }
  12074. else
  12075. {
  12076. Owned<IWorkUnit> w = &workunit.lock();
  12077. WUState state = w->getState();
  12078. if (WUStateFailed == state)
  12079. throw makeStringException(0, "Workunit failed");
  12080. }
  12081. {
  12082. Owned<IWorkUnit> w = &workunit.lock();
  12083. w->setState(WUStateRunning);
  12084. }
  12085. #else
  12086. StringAttr owner(workunit.queryUser());
  12087. StringAttr cluster(workunit.queryClusterName());
  12088. int priority = workunit.getPriorityValue();
  12089. Owned<IConstWUClusterInfo> c = getTargetClusterInfo(cluster);
  12090. if (!c)
  12091. throw MakeStringException(0, "Invalid thor cluster %s", cluster.str());
  12092. SCMStringBuffer queueName;
  12093. c->getThorQueue(queueName);
  12094. Owned<IJobQueue> jq = createJobQueue(queueName.str());
  12095. bool resubmit;
  12096. Owned<IWorkUnitFactory> wuFactory = getWorkUnitFactory();
  12097. do // loop if pause interrupted graph and needs resubmitting on resume
  12098. {
  12099. resubmit = false; // set if job interrupted in thor
  12100. if (WUStatePaused == workunit.getState()) // check initial state - and wait if paused
  12101. {
  12102. for (;;)
  12103. {
  12104. WUAction action = wuFactory->waitForWorkUnitAction(wuid, workunit.getAction());
  12105. if (action == WUActionUnknown)
  12106. throw new WorkflowException(0, "Workunit aborting", 0, WorkflowException::ABORT, MSGAUD_user);
  12107. if (action != WUActionPause && action != WUActionPauseNow)
  12108. break;
  12109. }
  12110. }
  12111. {
  12112. Owned<IWorkUnit> w = &workunit.lock();
  12113. w->setState(WUStateBlocked);
  12114. }
  12115. class cPollThread: public Thread // MORE - why do we ned a thread here?
  12116. {
  12117. Semaphore sem;
  12118. bool stopped;
  12119. IJobQueue *jq;
  12120. IConstWorkUnit *wu;
  12121. public:
  12122. bool timedout;
  12123. CTimeMon tm;
  12124. cPollThread(IJobQueue *_jq, IConstWorkUnit *_wu, unsigned timelimit)
  12125. : tm(timelimit)
  12126. {
  12127. stopped = false;
  12128. jq = _jq;
  12129. wu = _wu;
  12130. timedout = false;
  12131. }
  12132. ~cPollThread()
  12133. {
  12134. stop();
  12135. }
  12136. int run()
  12137. {
  12138. while (!stopped) {
  12139. sem.wait(ABORT_POLL_PERIOD);
  12140. if (stopped)
  12141. break;
  12142. if (tm.timedout()) {
  12143. timedout = true;
  12144. stopped = true;
  12145. jq->cancelInitiateConversation();
  12146. }
  12147. else if (wu->aborting()) {
  12148. stopped = true;
  12149. jq->cancelInitiateConversation();
  12150. }
  12151. }
  12152. return 0;
  12153. }
  12154. void stop()
  12155. {
  12156. stopped = true;
  12157. sem.signal();
  12158. }
  12159. } pollthread(jq, &workunit, timelimit*1000);
  12160. pollthread.start();
  12161. PROGLOG("Enqueuing on %s to run wuid=%s, graph=%s, timelimit=%d seconds, priority=%d", queueName.str(), wuid.str(), graphName, timelimit, priority);
  12162. IJobQueueItem* item = createJobQueueItem(wuid.str());
  12163. item->setOwner(owner.str());
  12164. item->setPriority(priority);
  12165. Owned<IConversation> conversation = jq->initiateConversation(item);
  12166. bool got = conversation.get()!=NULL;
  12167. pollthread.stop();
  12168. pollthread.join();
  12169. if (!got)
  12170. {
  12171. if (pollthread.timedout)
  12172. throw MakeStringException(0, "Query %s failed to start within specified timelimit (%d) seconds", wuid.str(), timelimit);
  12173. throw MakeStringException(0, "Query %s cancelled (1)",wuid.str());
  12174. }
  12175. // get the thor ep from whoever picked up
  12176. SocketEndpoint thorMaster;
  12177. MemoryBuffer msg;
  12178. if (!conversation->recv(msg,1000*60))
  12179. throw MakeStringException(0, "Query %s cancelled (2)",wuid.str());
  12180. thorMaster.deserialize(msg);
  12181. msg.clear().append(graphName);
  12182. SocketEndpoint myep;
  12183. myep.setLocalHost(0);
  12184. myep.serialize(msg); // only used for tracing
  12185. if (!conversation->send(msg)) {
  12186. StringBuffer s("Failed to send query to Thor on ");
  12187. thorMaster.getUrlStr(s);
  12188. throw MakeStringExceptionDirect(-1, s.str()); // maybe retry?
  12189. }
  12190. StringBuffer eps;
  12191. PROGLOG("Thor on %s running %s",thorMaster.getUrlStr(eps).str(),wuid.str());
  12192. MemoryBuffer reply;
  12193. try
  12194. {
  12195. if (!conversation->recv(reply,INFINITE))
  12196. {
  12197. StringBuffer s("Failed to receive reply from thor ");
  12198. thorMaster.getUrlStr(s);
  12199. throw MakeStringExceptionDirect(-1, s.str());
  12200. }
  12201. }
  12202. catch (IException *e)
  12203. {
  12204. StringBuffer s("Failed to receive reply from thor ");
  12205. thorMaster.getUrlStr(s);
  12206. s.append("; (").append(e->errorCode()).append(", ");
  12207. e->errorMessage(s).append(")");
  12208. e->Release();
  12209. throw MakeStringExceptionDirect(-1, s.str());
  12210. }
  12211. unsigned replyCode;
  12212. reply.read(replyCode);
  12213. switch ((ThorReplyCodes) replyCode)
  12214. {
  12215. case DAMP_THOR_REPLY_PAUSED:
  12216. {
  12217. bool isException;
  12218. reply.read(isException);
  12219. if (isException)
  12220. {
  12221. Owned<IException> e = deserializeException(reply);
  12222. VStringBuffer str("Pausing job %s caused exception", wuid.get());
  12223. EXCLOG(e, str.str());
  12224. }
  12225. Owned<IWorkUnit> w = &workunit.lock();
  12226. w->setState(WUStatePaused); // will trigger executeThorGraph to pause next time around.
  12227. WUAction action = w->getAction();
  12228. switch (action)
  12229. {
  12230. case WUActionPause:
  12231. case WUActionPauseNow:
  12232. w->setAction(WUActionUnknown);
  12233. }
  12234. resubmit = true; // JCSMORE - all subgraph _could_ be done, thor will check though and not rerun
  12235. break;
  12236. }
  12237. case DAMP_THOR_REPLY_GOOD:
  12238. break;
  12239. case DAMP_THOR_REPLY_ERROR:
  12240. {
  12241. throw deserializeException(reply);
  12242. }
  12243. case DAMP_THOR_REPLY_ABORT:
  12244. {
  12245. Owned<IException> e = deserializeException(reply);
  12246. StringBuffer msg;
  12247. e->errorMessage(msg);
  12248. throw new WorkflowException(e->errorCode(), msg.str(), 0, WorkflowException::ABORT, MSGAUD_user);
  12249. }
  12250. default:
  12251. throwUnexpected();
  12252. }
  12253. workunit.forceReload();
  12254. }
  12255. while (resubmit); // if pause interrupted job (i.e. with pausenow action), resubmit graph
  12256. #endif
  12257. }
  12258. #ifdef _CONTAINERIZED
  12259. bool executeGraphOnLingeringThor(IConstWorkUnit &workunit, const char *graphName, const char *multiJobLingerQueueName)
  12260. {
  12261. // check if lingering thor instance is up.
  12262. // Returns true if successfully submitted graph to a lingering Thor.
  12263. /* If code was dependent on reading a workunit in parallel, the whole area of
  12264. * workunit locking and reading will need revisiting, because at the moment the
  12265. * workunit reading code does not lock at all.
  12266. *
  12267. * Either,
  12268. * 1) multiJobThorLinger is set, meaning Thor instances will wait for any job's graph.
  12269. * OR
  12270. * 2) if not set, the Thor will wait for graphs from same job only, and will be
  12271. * notified to quit by the agent, when the last graph is complete.
  12272. *
  12273. * This code is called from the client (agent) when it wants to execute a Thor graph.
  12274. * This function checks to see if there any registered lingering Thor instances available.
  12275. *
  12276. * Lingering Thor's register when they are idle either with the workunit itself in
  12277. * the case of [2], or with a Dali psuedo queue (a branch under /Status/ThorLinger),
  12278. * in the case of [1]
  12279. * If they have not been contacted within the 'lingerPeriod' they shutdown and remove
  12280. * their registered instance from the queue.
  12281. *
  12282. * The client will attempt to find a lingering Thor in either the workunit or a global
  12283. * named dali queue (depending on the configuration), it will then remove that entry,
  12284. * and attempt to post the graph to that lingering Thor. If the Thor acknowledges the
  12285. * request, this function exits with success. If it it fails, or there are no more
  12286. * lingering Thor instances, it returns with false to indicate that the graph was not
  12287. * submitted to a lingering Thor.
  12288. * The client should then queue the wuid/graph normally, which will invoke a new Thor
  12289. * instance.
  12290. */
  12291. try
  12292. {
  12293. if (multiJobLingerQueueName && graphName)
  12294. {
  12295. // check a Dali queue for idle spare Thor's
  12296. DBGLOG("Checking multi job lingering queue: %s", multiJobLingerQueueName);
  12297. VStringBuffer xpath("/Status/ThorLinger/%s", multiJobLingerQueueName);
  12298. while (true)
  12299. {
  12300. Owned<IRemoteConnection> conn = querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE, 5*60*1000);
  12301. if (!conn)
  12302. break;
  12303. IPropertyTree *root = conn->queryRoot();
  12304. if (0 == root->numChildren())
  12305. break;
  12306. IPropertyTree *entry = root->queryPropTree("Thor*[1]");
  12307. const char *entryName = entry->queryName();
  12308. // get available instance and remove it
  12309. VStringBuffer entryXPath("%s/%s", xpath.str(), entryName);
  12310. Owned<IRemoteConnection> lingerInstanceConn = querySDS().connect(entryXPath, myProcessSession(), RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, 5*1000);
  12311. if (lingerInstanceConn)
  12312. {
  12313. StringBuffer instanceName;
  12314. lingerInstanceConn->queryRoot()->getProp(nullptr, instanceName);
  12315. lingerInstanceConn->close(true);
  12316. lingerInstanceConn.clear();
  12317. conn.clear();
  12318. Owned<INode> masterNode = createINode(instanceName);
  12319. CMessageBuffer msg;
  12320. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName);
  12321. msg.append(jobStr);
  12322. bool success = queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000);
  12323. DBGLOG("Found lingering Thor: %s, submitted: %s, success: %s", instanceName.str(), jobStr.str(), boolToStr(success));
  12324. if (success)
  12325. {
  12326. bool ok;
  12327. msg.read(ok);
  12328. return true;
  12329. }
  12330. }
  12331. }
  12332. }
  12333. else
  12334. {
  12335. /* NB: forcing a reload here to ensure Debug values are recent.
  12336. * Could be improved by refreshing only the specific area of interest (i.e. Debug/ in this case).
  12337. * The area of persisting a non-locked connection to workunits should be resivisted..
  12338. */
  12339. workunit.forceReload();
  12340. Owned<IStringIterator> iter = &workunit.getDebugValues("thorinstance_*");
  12341. ForEach(*iter)
  12342. {
  12343. /* NB: Thor's set their running endpoint into Debug values of workunit
  12344. * Check to see if workunit has any Thor's available lingering instances.
  12345. */
  12346. SCMStringBuffer thorInstance;
  12347. iter->str(thorInstance);
  12348. SCMStringBuffer thorInstanceValue;
  12349. if (workunit.getDebugValueBool(thorInstance.s, false))
  12350. {
  12351. {
  12352. Owned<IWorkUnit> w = &workunit.lock();
  12353. w->setDebugValue(thorInstance.s, "0", true);
  12354. }
  12355. /* NB: there's a window where Thor could shutdown here.
  12356. * In that case, the sendRecv will fail and it will fall through to queueing.
  12357. */
  12358. const char *instanceName = strchr(thorInstance.str(), '_') + 1;
  12359. Owned<INode> masterNode = createINode(instanceName);
  12360. CMessageBuffer msg;
  12361. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName?graphName:"");
  12362. msg.append(jobStr);
  12363. if (queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000))
  12364. {
  12365. bool ok;
  12366. msg.read(ok);
  12367. if (graphName) // if graphName==nullptr, then continue around to look at others
  12368. {
  12369. if (ok)
  12370. return true;
  12371. }
  12372. }
  12373. }
  12374. }
  12375. }
  12376. }
  12377. catch (IException *e)
  12378. {
  12379. EXCLOG(e, "executeGraphOnLingeringThor");
  12380. e->Release();
  12381. }
  12382. return false;
  12383. }
  12384. static void setResources(StringBuffer &jobYaml, const IConstWorkUnit *workunit, const char *process)
  12385. {
  12386. StringBuffer s;
  12387. unsigned memRequest = workunit->getDebugValueInt(s.clear().appendf("%s-memRequest", process), 0);
  12388. unsigned memLimit = workunit->getDebugValueInt(s.clear().appendf("%s-memLimit", process), 0);
  12389. if (memLimit && memLimit < memRequest)
  12390. memLimit = memRequest;
  12391. if (memRequest)
  12392. jobYaml.replaceString("#request-memory", s.clear().appendf("memory: \"%uMi\"", memRequest));
  12393. if (memLimit)
  12394. jobYaml.replaceString("#limit-memory", s.clear().appendf("memory: \"%uMi\"", memLimit));
  12395. unsigned cpuRequest = workunit->getDebugValueInt(s.clear().appendf("%s-cpuRequest", process), 0);
  12396. unsigned cpuLimit = workunit->getDebugValueInt(s.clear().appendf("%s-cpuLimit", process), 0);
  12397. if (cpuLimit && cpuLimit < cpuRequest)
  12398. cpuLimit = cpuRequest;
  12399. if (cpuRequest)
  12400. jobYaml.replaceString("#request-cpu", s.clear().appendf("cpu: \"%um\"", cpuRequest));
  12401. if (cpuLimit)
  12402. jobYaml.replaceString("#limit-cpu", s.clear().appendf("cpu: \"%um\"", cpuLimit));
  12403. }
  12404. void deleteK8sJob(const char *componentName, const char *job)
  12405. {
  12406. VStringBuffer jobname("%s-%s", componentName, job);
  12407. jobname.toLowerCase();
  12408. VStringBuffer deleteJob("kubectl delete job/%s", jobname.str());
  12409. StringBuffer output, error;
  12410. bool ret = runExternalCommand(output, error, deleteJob.str(), nullptr);
  12411. DBGLOG("kubectl delete output: %s", output.str());
  12412. if (error.length())
  12413. DBGLOG("kubectl delete error: %s", error.str());
  12414. if (ret)
  12415. throw makeStringException(0, "Failed to run kubectl delete");
  12416. }
  12417. void waitK8sJob(const char *componentName, const char *job, const char *condition)
  12418. {
  12419. VStringBuffer jobname("%s-%s", componentName, job);
  12420. jobname.toLowerCase();
  12421. if (isEmptyString(condition))
  12422. condition = "condition=complete";
  12423. // MORE - blocks indefinitely here if you request too many resources
  12424. VStringBuffer waitJob("kubectl wait --for=%s --timeout=10h job/%s", condition, jobname.str()); // MORE - make timeout configurable
  12425. StringBuffer output, error;
  12426. bool ret = runExternalCommand(output, error, waitJob.str(), nullptr);
  12427. DBGLOG("kubectl wait output: %s", output.str());
  12428. if (error.length())
  12429. DBGLOG("kubectl wait error: %s", error.str());
  12430. if (ret)
  12431. throw makeStringException(0, "Failed to run kubectl wait");
  12432. }
  12433. void launchK8sJob(const char *componentName, const char *wuid, const char *job, const std::list<std::pair<std::string, std::string>> &extraParams)
  12434. {
  12435. VStringBuffer jobname("%s-%s", componentName, job);
  12436. jobname.toLowerCase();
  12437. VStringBuffer args("\"--workunit=%s\"", wuid);
  12438. for (const auto &p: extraParams)
  12439. args.append(',').newline().append("\"--").append(p.first.c_str()).append('=').append(p.second.c_str()).append("\"");
  12440. VStringBuffer jobSpecFilename("/etc/config/%s-jobspec.yaml", componentName);
  12441. StringBuffer jobYaml;
  12442. jobYaml.loadFile(jobSpecFilename, false);
  12443. jobYaml.replaceString("%jobname", jobname.str());
  12444. jobYaml.replaceString("%args", args.str());
  12445. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  12446. if (factory)
  12447. {
  12448. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(wuid);
  12449. if (workunit)
  12450. setResources(jobYaml, workunit, componentName);
  12451. }
  12452. StringBuffer output, error;
  12453. unsigned ret = runExternalCommand(output, error, "kubectl replace --force -f -", jobYaml.str());
  12454. DBGLOG("kubectl output: %s", output.str());
  12455. if (error.length())
  12456. DBGLOG("kubectl error: %s", error.str());
  12457. if (ret)
  12458. {
  12459. DBGLOG("Using job yaml %s", jobYaml.str());
  12460. throw makeStringException(0, "Failed to start kubectl job");
  12461. }
  12462. }
  12463. void runK8sJob(const char *componentName, const char *wuid, const char *job, bool del, const std::list<std::pair<std::string, std::string>> &extraParams)
  12464. {
  12465. launchK8sJob(componentName, wuid, job, extraParams);
  12466. waitK8sJob(componentName, job);
  12467. if (del)
  12468. deleteK8sJob(componentName, job);
  12469. }
  12470. #endif