workunit.cpp 461 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103
  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 && !filter.includeScope(scope))
  2045. include = false;
  2046. if (include && filter.requiredStats.size())
  2047. {
  2048. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2049. for (unsigned iReq=0; iReq < filter.requiredStats.size(); iReq++)
  2050. {
  2051. const StatisticValueFilter & cur = filter.requiredStats[iReq];
  2052. unsigned __int64 value;
  2053. if (getStat(cur.queryKind(), value))
  2054. {
  2055. if (!cur.matches(value))
  2056. include = false;
  2057. }
  2058. else
  2059. include = false;
  2060. }
  2061. }
  2062. if (include && filter.requiredAttrs.size())
  2063. {
  2064. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2065. StringBuffer temp;
  2066. for (unsigned iReq=0; iReq < filter.requiredAttrs.size(); iReq++)
  2067. {
  2068. const AttributeValueFilter & cur = filter.requiredAttrs[iReq];
  2069. const char * value = queryAttribute(cur.queryKind(), temp.clear());
  2070. if (!value || !cur.matches(value))
  2071. {
  2072. include = false;
  2073. break;
  2074. }
  2075. }
  2076. }
  2077. if (include)
  2078. return true;
  2079. //MORE: Optimize based on filter.compareScope()
  2080. selectNext();
  2081. }
  2082. }
  2083. void checkScopeOrder(unsigned input, const char * prevScope)
  2084. {
  2085. if (isAlive(input))
  2086. {
  2087. const char * curScope = iters.item(input).queryScope();
  2088. int compare = compareScopeName(prevScope, curScope);
  2089. if (compare >= 0)
  2090. throw MakeStringException(0, "Out of order (%u) scopes %s,%s = %d", input, prevScope, curScope, compare);
  2091. }
  2092. }
  2093. void selectNext()
  2094. {
  2095. ForEachItemIn(i, iters)
  2096. {
  2097. if (iterMatchesCurrentScope(i))
  2098. {
  2099. #ifdef _DEBUG
  2100. StringBuffer prevScope(iters.item(i).queryScope());
  2101. #endif
  2102. if (!iters.item(i).next())
  2103. activeIterMask &= ~(1U << i);
  2104. #ifdef _DEBUG
  2105. checkScopeOrder(i, prevScope);
  2106. #endif
  2107. }
  2108. }
  2109. }
  2110. void selectNextSibling()
  2111. {
  2112. ForEachItemIn(i, iters)
  2113. {
  2114. if (iterMatchesCurrentScope(i))
  2115. {
  2116. #ifdef _DEBUG
  2117. StringBuffer prevScope(iters.item(i).queryScope());
  2118. #endif
  2119. if (!iters.item(i).nextSibling())
  2120. activeIterMask &= ~(1U << i);
  2121. #ifdef _DEBUG
  2122. checkScopeOrder(i, prevScope);
  2123. #endif
  2124. }
  2125. }
  2126. }
  2127. void selectNextParent()
  2128. {
  2129. ForEachItemIn(i, iters)
  2130. {
  2131. if (iterMatchesCurrentScope(i))
  2132. {
  2133. #ifdef _DEBUG
  2134. StringBuffer prevScope(iters.item(i).queryScope());
  2135. #endif
  2136. if (!iters.item(i).nextParent())
  2137. activeIterMask &= ~(1U << i);
  2138. #ifdef _DEBUG
  2139. checkScopeOrder(i, prevScope);
  2140. #endif
  2141. }
  2142. }
  2143. }
  2144. protected:
  2145. const WuScopeFilter & filter;
  2146. IArrayOf<IConstWUScopeIterator> iters;
  2147. unsigned curIter = 0;
  2148. unsigned firstMatchIter = 0;
  2149. unsigned matchIterMask = 0; // bit set of iterators which have a valid entry for the current scope
  2150. unsigned activeIterMask = 0; // bit set of iterators which are still active
  2151. StringArray activeScopes;
  2152. };
  2153. //---------------------------------------------------------------------------------------------------------------------
  2154. class AggregateFilter
  2155. {
  2156. public:
  2157. AggregateFilter(StatisticKind _search) : search(_search) {}
  2158. inline bool matches(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) const
  2159. {
  2160. return (kind == search);
  2161. }
  2162. protected:
  2163. StatisticKind search;
  2164. //MORE: Allow filtering by scope?
  2165. };
  2166. class StatisticAggregator : public CInterfaceOf<IWuScopeVisitor>
  2167. {
  2168. public:
  2169. StatisticAggregator(StatisticKind _search) : filter(_search) {}
  2170. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2171. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2172. virtual void noteException(IConstWUException & exception) { throwUnexpected();}
  2173. protected:
  2174. AggregateFilter filter;
  2175. };
  2176. class SimpleAggregator : public StatisticAggregator
  2177. {
  2178. public:
  2179. SimpleAggregator(StatisticKind _search) : StatisticAggregator(_search) {}
  2180. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2181. {
  2182. if (filter.matches(kind, value, extra))
  2183. summary.noteValue(value);
  2184. }
  2185. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2186. //with a noteAggregate(value, variant, value, grouping)?
  2187. protected:
  2188. StatsAggregation summary;
  2189. };
  2190. class SimpleReferenceAggregator : public StatisticAggregator
  2191. {
  2192. public:
  2193. SimpleReferenceAggregator(StatisticKind _search, StatsAggregation & _summary) : StatisticAggregator(_search), summary(_summary) {}
  2194. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2195. {
  2196. if (filter.matches(kind, value, extra))
  2197. summary.noteValue(value);
  2198. }
  2199. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2200. //with a noteAggregate(value, variant, value, grouping)?
  2201. protected:
  2202. StatsAggregation & summary;
  2203. };
  2204. class GroupedAggregator : public StatisticAggregator
  2205. {
  2206. public:
  2207. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2208. {
  2209. if (filter.matches(kind, value, extra))
  2210. {
  2211. StatsAggregation & match = summary; // look up in hash table.
  2212. match.noteValue(value);
  2213. }
  2214. }
  2215. protected:
  2216. //HashTable of (possible groupings->summary)
  2217. StatsAggregation summary;
  2218. };
  2219. class CompoundAggregator : implements StatisticAggregator
  2220. {
  2221. public:
  2222. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra)
  2223. {
  2224. ForEachItemIn(i, aggregators)
  2225. aggregators.item(i).noteStatistic(kind, value, extra);
  2226. }
  2227. protected:
  2228. IArrayOf<StatisticAggregator> aggregators;
  2229. };
  2230. // Aggregate costs excluding all hThor costs
  2231. // Note: the only reason that this class is required is that it is not possible to determine the creator
  2232. // of a scope when iterating with IConstWUScopeIterator. (When this functionlity becomes available,
  2233. // consider filtering within aggregateCost and eliminating this class.)
  2234. class CostAggregatorExcludeHThor : public CInterfaceOf<IWuScopeVisitor>
  2235. {
  2236. public:
  2237. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2238. {
  2239. if (extra.getCreatorType() != SCThthor)
  2240. totalCost += value;
  2241. }
  2242. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2243. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2244. virtual void noteException(IConstWUException & exception) { throwUnexpected(); }
  2245. virtual cost_type getTotalCost() const { return totalCost; }
  2246. protected:
  2247. cost_type totalCost = 0;
  2248. };
  2249. // Aggregrate Thor or hThor costs
  2250. cost_type aggregateCost(const IConstWorkUnit * wu, const char *scope, bool excludeHThor)
  2251. {
  2252. // depth 1: workflow, depth 2: graph, depth 3: subgraph
  2253. WuScopeFilter filter;
  2254. if (scope && *scope) // All costs under specified scope (used to calculate all costs for a workflow)
  2255. {
  2256. filter.addScope(scope);
  2257. filter.setIncludeNesting(3);
  2258. filter.addOutputStatistic(StCostExecute);
  2259. filter.addRequiredStat(StCostExecute);
  2260. }
  2261. else
  2262. filter.addFilter("stat[CostExecute],depth[1..3],nested[0],where[CostExecute]");
  2263. filter.addSource("global");
  2264. filter.finishedFilter();
  2265. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  2266. // Note: use of CostAggregatorExcludeHThor will be a slower, so use only when necessary
  2267. if (excludeHThor)
  2268. {
  2269. CostAggregatorExcludeHThor aggregator;
  2270. for (it->first(); it->isValid(); )
  2271. {
  2272. it->playProperties(aggregator);
  2273. stat_type value;
  2274. if (it->getStat(StCostExecute, value))
  2275. it->nextSibling();
  2276. else
  2277. it->next();
  2278. }
  2279. return aggregator.getTotalCost();
  2280. }
  2281. else
  2282. {
  2283. cost_type totalCost = 0;
  2284. for (it->first(); it->isValid(); )
  2285. {
  2286. stat_type value = 0.0;
  2287. if (it->getStat(StCostExecute, value))
  2288. {
  2289. totalCost += value;
  2290. it->nextSibling();
  2291. }
  2292. else
  2293. it->next();
  2294. }
  2295. return totalCost;
  2296. }
  2297. }
  2298. //---------------------------------------------------------------------------------------------------------------------
  2299. //Extract an argument of the format abc[def[ghi...,]],... as (abc,def[...])
  2300. static bool extractOption(const char * & finger, StringBuffer & option, StringBuffer & arg)
  2301. {
  2302. const char * start = finger;
  2303. if (!*start)
  2304. return false;
  2305. const char * cur = start;
  2306. const char * bra = nullptr;
  2307. const char * end = nullptr;
  2308. unsigned braDepth = 0;
  2309. char next;
  2310. arg.clear();
  2311. for (;;)
  2312. {
  2313. next = *cur;
  2314. if (!next || ((next == ',') && (braDepth == 0)))
  2315. break;
  2316. switch (next)
  2317. {
  2318. case '[':
  2319. if (braDepth == 0)
  2320. {
  2321. if (bra)
  2322. throw makeStringExceptionV(0, "Multiple [ in filter : %s", bra);
  2323. bra = cur;
  2324. }
  2325. braDepth++;
  2326. break;
  2327. case ']':
  2328. if (braDepth > 0)
  2329. {
  2330. if (--braDepth == 0)
  2331. {
  2332. end = cur;
  2333. arg.append(cur - (bra+1), bra+1);
  2334. }
  2335. }
  2336. break;
  2337. }
  2338. cur++;
  2339. }
  2340. if (braDepth != 0)
  2341. throw makeStringExceptionV(0, "Mismatched ] in filter : %s", start);
  2342. option.clear();
  2343. if (bra)
  2344. {
  2345. if (cur != end+1)
  2346. throw makeStringExceptionV(0, "Text follows closing bracket: %s", end);
  2347. option.append(bra-start, start);
  2348. }
  2349. else
  2350. option.append(cur-start, start);
  2351. if (next)
  2352. finger = cur+1;
  2353. else
  2354. finger = cur;
  2355. return true;
  2356. }
  2357. static unsigned readOptValue(const char * start, const char * end, unsigned dft, const char * type)
  2358. {
  2359. if (start == end)
  2360. return dft;
  2361. char * next;
  2362. unsigned value = (unsigned)strtoll(start, &next, 10);
  2363. if (next != end)
  2364. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2365. return value;
  2366. }
  2367. static unsigned readValue(const char * start, const char * type)
  2368. {
  2369. if (*start == '\0')
  2370. throw makeStringExceptionV(0, "Expected a value for the %s option", type);
  2371. char * next;
  2372. unsigned value = (unsigned)strtoll(start, &next, 10);
  2373. if (*next != '\0')
  2374. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2375. return value;
  2376. }
  2377. StringBuffer & AttributeValueFilter::describe(StringBuffer & out) const
  2378. {
  2379. out.append(queryWuAttributeName(attr));
  2380. if (value)
  2381. out.append("=").append(value);
  2382. return out;
  2383. }
  2384. /*
  2385. Scope service matching Syntax: * indicates
  2386. Which items are matched:
  2387. scope[<scope-id>]* | stype[<scope-type>]* | id[<id>]* - which scopes should be matched?
  2388. depth[n | low..high] - range of depths to search for a match
  2389. source[global|stats|graph|all]* - which sources to search within the workunit
  2390. where[<statistickind> | <statistickind> (=|<|<=|>|>=) value | <statistickind>=low..high] - a statistic filter
  2391. Which items are include in the results:
  2392. matched[true|false] - are the matched scopes returned?
  2393. nested[<depth>|all] - how deep within a scope should be matched (default = 0 if matched[true], all if matched[false])
  2394. includetype[<scope-type>] - which scope types should be included?
  2395. Which properties of the items are returned:
  2396. properties[statistics|hints|attributes|scope|all]
  2397. statistic[<statistic-kind>|none|all] - include statistic
  2398. attribute[<attribute-name>|none|all] - include attribute
  2399. hint[<hint-name>] - include hint
  2400. property[<statistic-kind>|<attribute-name>|<hint-name>] - include property
  2401. measure[<measure>] - all statistics with a particular measure
  2402. version[<version>] - minimum version to return
  2403. */
  2404. enum { FOscope, FOstype, FOid, FOdepth, FOsource, FOwhere, FOmatched, FOnested, FOinclude, FOproperties, FOstatistic, FOattribute, FOhint, FOproperty, FOmeasure, FOversion, FOunknown };
  2405. //Some of the following contains aliases for the same option e.g. stat and statistic
  2406. static constexpr EnumMapping filterOptions[] = {
  2407. { FOscope, "scope" }, { FOstype, "stype" }, { FOid, "id" },
  2408. { FOdepth, "depth" }, { FOsource, "source" }, { FOwhere, "where" },
  2409. { FOmatched, "matched" }, { FOnested, "nested" },
  2410. { FOinclude, "include" }, { FOinclude, "includetype" },
  2411. { FOproperties, "props" }, { FOproperties, "properties" }, // some aliases
  2412. { FOstatistic, "stat" }, { FOstatistic, "statistic" }, { FOattribute, "attr" }, { FOattribute, "attribute" }, { FOhint, "hint" },
  2413. { FOproperty, "prop" }, { FOproperty, "property" },
  2414. { FOmeasure, "measure" }, { FOversion, "version" }, { 0, nullptr} };
  2415. static constexpr EnumMapping sourceMappings[] = {
  2416. { SSFsearchGlobalStats, "global" }, { SSFsearchGraphStats, "stats" }, { SSFsearchGraphStats, "statistics" }, { SSFsearchGraph, "graph" }, { SSFsearchExceptions, "exception" }, { SSFsearchWorkflow, "workflow" },
  2417. { (int)SSFsearchAll, "all" }, { 0, nullptr } };
  2418. static constexpr EnumMapping propertyMappings[] = {
  2419. { PTstatistics, "stat" }, { PTstatistics, "statistic" }, { PTattributes, "attr" }, { PTattributes, "attribute" }, { PThints, "hint" },{ PTnotes, "note" },
  2420. { PTstatistics, "stats" }, { PTstatistics, "statistics" }, { PTattributes, "attrs" }, { PTattributes, "attributes" }, { PThints, "hints" }, { PTnotes, "notes" },
  2421. { PTnone, "none" }, { PTscope, "scope" }, { PTall, "all" }, { 0, nullptr } };
  2422. WuScopeSourceFlags querySource(const char * source) { return (WuScopeSourceFlags)getEnum(source, sourceMappings, SSFunknown); }
  2423. const char * querySourceText(WuScopeSourceFlags source) { return getEnumText(source, sourceMappings, nullptr); }
  2424. WuScopeFilter::WuScopeFilter(const char * filter)
  2425. {
  2426. addFilter(filter);
  2427. finishedFilter();
  2428. }
  2429. WuScopeFilter & WuScopeFilter::addFilter(const char * filter)
  2430. {
  2431. if (!filter)
  2432. return *this;
  2433. StringBuffer option;
  2434. StringBuffer arg;
  2435. while (extractOption(filter, option, arg))
  2436. {
  2437. switch (getEnum(option, filterOptions, FOunknown))
  2438. {
  2439. case FOscope:
  2440. addScope(arg);
  2441. break;
  2442. case FOstype:
  2443. addScopeType(arg);
  2444. break;
  2445. case FOid:
  2446. addId(arg);
  2447. break;
  2448. case FOdepth:
  2449. {
  2450. //Allow depth[n], depth[a,b] or depth[a..b]
  2451. const char * comma = strchr(arg, ',');
  2452. const char * dotdot = strstr(arg, "..");
  2453. if (comma)
  2454. {
  2455. unsigned low = readOptValue(arg, comma, 0, "depth");
  2456. if (comma[1])
  2457. {
  2458. scopeFilter.setDepth(low, readValue(comma+1, "depth"));
  2459. }
  2460. else
  2461. scopeFilter.setDepth(low, UINT_MAX);
  2462. }
  2463. else if (dotdot)
  2464. {
  2465. unsigned low = readOptValue(arg, dotdot, 0, "depth");
  2466. if (dotdot[2])
  2467. scopeFilter.setDepth(low, readValue(dotdot+2, "depth"));
  2468. else
  2469. scopeFilter.setDepth(low, UINT_MAX);
  2470. }
  2471. else
  2472. {
  2473. scopeFilter.setDepth(readValue(arg, "depth"));
  2474. }
  2475. break;
  2476. }
  2477. case FOsource:
  2478. addSource(arg);
  2479. break;
  2480. case FOwhere: // where[stat<op>value]
  2481. addRequiredStat(arg);
  2482. break;
  2483. case FOmatched:
  2484. setIncludeMatch(strToBool(arg));
  2485. break;
  2486. case FOnested:
  2487. if (strieq(arg, "all"))
  2488. setIncludeNesting(UINT_MAX);
  2489. else if (isdigit(*arg))
  2490. setIncludeNesting(atoi(arg));
  2491. else
  2492. throw makeStringExceptionV(0, "Expected a value for the nesting depth: %s", arg.str());
  2493. break;
  2494. case FOinclude:
  2495. setIncludeScopeType(arg);
  2496. break;
  2497. case FOproperties:
  2498. {
  2499. WuPropertyTypes prop = (WuPropertyTypes)getEnum(arg, propertyMappings, PTunknown);
  2500. if (prop == PTunknown)
  2501. throw makeStringExceptionV(0, "Unexpected properties '%s'", arg.str());
  2502. addOutputProperties(prop);
  2503. break;
  2504. }
  2505. case FOstatistic:
  2506. addOutputStatistic(arg);
  2507. break;
  2508. case FOattribute:
  2509. addOutputAttribute(arg);
  2510. break;
  2511. case FOhint:
  2512. addOutputHint(arg);
  2513. break;
  2514. case FOproperty:
  2515. addOutput(arg);
  2516. break;
  2517. case FOmeasure:
  2518. setMeasure(arg);
  2519. break;
  2520. case FOversion:
  2521. if (isdigit(*arg))
  2522. minVersion = atoi64(arg);
  2523. else
  2524. throw makeStringExceptionV(0, "Expected a value for the version: %s", arg.str());
  2525. break;
  2526. default:
  2527. throw makeStringExceptionV(0, "Unrecognised filter option: %s", option.str());
  2528. }
  2529. }
  2530. return *this;
  2531. }
  2532. WuScopeFilter & WuScopeFilter::addScope(const char * scope)
  2533. {
  2534. if (scope)
  2535. {
  2536. validateScope(scope);
  2537. scopeFilter.addScope(scope);
  2538. }
  2539. return *this;
  2540. }
  2541. WuScopeFilter & WuScopeFilter::addScopeType(const char * scopeType)
  2542. {
  2543. if (scopeType)
  2544. {
  2545. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2546. if (sst == SSTmax)
  2547. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2548. scopeFilter.addScopeType(sst);
  2549. }
  2550. return *this;
  2551. }
  2552. WuScopeFilter & WuScopeFilter::addId(const char * id)
  2553. {
  2554. validateScopeId(id);
  2555. scopeFilter.addId(id);
  2556. return *this;
  2557. }
  2558. WuScopeFilter & WuScopeFilter::addOutput(const char * prop)
  2559. {
  2560. WuAttr attr = queryWuAttribute(prop, WaNone);
  2561. if (attr != WaNone)
  2562. {
  2563. WuAttr singleKindAttr = getSingleKindOfListAttribute(attr);
  2564. if (singleKindAttr != WaNone)
  2565. addOutputAttribute(singleKindAttr);
  2566. else
  2567. addOutputAttribute(attr);
  2568. } else if (queryStatisticKind(prop, StMax) != StMax)
  2569. addOutputStatistic(prop);
  2570. else
  2571. addOutputHint(prop);
  2572. return *this;
  2573. }
  2574. WuScopeFilter & WuScopeFilter::addOutputStatistic(const char * prop)
  2575. {
  2576. if (!prop)
  2577. return *this;
  2578. StatisticKind kind = queryStatisticKind(prop, StMax);
  2579. if (kind == StMax)
  2580. throw makeStringExceptionV(0, "Unrecognised statistic '%s'", prop);
  2581. return addOutputStatistic(kind);
  2582. }
  2583. WuScopeFilter & WuScopeFilter::addOutputStatistic(StatisticKind stat)
  2584. {
  2585. if (stat != StKindNone)
  2586. {
  2587. if (stat != StKindAll)
  2588. desiredStats.append(stat);
  2589. else
  2590. desiredStats.kill();
  2591. properties |= PTstatistics;
  2592. }
  2593. else
  2594. properties &= ~PTstatistics;
  2595. return *this;
  2596. }
  2597. WuScopeFilter & WuScopeFilter::addOutputAttribute(const char * prop)
  2598. {
  2599. if (!prop)
  2600. return *this;
  2601. WuAttr attr = queryWuAttribute(prop, WaMax);
  2602. if (attr == WaMax)
  2603. throw makeStringExceptionV(0, "Unrecognised attribute '%s'", prop);
  2604. return addOutputAttribute(attr);
  2605. }
  2606. WuScopeFilter & WuScopeFilter::addOutputAttribute(WuAttr attr)
  2607. {
  2608. if (attr != WaNone)
  2609. {
  2610. if (attr != WaAll)
  2611. desiredAttrs.append(attr);
  2612. else
  2613. desiredAttrs.kill();
  2614. properties |= PTattributes;
  2615. }
  2616. else
  2617. properties &= ~PTattributes;
  2618. return *this;
  2619. }
  2620. WuScopeFilter & WuScopeFilter::addOutputHint(const char * prop)
  2621. {
  2622. if (strieq(prop, "none"))
  2623. {
  2624. desiredHints.kill();
  2625. properties &= ~PThints;
  2626. }
  2627. else
  2628. {
  2629. if (!strieq(prop, "all"))
  2630. desiredHints.append(prop);
  2631. else
  2632. desiredHints.kill();
  2633. properties |= PThints;
  2634. }
  2635. return *this;
  2636. }
  2637. WuScopeFilter & WuScopeFilter::setIncludeMatch(bool value)
  2638. {
  2639. include.matchedScope = value;
  2640. return *this;
  2641. }
  2642. WuScopeFilter & WuScopeFilter::setIncludeNesting(unsigned depth)
  2643. {
  2644. include.nestedDepth = depth;
  2645. return *this;
  2646. }
  2647. WuScopeFilter & WuScopeFilter::setIncludeScopeType(const char * scopeType)
  2648. {
  2649. if (scopeType)
  2650. {
  2651. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2652. if (sst == SSTmax)
  2653. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2654. include.scopeTypes.append(sst);
  2655. }
  2656. return *this;
  2657. }
  2658. WuScopeFilter & WuScopeFilter::setMeasure(const char * measure)
  2659. {
  2660. if (measure)
  2661. {
  2662. desiredMeasure = queryMeasure(measure, SMeasureNone);
  2663. if (desiredMeasure == SMeasureNone)
  2664. throw makeStringExceptionV(0, "Unrecognised measure '%s'", measure);
  2665. properties |= PTstatistics;
  2666. }
  2667. return *this;
  2668. }
  2669. WuScopeFilter & WuScopeFilter::addOutputProperties(WuPropertyTypes mask)
  2670. {
  2671. if (properties == PTnone)
  2672. properties = mask;
  2673. else
  2674. properties |= mask;
  2675. return *this;
  2676. }
  2677. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue)
  2678. {
  2679. requiredStats.emplace_back(statKind, lowValue, highValue);
  2680. return *this;
  2681. }
  2682. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind)
  2683. {
  2684. requiredStats.emplace_back(statKind, 0, MaxStatisticValue);
  2685. return *this;
  2686. }
  2687. WuScopeFilter & WuScopeFilter::addRequiredAttr(WuAttr attr, const char * value)
  2688. {
  2689. requiredAttrs.emplace_back(attr, value);
  2690. return *this;
  2691. }
  2692. //process a filter in one of the following forms:
  2693. // <statistic-name>
  2694. // <statistic-name> (=|<|<=|>|>=) <value>
  2695. // <statistic-name>=[<low>]..[<high>]
  2696. void WuScopeFilter::addRequiredStat(const char * filter)
  2697. {
  2698. const char * stat = filter;
  2699. const char * cur = stat;
  2700. while (isalpha(*cur))
  2701. cur++;
  2702. StringBuffer statisticName(cur-stat, stat);
  2703. //Skip any spaces before a comparison operator.
  2704. while (*cur && isspace(*cur))
  2705. cur++;
  2706. StatisticKind statKind = queryStatisticKind(statisticName, StKindNone);
  2707. if (statKind == StKindNone)
  2708. {
  2709. WuAttr attr = queryWuAttribute(statisticName, WaNone);
  2710. if (attr == WaNone)
  2711. throw makeStringExceptionV(0, "Unknown property name '%s'", statisticName.str());
  2712. if (*cur == '=')
  2713. requiredAttrs.emplace_back(attr, cur+1);
  2714. else if (*cur == '\0')
  2715. requiredAttrs.emplace_back(attr, nullptr);
  2716. else
  2717. throw makeStringExceptionV(0, "Unknown attribute comparison '%s'", cur);
  2718. return;
  2719. }
  2720. //Save the operator, and skip over any non digits.
  2721. const char * op = cur;
  2722. switch (*op)
  2723. {
  2724. case '=':
  2725. cur++;
  2726. break;
  2727. case '<':
  2728. case '>':
  2729. if (op[1] == '=')
  2730. cur += 2;
  2731. else
  2732. cur++;
  2733. break;
  2734. case '\0':
  2735. break;
  2736. default:
  2737. throw makeStringExceptionV(0, "Unknown comparison '%s'", op);
  2738. }
  2739. const char * next;
  2740. stat_type value = readStatisticValue(cur, &next, queryMeasure(statKind));
  2741. stat_type lowValue = 0;
  2742. stat_type highValue = MaxStatisticValue;
  2743. switch (op[0])
  2744. {
  2745. case '=':
  2746. {
  2747. //Allow a,b or a..b to specify a range - either bound may be omitted.
  2748. if (next[0] == ',')
  2749. {
  2750. lowValue = value;
  2751. next++;
  2752. if (*next != '\0')
  2753. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2754. }
  2755. else if (strncmp(next, "..", 2) == 0)
  2756. {
  2757. lowValue = value;
  2758. next += 2;
  2759. if (*next != '\0')
  2760. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2761. }
  2762. else
  2763. {
  2764. lowValue = value;
  2765. highValue = value;
  2766. }
  2767. break;
  2768. }
  2769. case '<':
  2770. if (op[1] == '=')
  2771. highValue = value;
  2772. else
  2773. highValue = value-1;
  2774. break;
  2775. case '>':
  2776. if (op[1] == '=')
  2777. lowValue = value;
  2778. else
  2779. lowValue = value+1;
  2780. break;
  2781. }
  2782. if (*next)
  2783. throw makeStringExceptionV(0, "Trailing characters in where '%s'", next);
  2784. requiredStats.emplace_back(statKind, lowValue, highValue);
  2785. }
  2786. WuScopeFilter & WuScopeFilter::addSource(const char * source)
  2787. {
  2788. WuScopeSourceFlags mask = querySource(source);
  2789. if (mask == SSFunknown)
  2790. throw makeStringExceptionV(0, "Unexpected source '%s'", source);
  2791. if (!mask)
  2792. sourceFlags = mask;
  2793. else
  2794. sourceFlags |= mask;
  2795. return *this;
  2796. }
  2797. WuScopeFilter & WuScopeFilter::setDepth(unsigned low, unsigned high)
  2798. {
  2799. scopeFilter.setDepth(low, high);
  2800. return *this;
  2801. }
  2802. bool WuScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2803. {
  2804. //If there is a post filter on the scopeType, then check if it matches
  2805. if (include.scopeTypes.ordinality() == 1)
  2806. return (include.scopeTypes.item(0) == scopeType);
  2807. //If filter doesn't match nested items, then check if the scope filter matches.
  2808. if (include.nestedDepth == 0)
  2809. {
  2810. if (scopeFilter.matchOnly(scopeType))
  2811. return true;
  2812. }
  2813. return false;
  2814. }
  2815. //Called once the filter has been updated to optimize the filter
  2816. void WuScopeFilter::finishedFilter()
  2817. {
  2818. scopeFilter.finishedFilter();
  2819. assertex(!optimized);
  2820. optimized = true;
  2821. if ((include.nestedDepth == 0) && !include.matchedScope)
  2822. include.nestedDepth = UINT_MAX;
  2823. preFilterScope = include.matchedScope && (include.nestedDepth == 0);
  2824. if (scopeFilter.canAlwaysPreFilter())
  2825. preFilterScope = true;
  2826. //If the source flags have not been explicitly set then calculate which sources will provide the results
  2827. if (!sourceFlags)
  2828. {
  2829. sourceFlags = SSFsearchAll;
  2830. //Use the other options to reduce the number of elements that are searched.
  2831. //If not interested in scopes on their own then...
  2832. if (!(properties & PTscope))
  2833. {
  2834. //Global stats and graph stats only contain stats => remove if not interested in them
  2835. if (!(properties & PTstatistics) && (requiredStats.size() == 0))
  2836. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchGraphStats);
  2837. //graph, workflow only contains attributes and hints => remove if not interested
  2838. if (!(properties & (PTattributes|PThints)) && (requiredAttrs.size() == 0))
  2839. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2840. }
  2841. if (!(properties & PTnotes))
  2842. sourceFlags &= ~SSFsearchExceptions;
  2843. }
  2844. //Optimize sources if they haven't been explicitly specified
  2845. //Most of the following are dependent on internal knowledge of the way that information is represented
  2846. if (matchOnly(SSTworkflow))
  2847. {
  2848. //Workflow is not nested within a graph
  2849. sourceFlags &= ~(SSFsearchGraph|SSFsearchGraphStats);
  2850. setDepth(1, 1);
  2851. }
  2852. else if (matchOnly(SSTgraph))
  2853. {
  2854. //Graph starts are stored globally, not in the graph stats.
  2855. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchWorkflow);
  2856. if (!(properties & (PTattributes|PThints)))
  2857. sourceFlags &= ~(SSFsearchGraph);
  2858. //This should really be setDepth(2,2) but workunits prior to 7.4 did not have graph ids prefixed by the wfid
  2859. //Remove once 7.2 is a distant memory (see HPCC-22887)
  2860. setDepth(1, 2);
  2861. }
  2862. else if (matchOnly(SSTsubgraph))
  2863. {
  2864. sourceFlags &= ~(SSFsearchWorkflow);
  2865. }
  2866. else if (matchOnly(SSTcompilestage))
  2867. {
  2868. //compile stages are not stored in the graph
  2869. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchGraph|SSFsearchWorkflow);
  2870. }
  2871. else if (matchOnly(SSTactivity))
  2872. {
  2873. //information about activities is not stored globally
  2874. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchWorkflow);
  2875. }
  2876. // Everything stored in the graphs stats has a depth of 3 or more - so ignore if there are not matches in that depth
  2877. if (include.nestedDepth == 0)
  2878. {
  2879. if (scopeFilter.compareDepth(3) > 0) // 3 is larger than any scope in the filter
  2880. sourceFlags &= ~(SSFsearchGraphStats);
  2881. else if (scopeFilter.compareDepth(3) == 0) // 3 matches the maximum scope in the filter
  2882. {
  2883. //Subgraph WhenStarted and TimeElapsed are stored globally. If that is all that is required
  2884. //then do not include the subgraph timings
  2885. if (desiredStats.ordinality())
  2886. {
  2887. bool needGraphStats = false;
  2888. ForEachItemIn(i, desiredStats)
  2889. {
  2890. unsigned stat = desiredStats.item(i);
  2891. if ((stat != StWhenStarted) && (stat != StTimeElapsed))
  2892. needGraphStats = true;
  2893. }
  2894. if (!needGraphStats)
  2895. {
  2896. sourceFlags &= ~(SSFsearchGraphStats);
  2897. if (matchOnly(SSTsubgraph))
  2898. sourceFlags &= SSFsearchGlobalStats;
  2899. }
  2900. }
  2901. }
  2902. }
  2903. if (scopeFilter.compareDepth(1) < 0)
  2904. {
  2905. //If minimum match depth is > 1 then it will never match workflow
  2906. sourceFlags &= ~(SSFsearchWorkflow);
  2907. }
  2908. //The xml graph is never updated, so do not check it if minVersion != 0
  2909. if (minVersion != 0)
  2910. {
  2911. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2912. }
  2913. }
  2914. bool WuScopeFilter::includeStatistic(StatisticKind kind) const
  2915. {
  2916. if (!(properties & PTstatistics))
  2917. return false;
  2918. if ((desiredMeasure != SMeasureAll) && (queryMeasure(kind) != desiredMeasure))
  2919. return false;
  2920. if (desiredStats.empty())
  2921. return true;
  2922. return desiredStats.contains(kind);
  2923. }
  2924. bool WuScopeFilter::includeAttribute(WuAttr attr) const
  2925. {
  2926. if (!(properties & PTattributes))
  2927. return false;
  2928. if (desiredAttrs.empty())
  2929. return true;
  2930. return desiredAttrs.contains(attr);
  2931. }
  2932. bool WuScopeFilter::includeHint(const char * kind) const
  2933. {
  2934. if (!(properties & PThints))
  2935. return false;
  2936. if (desiredHints.empty())
  2937. return true;
  2938. return desiredHints.contains(kind);
  2939. }
  2940. bool WuScopeFilter::includeScope(const char * scope) const
  2941. {
  2942. if (include.scopeTypes)
  2943. {
  2944. const char * tail = queryScopeTail(scope);
  2945. StatsScopeId id(tail);
  2946. if (!include.scopeTypes.contains(id.queryScopeType()))
  2947. return false;
  2948. }
  2949. return true;
  2950. }
  2951. const static ScopeFilter nullScopeFilter {};
  2952. const ScopeFilter & WuScopeFilter::queryIterFilter() const
  2953. {
  2954. if (preFilterScope)
  2955. return scopeFilter;
  2956. else
  2957. return nullScopeFilter;
  2958. }
  2959. ScopeCompare WuScopeFilter::compareMatchScopes(const char * scope) const
  2960. {
  2961. return scopeFilter.compare(scope);
  2962. }
  2963. StringBuffer & WuScopeFilter::describe(StringBuffer & out) const
  2964. {
  2965. scopeFilter.describe(out);
  2966. if (requiredStats.size() || requiredAttrs.size())
  2967. {
  2968. out.append(",where[");
  2969. bool first = false;
  2970. for (const auto & stat : requiredStats)
  2971. {
  2972. if (!first)
  2973. out.append(",");
  2974. stat.describe(out);
  2975. first = false;
  2976. }
  2977. for (const auto & attr : requiredAttrs)
  2978. {
  2979. if (!first)
  2980. out.append(",");
  2981. attr.describe(out);
  2982. first = false;
  2983. }
  2984. out.append("]");
  2985. }
  2986. {
  2987. StringBuffer sources;
  2988. for (unsigned mask=1; mask; mask *= 2)
  2989. {
  2990. if (sourceFlags & mask)
  2991. {
  2992. const char * source = querySourceText((WuScopeSourceFlags)mask);
  2993. if (source)
  2994. sources.append(",").append(source);
  2995. }
  2996. }
  2997. if (sources)
  2998. out.append(",source[").append(sources.str()+1).append("]");
  2999. }
  3000. if (include.nestedDepth != UINT_MAX)
  3001. out.appendf(",nested[%u]", include.nestedDepth);
  3002. if (include.scopeTypes)
  3003. {
  3004. out.append(",include[");
  3005. ForEachItemIn(i, include.scopeTypes)
  3006. {
  3007. if (i)
  3008. out.append(",");
  3009. out.append(queryScopeTypeName((StatisticScopeType)include.scopeTypes.item(i)));
  3010. }
  3011. out.append("]");
  3012. }
  3013. {
  3014. StringBuffer props;
  3015. if (properties == PTnone)
  3016. props.append(",none");
  3017. else if (properties == PTall)
  3018. props.append(",all");
  3019. else
  3020. {
  3021. if (properties & PTstatistics)
  3022. props.append(",stat");
  3023. if (properties & PTattributes)
  3024. props.append(",attr");
  3025. if (properties & PThints)
  3026. props.append(",hint");
  3027. if (properties & PTscope)
  3028. props.append(",scope");
  3029. if (properties & PTnotes)
  3030. props.append(",note");
  3031. }
  3032. out.append(",properties[").append(props.str()+1).append("]");
  3033. }
  3034. if (desiredStats)
  3035. {
  3036. out.append(",stat[");
  3037. ForEachItemIn(i, desiredStats)
  3038. {
  3039. if (i)
  3040. out.append(",");
  3041. out.append(queryStatisticName((StatisticKind)desiredStats.item(i)));
  3042. }
  3043. out.append("]");
  3044. }
  3045. if (desiredAttrs)
  3046. {
  3047. out.append(",attr[");
  3048. ForEachItemIn(i, desiredAttrs)
  3049. {
  3050. if (i)
  3051. out.append(",");
  3052. out.append(queryWuAttributeName((WuAttr)desiredAttrs.item(i)));
  3053. }
  3054. out.append("]");
  3055. }
  3056. if (desiredHints)
  3057. {
  3058. out.append(",hint[");
  3059. ForEachItemIn(i, desiredHints)
  3060. {
  3061. if (i)
  3062. out.append(",");
  3063. out.append(desiredHints.item(i));
  3064. }
  3065. out.append("]");
  3066. }
  3067. if (desiredMeasure != SMeasureAll)
  3068. out.append(",measure[").append(queryMeasureName(desiredMeasure)).append("]");
  3069. if (minVersion != 0)
  3070. out.appendf(",version(%" I64F "u)", minVersion);
  3071. return out;
  3072. }
  3073. //--------------------------------------------------------------------------------------------------------------------
  3074. EnumMapping states[] = {
  3075. { WUStateUnknown, "unknown" },
  3076. { WUStateCompiled, "compiled" },
  3077. { WUStateRunning, "running" },
  3078. { WUStateCompleted, "completed" },
  3079. { WUStateFailed, "failed" },
  3080. { WUStateArchived, "archived" },
  3081. { WUStateAborting, "aborting" },
  3082. { WUStateAborted, "aborted" },
  3083. { WUStateBlocked, "blocked" },
  3084. { WUStateSubmitted, "submitted" },
  3085. { WUStateScheduled, "scheduled" },
  3086. { WUStateCompiling, "compiling" },
  3087. { WUStateWait, "wait" },
  3088. { WUStateUploadingFiles, "uploading_files" },
  3089. { WUStateDebugPaused, "debugging" },
  3090. { WUStateDebugRunning, "debug_running" },
  3091. { WUStatePaused, "paused" },
  3092. { WUStateSize, NULL }
  3093. };
  3094. EnumMapping actions[] = {
  3095. { WUActionUnknown, "unknown" },
  3096. { WUActionCompile, "compile" },
  3097. { WUActionCheck, "check" },
  3098. { WUActionRun, "run" },
  3099. { WUActionExecuteExisting, "execute" },
  3100. { WUActionPause, "pause" },
  3101. { WUActionPauseNow, "pausenow" },
  3102. { WUActionResume, "resume" },
  3103. { WUActionSize, NULL },
  3104. };
  3105. EnumMapping priorityClasses[] = {
  3106. { PriorityClassUnknown, "unknown" },
  3107. { PriorityClassLow, "low" },
  3108. { PriorityClassNormal, "normal" },
  3109. { PriorityClassHigh, "high" },
  3110. { PriorityClassSize, NULL },
  3111. };
  3112. const char * getWorkunitStateStr(WUState state)
  3113. {
  3114. dbgassertex(state < WUStateSize);
  3115. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  3116. }
  3117. void setEnum(IPropertyTree *p, const char *propname, int value, const EnumMapping *map)
  3118. {
  3119. const char *defval = map->str;
  3120. while (map->str)
  3121. {
  3122. if (value==map->val)
  3123. {
  3124. p->setProp(propname, map->str);
  3125. return;
  3126. }
  3127. map++;
  3128. }
  3129. assertex(!"Unexpected value in setEnum");
  3130. p->setProp(propname, defval);
  3131. }
  3132. static int getEnum(const IPropertyTree *p, const char *propname, const EnumMapping *map)
  3133. {
  3134. return getEnum(p->queryProp(propname),map);
  3135. }
  3136. const char * getWorkunitActionStr(WUAction action)
  3137. {
  3138. return getEnumText(action, actions);
  3139. }
  3140. WUAction getWorkunitAction(const char *actionStr)
  3141. {
  3142. return (WUAction) getEnum(actionStr, actions);
  3143. }
  3144. //==========================================================================================
  3145. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  3146. {
  3147. public:
  3148. CLightweightWorkunitInfo(IPropertyTree &p)
  3149. {
  3150. wuid.set(p.queryName());
  3151. user.set(p.queryProp("@submitID"));
  3152. jobName.set(p.queryProp("@jobName"));
  3153. clusterName.set(p.queryProp("@clusterName"));
  3154. timeScheduled.set(p.queryProp("@timeScheduled"));
  3155. state = (WUState) getEnum(&p, "@state", states);
  3156. action = (WUAction) getEnum(&p, "Action", actions);
  3157. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  3158. priorityLevel = calcPriorityValue(&p);
  3159. wuscope.set(p.queryProp("@scope"));
  3160. appvalues.loadBranch(&p,"Application");
  3161. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  3162. _isProtected = p.getPropBool("@protected", false);
  3163. }
  3164. virtual const char *queryWuid() const { return wuid.str(); }
  3165. virtual const char *queryUser() const { return user.str(); }
  3166. virtual const char *queryJobName() const { return jobName.str(); }
  3167. virtual const char *queryClusterName() const { return clusterName.str(); }
  3168. virtual const char *queryWuScope() const { return wuscope.str(); }
  3169. virtual WUState getState() const { return state; }
  3170. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  3171. virtual WUAction getAction() const { return action; }
  3172. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  3173. virtual WUPriorityClass getPriority() const { return priority; }
  3174. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  3175. virtual int getPriorityLevel() const { return priorityLevel; }
  3176. virtual bool isProtected() const { return _isProtected; }
  3177. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  3178. {
  3179. if (timeScheduled.length())
  3180. val.setGmtString(timeScheduled.str());
  3181. return val;
  3182. }
  3183. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  3184. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  3185. protected:
  3186. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  3187. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  3188. unsigned totalThorTime;
  3189. WUState state;
  3190. WUAction action;
  3191. WUPriorityClass priority;
  3192. int priorityLevel;
  3193. bool _isProtected;
  3194. };
  3195. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  3196. {
  3197. return new CLightweightWorkunitInfo(p);
  3198. }
  3199. class CDaliWuGraphStats : public CWuGraphStats
  3200. {
  3201. public:
  3202. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, unsigned _wfid, const char * _rootScope, unsigned _id)
  3203. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _wfid, _rootScope, _id), conn(_conn)
  3204. {
  3205. }
  3206. protected:
  3207. Owned<IRemoteConnection> conn;
  3208. };
  3209. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  3210. {
  3211. abortId = 0;
  3212. stateId = 0;
  3213. actionId = 0;
  3214. assertex((flags & ~SubscribeOptionAbort) == 0);
  3215. if (flags & SubscribeOptionAbort)
  3216. {
  3217. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  3218. abortId = querySDS().subscribe(xpath.str(), *this, false, true);
  3219. }
  3220. }
  3221. CWorkUnitWatcher::~CWorkUnitWatcher()
  3222. {
  3223. assertex(abortId==0 && stateId==0 && actionId==0);
  3224. }
  3225. void CWorkUnitWatcher::unsubscribe()
  3226. {
  3227. CriticalBlock b(crit);
  3228. if (abortId)
  3229. querySDS().unsubscribe(abortId);
  3230. if (stateId)
  3231. querySDS().unsubscribe(stateId);
  3232. if (actionId)
  3233. querySDS().unsubscribe(actionId);
  3234. abortId = 0;
  3235. stateId = 0;
  3236. actionId = 0;
  3237. }
  3238. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  3239. {
  3240. CriticalBlock b(crit);
  3241. if (id==stateId)
  3242. subscriber->notify(SubscribeOptionState, valueLen, valueData);
  3243. else if (id==actionId)
  3244. subscriber->notify(SubscribeOptionAction, valueLen, valueData);
  3245. else if (id==abortId)
  3246. subscriber->notify(SubscribeOptionAbort, valueLen, valueData);
  3247. }
  3248. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  3249. {
  3250. public:
  3251. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  3252. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  3253. {
  3254. if (flags & SubscribeOptionState)
  3255. {
  3256. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  3257. stateId = querySDS().subscribe(xpath.str(), *this);
  3258. }
  3259. if (flags & SubscribeOptionAction)
  3260. {
  3261. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  3262. actionId = querySDS().subscribe(xpath.str(), *this);
  3263. }
  3264. }
  3265. };
  3266. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  3267. {
  3268. CriticalBlock block(crit);
  3269. assertex(options==SubscribeOptionAbort);
  3270. if (!abortWatcher)
  3271. {
  3272. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  3273. abortDirty = true;
  3274. }
  3275. }
  3276. void CPersistedWorkUnit::unsubscribe()
  3277. {
  3278. CriticalBlock block(crit);
  3279. if (abortWatcher)
  3280. {
  3281. abortWatcher->unsubscribe();
  3282. abortWatcher.clear();
  3283. }
  3284. }
  3285. bool CPersistedWorkUnit::aborting() const
  3286. {
  3287. CriticalBlock block(crit);
  3288. if (abortDirty)
  3289. {
  3290. StringBuffer apath;
  3291. apath.append("/WorkUnitAborts/").append(p->queryName());
  3292. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  3293. if (acon)
  3294. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  3295. else
  3296. abortState = false;
  3297. abortDirty = false;
  3298. }
  3299. return abortState;
  3300. }
  3301. class CDaliWorkUnit : public CPersistedWorkUnit
  3302. {
  3303. public:
  3304. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  3305. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  3306. {
  3307. loadPTree(connection->getRoot());
  3308. }
  3309. ~CDaliWorkUnit()
  3310. {
  3311. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  3312. // We use the beforeDispose() in base class to help ensure this
  3313. p.clear();
  3314. }
  3315. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  3316. {
  3317. Owned<IRemoteConnection> conn = getProgressConnection();
  3318. if (conn)
  3319. {
  3320. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3321. if (progress)
  3322. return new CConstGraphProgress(p->queryName(), graphName, progress);
  3323. }
  3324. return NULL;
  3325. }
  3326. virtual WUGraphState queryGraphState(const char *graphName) const
  3327. {
  3328. Owned<IRemoteConnection> conn = getProgressConnection();
  3329. if (conn)
  3330. {
  3331. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3332. if (progress)
  3333. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  3334. }
  3335. return WUGraphUnknown;
  3336. }
  3337. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3338. {
  3339. Owned<IRemoteConnection> conn = getProgressConnection();
  3340. if (conn)
  3341. {
  3342. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3343. if (progress)
  3344. {
  3345. StringBuffer path;
  3346. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3347. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  3348. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  3349. }
  3350. }
  3351. return WUGraphUnknown;
  3352. }
  3353. virtual void clearGraphProgress() const
  3354. {
  3355. CriticalBlock block(crit);
  3356. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3357. StringBuffer path("/GraphProgress/");
  3358. path.append(p->queryName());
  3359. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  3360. if (delconn)
  3361. delconn->close(true);
  3362. }
  3363. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3364. {
  3365. Owned<IRemoteConnection> conn = getProgressConnection();
  3366. if (!conn)
  3367. return false;
  3368. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  3369. if (name)
  3370. {
  3371. graphName.set(name);
  3372. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  3373. return true;
  3374. }
  3375. else
  3376. return false;
  3377. }
  3378. virtual void forceReload()
  3379. {
  3380. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  3381. CriticalBlock block(crit);
  3382. clearCached(true);
  3383. connection->reload();
  3384. progressConnection.clear();
  3385. abortDirty = true;
  3386. p.setown(connection->getRoot());
  3387. }
  3388. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3389. {
  3390. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  3391. clearGraphProgress();
  3392. connection->close(true);
  3393. connection.clear();
  3394. }
  3395. virtual void commit()
  3396. {
  3397. CPersistedWorkUnit::commit();
  3398. if (connection)
  3399. connection->commit();
  3400. }
  3401. virtual void _lockRemote()
  3402. {
  3403. StringBuffer wuRoot;
  3404. getXPath(wuRoot, p->queryName());
  3405. if (connection)
  3406. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  3407. else
  3408. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  3409. if (!connection)
  3410. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  3411. clearCached(true);
  3412. p.setown(connection->getRoot());
  3413. }
  3414. virtual void _unlockRemote()
  3415. {
  3416. if (connection)
  3417. {
  3418. try
  3419. {
  3420. try
  3421. {
  3422. connection->commit();
  3423. }
  3424. catch (IException *e)
  3425. {
  3426. EXCLOG(e, "Error during workunit commit");
  3427. connection->rollback();
  3428. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3429. throw;
  3430. }
  3431. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3432. }
  3433. catch (IException *E)
  3434. {
  3435. StringBuffer s;
  3436. IERRLOG("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  3437. throw;
  3438. }
  3439. }
  3440. }
  3441. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3442. {
  3443. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName, wfid);
  3444. conn->queryRoot()->setPropInt("@_state", state);
  3445. }
  3446. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3447. {
  3448. CriticalBlock block(crit);
  3449. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3450. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3451. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3452. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  3453. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3454. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  3455. IPropertyTree *node = progress->queryPropTree(path.str());
  3456. if (!node)
  3457. {
  3458. node = progress->addPropTree("node");
  3459. node->setPropInt64("@id", nodeId);
  3460. }
  3461. node->setPropInt("@_state", (unsigned)state);
  3462. switch (state)
  3463. {
  3464. case WUGraphRunning:
  3465. {
  3466. IPropertyTree *running = conn->queryRoot()->setPropTree("Running");
  3467. running->setProp("@graph", graphName);
  3468. running->setPropInt64("@subId", nodeId);
  3469. break;
  3470. }
  3471. case WUGraphComplete:
  3472. {
  3473. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  3474. break;
  3475. }
  3476. }
  3477. }
  3478. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3479. {
  3480. return new CDaliWuGraphStats(getWritableProgressConnection(graphName, _wfid), creatorType, creator, _wfid, graphName, subgraph);
  3481. }
  3482. virtual void import(IPropertyTree *wuTree, IPropertyTree *graphProgressTree)
  3483. {
  3484. connection->queryRoot()->setPropTree(nullptr, LINK(wuTree));
  3485. loadPTree(connection->getRoot());
  3486. if (!graphProgressTree)
  3487. return;
  3488. VStringBuffer xpath("/GraphProgress/%s", queryWuid());
  3489. Owned<IRemoteConnection> progressConn = querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  3490. if (!progressConn)
  3491. throw MakeStringException(0, "Failed to access %s.", xpath.str());
  3492. progressConn->queryRoot()->setPropTree(nullptr, LINK(graphProgressTree));
  3493. }
  3494. protected:
  3495. IRemoteConnection *getProgressConnection() const
  3496. {
  3497. CriticalBlock block(crit);
  3498. if (!progressConnection)
  3499. {
  3500. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3501. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  3502. }
  3503. return progressConnection.getLink();
  3504. }
  3505. IRemoteConnection *getWritableProgressConnection(const char *graphName, unsigned wfid) const
  3506. {
  3507. CriticalBlock block(crit);
  3508. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  3509. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  3510. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3511. IPropertyTree * root = conn->queryRoot();
  3512. assertex(wfid);
  3513. if (!root->hasProp("@wfid"))
  3514. {
  3515. root->setPropInt("@wfid", wfid);
  3516. }
  3517. else
  3518. {
  3519. //Ideally the following code would check that the wfids are passed consistently.
  3520. //However there is an obscure problem with out of line functions being called from multiple workflow
  3521. //ids, and possibly library graphs.
  3522. //Stats for library graphs should be nested below the library call activity
  3523. //assertex(root->getPropInt("@wfid", 0) == wfid); // check that wfid is passed consistently
  3524. }
  3525. return conn.getClear();
  3526. }
  3527. IPropertyTree *getGraphProgressTree() const
  3528. {
  3529. Owned<IRemoteConnection> conn = getProgressConnection();
  3530. if (conn)
  3531. {
  3532. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  3533. mergePTree(tmp,conn->queryRoot());
  3534. return tmp.getClear();
  3535. }
  3536. return NULL;
  3537. }
  3538. Owned<IRemoteConnection> connection;
  3539. mutable Owned<IRemoteConnection> progressConnection;
  3540. };
  3541. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  3542. {
  3543. public:
  3544. Owned<CLocalWorkUnit> c;
  3545. IMPLEMENT_IINTERFACE;
  3546. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  3547. ~CLockedWorkUnit()
  3548. {
  3549. if (workUnitTraceLevel > 1)
  3550. DBGLOG("Releasing locked workunit %s", queryWuid());
  3551. if (c)
  3552. c->unlockRemote();
  3553. }
  3554. virtual IConstWorkUnit * unlock()
  3555. {
  3556. c->unlockRemote();
  3557. return c.getClear();
  3558. }
  3559. virtual bool aborting() const
  3560. { return c->aborting(); }
  3561. virtual void forceReload()
  3562. { }
  3563. virtual WUAction getAction() const
  3564. { return c->getAction(); }
  3565. virtual const char *queryActionDesc() const
  3566. { return c->queryActionDesc(); }
  3567. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  3568. { return c->getApplicationValue(application, propname, str); }
  3569. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  3570. { return c->getApplicationValueInt(application, propname, defVal); }
  3571. virtual IConstWUAppValueIterator & getApplicationValues() const
  3572. { return c->getApplicationValues(); }
  3573. virtual bool hasWorkflow() const
  3574. { return c->hasWorkflow(); }
  3575. virtual unsigned queryEventScheduledCount() const
  3576. { return c->queryEventScheduledCount(); }
  3577. virtual IPropertyTree * queryWorkflowTree() const
  3578. { return c->queryWorkflowTree(); }
  3579. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  3580. { return c->getWorkflowItems(); }
  3581. virtual IWorkflowItemArray * getWorkflowClone() const
  3582. { return c->getWorkflowClone(); }
  3583. virtual bool requiresLocalFileUpload() const
  3584. { return c->requiresLocalFileUpload(); }
  3585. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  3586. { return c->getLocalFileUploads(); }
  3587. virtual bool getIsQueryService() const
  3588. { return c->getIsQueryService(); }
  3589. virtual bool getCloneable() const
  3590. { return c->getCloneable(); }
  3591. virtual IUserDescriptor * queryUserDescriptor() const
  3592. { return c->queryUserDescriptor(); }
  3593. virtual const char *queryClusterName() const
  3594. { return c->queryClusterName(); }
  3595. virtual unsigned getCodeVersion() const
  3596. { return c->getCodeVersion(); }
  3597. virtual unsigned getWuidVersion() const
  3598. { return c->getWuidVersion(); }
  3599. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3600. { c->getBuildVersion(buildVersion, eclVersion); }
  3601. virtual bool hasDebugValue(const char * propname) const
  3602. { return c->hasDebugValue(propname); }
  3603. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  3604. { return c->getDebugValue(propname, str); }
  3605. virtual int getDebugValueInt(const char * propname, int defVal) const
  3606. { return c->getDebugValueInt(propname, defVal); }
  3607. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  3608. { return c->getDebugValueInt64(propname, defVal); }
  3609. virtual double getDebugValueReal(const char * propname, double defVal) const
  3610. { return c->getDebugValueReal(propname, defVal); }
  3611. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  3612. { return c->getDebugValueBool(propname, defVal); }
  3613. virtual IStringIterator & getDebugValues() const
  3614. { return c->getDebugValues(NULL); }
  3615. virtual IStringIterator & getDebugValues(const char *prop) const
  3616. { return c->getDebugValues(prop); }
  3617. virtual unsigned getExceptionCount() const
  3618. { return c->getExceptionCount(); }
  3619. virtual IConstWUExceptionIterator & getExceptions() const
  3620. { return c->getExceptions(); }
  3621. virtual unsigned getGraphCount() const
  3622. { return c->getGraphCount(); }
  3623. virtual unsigned getSourceFileCount() const
  3624. { return c->getSourceFileCount(); }
  3625. virtual unsigned getResultCount() const
  3626. { return c->getResultCount(); }
  3627. virtual unsigned getVariableCount() const
  3628. { return c->getVariableCount(); }
  3629. virtual unsigned getApplicationValueCount() const
  3630. { return c->getApplicationValueCount(); }
  3631. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  3632. { return c->getGraphs(type); }
  3633. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  3634. { return c->getGraphsMeta(type); }
  3635. virtual IConstWUGraph * getGraph(const char *name) const
  3636. { return c->getGraph(name); }
  3637. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  3638. { return c->getGraphProgress(name); }
  3639. virtual const char *queryJobName() const
  3640. { return c->queryJobName(); }
  3641. virtual IConstWUPlugin * getPluginByName(const char * name) const
  3642. { return c->getPluginByName(name); }
  3643. virtual IConstWUPluginIterator & getPlugins() const
  3644. { return c->getPlugins(); }
  3645. virtual IConstWULibrary* getLibraryByName(const char *name) const
  3646. { return c->getLibraryByName(name); }
  3647. virtual IConstWULibraryIterator & getLibraries() const
  3648. { return c->getLibraries(); }
  3649. virtual WUPriorityClass getPriority() const
  3650. { return c->getPriority(); }
  3651. virtual const char *queryPriorityDesc() const
  3652. { return c->queryPriorityDesc(); }
  3653. virtual int getPriorityLevel() const
  3654. { return c->getPriorityLevel(); }
  3655. virtual int getPriorityValue() const
  3656. { return c->getPriorityValue(); }
  3657. virtual IConstWUQuery * getQuery() const
  3658. { return c->getQuery(); }
  3659. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  3660. { return c->getWebServicesInfo(); }
  3661. virtual bool getRescheduleFlag() const
  3662. { return c->getRescheduleFlag(); }
  3663. virtual IConstWUResult * getResultByName(const char * name) const
  3664. { return c->getResultByName(name); }
  3665. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  3666. { return c->getResultBySequence(seq); }
  3667. virtual IConstWUResult * getQueryResultByName(const char * name) const
  3668. { return c->getQueryResultByName(name); }
  3669. virtual unsigned getResultLimit() const
  3670. { return c->getResultLimit(); }
  3671. virtual IConstWUResultIterator & getResults() const
  3672. { return c->getResults(); }
  3673. virtual IStringVal & getScope(IStringVal & str) const
  3674. { return c->getScope(str); }
  3675. virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & str) const
  3676. { return c->getWorkunitDistributedAccessToken(str); }
  3677. virtual WUState getState() const
  3678. { return c->getState(); }
  3679. virtual IStringVal & getStateEx(IStringVal & str) const
  3680. { return c->getStateEx(str); }
  3681. virtual __int64 getAgentSession() const
  3682. { return c->getAgentSession(); }
  3683. virtual unsigned getAgentPID() const
  3684. { return c->getAgentPID(); }
  3685. virtual const char *queryStateDesc() const
  3686. { return c->queryStateDesc(); }
  3687. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  3688. { return c->getRunningGraph(graphName, subId); }
  3689. virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const override
  3690. { return c->getScopeIterator(filter); }
  3691. virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const override
  3692. { return c->getStatistic(value, scope, kind); }
  3693. virtual IStringVal & getSnapshot(IStringVal & str) const
  3694. { return c->getSnapshot(str); }
  3695. virtual const char *queryUser() const
  3696. { return c->queryUser(); }
  3697. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  3698. { return c->getWarningSeverity(code, defaultSeverity); }
  3699. virtual const char *queryWuScope() const
  3700. { return c->queryWuScope(); }
  3701. virtual const char *queryWuid() const
  3702. { return c->queryWuid(); }
  3703. virtual IConstWUResult * getGlobalByName(const char * name) const
  3704. { return c->getGlobalByName(name); }
  3705. virtual IConstWUResult * getTemporaryByName(const char * name) const
  3706. { return c->getTemporaryByName(name); }
  3707. virtual IConstWUResultIterator & getTemporaries() const
  3708. { return c->getTemporaries(); }
  3709. virtual IConstWUResult * getVariableByName(const char * name) const
  3710. { return c->getVariableByName(name); }
  3711. virtual IConstWUResultIterator & getVariables() const
  3712. { return c->getVariables(); }
  3713. virtual bool isProtected() const
  3714. { return c->isProtected(); }
  3715. virtual bool isPausing() const
  3716. { return c->isPausing(); }
  3717. virtual IWorkUnit & lock()
  3718. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  3719. virtual bool reload()
  3720. { UNIMPLEMENTED; }
  3721. virtual void subscribe(WUSubscribeOptions options)
  3722. { c->subscribe(options); }
  3723. virtual void requestAbort()
  3724. { c->requestAbort(); }
  3725. virtual unsigned calculateHash(unsigned prevHash)
  3726. { return queryExtendedWU(c)->calculateHash(prevHash); }
  3727. virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  3728. { queryExtendedWU(c)->copyWorkUnit(cached, copyStats, all); }
  3729. virtual IPropertyTree *queryPTree() const
  3730. { return queryExtendedWU(c)->queryPTree(); }
  3731. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  3732. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  3733. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  3734. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  3735. virtual unsigned queryFileUsage(const char *filename) const
  3736. { return c->queryFileUsage(filename); }
  3737. virtual IConstWUFileUsageIterator * getFieldUsage() const
  3738. { return c->getFieldUsage(); }
  3739. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  3740. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  3741. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  3742. { return c->getTimeScheduled(val); }
  3743. virtual unsigned getDebugAgentListenerPort() const
  3744. { return c->getDebugAgentListenerPort(); }
  3745. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  3746. { return c->getDebugAgentListenerIP(ip); }
  3747. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  3748. { return c->getXmlParams(params, hidePasswords); }
  3749. virtual const IPropertyTree *getXmlParams() const
  3750. { return c->getXmlParams(); }
  3751. virtual unsigned __int64 getHash() const
  3752. { return c->getHash(); }
  3753. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  3754. { return c->getLogs(type, instance); }
  3755. virtual IStringIterator *getProcesses(const char *type) const
  3756. { return c->getProcesses(type); }
  3757. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  3758. { return c->getProcesses(type, instance); }
  3759. virtual unsigned getTotalThorTime() const
  3760. { return c->getTotalThorTime(); }
  3761. virtual WUGraphState queryGraphState(const char *graphName) const
  3762. { return c->queryGraphState(graphName); }
  3763. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3764. { return c->queryNodeState(graphName, nodeId); }
  3765. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3766. { c->setGraphState(graphName, wfid, state); }
  3767. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3768. { c->setNodeState(graphName, nodeId, state); }
  3769. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3770. { return c->updateStats(graphName, creatorType, creator, _wfid, subgraph); }
  3771. virtual void clearGraphProgress() const
  3772. { c->clearGraphProgress(); }
  3773. virtual IStringVal & getAbortBy(IStringVal & str) const
  3774. { return c->getAbortBy(str); }
  3775. virtual unsigned __int64 getAbortTimeStamp() const
  3776. { return c->getAbortTimeStamp(); }
  3777. virtual void import(IPropertyTree *wuTree, IPropertyTree *graphProgressTree)
  3778. { return c->import(wuTree, graphProgressTree); }
  3779. virtual void clearExceptions(const char *source=nullptr)
  3780. { c->clearExceptions(source); }
  3781. virtual void commit()
  3782. { c->commit(); }
  3783. virtual IWUException * createException()
  3784. { return c->createException(); }
  3785. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  3786. { c->addProcess(type, instance, pid, log); }
  3787. virtual void protect(bool protectMode)
  3788. { c->protect(protectMode); }
  3789. virtual void setAction(WUAction action)
  3790. { c->setAction(action); }
  3791. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  3792. { c->setApplicationValue(application, propname, value, overwrite); }
  3793. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  3794. { c->setApplicationValueInt(application, propname, value, overwrite); }
  3795. virtual void incEventScheduledCount()
  3796. { c->incEventScheduledCount(); }
  3797. virtual void setIsQueryService(bool value)
  3798. { c->setIsQueryService(value); }
  3799. virtual void setCloneable(bool value)
  3800. { c->setCloneable(value); }
  3801. virtual void setIsClone(bool value)
  3802. { c->setIsClone(value); }
  3803. virtual void setClusterName(const char * value)
  3804. { c->setClusterName(value); }
  3805. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  3806. { c->setCodeVersion(version, buildVersion, eclVersion); }
  3807. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  3808. { c->setDebugValue(propname, value, overwrite); }
  3809. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  3810. { c->setDebugValueInt(propname, value, overwrite); }
  3811. virtual void setJobName(const char * value)
  3812. { c->setJobName(value); }
  3813. virtual void setPriority(WUPriorityClass cls)
  3814. { c->setPriority(cls); }
  3815. virtual void setPriorityLevel(int level)
  3816. { c->setPriorityLevel(level); }
  3817. virtual void setRescheduleFlag(bool value)
  3818. { c->setRescheduleFlag(value); }
  3819. virtual void setResultLimit(unsigned value)
  3820. { c->setResultLimit(value); }
  3821. virtual void setState(WUState state)
  3822. { c->setState(state); }
  3823. virtual void setStateEx(const char * text)
  3824. { c->setStateEx(text); }
  3825. virtual void setAgentSession(__int64 sessionId)
  3826. { c->setAgentSession(sessionId); }
  3827. 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)
  3828. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  3829. virtual void setTracingValue(const char * propname, const char * value)
  3830. { c->setTracingValue(propname, value); }
  3831. virtual void setTracingValueInt(const char * propname, int value)
  3832. { c->setTracingValueInt(propname, value); }
  3833. virtual void setTracingValueInt64(const char * propname, __int64 value)
  3834. { c->setTracingValueInt64(propname, value); }
  3835. virtual void setUser(const char * value)
  3836. { c->setUser(value); }
  3837. virtual void setWuScope(const char * value)
  3838. { c->setWuScope(value); }
  3839. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  3840. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  3841. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  3842. { c->syncRuntimeWorkflow(array); }
  3843. virtual IWorkflowItemIterator * updateWorkflowItems()
  3844. { return c->updateWorkflowItems(); }
  3845. virtual void resetWorkflow()
  3846. { c->resetWorkflow(); }
  3847. virtual void schedule()
  3848. { c->schedule(); }
  3849. virtual void deschedule()
  3850. { c->deschedule(); }
  3851. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  3852. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  3853. virtual IWUResult * updateGlobalByName(const char * name)
  3854. { return c->updateGlobalByName(name); }
  3855. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  3856. { c->createGraph(name, label, type, xgmml, wfid); }
  3857. virtual IWUQuery * updateQuery()
  3858. { return c->updateQuery(); }
  3859. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  3860. { return c->updateWebServicesInfo(create); }
  3861. virtual IWUPlugin * updatePluginByName(const char * name)
  3862. { return c->updatePluginByName(name); }
  3863. virtual IWULibrary * updateLibraryByName(const char * name)
  3864. { return c->updateLibraryByName(name); }
  3865. virtual IWUResult * updateResultByName(const char * name)
  3866. { return c->updateResultByName(name); }
  3867. virtual IWUResult * updateResultBySequence(unsigned seq)
  3868. { return c->updateResultBySequence(seq); }
  3869. virtual IWUResult * updateTemporaryByName(const char * name)
  3870. { return c->updateTemporaryByName(name); }
  3871. virtual IWUResult * updateVariableByName(const char * name)
  3872. { return c->updateVariableByName(name); }
  3873. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  3874. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  3875. virtual void noteFileRead(IDistributedFile *file)
  3876. { c->noteFileRead(file); }
  3877. virtual void noteFieldUsage(IPropertyTree * usage)
  3878. { c->noteFieldUsage(usage); }
  3879. virtual void releaseFile(const char *fileName)
  3880. { c->releaseFile(fileName); }
  3881. virtual void resetBeforeGeneration()
  3882. { c->resetBeforeGeneration(); }
  3883. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  3884. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  3885. virtual void deleteTemporaries()
  3886. { c->deleteTemporaries(); }
  3887. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  3888. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  3889. virtual IPropertyTree * getDiskUsageStats()
  3890. { return c->getDiskUsageStats(); }
  3891. virtual IPropertyTreeIterator & getFileIterator() const
  3892. { return c->getFileIterator(); }
  3893. virtual IPropertyTreeIterator & getFilesReadIterator() const
  3894. { return c->getFilesReadIterator(); }
  3895. virtual void setSnapshot(const char * value)
  3896. { c->setSnapshot(value); }
  3897. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  3898. { c->setWarningSeverity(code, severity); }
  3899. virtual void setTimeScheduled(const IJlibDateTime &val)
  3900. { c->setTimeScheduled(val); }
  3901. virtual void setDebugAgentListenerPort(unsigned port)
  3902. { c->setDebugAgentListenerPort(port); }
  3903. virtual void setDebugAgentListenerIP(const char * ip)
  3904. { c->setDebugAgentListenerIP(ip); }
  3905. virtual void setXmlParams(const char *params)
  3906. { c->setXmlParams(params); }
  3907. virtual void setXmlParams(IPropertyTree *tree)
  3908. { c->setXmlParams(tree); }
  3909. virtual void setHash(unsigned __int64 hash)
  3910. { c->setHash(hash); }
  3911. // ILocalWorkUnit - used for debugging etc
  3912. virtual void serialize(MemoryBuffer &tgt)
  3913. { c->serialize(tgt); }
  3914. virtual void deserialize(MemoryBuffer &src)
  3915. { c->deserialize(src); }
  3916. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  3917. { return c->switchThorQueue(cluster,qs); }
  3918. virtual void setAllowedClusters(const char *value)
  3919. { c->setAllowedClusters(value); }
  3920. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  3921. { return c->getAllowedClusters(str); }
  3922. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3923. { c->remoteCheckAccess(user,writeaccess); }
  3924. virtual void setAllowAutoQueueSwitch(bool val)
  3925. { c->setAllowAutoQueueSwitch(val); }
  3926. virtual bool getAllowAutoQueueSwitch() const
  3927. { return c->getAllowAutoQueueSwitch(); }
  3928. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3929. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  3930. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  3931. { c->setResultInt(name, sequence, val); }
  3932. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  3933. { c->setResultUInt(name, sequence, val); }
  3934. virtual void setResultReal(const char *name, unsigned sequence, double val)
  3935. { c->setResultReal(name, sequence, val); }
  3936. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  3937. { c->setResultVarString(stepname, sequence, val); }
  3938. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  3939. { c->setResultVarUnicode(stepname, sequence, val); }
  3940. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  3941. { c->setResultString(stepname, sequence, len, val); }
  3942. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  3943. { c->setResultData(stepname, sequence, len, val); }
  3944. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  3945. { c->setResultRaw(name, sequence, len, val); }
  3946. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  3947. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  3948. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  3949. { c->setResultUnicode(name, sequence, len, val); }
  3950. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  3951. { c->setResultBool(name, sequence, val); }
  3952. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  3953. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  3954. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  3955. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  3956. };
  3957. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  3958. {
  3959. Owned<IPropertyTree> p;
  3960. public:
  3961. IMPLEMENT_IINTERFACE;
  3962. CLocalWUAssociated(IPropertyTree *p);
  3963. virtual WUFileType getType() const;
  3964. virtual IStringVal & getDescription(IStringVal & ret) const;
  3965. virtual IStringVal & getIp(IStringVal & ret) const;
  3966. virtual IStringVal & getName(IStringVal & ret) const;
  3967. virtual IStringVal & getNameTail(IStringVal & ret) const;
  3968. virtual unsigned getCrc() const;
  3969. virtual unsigned getMinActivityId() const;
  3970. virtual unsigned getMaxActivityId() const;
  3971. };
  3972. class CLocalWUQuery : implements IWUQuery, public CInterface
  3973. {
  3974. Owned<IPropertyTree> p;
  3975. mutable IArrayOf<IConstWUAssociatedFile> associated;
  3976. mutable CriticalSection crit;
  3977. mutable bool associatedCached;
  3978. private:
  3979. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  3980. void loadAssociated() const;
  3981. public:
  3982. IMPLEMENT_IINTERFACE;
  3983. CLocalWUQuery(IPropertyTree *p);
  3984. virtual WUQueryType getQueryType() const;
  3985. virtual IStringVal& getQueryText(IStringVal &str) const;
  3986. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  3987. virtual IStringVal& getQueryName(IStringVal &str) const;
  3988. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  3989. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  3990. virtual unsigned getQueryDllCrc() const;
  3991. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  3992. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  3993. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  3994. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  3995. virtual bool isArchive() const;
  3996. virtual bool hasArchive() const
  3997. {
  3998. return p->getPropBool("@hasArchive");
  3999. }
  4000. virtual void setQueryType(WUQueryType qt);
  4001. virtual void setQueryText(const char *pstr);
  4002. virtual void setQueryName(const char *);
  4003. virtual void setQueryMainDefinition(const char * str);
  4004. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  4005. virtual void removeAssociatedFiles();
  4006. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  4007. };
  4008. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  4009. {
  4010. Owned<IPropertyTree> p;
  4011. mutable CriticalSection crit;
  4012. private:
  4013. public:
  4014. IMPLEMENT_IINTERFACE;
  4015. CLocalWUWebServicesInfo(IPropertyTree *p);
  4016. virtual IStringVal& getModuleName(IStringVal &str) const;
  4017. virtual IStringVal& getAttributeName(IStringVal &str) const;
  4018. virtual IStringVal& getDefaultName(IStringVal &str) const;
  4019. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  4020. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  4021. virtual unsigned getWebServicesCRC() const;
  4022. virtual void setModuleName(const char *);
  4023. virtual void setAttributeName(const char *);
  4024. virtual void setDefaultName(const char *);
  4025. virtual void setInfo(const char *name, const char *info);
  4026. virtual void setText(const char *name, const char *info);
  4027. virtual void setWebServicesCRC(unsigned);
  4028. };
  4029. class CLocalWUResult : implements IWUResult, public CInterface
  4030. {
  4031. friend class CLocalWorkUnit;
  4032. mutable CriticalSection crit;
  4033. Owned<IPropertyTree> p;
  4034. Owned<IProperties> xmlns;
  4035. public:
  4036. IMPLEMENT_IINTERFACE;
  4037. CLocalWUResult(IPropertyTree *props);
  4038. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  4039. virtual WUResultStatus getResultStatus() const;
  4040. virtual IStringVal& getResultName(IStringVal &str) const;
  4041. virtual int getResultSequence() const;
  4042. virtual bool isResultScalar() const;
  4043. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  4044. virtual unsigned getResultFetchSize() const;
  4045. virtual __int64 getResultTotalRowCount() const;
  4046. virtual __int64 getResultRowCount() const;
  4047. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  4048. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  4049. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  4050. virtual unsigned getResultRequestedRows() const;
  4051. virtual __int64 getResultInt() const;
  4052. virtual bool getResultBool() const;
  4053. virtual double getResultReal() const;
  4054. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  4055. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4056. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  4057. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  4058. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  4059. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4060. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4061. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  4062. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  4063. virtual __int64 getResultRowLimit() const;
  4064. virtual IStringVal& getResultFilename(IStringVal & str) const;
  4065. virtual WUResultFormat getResultFormat() const;
  4066. virtual unsigned getResultHash() const;
  4067. virtual bool getResultIsAll() const;
  4068. virtual IProperties *queryResultXmlns();
  4069. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  4070. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  4071. virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const;
  4072. // interface IWUResult
  4073. virtual void setResultStatus(WUResultStatus status);
  4074. virtual void setResultName(const char *name);
  4075. virtual void setResultSequence(unsigned seq);
  4076. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  4077. virtual void setResultScalar(bool isScalar);
  4078. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  4079. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  4080. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  4081. virtual void setResultRowCount(__int64 rows);
  4082. virtual void setResultDataset(const char *ecl, const char *defs);
  4083. virtual void setResultLogicalName(const char *logicalName);
  4084. virtual void setResultKeyField(const char * name);
  4085. virtual void setResultRequestedRows(unsigned req);
  4086. virtual void setResultRecordSizeEntry(const char * val);
  4087. virtual void setResultTransformerEntry(const char * val);
  4088. virtual void setResultInt(__int64 val);
  4089. virtual void setResultReal(double val);
  4090. virtual void setResultBool(bool val);
  4091. virtual void setResultString(const char * val, unsigned length);
  4092. virtual void setResultUnicode(const void * val, unsigned length);
  4093. virtual void setResultData(const void * val, unsigned length);
  4094. virtual void setResultDecimal(const void * val, unsigned length);
  4095. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  4096. virtual void setResultRowLimit(__int64 value);
  4097. virtual void setResultFilename(const char * name);
  4098. virtual void setResultUInt(unsigned __int64 val);
  4099. virtual void setResultIsAll(bool value);
  4100. virtual void setResultFormat(WUResultFormat format);
  4101. virtual void setResultXML(const char *val);
  4102. virtual void setResultRow(unsigned len, const void * data);
  4103. virtual void setResultXmlns(const char *prefix, const char *uri);
  4104. virtual void setResultFieldOpt(const char *name, const char *value);
  4105. virtual void setResultWriteLocation(const char * _graph, unsigned _activityId);
  4106. virtual IPropertyTree *queryPTree() { return p; }
  4107. };
  4108. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  4109. {
  4110. Owned<IPropertyTree> p;
  4111. public:
  4112. IMPLEMENT_IINTERFACE;
  4113. CLocalWUPlugin(IPropertyTree *p);
  4114. virtual IStringVal& getPluginName(IStringVal &str) const;
  4115. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  4116. virtual void setPluginName(const char *str);
  4117. virtual void setPluginVersion(const char *str);
  4118. };
  4119. class CLocalWULibrary : implements IWULibrary, public CInterface
  4120. {
  4121. Owned<IPropertyTree> p;
  4122. public:
  4123. IMPLEMENT_IINTERFACE;
  4124. CLocalWULibrary(IPropertyTree *p);
  4125. virtual IStringVal & getName(IStringVal & str) const;
  4126. virtual void setName(const char * str);
  4127. };
  4128. class CLocalWUException : implements IWUException, public CInterface
  4129. {
  4130. Owned<IPropertyTree> p;
  4131. public:
  4132. IMPLEMENT_IINTERFACE;
  4133. CLocalWUException(IPropertyTree *p);
  4134. virtual IStringVal& getExceptionSource(IStringVal &str) const override;
  4135. virtual IStringVal& getExceptionMessage(IStringVal &str) const override;
  4136. virtual unsigned getExceptionCode() const override;
  4137. virtual ErrorSeverity getSeverity() const override;
  4138. virtual IStringVal & getTimeStamp(IStringVal & dt) const override;
  4139. virtual IStringVal & getExceptionFileName(IStringVal & str) const override;
  4140. virtual unsigned getExceptionLineNo() const override;
  4141. virtual unsigned getExceptionColumn() const override;
  4142. virtual unsigned getActivityId() const override;
  4143. virtual unsigned getSequence() const override;
  4144. virtual const char * queryScope() const override;
  4145. virtual unsigned getPriority() const override;
  4146. virtual void setExceptionSource(const char *str) override;
  4147. virtual void setExceptionMessage(const char *str) override;
  4148. virtual void setExceptionCode(unsigned code) override;
  4149. virtual void setSeverity(ErrorSeverity level) override;
  4150. virtual void setTimeStamp(const char * dt) override;
  4151. virtual void setExceptionFileName(const char *str) override;
  4152. virtual void setExceptionLineNo(unsigned r) override;
  4153. virtual void setExceptionColumn(unsigned c) override;
  4154. virtual void setActivityId(unsigned _id) override;
  4155. virtual void setScope(const char * _scope) override;
  4156. virtual void setPriority(unsigned _priority) override;
  4157. };
  4158. //==========================================================================================
  4159. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  4160. {
  4161. switch ((int) sequence)
  4162. {
  4163. case ResultSequenceInternal:
  4164. case ResultSequenceOnce:
  4165. case ResultSequencePersist:
  4166. case ResultSequenceStored:
  4167. return true;
  4168. default:
  4169. assertex(sequence <= INT_MAX);
  4170. if ((int) sequence >= LibraryBaseSequence)
  4171. return true;
  4172. return false;
  4173. }
  4174. }
  4175. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  4176. {
  4177. unsigned curTreeNum;
  4178. IArrayOf<IPropertyTree> trees;
  4179. Owned<IConstWorkUnitInfo> cur;
  4180. void setCurrent()
  4181. {
  4182. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  4183. }
  4184. public:
  4185. IMPLEMENT_IINTERFACE;
  4186. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  4187. {
  4188. ForEachItemIn(t, _trees)
  4189. trees.append(*LINK(&_trees.item(t)));
  4190. curTreeNum = 0;
  4191. }
  4192. bool first()
  4193. {
  4194. curTreeNum = 0;
  4195. return next();
  4196. }
  4197. bool isValid()
  4198. {
  4199. return (NULL != cur.get());
  4200. }
  4201. bool next()
  4202. {
  4203. if (curTreeNum >= trees.ordinality())
  4204. {
  4205. cur.clear();
  4206. return false;
  4207. }
  4208. setCurrent();
  4209. ++curTreeNum;
  4210. return true;
  4211. }
  4212. IConstWorkUnitInfo & query() { return *cur; }
  4213. };
  4214. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  4215. {
  4216. Owned<IPropertyTree> p;
  4217. public:
  4218. IMPLEMENT_IINTERFACE;
  4219. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  4220. virtual const char * queryName() const { return p->queryProp("@name"); }
  4221. };
  4222. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  4223. {
  4224. public:
  4225. IMPLEMENT_IINTERFACE;
  4226. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4227. bool first() override { return iter->first(); }
  4228. bool isValid() override { return iter->isValid(); }
  4229. bool next() override { return iter->next(); }
  4230. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  4231. private:
  4232. Owned<IPropertyTreeIterator> iter;
  4233. };
  4234. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  4235. {
  4236. Owned<IPropertyTree> p;
  4237. public:
  4238. IMPLEMENT_IINTERFACE;
  4239. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  4240. virtual const char * queryName() const { return p->queryProp("@name"); }
  4241. virtual const char * queryType() const { return p->queryProp("@type"); }
  4242. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  4243. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  4244. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  4245. };
  4246. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  4247. {
  4248. public:
  4249. IMPLEMENT_IINTERFACE;
  4250. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4251. bool first() override { return iter->first(); }
  4252. bool isValid() override { return iter->isValid(); }
  4253. bool next() override { return iter->next(); }
  4254. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  4255. private:
  4256. Owned<IPropertyTreeIterator> iter;
  4257. };
  4258. //==========================================================================================
  4259. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  4260. {
  4261. Owned<IPropertyTreeIterator> it;
  4262. public:
  4263. IMPLEMENT_IINTERFACE;
  4264. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  4265. virtual bool first() { return it->first(); }
  4266. virtual bool next() { return it->next(); }
  4267. virtual bool isValid() { return it->isValid(); }
  4268. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  4269. };
  4270. EnumMapping workunitSortFields[] =
  4271. {
  4272. { WUSFuser, "@submitID" },
  4273. { WUSFcluster, "@clusterName" },
  4274. { WUSFjob, "@jobName" },
  4275. { WUSFstate, "@state" },
  4276. { WUSFpriority, "@priorityClass" },
  4277. { WUSFprotected, "@protected" },
  4278. { WUSFwuid, "@" },
  4279. { WUSFecl, "Query/ShortText" },
  4280. { WUSFfileread, "FilesRead/File/@name" },
  4281. { WUSFtotalthortime, "@totalThorTime|"
  4282. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  4283. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  4284. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  4285. "Statistics/Statistic[@desc='Total thor time']/@value|"
  4286. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  4287. },
  4288. { WUSFwuidhigh, "@" },
  4289. { WUSFwildwuid, "@" },
  4290. { WUSFappvalue, "Application" },
  4291. { WUSFfilewritten, "Files/File/@name" },
  4292. { WUSFterm, NULL }
  4293. };
  4294. extern const char *queryFilterXPath(WUSortField field)
  4295. {
  4296. return getEnumText(field, workunitSortFields);
  4297. }
  4298. EnumMapping querySortFields[] =
  4299. {
  4300. { WUQSFId, "@id" },
  4301. { WUQSFwuid, "@wuid" },
  4302. { WUQSFname, "@name" },
  4303. { WUQSFdll, "@dll" },
  4304. { WUQSFmemoryLimit, "@memoryLimit" },
  4305. { WUQSFmemoryLimitHi, "@memoryLimit" },
  4306. { WUQSFtimeLimit, "@timeLimit" },
  4307. { WUQSFtimeLimitHi, "@timeLimit" },
  4308. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  4309. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  4310. { WUQSFpriority, "@priority" },
  4311. { WUQSFpriorityHi, "@priority" },
  4312. { WUQSFQuerySet, "@querySetId" },
  4313. { WUQSFActivited, "@activated" },
  4314. { WUQSFSuspendedByUser, "@suspended" },
  4315. { WUQSFLibrary, "Library"},
  4316. { WUQSFPublishedBy, "@publishedBy" },
  4317. { WUQSFterm, NULL }
  4318. };
  4319. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  4320. {
  4321. StringAttr name;
  4322. public:
  4323. IMPLEMENT_IINTERFACE;
  4324. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  4325. {
  4326. }
  4327. void execute()
  4328. {
  4329. PROGLOG("WU removeDll %s", name.get());
  4330. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  4331. }
  4332. };
  4333. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  4334. {
  4335. RemoteFilename name;
  4336. public:
  4337. IMPLEMENT_IINTERFACE;
  4338. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  4339. {
  4340. SocketEndpoint ep(_ip);
  4341. name.setPath(ep, _name);
  4342. }
  4343. void execute()
  4344. {
  4345. Owned<IFile> file = createIFile(name);
  4346. PROGLOG("WU removeDll %s",file->queryFilename());
  4347. file->remove();
  4348. }
  4349. };
  4350. //==========================================================================================
  4351. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  4352. {
  4353. unsigned index;
  4354. IArrayOf<IPropertyTree> trees;
  4355. public:
  4356. IMPLEMENT_IINTERFACE;
  4357. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  4358. {
  4359. ForEachItemIn(t, _trees)
  4360. trees.append(*LINK(&_trees.item(t)));
  4361. index = 0;
  4362. }
  4363. ~CConstQuerySetQueryIterator()
  4364. {
  4365. trees.kill();
  4366. }
  4367. bool first()
  4368. {
  4369. index = 0;
  4370. return (trees.ordinality()!=0);
  4371. }
  4372. bool next()
  4373. {
  4374. index++;
  4375. return (index<trees.ordinality());
  4376. }
  4377. bool isValid()
  4378. {
  4379. return (index<trees.ordinality());
  4380. }
  4381. IPropertyTree &query()
  4382. {
  4383. return trees.item(index);
  4384. }
  4385. };
  4386. class CSecurityCache
  4387. {
  4388. };
  4389. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  4390. {
  4391. public:
  4392. IMPLEMENT_IINTERFACE;
  4393. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  4394. : ptreeIter(_ptreeIter)
  4395. {
  4396. }
  4397. bool first()
  4398. {
  4399. if (!ptreeIter->first())
  4400. {
  4401. cur.clear();
  4402. return false;
  4403. }
  4404. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4405. return true;
  4406. }
  4407. bool isValid()
  4408. {
  4409. return (NULL != cur.get());
  4410. }
  4411. bool next()
  4412. {
  4413. if (!ptreeIter->next())
  4414. {
  4415. cur.clear();
  4416. return false;
  4417. }
  4418. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4419. return true;
  4420. }
  4421. IConstWorkUnitInfo & query() { return *cur; }
  4422. private:
  4423. Owned<IConstWorkUnitInfo> cur;
  4424. Owned<IPropertyTreeIterator> ptreeIter;
  4425. };
  4426. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  4427. {
  4428. public:
  4429. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  4430. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  4431. {
  4432. assertex(_secuser && _secmgr);
  4433. }
  4434. bool first()
  4435. {
  4436. if (!parent->first())
  4437. return false;
  4438. return getNext();
  4439. }
  4440. bool next()
  4441. {
  4442. if (!parent->next())
  4443. return false;
  4444. return getNext();
  4445. }
  4446. virtual bool isValid()
  4447. {
  4448. return parent->isValid();
  4449. }
  4450. virtual IConstWorkUnitInfo &query()
  4451. {
  4452. return parent->query();
  4453. }
  4454. private:
  4455. Owned<IConstWorkUnitIterator> parent;
  4456. MapStringTo<int> scopePermissions;
  4457. Linked<ISecManager> secmgr;
  4458. Linked<ISecUser> secuser;
  4459. bool getNext() // scan for a workunit with permissions
  4460. {
  4461. do
  4462. {
  4463. const char *scopeName = parent->query().queryWuScope();
  4464. if (!scopeName || !*scopeName || checkScope(scopeName))
  4465. return true;
  4466. } while (parent->next());
  4467. return false;
  4468. }
  4469. bool checkScope(const char *scopeName)
  4470. {
  4471. int *perms = scopePermissions.getValue(scopeName);
  4472. SecAccessFlags perm;
  4473. if (!perms)
  4474. {
  4475. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  4476. scopePermissions.setValue(scopeName, perm);
  4477. }
  4478. else
  4479. perm = (SecAccessFlags)*perms;
  4480. return perm >= SecAccess_Read;
  4481. }
  4482. };
  4483. CWorkUnitFactory::CWorkUnitFactory()
  4484. {
  4485. }
  4486. CWorkUnitFactory::~CWorkUnitFactory()
  4487. {
  4488. }
  4489. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4490. {
  4491. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  4492. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  4493. if (scope)
  4494. 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...
  4495. cw->setDistributedAccessToken(secuser ? secuser->getName() : "");//create and sign the workunit distributed access token
  4496. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  4497. ret->setDebugValue("CREATED_BY", app, true);
  4498. ret->setDebugValue("CREATED_FOR", scope, true);
  4499. return ret;
  4500. }
  4501. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4502. {
  4503. StringBuffer wuid("W");
  4504. char result[32];
  4505. time_t ltime;
  4506. time( &ltime );
  4507. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  4508. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  4509. wuid.append(result);
  4510. if (workUnitTraceLevel > 1)
  4511. DBGLOG("createWorkUnit created %s", wuid.str());
  4512. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  4513. if (workUnitTraceLevel > 1)
  4514. DBGLOG("createWorkUnit created %s", ret->queryWuid());
  4515. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  4516. return ret;
  4517. }
  4518. bool CWorkUnitFactory::deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secmgr, ISecUser *secuser)
  4519. {
  4520. if (workUnitTraceLevel > 1)
  4521. DBGLOG("deleteWorkUnit %s", wuid);
  4522. StringBuffer wuRoot;
  4523. getXPath(wuRoot, wuid);
  4524. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  4525. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  4526. return false;
  4527. if (throwException)
  4528. cw->cleanupAndDelete(true, true);
  4529. else
  4530. {
  4531. try
  4532. {
  4533. cw->cleanupAndDelete(true, true);
  4534. }
  4535. catch (IException *E)
  4536. {
  4537. StringBuffer s;
  4538. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  4539. E->Release();
  4540. return false;
  4541. }
  4542. }
  4543. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  4544. return true;
  4545. }
  4546. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  4547. {
  4548. return deleteWorkUnitEx(wuid, false, secmgr, secuser);
  4549. }
  4550. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4551. {
  4552. StringBuffer wuidStr(wuid);
  4553. wuidStr.trim();
  4554. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  4555. wuidStr.setCharAt(0, 'W');
  4556. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  4557. {
  4558. if (workUnitTraceLevel > 1)
  4559. DBGLOG("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  4560. return NULL;
  4561. }
  4562. if (workUnitTraceLevel > 1)
  4563. DBGLOG("openWorkUnit %s", wuidStr.str());
  4564. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  4565. if (wu)
  4566. {
  4567. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  4568. return NULL; // Actually throws exception on failure, so won't reach here
  4569. return wu.getClear();
  4570. }
  4571. else
  4572. {
  4573. if (workUnitTraceLevel > 0)
  4574. IERRLOG("openWorkUnit %s not found", wuidStr.str());
  4575. return NULL;
  4576. }
  4577. }
  4578. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4579. {
  4580. if (workUnitTraceLevel > 1)
  4581. DBGLOG("updateWorkUnit %s", wuid);
  4582. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  4583. if (wu)
  4584. {
  4585. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  4586. return NULL;
  4587. return &wu->lockRemote(false);
  4588. }
  4589. else
  4590. {
  4591. if (workUnitTraceLevel > 0)
  4592. IERRLOG("updateWorkUnit %s not found", wuid);
  4593. return NULL;
  4594. }
  4595. }
  4596. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  4597. {
  4598. Owned<IPropertyTree> ret;
  4599. IPropertyTree * branch = from->queryPropTree(xpath);
  4600. if(branch)
  4601. {
  4602. ret.setown(createPTreeFromIPT(branch));
  4603. from->removeTree(branch);
  4604. }
  4605. return ret.getClear();
  4606. }
  4607. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  4608. {
  4609. StringBuffer path(base);
  4610. addPathSepChar(path).append(wuid).append(".xml");
  4611. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  4612. if (!pt)
  4613. return false;
  4614. CDateTime dt;
  4615. dt.setNow();
  4616. StringBuffer dts;
  4617. dt.getString(dts);
  4618. pt->setProp("@restoredDate", dts.str());
  4619. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  4620. Owned<IPropertyTree> associatedFiles;
  4621. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  4622. if (srcAssociated)
  4623. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  4624. // The updating of the repo is implementation specific...
  4625. if (!_restoreWorkUnit(pt.getClear(), wuid))
  4626. return false;
  4627. // now kludge back GeneratedDlls
  4628. if (generatedDlls)
  4629. {
  4630. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  4631. for(dlls->first(); dlls->isValid(); dlls->next())
  4632. {
  4633. IPropertyTree & dll = dlls->query();
  4634. char const * name = dll.queryProp("@name");
  4635. char const * kind = dll.queryProp("@kind");
  4636. char const * location = dll.queryProp("@location");
  4637. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  4638. if (!got)
  4639. {
  4640. RemoteFilename dstRfn;
  4641. dstRfn.setRemotePath(location);
  4642. StringBuffer srcPath(base);
  4643. addPathSepChar(srcPath);
  4644. dstRfn.getTail(srcPath);
  4645. OwnedIFile srcFile = createIFile(srcPath);
  4646. OwnedIFile dstFile = createIFile(dstRfn);
  4647. copyFile(dstFile, srcFile);
  4648. queryDllServer().registerDll(name, kind, location);
  4649. }
  4650. }
  4651. }
  4652. if (associatedFiles)
  4653. {
  4654. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  4655. ForEach(*associated)
  4656. {
  4657. IPropertyTree &file = associated->query();
  4658. const char *filename = file.queryProp("@filename");
  4659. SocketEndpoint ep(file.queryProp("@ip"));
  4660. RemoteFilename rfn;
  4661. rfn.setPath(ep, filename);
  4662. OwnedIFile dstFile = createIFile(rfn);
  4663. StringBuffer srcPath(base), name;
  4664. addPathSepChar(srcPath);
  4665. rfn.getTail(name);
  4666. srcPath.append(name);
  4667. if (generatedDlls)
  4668. {
  4669. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  4670. if (generatedDlls->hasProp(gDllPath))
  4671. continue; // generated dlls handled separately - see above
  4672. }
  4673. OwnedIFile srcFile = createIFile(srcPath);
  4674. if (srcFile->exists())
  4675. {
  4676. try
  4677. {
  4678. copyFile(dstFile, srcFile);
  4679. }
  4680. catch (IException *e)
  4681. {
  4682. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  4683. EXCLOG(e, msg.str());
  4684. e->Release();
  4685. }
  4686. }
  4687. }
  4688. }
  4689. return true;
  4690. }
  4691. void CWorkUnitFactory::importWorkUnit(const char *zapReportFileName, const char *zapReportPassword,
  4692. const char *importDir, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  4693. {
  4694. class CImportWorkUnitHelper
  4695. {
  4696. StringAttr zapReportFileName, zapReportPassword, importDir, user, wuid, fromWUID, scope;
  4697. StringBuffer unzipDir;
  4698. Owned<IPTree> wuTree, graphProgressTree;
  4699. bool findZAPFile(const char *mask, bool optional, StringBuffer &fileName)
  4700. {
  4701. Owned<IFile> d = createIFile(unzipDir);
  4702. if (!d->exists())
  4703. throw MakeStringException(WUERR_InvalidUserInput, "%s not found.", unzipDir.str());
  4704. Owned<IDirectoryIterator> di = d->directoryFiles(mask, false, false);
  4705. if (!di->first())
  4706. {
  4707. if (optional)
  4708. return false;
  4709. throw MakeStringException(WUERR_InvalidUserInput, "Failed to find %s in %s.", mask, unzipDir.str());
  4710. }
  4711. fileName.set(unzipDir).append(PATHSEPSTR);
  4712. di->getName(fileName);
  4713. if (di->next())
  4714. throw MakeStringException(WUERR_InvalidUserInput, "More than 1 %s files found in %s.", mask, unzipDir.str());
  4715. return true;
  4716. }
  4717. IPTree *readWUXMLFile(const char *pattern, bool optional)
  4718. {
  4719. StringBuffer fileName;
  4720. if (!findZAPFile(pattern, optional, fileName))
  4721. return nullptr;
  4722. Owned<IPTree> tree = createPTreeFromXMLFile(fileName);
  4723. if (!tree)
  4724. throw MakeStringException(WUERR_InvalidUserInput, "Failed to retrieve %s.", pattern);
  4725. Owned<IFile> f = createIFile(fileName);
  4726. f->remove();
  4727. return tree.getClear();
  4728. }
  4729. void updateWUQueryAssociatedFilesAttrs(const char *localIP)
  4730. {
  4731. ICopyArrayOf<IPropertyTree> fileTreesToRemove;
  4732. IPropertyTree *queryAssociatedTreeRoot = wuTree->queryPropTree("Query/Associated");
  4733. Owned<IPropertyTreeIterator> itr = queryAssociatedTreeRoot->getElements("File");
  4734. ForEach (*itr)
  4735. {
  4736. IPropertyTree &fileTree = itr->query();
  4737. const char *fileName = fileTree.queryProp("@filename");
  4738. StringBuffer fileNameWithPath(unzipDir);
  4739. fileNameWithPath.append(PATHSEPSTR).append(pathTail(fileName));
  4740. if (checkFileExists(fileNameWithPath)) //Check if the ZAP report contains this file.
  4741. {
  4742. fileTree.setProp("@ip", localIP);
  4743. fileTree.setProp("@filename", fileNameWithPath);
  4744. }
  4745. else
  4746. fileTreesToRemove.append(fileTree);
  4747. }
  4748. ForEachItemIn(r, fileTreesToRemove)
  4749. queryAssociatedTreeRoot->removeTree(&fileTreesToRemove.item(r));
  4750. }
  4751. void getWUAttributes(IWorkUnit *workunit)
  4752. {
  4753. wuid.set(workunit->queryWuid());
  4754. scope.set(workunit->queryWuScope());
  4755. }
  4756. IPTree *queryWUPTree() const
  4757. {
  4758. return wuTree;
  4759. }
  4760. IPTree *queryGraphProgressPTree() const
  4761. {
  4762. return graphProgressTree;
  4763. }
  4764. void setUNZIPDir()
  4765. { //Set a unique unzip folder inside the component's data folder
  4766. unzipDir.append(importDir).append(PATHSEPSTR).append(wuid.get());
  4767. }
  4768. void unzipZAPReport()
  4769. {
  4770. Owned<IFile> unzipFolder = createIFile(unzipDir);
  4771. if (!unzipFolder->exists())
  4772. unzipFolder->createDirectory();
  4773. else
  4774. {//This should not happen. Just in case.
  4775. throw MakeStringException(WUERR_CannotImportWorkunit, "Workunit %s had been created twice and passed to import()..", wuid.get());
  4776. }
  4777. //Unzip ZAP Report
  4778. VStringBuffer zipCommand("unzip %s -d %s", zapReportFileName.get(), unzipDir.str());
  4779. if (!isEmptyString(zapReportPassword))
  4780. zipCommand.appendf(" -P %s", zapReportPassword.get());
  4781. DWORD runcode;
  4782. bool success = invoke_program(zipCommand.str(), runcode, true);
  4783. if (!success)
  4784. throw MakeStringException(WUERR_CannotImportWorkunit, "Failed in execution : %s.", zipCommand.str());
  4785. if (runcode != 0)
  4786. throw MakeStringException(WUERR_CannotImportWorkunit, "Failed in execution : %s, error(%" I64F "i)", zipCommand.str(), (unsigned __int64) runcode);
  4787. }
  4788. void buildPTreesFromZAPReport()
  4789. {
  4790. wuTree.setown(readWUXMLFile("ZAPReport_W*.xml", false));
  4791. fromWUID.set(wuTree->queryName());
  4792. wuTree->setProp("@scope", scope);
  4793. //update QueryAssociatedFiles in WU XML;
  4794. updateWUQueryAssociatedFilesAttrs(GetCachedHostName());
  4795. graphProgressTree.setown(readWUXMLFile("ZAPReport_*.graphprogress", true));
  4796. }
  4797. void updateJobName(IWorkUnit *workunit)
  4798. {
  4799. StringBuffer newJobName;
  4800. const char *jobName = workunit->queryJobName();
  4801. if (isEmptyString(jobName))
  4802. newJobName.appendf("IMPORTED from %s", fromWUID.get());
  4803. else
  4804. newJobName.appendf("IMPORTED: %s", jobName);
  4805. workunit->setJobName(newJobName);
  4806. }
  4807. void setImportDebugAttribute(IWorkUnit *workunit)
  4808. {
  4809. StringBuffer attr, importDateTime;
  4810. CDateTime dt;
  4811. dt.setNow();
  4812. dt.getString(importDateTime);
  4813. attr.append("FromWUID=").append(fromWUID).append(",");
  4814. attr.append("ImportDT=").append(importDateTime).append(",");
  4815. attr.append("ZAPReport=").append(pathTail(zapReportFileName));
  4816. workunit->setDebugValue("imported", attr, true);
  4817. }
  4818. public:
  4819. CImportWorkUnitHelper(const char *_zapReportFileName, const char *_zapReportPassword, const char *_importDir, const char *_user)
  4820. : zapReportFileName(_zapReportFileName), zapReportPassword(_zapReportPassword), importDir(_importDir), user(_user) { };
  4821. void import(IWorkUnit *workunit)
  4822. {
  4823. getWUAttributes(workunit);
  4824. setUNZIPDir();
  4825. unzipZAPReport();
  4826. buildPTreesFromZAPReport();
  4827. workunit->import(queryWUPTree(), queryGraphProgressPTree());
  4828. setImportDebugAttribute(workunit);
  4829. updateJobName(workunit);
  4830. removeFileTraceIfFail(zapReportFileName);
  4831. }
  4832. };
  4833. Owned<IWorkUnit> newWU = createWorkUnit(app, user, secMgr, secUser);
  4834. CImportWorkUnitHelper helper(zapReportFileName, zapReportPassword, importDir, user);
  4835. helper.import(newWU);
  4836. }
  4837. int CWorkUnitFactory::setTracingLevel(int newLevel)
  4838. {
  4839. if (newLevel)
  4840. DBGLOG("Setting workunit trace level to %d", newLevel);
  4841. int level = workUnitTraceLevel;
  4842. workUnitTraceLevel = newLevel;
  4843. return level;
  4844. }
  4845. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4846. {
  4847. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4848. if(!conn) return;
  4849. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  4850. KeptAtomTable entries;
  4851. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  4852. StringBuffer wuid;
  4853. for(iter->first(); iter->isValid(); iter->next())
  4854. {
  4855. char const * entry = iter->query().queryName();
  4856. if(!entries.find(entry))
  4857. {
  4858. entries.addAtom(entry);
  4859. ncnameUnescape(entry, wuid.clear());
  4860. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  4861. if(wu && (wu->getState() == WUStateWait))
  4862. wu->setState(WUStateCompleted);
  4863. }
  4864. }
  4865. bool more;
  4866. do more = root->removeProp("*"); while(more);
  4867. }
  4868. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  4869. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4870. const void *filterbuf, // (appended) string values for filters
  4871. unsigned startoffset,
  4872. unsigned maxnum,
  4873. __int64 *cachehint,
  4874. unsigned *total,
  4875. const MapStringTo<bool> *_subset,
  4876. const MapStringTo<bool> *_suspendedQueriesByCluster)
  4877. {
  4878. struct PostFilters
  4879. {
  4880. WUQueryFilterBoolean activatedFilter;
  4881. WUQueryFilterSuspended suspendedFilter;
  4882. PostFilters()
  4883. {
  4884. activatedFilter = WUQFSAll;
  4885. suspendedFilter = WUQFAllQueries;
  4886. };
  4887. } postFilters;
  4888. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  4889. {
  4890. StringAttr querySet;
  4891. StringAttr xPath;
  4892. StringAttr sortOrder;
  4893. PostFilters postFilters;
  4894. StringArray unknownAttributes;
  4895. const MapStringTo<bool> *subset;
  4896. const MapStringTo<bool> *suspendedQueriesByCluster;
  4897. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  4898. {
  4899. const char* querySetId = querySetTree->queryProp("@id");
  4900. std::unordered_set<std::string> aliasSet;
  4901. Owned<IPropertyTreeIterator> aliasIter = querySetTree->getElements("Alias");
  4902. ForEach(*aliasIter)
  4903. {
  4904. const char *id = aliasIter->query().queryProp("@id");
  4905. if (!isEmptyString(id))
  4906. aliasSet.insert(id);
  4907. }
  4908. VStringBuffer path("Query%s", xPath.get());
  4909. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  4910. ForEach(*iter)
  4911. {
  4912. IPropertyTree &query = iter->query();
  4913. bool activated = false;
  4914. const char* queryId = query.queryProp("@id");
  4915. if (queryId && *queryId)
  4916. {
  4917. if (subset)
  4918. {
  4919. VStringBuffer match("%s/%s", querySetId, queryId);
  4920. if (!subset->getValue(match))
  4921. continue;
  4922. }
  4923. if (aliasSet.find(queryId) != aliasSet.end())
  4924. activated = true;
  4925. }
  4926. if (activated && (postFilters.activatedFilter == WUQFSNo))
  4927. continue;
  4928. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  4929. continue;
  4930. bool isSuspendedByUser = query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields));
  4931. bool skip = false;
  4932. switch(postFilters.suspendedFilter)
  4933. {
  4934. case WUQFSUSPDNo:
  4935. if (isSuspendedByUser || checkSuspendedByCluster(querySetId, queryId))
  4936. skip = true;
  4937. break;
  4938. case WUQFSUSPDYes:
  4939. if (!isSuspendedByUser && !checkSuspendedByCluster(querySetId, queryId))
  4940. skip = true;
  4941. break;
  4942. case WUQFSUSPDByUser:
  4943. if (!isSuspendedByUser)
  4944. skip = true;
  4945. break;
  4946. case WUQFSUSPDByFirstNode:
  4947. case WUQFSUSPDByAnyNode:
  4948. if (!checkSuspendedByCluster(querySetId, queryId))
  4949. skip = true;
  4950. break;
  4951. }
  4952. if (skip)
  4953. continue;
  4954. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  4955. queryWithSetId->setProp("@querySetId", querySetId);
  4956. queryWithSetId->setPropBool("@activated", activated);
  4957. }
  4958. }
  4959. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  4960. {
  4961. StringBuffer querySetXPath("QuerySets");
  4962. if (!querySet.isEmpty())
  4963. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  4964. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4965. if (!conn)
  4966. return NULL;
  4967. IPropertyTree *root = conn->queryRoot()->queryBranch(nullptr);
  4968. if (querySet.isEmpty())
  4969. {
  4970. Owned<IPropertyTreeIterator> querySetIter = root->getElements("*");
  4971. ForEach(*querySetIter)
  4972. populateQueryTree(&querySetIter->query(), queryTree);
  4973. }
  4974. else
  4975. populateQueryTree(root, queryTree);
  4976. return conn.getClear();
  4977. }
  4978. bool checkSuspendedByCluster(const char *querySetId, const char *queryId)
  4979. {
  4980. if (!suspendedQueriesByCluster)
  4981. return false;
  4982. VStringBuffer match("%s/%s", querySetId, queryId);
  4983. bool *found = suspendedQueriesByCluster->getValue(match);
  4984. return (found && *found);
  4985. }
  4986. public:
  4987. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  4988. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters,
  4989. StringArray& _unknownAttributes, const MapStringTo<bool> *_subset, const MapStringTo<bool> *_suspendedQueriesByCluster)
  4990. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset), suspendedQueriesByCluster(_suspendedQueriesByCluster)
  4991. {
  4992. postFilters.activatedFilter = _postFilters.activatedFilter;
  4993. postFilters.suspendedFilter = _postFilters.suspendedFilter;
  4994. ForEachItemIn(x, _unknownAttributes)
  4995. unknownAttributes.append(_unknownAttributes.item(x));
  4996. }
  4997. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  4998. {
  4999. Owned<IPropertyTree> elementTree = createPTree("Queries");
  5000. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  5001. if (!conn)
  5002. return NULL;
  5003. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  5004. if (!iter)
  5005. return NULL;
  5006. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  5007. return conn.getClear();
  5008. }
  5009. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  5010. };
  5011. StringAttr querySet;
  5012. StringBuffer xPath;
  5013. StringBuffer so;
  5014. StringArray unknownAttributes;
  5015. if (filters)
  5016. {
  5017. const char *fv = (const char *)filterbuf;
  5018. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  5019. int fmt = filters[i];
  5020. int subfmt = (fmt&0xff);
  5021. if (subfmt==WUQSFQuerySet)
  5022. querySet.set(fv);
  5023. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  5024. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  5025. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  5026. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  5027. else if (subfmt==WUQSFActivited)
  5028. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  5029. else if (subfmt==WUQSFSuspendedFilter)
  5030. postFilters.suspendedFilter = (WUQueryFilterSuspended) atoi(fv);
  5031. else if (!fv || !*fv)
  5032. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  5033. else {
  5034. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  5035. if (fmt&WUQSFnocase)
  5036. xPath.append('?');
  5037. if (fmt&WUQSFnumeric)
  5038. xPath.append('#');
  5039. if (fmt&WUQSFwild)
  5040. xPath.append('~');
  5041. xPath.append('"').append(fv).append("\"]");
  5042. }
  5043. fv = fv + strlen(fv)+1;
  5044. }
  5045. }
  5046. if (sortorder) {
  5047. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  5048. if (so.length())
  5049. so.append(',');
  5050. int fmt = sortorder[i];
  5051. if (fmt&WUQSFreverse)
  5052. so.append('-');
  5053. if (fmt&WUQSFnocase)
  5054. so.append('?');
  5055. if (fmt&WUQSFnumeric)
  5056. so.append('#');
  5057. so.append(getEnumText(fmt&0xff,querySortFields));
  5058. }
  5059. }
  5060. IArrayOf<IPropertyTree> results;
  5061. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL,
  5062. postFilters, unknownAttributes, _subset, _suspendedQueriesByCluster);
  5063. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  5064. return new CConstQuerySetQueryIterator(results);
  5065. }
  5066. bool CWorkUnitFactory::isAborting(const char *wuid) const
  5067. {
  5068. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  5069. try
  5070. {
  5071. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5072. if (acon)
  5073. return acon->queryRoot()->getPropInt(NULL) != 0;
  5074. }
  5075. catch (IException *E)
  5076. {
  5077. EXCLOG(E);
  5078. E->Release();
  5079. }
  5080. return false;
  5081. }
  5082. void CWorkUnitFactory::clearAborting(const char *wuid)
  5083. {
  5084. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  5085. try
  5086. {
  5087. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  5088. if (acon)
  5089. acon->close(true);
  5090. }
  5091. catch (IException *E)
  5092. {
  5093. EXCLOG(E);
  5094. E->Release();
  5095. }
  5096. }
  5097. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  5098. {
  5099. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  5100. bool isEcl = false;
  5101. switch (state)
  5102. {
  5103. case WUStateAborting:
  5104. state = WUStateAborted;
  5105. break;
  5106. case WUStateCompiling:
  5107. isEcl = true;
  5108. // drop into
  5109. default:
  5110. state = WUStateFailed;
  5111. }
  5112. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  5113. wu->setState(state);
  5114. Owned<IWUException> e = wu->createException();
  5115. e->setExceptionCode(isEcl ? 1001 : 1000);
  5116. e->setExceptionMessage(isEcl ? "EclCC terminated unexpectedly" : "Workunit terminated unexpectedly");
  5117. }
  5118. static CriticalSection deleteDllLock;
  5119. static IWorkQueueThread *deleteDllWorkQ = nullptr;
  5120. MODULE_INIT(INIT_PRIORITY_STANDARD)
  5121. {
  5122. return true;
  5123. }
  5124. MODULE_EXIT()
  5125. {
  5126. CriticalBlock b(deleteDllLock);
  5127. if (deleteDllWorkQ)
  5128. ::Release(deleteDllWorkQ);
  5129. deleteDllWorkQ = nullptr;
  5130. }
  5131. static void asyncRemoveDll(const char * name)
  5132. {
  5133. CriticalBlock b(deleteDllLock);
  5134. if (!deleteDllWorkQ)
  5135. deleteDllWorkQ = createWorkQueueThread();
  5136. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  5137. }
  5138. static void asyncRemoveFile(const char * ip, const char * name)
  5139. {
  5140. CriticalBlock b(deleteDllLock);
  5141. if (!deleteDllWorkQ)
  5142. deleteDllWorkQ = createWorkQueueThread();
  5143. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  5144. }
  5145. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  5146. {
  5147. public:
  5148. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  5149. CDaliWorkUnitFactory()
  5150. {
  5151. // Assumes dali client configuration has already been done
  5152. sdsManager = &querySDS();
  5153. session = myProcessSession();
  5154. addShutdownHook(*this);
  5155. }
  5156. ~CDaliWorkUnitFactory()
  5157. {
  5158. removeShutdownHook(*this);
  5159. }
  5160. virtual bool initializeStore()
  5161. {
  5162. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5163. }
  5164. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5165. {
  5166. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  5167. }
  5168. virtual unsigned validateRepository(bool fixErrors)
  5169. {
  5170. return 0;
  5171. }
  5172. virtual void deleteRepository(bool recreate)
  5173. {
  5174. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  5175. if (conn)
  5176. conn->close(true);
  5177. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  5178. if (conn)
  5179. conn->close(true);
  5180. }
  5181. virtual void createRepository()
  5182. {
  5183. // Nothing to do
  5184. }
  5185. virtual const char *queryStoreType() const
  5186. {
  5187. return "Dali";
  5188. }
  5189. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5190. {
  5191. StringBuffer wuRoot;
  5192. getXPath(wuRoot, wuid);
  5193. IRemoteConnection *conn;
  5194. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  5195. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  5196. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  5197. conn->queryRoot()->setProp("@totalThorTime", "");
  5198. return new CDaliWorkUnit(conn, secmgr, secuser);
  5199. }
  5200. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5201. {
  5202. StringBuffer wuRoot;
  5203. getXPath(wuRoot, wuid);
  5204. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5205. if (conn)
  5206. return new CDaliWorkUnit(conn, secmgr, secuser);
  5207. else
  5208. return NULL;
  5209. }
  5210. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  5211. {
  5212. Owned<IPTree> pt(_pt);
  5213. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  5214. StringBuffer wuRoot;
  5215. getXPath(wuRoot, wuid);
  5216. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  5217. if (!conn)
  5218. {
  5219. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  5220. return false;
  5221. }
  5222. IPropertyTree *root = conn->queryRoot();
  5223. if (root->hasChildren())
  5224. {
  5225. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  5226. return false;
  5227. }
  5228. root->setPropTree(NULL, pt.getClear());
  5229. conn.clear();
  5230. // now kludge back GraphProgress
  5231. if (gprogress)
  5232. {
  5233. VStringBuffer xpath("/GraphProgress/%s", wuid);
  5234. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  5235. if (conn)
  5236. {
  5237. IPropertyTree *groot = conn->queryRoot();
  5238. if (groot->hasChildren())
  5239. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  5240. groot->setPropTree(NULL, gprogress.getClear());
  5241. }
  5242. }
  5243. return true;
  5244. }
  5245. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5246. {
  5247. StringBuffer wuRoot;
  5248. getXPath(wuRoot, wuid);
  5249. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  5250. if (conn)
  5251. return new CDaliWorkUnit(conn, secmgr, secuser);
  5252. else
  5253. return NULL;
  5254. }
  5255. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5256. {
  5257. // MORE - should it check security?
  5258. StringBuffer wuRoot;
  5259. getXPath(wuRoot, GLOBAL_WORKUNIT);
  5260. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  5261. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  5262. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  5263. return &cw->lockRemote(false);
  5264. }
  5265. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  5266. {
  5267. StringBuffer path("*");
  5268. if (owner && *owner)
  5269. path.append("[@submitID=?~\"").append(owner).append("\"]");
  5270. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5271. }
  5272. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  5273. {
  5274. StringBuffer path("*");
  5275. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  5276. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5277. }
  5278. virtual void clientShutdown();
  5279. virtual unsigned numWorkUnits()
  5280. {
  5281. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5282. if (!conn)
  5283. return 0;
  5284. IPropertyTree *root = conn->queryRoot();
  5285. return root->numChildren();
  5286. }
  5287. /**
  5288. * Add a filter to an xpath query, with the appropriate filter flags
  5289. */
  5290. static void appendFilterToQueryString(StringBuffer& query, int flags, const char* name, const char* value)
  5291. {
  5292. query.append('[').append(name).append('=');
  5293. if (flags & WUSFnocase)
  5294. query.append('?');
  5295. if (flags & WUSFwild)
  5296. query.append('~');
  5297. query.append('"').append(value).append("\"]");
  5298. };
  5299. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  5300. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5301. const void *filterbuf, // (appended) string values for filters
  5302. unsigned startoffset,
  5303. unsigned maxnum,
  5304. __int64 *cachehint,
  5305. unsigned *total,
  5306. ISecManager *secmgr,
  5307. ISecUser *secuser)
  5308. {
  5309. class CQueryOrFilter : public CInterface
  5310. {
  5311. unsigned flags;
  5312. StringAttr name;
  5313. StringArray values;
  5314. public:
  5315. IMPLEMENT_IINTERFACE;
  5316. CQueryOrFilter(unsigned _flags, const char *_name, const char *_value)
  5317. : flags(_flags), name(_name)
  5318. {
  5319. values.appendListUniq(_value, "|");
  5320. };
  5321. const char* queryName() { return name.get(); };
  5322. unsigned querySearchFlags() { return flags; };
  5323. const StringArray& queryValues() const { return values; };
  5324. };
  5325. class CMultiPTreeIterator : public CInterfaceOf<IPropertyTreeIterator>
  5326. {
  5327. public:
  5328. virtual bool first() override
  5329. {
  5330. curSource = 0;
  5331. while (sources.isItem(curSource))
  5332. {
  5333. if (sources.item(curSource).first())
  5334. return true;
  5335. curSource++;
  5336. }
  5337. return false;
  5338. }
  5339. virtual bool next() override
  5340. {
  5341. if (sources.isItem(curSource))
  5342. {
  5343. if (sources.item(curSource).next())
  5344. return true;
  5345. curSource++;
  5346. while (sources.isItem(curSource))
  5347. {
  5348. if (sources.item(curSource).first())
  5349. return true;
  5350. curSource++;
  5351. }
  5352. }
  5353. return false;
  5354. }
  5355. virtual bool isValid() override
  5356. {
  5357. return sources.isItem(curSource);
  5358. }
  5359. virtual IPropertyTree & query() override
  5360. {
  5361. return sources.item(curSource).query();
  5362. }
  5363. void addSource(IPropertyTreeIterator &source)
  5364. {
  5365. sources.append(source);
  5366. }
  5367. private:
  5368. IArrayOf<IPropertyTreeIterator> sources;
  5369. unsigned curSource = 0;
  5370. };
  5371. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  5372. {
  5373. StringAttr xPath;
  5374. StringAttr sortOrder;
  5375. StringAttr nameFilterLo;
  5376. StringAttr nameFilterHi;
  5377. StringArray unknownAttributes;
  5378. Owned<CQueryOrFilter> orFilter;
  5379. public:
  5380. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5381. CWorkUnitsPager(const char* _xPath, CQueryOrFilter* _orFilter, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  5382. : xPath(_xPath), orFilter(_orFilter), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  5383. {
  5384. ForEachItemIn(x, _unknownAttributes)
  5385. unknownAttributes.append(_unknownAttributes.item(x));
  5386. }
  5387. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5388. {
  5389. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5390. if (!conn)
  5391. return NULL;
  5392. Owned<IPropertyTreeIterator> iter;
  5393. if (!orFilter)
  5394. {
  5395. iter.setown(conn->getElements(xPath.get()));
  5396. }
  5397. else
  5398. {
  5399. Owned <CMultiPTreeIterator> multi = new CMultiPTreeIterator;
  5400. bool added = false;
  5401. const char* fieldName = orFilter->queryName();
  5402. unsigned flags = orFilter->querySearchFlags();
  5403. const StringArray& values = orFilter->queryValues();
  5404. ForEachItemIn(i, values)
  5405. {
  5406. StringBuffer path(xPath.get());
  5407. const char* value = values.item(i);
  5408. if (!isEmptyString(value))
  5409. {
  5410. appendFilterToQueryString(path, flags, fieldName, value);
  5411. IPropertyTreeIterator *itr = conn->getElements(path.str());
  5412. if (itr)
  5413. {
  5414. multi->addSource(*itr);
  5415. added = true;
  5416. }
  5417. }
  5418. }
  5419. if (added)
  5420. iter.setown(multi.getClear());
  5421. }
  5422. if (!iter)
  5423. return NULL;
  5424. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  5425. return conn.getClear();
  5426. }
  5427. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  5428. };
  5429. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  5430. {
  5431. UniqueScopes done;
  5432. ISecManager *secmgr;
  5433. ISecUser *secuser;
  5434. CriticalSection crit;
  5435. public:
  5436. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5437. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  5438. {
  5439. secmgr = _secmgr;
  5440. secuser = _secuser;
  5441. }
  5442. bool isOK(IPropertyTree &tree)
  5443. {
  5444. const char *scopename = tree.queryProp("@scope");
  5445. if (!scopename||!*scopename)
  5446. return true;
  5447. {
  5448. CriticalBlock block(crit);
  5449. const bool *b = done.getValue(scopename);
  5450. if (b)
  5451. return *b;
  5452. }
  5453. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  5454. {
  5455. // conceivably could have already been checked and added, but ok.
  5456. CriticalBlock block(crit);
  5457. done.setValue(scopename,ret);
  5458. }
  5459. return ret;
  5460. }
  5461. };
  5462. Owned<CQueryOrFilter> orFilter;
  5463. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  5464. StringBuffer query;
  5465. StringBuffer so;
  5466. StringAttr namefilter("*");
  5467. StringAttr namefilterlo;
  5468. StringAttr namefilterhi;
  5469. StringArray unknownAttributes;
  5470. if (filters)
  5471. {
  5472. const char *fv = (const char *) filterbuf;
  5473. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  5474. {
  5475. assertex(fv);
  5476. int fmt = filters[i];
  5477. int subfmt = (fmt&0xff);
  5478. if (subfmt==WUSFwuid)
  5479. namefilterlo.set(fv);
  5480. else if (subfmt==WUSFwuidhigh)
  5481. namefilterhi.set(fv);
  5482. else if (subfmt==WUSFwildwuid)
  5483. namefilter.set(fv);
  5484. else if (subfmt==WUSFappvalue)
  5485. {
  5486. const char *app = fv;
  5487. fv = fv + strlen(fv)+1;
  5488. query.append("[Application/").append(app);
  5489. if (*fv)
  5490. query.append("=?~\"").append(fv).append('\"');
  5491. query.append("]");
  5492. }
  5493. else if (subfmt==WUSFtotalthortime)
  5494. {
  5495. query.append("[@totalThorTime>=\"");
  5496. formatTimeCollatable(query, milliToNano(atoi(fv)), false);
  5497. query.append("\"]");
  5498. }
  5499. else if (!*fv)
  5500. {
  5501. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  5502. if (subfmt==WUSFtotalthortime)
  5503. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5504. }
  5505. else
  5506. {
  5507. const char* fieldName = getEnumText(subfmt,workunitSortFields);
  5508. if (!strchr(fv, '|'))
  5509. appendFilterToQueryString(query, fmt, fieldName, fv);
  5510. else if (orFilter)
  5511. throw MakeStringException(WUERR_InvalidUserInput, "Multiple OR filters not allowed");
  5512. else
  5513. {
  5514. if (!strieq(fieldName, getEnumText(WUSFstate,workunitSortFields)) &&
  5515. !strieq(fieldName, getEnumText(WUSFuser,workunitSortFields)) &&
  5516. !strieq(fieldName, getEnumText(WUSFcluster,workunitSortFields)))
  5517. throw MakeStringException(WUERR_InvalidUserInput, "OR filters not allowed for %s", fieldName);
  5518. orFilter.setown(new CQueryOrFilter(fmt, fieldName, fv));
  5519. }
  5520. }
  5521. fv = fv + strlen(fv)+1;
  5522. }
  5523. }
  5524. if ((sortorder&0xff)==WUSFtotalthortime)
  5525. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5526. query.insert(0, namefilter.get());
  5527. if (sortorder)
  5528. {
  5529. if (so.length())
  5530. so.append(',');
  5531. if (sortorder & WUSFreverse)
  5532. so.append('-');
  5533. if (sortorder & WUSFnocase)
  5534. so.append('?');
  5535. if (sortorder & WUSFnumeric)
  5536. so.append('#');
  5537. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  5538. }
  5539. IArrayOf<IPropertyTree> results;
  5540. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), orFilter.getClear(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  5541. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  5542. return new CConstWUArrayIterator(results);
  5543. }
  5544. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5545. {
  5546. WUState ret = WUStateUnknown;
  5547. StringBuffer wuRoot;
  5548. getXPath(wuRoot, wuid);
  5549. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5550. if (timeout == 0) //no need to subscribe
  5551. {
  5552. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5553. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5554. if (it != expectedStates.end())
  5555. return ret;
  5556. switch (ret)
  5557. {
  5558. case WUStateCompiled:
  5559. case WUStateUploadingFiles:
  5560. if (!compiled)
  5561. break;
  5562. //fall through
  5563. case WUStateCompleted:
  5564. case WUStateFailed:
  5565. case WUStateAborted:
  5566. return ret;
  5567. default:
  5568. break;
  5569. }
  5570. return WUStateUnknown;
  5571. }
  5572. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  5573. LocalIAbortHandler abortHandler(*waiter);
  5574. if (conn)
  5575. {
  5576. SessionId agent = -1;
  5577. bool agentSessionStopped = false;
  5578. unsigned start = msTick();
  5579. for (;;)
  5580. {
  5581. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5582. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5583. if (it != expectedStates.end())
  5584. return ret;
  5585. switch (ret)
  5586. {
  5587. case WUStateCompiled:
  5588. case WUStateUploadingFiles:
  5589. if (!compiled)
  5590. break;
  5591. // fall into
  5592. case WUStateCompleted:
  5593. case WUStateFailed:
  5594. case WUStateAborted:
  5595. return ret;
  5596. case WUStateWait:
  5597. break;
  5598. case WUStateCompiling:
  5599. case WUStateRunning:
  5600. case WUStateDebugPaused:
  5601. case WUStateDebugRunning:
  5602. case WUStateBlocked:
  5603. case WUStateAborting:
  5604. if (agentSessionStopped)
  5605. {
  5606. reportAbnormalTermination(wuid, ret, agent);
  5607. return ret;
  5608. }
  5609. if (queryDaliServerVersion().compare("2.1")>=0)
  5610. {
  5611. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  5612. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  5613. {
  5614. agentSessionStopped = true;
  5615. conn->reload();
  5616. continue;
  5617. }
  5618. }
  5619. break;
  5620. }
  5621. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  5622. unsigned waited = msTick() - start;
  5623. if (timeout==-1 || waited + 20000 < timeout)
  5624. {
  5625. waiter->wait(20000); // recheck state every 20 seconds, in case eclagent has crashed.
  5626. if (waiter->isAborted())
  5627. {
  5628. ret = WUStateUnknown; // MORE - throw an exception?
  5629. break;
  5630. }
  5631. }
  5632. else if (waited > timeout || !waiter->wait(timeout-waited))
  5633. {
  5634. ret = WUStateUnknown; // MORE - throw an exception?
  5635. break;
  5636. }
  5637. conn->reload();
  5638. }
  5639. }
  5640. return ret;
  5641. }
  5642. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5643. {
  5644. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  5645. LocalIAbortHandler abortHandler(*waiter);
  5646. WUAction ret = WUActionUnknown;
  5647. StringBuffer wuRoot;
  5648. getXPath(wuRoot, wuid);
  5649. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5650. if (conn)
  5651. {
  5652. unsigned start = msTick();
  5653. for (;;)
  5654. {
  5655. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  5656. if (ret != original)
  5657. break;
  5658. unsigned waited = msTick() - start;
  5659. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  5660. if (waiter->isAborted())
  5661. {
  5662. ret = WUActionUnknown; // MORE - throw an exception?
  5663. break;
  5664. }
  5665. conn->reload();
  5666. }
  5667. }
  5668. waiter->unsubscribe();
  5669. return ret;
  5670. }
  5671. protected:
  5672. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  5673. {
  5674. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5675. if (conn)
  5676. {
  5677. CDaliVersion serverVersionNeeded("3.2");
  5678. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  5679. conn->queryRoot()->getElements(xpath) :
  5680. conn->getElements(xpath));
  5681. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  5682. }
  5683. else
  5684. return NULL;
  5685. }
  5686. ISDSManager *sdsManager;
  5687. SessionId session;
  5688. };
  5689. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5690. {
  5691. if (secmgr)
  5692. return new CSecureConstWUIterator(iter, secmgr, secuser);
  5693. else
  5694. return iter;
  5695. }
  5696. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5697. {
  5698. if (secmgr)
  5699. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  5700. else
  5701. return new CConstWUIterator(iter);
  5702. }
  5703. static CriticalSection factoryCrit;
  5704. static Owned<IWorkUnitFactory> factory;
  5705. void CDaliWorkUnitFactory::clientShutdown()
  5706. {
  5707. CriticalBlock b(factoryCrit);
  5708. factory.clear();
  5709. }
  5710. void clientShutdownWorkUnit()
  5711. {
  5712. CriticalBlock b(factoryCrit);
  5713. factory.clear();
  5714. }
  5715. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  5716. {
  5717. CriticalBlock b(factoryCrit);
  5718. factory.setown(_factory);
  5719. }
  5720. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  5721. {
  5722. if (!factory)
  5723. {
  5724. CriticalBlock b(factoryCrit);
  5725. 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.
  5726. {
  5727. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  5728. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  5729. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5730. IPropertyTree *pluginInfo = NULL;
  5731. if (env)
  5732. {
  5733. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  5734. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  5735. if (daliInfo)
  5736. {
  5737. const char *daliName = daliInfo->queryProp("@name");
  5738. if (daliName)
  5739. {
  5740. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  5741. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  5742. }
  5743. if (!pluginInfo)
  5744. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  5745. }
  5746. }
  5747. if (pluginInfo && !forceDali)
  5748. factory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  5749. else
  5750. factory.setown(new CDaliWorkUnitFactory());
  5751. }
  5752. }
  5753. return factory.getLink();
  5754. }
  5755. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  5756. {
  5757. if (!factory)
  5758. {
  5759. CriticalBlock b(factoryCrit);
  5760. 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.
  5761. factory.setown(new CDaliWorkUnitFactory());
  5762. }
  5763. return factory.getLink();
  5764. }
  5765. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  5766. // They can still be supplied if you want...
  5767. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  5768. {
  5769. public:
  5770. IMPLEMENT_IINTERFACE;
  5771. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  5772. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  5773. {
  5774. }
  5775. virtual bool initializeStore()
  5776. {
  5777. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5778. }
  5779. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5780. {
  5781. return baseFactory->getWatcher(subscriber, options, wuid);
  5782. }
  5783. virtual unsigned validateRepository(bool fix)
  5784. {
  5785. return baseFactory->validateRepository(fix);
  5786. }
  5787. virtual void deleteRepository(bool recreate)
  5788. {
  5789. return baseFactory->deleteRepository(recreate);
  5790. }
  5791. virtual void createRepository()
  5792. {
  5793. return baseFactory->createRepository();
  5794. }
  5795. virtual const char *queryStoreType() const
  5796. {
  5797. return baseFactory->queryStoreType();
  5798. }
  5799. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  5800. {
  5801. return baseFactory->getUniqueValues(field, prefix, result);
  5802. }
  5803. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5804. {
  5805. if (!secMgr) secMgr = defaultSecMgr.get();
  5806. if (!secUser) secUser = defaultSecUser.get();
  5807. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  5808. }
  5809. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5810. {
  5811. if (!secMgr) secMgr = defaultSecMgr.get();
  5812. if (!secUser) secUser = defaultSecUser.get();
  5813. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  5814. }
  5815. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  5816. {
  5817. if (!secMgr) secMgr = defaultSecMgr.get();
  5818. if (!secUser) secUser = defaultSecUser.get();
  5819. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  5820. }
  5821. virtual bool deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secMgr, ISecUser *secUser)
  5822. {
  5823. if (!secMgr) secMgr = defaultSecMgr.get();
  5824. if (!secUser) secUser = defaultSecUser.get();
  5825. return baseFactory->deleteWorkUnitEx(wuid, throwException, secMgr, secUser);
  5826. }
  5827. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5828. {
  5829. if (!secMgr) secMgr = defaultSecMgr.get();
  5830. if (!secUser) secUser = defaultSecUser.get();
  5831. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  5832. }
  5833. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5834. {
  5835. if (!secMgr) secMgr = defaultSecMgr.get();
  5836. if (!secUser) secUser = defaultSecUser.get();
  5837. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  5838. }
  5839. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  5840. {
  5841. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  5842. }
  5843. virtual void importWorkUnit(const char *zapReportFileName, const char *zapReportPassword,
  5844. const char *importDir, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5845. {
  5846. baseFactory->importWorkUnit(zapReportFileName, zapReportPassword, importDir, app, user, secMgr, secUser);
  5847. }
  5848. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  5849. {
  5850. if (!secMgr) secMgr = defaultSecMgr.get();
  5851. if (!secUser) secUser = defaultSecUser.get();
  5852. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  5853. }
  5854. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  5855. {
  5856. if (!secMgr) secMgr = defaultSecMgr.get();
  5857. if (!secUser) secUser = defaultSecUser.get();
  5858. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  5859. }
  5860. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5861. {
  5862. if (!secMgr) secMgr = defaultSecMgr.get();
  5863. if (!secUser) secUser = defaultSecUser.get();
  5864. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  5865. }
  5866. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5867. {
  5868. if (!secMgr) secMgr = defaultSecMgr.get();
  5869. if (!secUser) secUser = defaultSecUser.get();
  5870. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  5871. }
  5872. virtual int setTracingLevel(int newLevel)
  5873. {
  5874. return baseFactory->setTracingLevel(newLevel);
  5875. }
  5876. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  5877. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5878. const void *filterbuf, // (appended) string values for filters
  5879. unsigned startoffset,
  5880. unsigned maxnum,
  5881. __int64 *cachehint,
  5882. unsigned *total,
  5883. ISecManager *secMgr, ISecUser *secUser)
  5884. {
  5885. if (!secMgr) secMgr = defaultSecMgr.get();
  5886. if (!secUser) secUser = defaultSecUser.get();
  5887. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  5888. }
  5889. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  5890. WUQuerySortField *filters,
  5891. const void *filterbuf,
  5892. unsigned startoffset,
  5893. unsigned maxnum,
  5894. __int64 *cachehint,
  5895. unsigned *total,
  5896. const MapStringTo<bool> *subset,
  5897. const MapStringTo<bool> *suspendedByCluster)
  5898. {
  5899. // MORE - why no security?
  5900. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset,suspendedByCluster);
  5901. }
  5902. virtual unsigned numWorkUnits()
  5903. {
  5904. return baseFactory->numWorkUnits();
  5905. }
  5906. virtual bool isAborting(const char *wuid) const
  5907. {
  5908. return baseFactory->isAborting(wuid);
  5909. }
  5910. virtual void clearAborting(const char *wuid)
  5911. {
  5912. baseFactory->clearAborting(wuid);
  5913. }
  5914. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5915. {
  5916. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, expectedStates);
  5917. }
  5918. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5919. {
  5920. return baseFactory->waitForWorkUnitAction(wuid, original);
  5921. }
  5922. private:
  5923. Owned<IWorkUnitFactory> baseFactory;
  5924. Linked<ISecManager> defaultSecMgr;
  5925. Linked<ISecUser> defaultSecUser;
  5926. };
  5927. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  5928. {
  5929. if (secmgr && secuser)
  5930. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  5931. else
  5932. return getWorkUnitFactory();
  5933. }
  5934. //==========================================================================================
  5935. class CStringPTreeIterator : implements IStringIterator, public CInterface
  5936. {
  5937. Owned<IPropertyTreeIterator> it;
  5938. public:
  5939. IMPLEMENT_IINTERFACE;
  5940. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  5941. virtual bool first() { return it->first(); }
  5942. virtual bool next() { return it->next(); }
  5943. virtual bool isValid() { return it->isValid(); }
  5944. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  5945. };
  5946. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  5947. {
  5948. Owned<IPropertyTreeIterator> it;
  5949. public:
  5950. IMPLEMENT_IINTERFACE;
  5951. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  5952. virtual bool first() { return it->first(); }
  5953. virtual bool next() { return it->next(); }
  5954. virtual bool isValid() { return it->isValid(); }
  5955. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  5956. };
  5957. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  5958. {
  5959. Owned<IPropertyTreeIterator> it;
  5960. StringAttr name;
  5961. public:
  5962. IMPLEMENT_IINTERFACE;
  5963. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  5964. virtual bool first() { return it->first(); }
  5965. virtual bool next() { return it->next(); }
  5966. virtual bool isValid() { return it->isValid(); }
  5967. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  5968. };
  5969. //==========================================================================================
  5970. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5971. {
  5972. clearCached(false);
  5973. secMgr.set(secmgr);
  5974. secUser.set(secuser);
  5975. workflowIteratorCached = false;
  5976. resultsCached = false;
  5977. graphsCached = false;
  5978. temporariesCached = false;
  5979. variablesCached = false;
  5980. exceptionsCached = false;
  5981. pluginsCached = false;
  5982. librariesCached = false;
  5983. activitiesCached = false;
  5984. webServicesInfoCached = false;
  5985. roxieQueryInfoCached = false;
  5986. }
  5987. void CLocalWorkUnit::clearCached(bool clearTree)
  5988. {
  5989. query.clear();
  5990. webServicesInfo.clear();
  5991. workflowIterator.clear();
  5992. graphs.kill();
  5993. results.kill();
  5994. variables.kill();
  5995. plugins.kill();
  5996. libraries.kill();
  5997. exceptions.kill();
  5998. temporaries.kill();
  5999. statistics.kill();
  6000. appvalues.kill();
  6001. if (clearTree)
  6002. p.clear();
  6003. workflowIteratorCached = false;
  6004. resultsCached = false;
  6005. graphsCached = false;
  6006. temporariesCached = false;
  6007. variablesCached = false;
  6008. exceptionsCached = false;
  6009. pluginsCached = false;
  6010. librariesCached = false;
  6011. activitiesCached = false;
  6012. webServicesInfoCached = false;
  6013. roxieQueryInfoCached = false;
  6014. }
  6015. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  6016. {
  6017. clearCached(false);
  6018. p.setown(ptree);
  6019. }
  6020. void CLocalWorkUnit::beforeDispose()
  6021. {
  6022. try
  6023. {
  6024. unsubscribe();
  6025. clearCached(true);
  6026. userDesc.clear();
  6027. secMgr.clear();
  6028. secUser.clear();
  6029. }
  6030. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  6031. }
  6032. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  6033. {
  6034. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  6035. // Delete any related things in SDS etc that might otherwise be forgotten
  6036. if (p->getPropBool("@protected", false))
  6037. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  6038. switch (getState())
  6039. {
  6040. case WUStateAborted:
  6041. case WUStateCompleted:
  6042. case WUStateFailed:
  6043. case WUStateArchived:
  6044. break;
  6045. case WUStateCompiled:
  6046. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  6047. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  6048. break;
  6049. case WUStateWait:
  6050. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  6051. default:
  6052. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  6053. break;
  6054. }
  6055. if (getIsQueryService())
  6056. {
  6057. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  6058. if (registry)
  6059. {
  6060. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  6061. if (registry->hasProp(xpath.str()))
  6062. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  6063. }
  6064. }
  6065. try
  6066. {
  6067. if (deldll && !p->getPropBool("@isClone", false))
  6068. {
  6069. Owned<IConstWUQuery> q = getQuery();
  6070. if (q)
  6071. {
  6072. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  6073. SCMStringBuffer name;
  6074. ForEach(*iter)
  6075. {
  6076. IConstWUAssociatedFile & cur = iter->query();
  6077. cur.getNameTail(name);
  6078. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  6079. {
  6080. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  6081. if (entry.get())
  6082. asyncRemoveDll(name.str());
  6083. else
  6084. {
  6085. SCMStringBuffer ip, localPath;
  6086. cur.getName(localPath);
  6087. cur.getIp(ip);
  6088. asyncRemoveFile(ip.str(), localPath.str());
  6089. }
  6090. }
  6091. }
  6092. }
  6093. }
  6094. factory->clearAborting(queryWuid());
  6095. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  6096. }
  6097. catch(IException *E)
  6098. {
  6099. StringBuffer s;
  6100. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  6101. E->Release();
  6102. }
  6103. catch (...)
  6104. {
  6105. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  6106. }
  6107. }
  6108. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  6109. {
  6110. SCMStringBuffer strval;
  6111. val.getGmtString(strval);
  6112. p->setProp("@timescheduled",strval.str());
  6113. }
  6114. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  6115. {
  6116. StringBuffer str;
  6117. p->getProp("@timescheduled",str);
  6118. if(str.length())
  6119. val.setGmtString(str.str());
  6120. return val;
  6121. }
  6122. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  6123. {
  6124. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  6125. if (extra.length())
  6126. {
  6127. const char *bufStart = buf.str();
  6128. const char *bufPtr = bufStart+buf.length();
  6129. while (bufStart != bufPtr)
  6130. {
  6131. --bufPtr;
  6132. if (!isspace(*bufPtr))
  6133. break;
  6134. }
  6135. assertex('>' == *bufPtr);
  6136. size_t l = strlen(wuid);
  6137. assertex((size_t)(bufPtr-bufStart) > l+2); // e.g. at least </W20171111-111111>
  6138. bufPtr -= l+2; // skip back over </wuid
  6139. assertex(0 == memcmp(bufPtr, "</", 2) );
  6140. assertex(0 == memcmp(bufPtr+2, wuid, l));
  6141. buf.insert(bufPtr-bufStart, extra);
  6142. }
  6143. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  6144. }
  6145. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  6146. {
  6147. CriticalBlock block(crit);
  6148. StringBuffer path(base);
  6149. if (!p)
  6150. return false;
  6151. const char *wuid = p->queryName();
  6152. if (!wuid||!*wuid)
  6153. return false;
  6154. addPathSepChar(path).append(wuid).append(".xml");
  6155. Owned<IFile> file = createIFile(path.str());
  6156. if (!file)
  6157. return false;
  6158. Owned<IFileIO> fileio = file->open(IFOcreate);
  6159. if (!fileio)
  6160. return false;
  6161. StringBuffer buf;
  6162. exportWorkUnitToXML(this, buf, false, false, true);
  6163. StringBuffer extraWorkUnitXML;
  6164. Owned<IPTree> graphProgress = getGraphProgressTree();
  6165. if (graphProgress)
  6166. {
  6167. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  6168. graphProgress.clear();
  6169. }
  6170. Owned<IConstWUQuery> q = getQuery();
  6171. if (!q)
  6172. {
  6173. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  6174. return false;
  6175. if (del)
  6176. {
  6177. if (getState()==WUStateUnknown)
  6178. setState(WUStateArchived); // to allow delete
  6179. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  6180. }
  6181. return false;
  6182. }
  6183. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  6184. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  6185. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  6186. ForEach(*iter)
  6187. {
  6188. IConstWUAssociatedFile & cur = iter->query();
  6189. SCMStringBuffer name;
  6190. cur.getNameTail(name);
  6191. if (name.length())
  6192. {
  6193. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  6194. SCMStringBuffer curPath, curIp;
  6195. cur.getName(curPath);
  6196. cur.getIp(curIp);
  6197. SocketEndpoint curEp(curIp.str());
  6198. RemoteFilename curRfn;
  6199. curRfn.setPath(curEp, curPath.str());
  6200. StringBuffer dst(base);
  6201. addPathSepChar(dst);
  6202. curRfn.getTail(dst);
  6203. Owned<IFile> dstFile = createIFile(dst.str());
  6204. if (entry.get())
  6205. {
  6206. Owned<IException> exception;
  6207. Owned<IDllLocation> loc;
  6208. Owned<IPropertyTree> generatedDllBranch = createPTree();
  6209. generatedDllBranch->setProp("@name", entry->queryName());
  6210. generatedDllBranch->setProp("@kind", entry->queryKind());
  6211. if (exportAssociatedFiles)
  6212. {
  6213. try
  6214. {
  6215. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  6216. }
  6217. catch(IException * e)
  6218. {
  6219. exception.setown(e);
  6220. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  6221. }
  6222. RemoteFilename filename;
  6223. loc->getDllFilename(filename);
  6224. if (!exception)
  6225. {
  6226. Owned<IFile> srcfile = createIFile(filename);
  6227. try
  6228. {
  6229. if (dstFile->exists())
  6230. {
  6231. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  6232. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  6233. // still want to delete if already archived but there are source file copies
  6234. }
  6235. else
  6236. copyFile(dstFile, srcfile);
  6237. }
  6238. catch(IException * e)
  6239. {
  6240. exception.setown(e);
  6241. }
  6242. }
  6243. if (exception)
  6244. {
  6245. if (ignoredllerrors)
  6246. {
  6247. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  6248. //copy failed, so don't delete the registered dll files
  6249. deleteExclusions.append(name.str());
  6250. }
  6251. else
  6252. throw exception.getClear();
  6253. }
  6254. }
  6255. // Record Associated path to restore back to
  6256. StringBuffer restorePath;
  6257. curRfn.getRemotePath(restorePath);
  6258. generatedDllBranch->setProp("@location", restorePath.str());
  6259. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  6260. }
  6261. else if (exportAssociatedFiles) // no generated dll entry
  6262. {
  6263. Owned<IFile> srcFile = createIFile(curRfn);
  6264. try
  6265. {
  6266. copyFile(dstFile, srcFile);
  6267. }
  6268. catch (IException *e)
  6269. {
  6270. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  6271. EXCLOG(e, msg.str());
  6272. e->Release();
  6273. deleteExclusions.append(name.str());
  6274. }
  6275. }
  6276. }
  6277. }
  6278. iter.clear();
  6279. if (generatedDlls->numChildren())
  6280. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  6281. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  6282. return false;
  6283. if (del)
  6284. {
  6285. //setState(WUStateArchived); // this isn't useful as about to delete it!
  6286. q.clear();
  6287. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  6288. }
  6289. return true;
  6290. }
  6291. void CLocalWorkUnit::loadXML(const char *xml)
  6292. {
  6293. CriticalBlock block(crit);
  6294. clearCached(true);
  6295. assertex(xml);
  6296. p.setown(createPTreeFromXMLString(xml,ipt_lowmem));
  6297. }
  6298. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  6299. {
  6300. CriticalBlock block(crit);
  6301. StringBuffer x;
  6302. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  6303. }
  6304. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  6305. {
  6306. CriticalBlock block(crit);
  6307. StringAttr value;
  6308. src.read(value);
  6309. loadXML(value);
  6310. }
  6311. void CLocalWorkUnit::requestAbort()
  6312. {
  6313. CriticalBlock block(crit);
  6314. abortWorkUnit(p->queryName());
  6315. }
  6316. void CLocalWorkUnit::unlockRemote()
  6317. {
  6318. CriticalBlock block(crit);
  6319. locked.unlock();
  6320. _unlockRemote();
  6321. }
  6322. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  6323. {
  6324. if (secMgr)
  6325. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  6326. locked.lock();
  6327. CriticalBlock block(crit);
  6328. if (commit)
  6329. {
  6330. try
  6331. {
  6332. _lockRemote();
  6333. }
  6334. catch (IException *E)
  6335. {
  6336. StringBuffer s;
  6337. IERRLOG("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  6338. locked.unlock();
  6339. throw;
  6340. }
  6341. }
  6342. return *new CLockedWorkUnit(LINK(this));
  6343. }
  6344. void CLocalWorkUnit::commit()
  6345. {
  6346. // Nothing to do if not backed by a persistent store
  6347. }
  6348. IWorkUnit& CLocalWorkUnit::lock()
  6349. {
  6350. return lockRemote(true);
  6351. }
  6352. const char *CLocalWorkUnit::queryWuid() const
  6353. {
  6354. CriticalBlock block(crit);
  6355. return p->queryName();
  6356. }
  6357. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  6358. {
  6359. CriticalBlock block(crit);
  6360. return p->getPropInt("@DebugListenerPort", 0);
  6361. }
  6362. unsigned CLocalWorkUnit::getTotalThorTime() const
  6363. {
  6364. CriticalBlock block(crit);
  6365. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  6366. }
  6367. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  6368. {
  6369. CriticalBlock block(crit);
  6370. p->setPropInt("@DebugListenerPort", port);
  6371. }
  6372. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  6373. {
  6374. CriticalBlock block(crit);
  6375. ip.set(p->queryProp("@DebugListenerIP"));
  6376. return ip;
  6377. }
  6378. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  6379. {
  6380. CriticalBlock block(crit);
  6381. p->setProp("@DebugListenerIP", ip);
  6382. }
  6383. IStringVal & CLocalWorkUnit::getWorkunitDistributedAccessToken(IStringVal & datoken) const
  6384. {
  6385. CriticalBlock block(crit);
  6386. datoken.set(p->queryProp("@distributedAccessToken"));
  6387. return datoken;
  6388. }
  6389. bool CLocalWorkUnit::setDistributedAccessToken(const char * user)
  6390. {
  6391. CriticalBlock block(crit);
  6392. //If this format changes, you must update the isWorkunitDAToken() and extractFromWorkunitDAToken() methods
  6393. VStringBuffer datoken("HPCC[u=%s,w=%s]", user, queryWuid());
  6394. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6395. if (pDSM && pDSM->isDigiSignerConfigured())
  6396. {
  6397. datoken.append(pDSM->queryKeyName()).append(';');
  6398. StringBuffer b64Signature;
  6399. if (pDSM->digiSign(b64Signature, datoken))
  6400. {
  6401. datoken.append(b64Signature.str());
  6402. }
  6403. else
  6404. {
  6405. ERRLOG("Cannot create workunit Distributed Access Token, digisign failed");
  6406. return false;
  6407. }
  6408. }
  6409. else
  6410. {
  6411. WARNLOG("Cannot sign Distributed Access Token, digisign signing not configured");
  6412. datoken.append(";");
  6413. }
  6414. p->setProp("@distributedAccessToken", datoken);
  6415. return true;
  6416. }
  6417. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  6418. {
  6419. // Only implemented in derived classes
  6420. return false;
  6421. }
  6422. void CLocalWorkUnit::setJobName(const char *value)
  6423. {
  6424. CriticalBlock block(crit);
  6425. p->setProp("@jobName", value);
  6426. }
  6427. const char *CLocalWorkUnit::queryJobName() const
  6428. {
  6429. CriticalBlock block(crit);
  6430. const char *ret = p->queryProp("@jobName");
  6431. if (!ret)
  6432. ret = "";
  6433. return ret;
  6434. }
  6435. void CLocalWorkUnit::setClusterName(const char *value)
  6436. {
  6437. CriticalBlock block(crit);
  6438. p->setProp("@clusterName", value);
  6439. }
  6440. const char *CLocalWorkUnit::queryClusterName() const
  6441. {
  6442. CriticalBlock block(crit);
  6443. const char *ret = p->queryProp("@clusterName");
  6444. if (!ret)
  6445. ret = "";
  6446. return ret;
  6447. }
  6448. void CLocalWorkUnit::setAllowedClusters(const char *value)
  6449. {
  6450. setDebugValue("allowedclusters",value, true);
  6451. }
  6452. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  6453. {
  6454. CriticalBlock block(crit);
  6455. getDebugValue("allowedclusters",str);
  6456. if (str.length()!=0)
  6457. return str;
  6458. str.set(p->queryProp("@clusterName"));
  6459. return str;
  6460. }
  6461. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  6462. {
  6463. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  6464. }
  6465. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  6466. {
  6467. CriticalBlock block(crit);
  6468. return getDebugValueBool("allowautoqueueswitch",false);
  6469. }
  6470. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  6471. {
  6472. StringBuffer suffix;
  6473. if (name && *name)
  6474. setApplicationValue("LibraryModule", "name", name, true);
  6475. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  6476. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  6477. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  6478. }
  6479. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  6480. {
  6481. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  6482. if (writeaccess)
  6483. auditflags |= DALI_LDAP_WRITE_WANTED;
  6484. SecAccessFlags perm = SecAccess_Full;
  6485. const char *scopename = p->queryProp("@scope");
  6486. if (scopename&&*scopename) {
  6487. if (!user)
  6488. user = queryUserDescriptor();
  6489. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  6490. if (perm<0) {
  6491. if (perm == SecAccess_Unavailable)
  6492. perm = SecAccess_Full;
  6493. else
  6494. perm = SecAccess_None;
  6495. }
  6496. }
  6497. if (!HASREADPERMISSION(perm))
  6498. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  6499. if (writeaccess && !HASWRITEPERMISSION(perm))
  6500. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  6501. }
  6502. void CLocalWorkUnit::setUser(const char * value)
  6503. {
  6504. CriticalBlock block(crit);
  6505. p->setProp("@submitID", value);
  6506. }
  6507. const char *CLocalWorkUnit::queryUser() const
  6508. {
  6509. CriticalBlock block(crit);
  6510. const char *ret = p->queryProp("@submitID");
  6511. if (!ret)
  6512. ret = "";
  6513. return ret;
  6514. }
  6515. void CLocalWorkUnit::setWuScope(const char * value)
  6516. {
  6517. if (value && *value)
  6518. {
  6519. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  6520. {
  6521. CriticalBlock block(crit);
  6522. p->setProp("@scope", value);
  6523. }
  6524. }
  6525. }
  6526. const char *CLocalWorkUnit::queryWuScope() const
  6527. {
  6528. CriticalBlock block(crit);
  6529. const char *ret = p->queryProp("@scope");
  6530. if (!ret)
  6531. ret = "";
  6532. return ret;
  6533. }
  6534. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  6535. {
  6536. CriticalBlock block(crit);
  6537. setEnum(p, "@priorityClass", cls, priorityClasses);
  6538. }
  6539. WUPriorityClass CLocalWorkUnit::getPriority() const
  6540. {
  6541. CriticalBlock block(crit);
  6542. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  6543. }
  6544. const char *CLocalWorkUnit::queryPriorityDesc() const
  6545. {
  6546. return getEnumText(getPriority(), priorityClasses);
  6547. }
  6548. void CLocalWorkUnit::setState(WUState value)
  6549. {
  6550. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  6551. {
  6552. if (factory)
  6553. factory->clearAborting(queryWuid());
  6554. }
  6555. CriticalBlock block(crit);
  6556. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  6557. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  6558. if (getDebugValueBool("monitorWorkunit", false))
  6559. {
  6560. switch(value)
  6561. {
  6562. case WUStateAborted:
  6563. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  6564. break;
  6565. case WUStateCompleted:
  6566. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  6567. break;
  6568. case WUStateFailed:
  6569. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  6570. break;
  6571. }
  6572. }
  6573. p->removeProp("@stateEx");
  6574. }
  6575. void CLocalWorkUnit::setStateEx(const char * text)
  6576. {
  6577. CriticalBlock block(crit);
  6578. p->setProp("@stateEx", text);
  6579. }
  6580. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  6581. {
  6582. CriticalBlock block(crit);
  6583. p->setPropInt64("@agentSession", sessionId);
  6584. }
  6585. bool CLocalWorkUnit::getIsQueryService() const
  6586. {
  6587. CriticalBlock block(crit);
  6588. return p->getPropBool("@isQueryService", false);
  6589. }
  6590. void CLocalWorkUnit::setIsQueryService(bool value)
  6591. {
  6592. CriticalBlock block(crit);
  6593. p->setPropBool("@isQueryService", value);
  6594. }
  6595. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  6596. {
  6597. if (queryDaliServerVersion().compare("2.1")<0)
  6598. return;
  6599. switch(state)
  6600. {
  6601. case WUStateRunning:
  6602. case WUStateDebugPaused:
  6603. case WUStateDebugRunning:
  6604. case WUStateBlocked:
  6605. case WUStateAborting:
  6606. case WUStateCompiling:
  6607. case WUStatePaused:
  6608. {
  6609. SessionId agent = getAgentSession();
  6610. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  6611. {
  6612. forceReload();
  6613. state = (WUState) getEnum(p, "@state", states);
  6614. bool isecl=state==WUStateCompiling;
  6615. if (aborting())
  6616. state = WUStateAborted;
  6617. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  6618. state = WUStateFailed;
  6619. else
  6620. return;
  6621. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  6622. Owned<IWorkUnit> w = &lock();
  6623. w->setState(state);
  6624. Owned<IWUException> e = w->createException();
  6625. WUAction action = w->getAction();
  6626. switch (action)
  6627. {
  6628. case WUActionPause:
  6629. case WUActionPauseNow:
  6630. case WUActionResume:
  6631. w->setAction(WUActionUnknown);
  6632. }
  6633. if(isecl)
  6634. {
  6635. e->setExceptionCode(1001);
  6636. e->setExceptionMessage("EclServer terminated unexpectedly");
  6637. }
  6638. else
  6639. {
  6640. e->setExceptionCode(1000);
  6641. e->setExceptionMessage("Workunit terminated unexpectedly");
  6642. }
  6643. }
  6644. }
  6645. }
  6646. }
  6647. WUState CLocalWorkUnit::getState() const
  6648. {
  6649. CriticalBlock block(crit);
  6650. WUState state = (WUState) getEnum(p, "@state", states);
  6651. switch (state)
  6652. {
  6653. case WUStateRunning:
  6654. case WUStateDebugPaused:
  6655. case WUStateDebugRunning:
  6656. case WUStateBlocked:
  6657. case WUStateCompiling:
  6658. if (aborting())
  6659. state = WUStateAborting;
  6660. break;
  6661. case WUStateSubmitted:
  6662. if (aborting())
  6663. state = WUStateAborted;
  6664. break;
  6665. }
  6666. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  6667. return state;
  6668. }
  6669. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  6670. {
  6671. CriticalBlock block(crit);
  6672. str.set(p->queryProp("@stateEx"));
  6673. return str;
  6674. }
  6675. __int64 CLocalWorkUnit::getAgentSession() const
  6676. {
  6677. CriticalBlock block(crit);
  6678. return p->getPropInt64("@agentSession", -1);
  6679. }
  6680. unsigned CLocalWorkUnit::getAgentPID() const
  6681. {
  6682. CriticalBlock block(crit);
  6683. return p->getPropInt("@agentPID", -1);
  6684. }
  6685. const char * CLocalWorkUnit::queryStateDesc() const
  6686. {
  6687. // MORE - not sure about this - may prefer a separate interface
  6688. CriticalBlock block(crit);
  6689. try
  6690. {
  6691. return getEnumText(getState(), states);
  6692. }
  6693. catch (...)
  6694. {
  6695. return "???";
  6696. }
  6697. }
  6698. void CLocalWorkUnit::setAction(WUAction value)
  6699. {
  6700. CriticalBlock block(crit);
  6701. setEnum(p, "Action", value, actions);
  6702. }
  6703. WUAction CLocalWorkUnit::getAction() const
  6704. {
  6705. CriticalBlock block(crit);
  6706. return (WUAction) getEnum(p, "Action", actions);
  6707. }
  6708. const char *CLocalWorkUnit::queryActionDesc() const
  6709. {
  6710. CriticalBlock block(crit);
  6711. return p->queryProp("Action");
  6712. }
  6713. bool CLocalWorkUnit::hasApplicationValue(const char *app, const char *propname) const
  6714. {
  6715. StringBuffer prop("Application/");
  6716. prop.append(app).append('/').append(propname);
  6717. CriticalBlock block(crit);
  6718. return p->hasProp(prop);
  6719. }
  6720. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  6721. {
  6722. StringBuffer prop("Application/");
  6723. prop.append(app).append('/').append(propname);
  6724. CriticalBlock block(crit);
  6725. str.set(p->queryProp(prop.str()));
  6726. return str;
  6727. }
  6728. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  6729. {
  6730. StringBuffer prop("Application/");
  6731. prop.append(app).append('/').append(propname);
  6732. CriticalBlock block(crit);
  6733. return p->getPropInt(prop.str(), defVal);
  6734. }
  6735. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  6736. {
  6737. CriticalBlock block(crit);
  6738. appvalues.load(p,"Application/*");
  6739. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  6740. }
  6741. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  6742. {
  6743. CriticalBlock block(crit);
  6744. StringBuffer prop("Application/");
  6745. prop.append(app).append('/').append(propname);
  6746. if (overwrite || !p->hasProp(prop.str()))
  6747. {
  6748. StringBuffer sp;
  6749. p->setProp(sp.append("Application").str(), "");
  6750. p->setProp(sp.append('/').append(app).str(), "");
  6751. p->setProp(prop.str(), value);
  6752. }
  6753. }
  6754. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  6755. {
  6756. VStringBuffer s("%d", value);
  6757. setApplicationValue(app, propname, s, overwrite);
  6758. }
  6759. void CLocalWorkUnit::setPriorityLevel(int level)
  6760. {
  6761. CriticalBlock block(crit);
  6762. p->setPropInt("PriorityFlag", level);
  6763. }
  6764. int CLocalWorkUnit::getPriorityLevel() const
  6765. {
  6766. CriticalBlock block(crit);
  6767. return p->getPropInt("PriorityFlag");
  6768. }
  6769. int calcPriorityValue(const IPropertyTree * p)
  6770. {
  6771. int priority = p->getPropInt("PriorityFlag");
  6772. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  6773. {
  6774. case PriorityClassLow:
  6775. priority -= 100;
  6776. break;
  6777. case PriorityClassHigh:
  6778. priority += 100;
  6779. break;
  6780. }
  6781. return priority;
  6782. }
  6783. int CLocalWorkUnit::getPriorityValue() const
  6784. {
  6785. CriticalBlock block(crit);
  6786. return calcPriorityValue(p);
  6787. }
  6788. void CLocalWorkUnit::setRescheduleFlag(bool value)
  6789. {
  6790. CriticalBlock block(crit);
  6791. p->setPropInt("RescheduleFlag", (int) value);
  6792. }
  6793. bool CLocalWorkUnit::getRescheduleFlag() const
  6794. {
  6795. CriticalBlock block(crit);
  6796. return p->getPropInt("RescheduleFlag") != 0;
  6797. }
  6798. class NullIStringIterator : implements IStringIterator, public CInterface
  6799. {
  6800. public:
  6801. IMPLEMENT_IINTERFACE;
  6802. bool first() { return false; }
  6803. bool next() { return false; }
  6804. bool isValid() { return false; }
  6805. IStringVal & str(IStringVal & str) { return str; }
  6806. };
  6807. ClusterType getClusterType(const char * platform, ClusterType dft)
  6808. {
  6809. if (stricmp(platform, "thor") == 0)
  6810. return ThorLCRCluster;
  6811. if (stricmp(platform, "thorlcr") == 0)
  6812. return ThorLCRCluster;
  6813. if (stricmp(platform, "hthor") == 0)
  6814. return HThorCluster;
  6815. if (stricmp(platform, "roxie") == 0)
  6816. return RoxieCluster;
  6817. return dft;
  6818. }
  6819. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  6820. {
  6821. switch (clusterType)
  6822. {
  6823. case ThorLCRCluster:
  6824. if (lcrSensitive)
  6825. return "thorlcr";
  6826. return "thor";
  6827. case RoxieCluster:
  6828. return "roxie";
  6829. case HThorCluster:
  6830. return "hthor";
  6831. }
  6832. throwUnexpected();
  6833. }
  6834. bool extractFromWorkunitDAToken(const char * distributedAccessToken, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey)
  6835. {
  6836. if (!isWorkunitDAToken(distributedAccessToken))
  6837. {
  6838. DBGLOG("Not a valid workunit distributed access token");
  6839. return false;
  6840. }
  6841. //Extract the string between [ and ]
  6842. const char * pEndBracket = strchr(distributedAccessToken + 5, ']');
  6843. StringBuffer tokenValues;
  6844. tokenValues.append(pEndBracket - distributedAccessToken - 5, distributedAccessToken + 5);
  6845. StringArray nameValues;
  6846. nameValues.appendList(tokenValues.str(), ",",true);
  6847. if (user || wuid)
  6848. {
  6849. for (int x = 0; x < nameValues.ordinality(); x++)
  6850. {
  6851. if (user && 0==strncmp(nameValues[x],"u=",2))//Extract user
  6852. user->append(nameValues[x] + 2);
  6853. if (wuid && 0==strncmp(nameValues[x],"w=",2))//Extract wuid
  6854. wuid->append(nameValues[x] + 2);
  6855. }
  6856. }
  6857. if (privKey)
  6858. {
  6859. const char * finger = pEndBracket;
  6860. ++finger;
  6861. while (*finger && *finger != ';')
  6862. privKey->append(1, finger++);
  6863. }
  6864. return true;
  6865. }
  6866. //Verifies the given signed workunit distributed access token was created
  6867. //and signed by the given wuid and user, and that the workunit is still active
  6868. //Returns:
  6869. // 0 : Success, token is valid and workunit is active
  6870. // 1 : Signature does not verify (wuid/username don't match, or signature does not verify)
  6871. // 2 : Workunit not active
  6872. // Throws if unable to open workunit
  6873. wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken)
  6874. {
  6875. if (isEmptyString(daToken))
  6876. {
  6877. ERRLOG("verifyWorkunitDAToken : Token must be provided");
  6878. return wuTokenInvalid;
  6879. }
  6880. StringBuffer tokWuid;
  6881. StringBuffer tokUser;
  6882. if (!extractFromWorkunitDAToken(daToken, &tokWuid, &tokUser, nullptr))//get the wuid and user
  6883. {
  6884. //Not a valid workunit distributed access token
  6885. return wuTokenInvalid;
  6886. }
  6887. //Validate signature
  6888. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6889. if (pDSM && pDSM->isDigiVerifierConfigured())
  6890. {
  6891. const char * finger;
  6892. StringBuffer token;//receives copy of everything up until signature
  6893. for (finger = daToken; *finger && *finger != ';'; finger++)
  6894. token.append(1, finger);
  6895. token.append(1, finger);//append ;
  6896. StringBuffer sig(++finger);
  6897. if (!pDSM->digiVerify(sig, token))
  6898. {
  6899. ERRLOG("verifyWorkunitDAToken : workunit distributed access token does not verify");
  6900. return wuTokenInvalid;
  6901. }
  6902. }
  6903. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6904. Owned<IConstWorkUnit> cw = factory->openWorkUnit(tokWuid.str());
  6905. if(!cw)
  6906. {
  6907. throw MakeStringException(WUERR_WorkunitAccessDenied,"verifyWorkunitDAToken : Cannot open workunit %s",tokWuid.str());
  6908. }
  6909. //Verify user matches
  6910. bool wuUserExist = !isEmptyString(cw->queryUser());
  6911. bool tokUserExist = !isEmptyString(tokUser.str());
  6912. bool ctxUserExist = !isEmptyString(ctxUser);
  6913. if (wuUserExist && tokUserExist)
  6914. {
  6915. //if both users are found, they must match
  6916. if (!streq(tokUser.str(), cw->queryUser()))
  6917. {
  6918. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match WU user (%s)", tokUser.str(), cw->queryUser());
  6919. return wuTokenInvalid;//Possible Internal error
  6920. }
  6921. else if (ctxUserExist && !streq(tokUser.str(), ctxUser))//ctxUser will be empty if security not enabled
  6922. {
  6923. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match Context user (%s)", cw->queryUser(), ctxUser);
  6924. return wuTokenInvalid;
  6925. }
  6926. }
  6927. else if (!wuUserExist && !tokUserExist)//both users will be empty if no security enabled
  6928. {
  6929. if (ctxUserExist)
  6930. {
  6931. ERRLOG("verifyWorkunitDAToken : Security enabled but WU user and Token user not specified");
  6932. return wuTokenInvalid;
  6933. }
  6934. //both users empty and no context user means if no security enabled
  6935. }
  6936. else
  6937. {
  6938. //one user found, but not the other, treat as an error
  6939. ERRLOG("verifyWorkunitDAToken : WU user %s and Token user %s must be provided", wuUserExist ? cw->queryUser() : "(NULL)", tokUserExist ? tokUser.str() : "(NULL)");
  6940. return wuTokenInvalid;
  6941. }
  6942. // no need to compare tokWuid with workunit wuid, because it will always match
  6943. bool wuActive;
  6944. switch (cw->getState())
  6945. {
  6946. case WUStateRunning:
  6947. case WUStateDebugRunning:
  6948. case WUStateBlocked:
  6949. case WUStateAborting:
  6950. case WUStateUploadingFiles:
  6951. #ifdef _DEBUG
  6952. DBGLOG("verifyWorkunitDAToken : Workunit token validated for %s %s, state is '%s'", cw->queryWuid(), cw->queryUser(), getWorkunitStateStr(cw->getState()));
  6953. #endif
  6954. wuActive = true;
  6955. break;
  6956. default:
  6957. ERRLOG("verifyWorkunitDAToken : Workunit %s not active, state is '%s'", cw->queryWuid(), getWorkunitStateStr(cw->getState()));
  6958. wuActive = false;
  6959. break;
  6960. }
  6961. return wuActive ? wuTokenValid : wuTokenWorkunitInactive;
  6962. }
  6963. bool CLocalWorkUnit::resolveFilePrefix(StringBuffer & prefix, const char * queue) const
  6964. {
  6965. if (hasApplicationValue("prefix", queue))
  6966. {
  6967. getApplicationValue("prefix", queue, StringBufferAdaptor(prefix));
  6968. return true;
  6969. }
  6970. #ifndef _CONTAINERIZED
  6971. Owned<IConstWUClusterInfo> ci = getTargetClusterInfo(queue);
  6972. if (ci)
  6973. {
  6974. ci->getScope(StringBufferAdaptor(prefix));
  6975. return true;
  6976. }
  6977. #endif
  6978. return false;
  6979. }
  6980. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  6981. {
  6982. StringBuffer prefix;
  6983. CriticalBlock block(crit);
  6984. if (p->hasProp("Debug/ForceScope"))
  6985. {
  6986. prefix.append(p->queryProp("Debug/ForceScope")).toLowerCase();
  6987. }
  6988. else
  6989. {
  6990. resolveFilePrefix(prefix, p->queryProp("@clusterName"));
  6991. }
  6992. str.set(prefix.str());
  6993. return str;
  6994. }
  6995. //Queries
  6996. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  6997. {
  6998. CriticalBlock block(crit);
  6999. p->setPropInt("@codeVersion", codeVersion);
  7000. p->setProp("@buildVersion", buildVersion);
  7001. p->setProp("@eclVersion", eclVersion);
  7002. }
  7003. unsigned CLocalWorkUnit::getCodeVersion() const
  7004. {
  7005. CriticalBlock block(crit);
  7006. return p->getPropInt("@codeVersion");
  7007. }
  7008. unsigned CLocalWorkUnit::getWuidVersion() const
  7009. {
  7010. CriticalBlock block(crit);
  7011. return p->getPropInt("@wuidVersion");
  7012. }
  7013. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  7014. {
  7015. CriticalBlock block(crit);
  7016. buildVersion.set(p->queryProp("@buildVersion"));
  7017. eclVersion.set(p->queryProp("@eclVersion"));
  7018. }
  7019. void CLocalWorkUnit::setCloneable(bool value)
  7020. {
  7021. CriticalBlock block(crit);
  7022. p->setPropInt("@cloneable", value);
  7023. }
  7024. void CLocalWorkUnit::setIsClone(bool value)
  7025. {
  7026. CriticalBlock block(crit);
  7027. p->setPropInt("@isClone", value);
  7028. }
  7029. bool CLocalWorkUnit::getCloneable() const
  7030. {
  7031. CriticalBlock block(crit);
  7032. return p->getPropBool("@cloneable", false);
  7033. }
  7034. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  7035. {
  7036. CriticalBlock block(crit);
  7037. if (!userDesc)
  7038. {
  7039. userDesc.setown(createUserDescriptor());
  7040. SCMStringBuffer token;
  7041. getWorkunitDistributedAccessToken(token);
  7042. userDesc->set(queryUser(), token.str());//use token as password
  7043. }
  7044. return userDesc;
  7045. }
  7046. bool CLocalWorkUnit::isProtected() const
  7047. {
  7048. CriticalBlock block(crit);
  7049. return p->getPropBool("@protected", false);
  7050. }
  7051. bool CLocalWorkUnit::isPausing() const
  7052. {
  7053. CriticalBlock block(crit);
  7054. if (WUActionPause == getAction())
  7055. {
  7056. switch (getState())
  7057. {
  7058. case WUStateRunning:
  7059. case WUStateAborting:
  7060. return true;
  7061. }
  7062. }
  7063. return false;
  7064. }
  7065. void CLocalWorkUnit::protect(bool protectMode)
  7066. {
  7067. CriticalBlock block(crit);
  7068. p->setPropBool("@protected", protectMode);
  7069. }
  7070. void CLocalWorkUnit::setResultLimit(unsigned value)
  7071. {
  7072. CriticalBlock block(crit);
  7073. p->setPropInt("resultLimit", value);
  7074. }
  7075. unsigned CLocalWorkUnit::getResultLimit() const
  7076. {
  7077. CriticalBlock block(crit);
  7078. return p->getPropInt("resultLimit");
  7079. }
  7080. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  7081. {
  7082. CriticalBlock block(crit);
  7083. str.set(p->queryProp("SNAPSHOT"));
  7084. return str;
  7085. }
  7086. void CLocalWorkUnit::setSnapshot(const char * val)
  7087. {
  7088. CriticalBlock block(crit);
  7089. p->setProp("SNAPSHOT", val);
  7090. }
  7091. const static EnumMapping warningSeverityMap[] =
  7092. {
  7093. { SeverityInformation, "info" },
  7094. { SeverityWarning, "warning" },
  7095. { SeverityError, "error" },
  7096. { SeverityAlert, "alert" },
  7097. { SeverityIgnore, "ignore" },
  7098. { SeverityFatal, "fatal" },
  7099. { SeverityUnknown, NULL }
  7100. };
  7101. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  7102. {
  7103. StringBuffer xpath;
  7104. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7105. CriticalBlock block(crit);
  7106. IPropertyTree * mapping = p->queryPropTree(xpath);
  7107. if (mapping)
  7108. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  7109. return defaultSeverity;
  7110. }
  7111. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  7112. {
  7113. StringBuffer xpath;
  7114. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7115. CriticalBlock block(crit);
  7116. IPropertyTree * mapping = p->queryPropTree(xpath);
  7117. if (!mapping)
  7118. {
  7119. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  7120. mapping = onWarnings->addPropTree("OnWarning");
  7121. mapping->setPropInt("@code", code);
  7122. }
  7123. setEnum(mapping, "@severity", severity, warningSeverityMap);
  7124. }
  7125. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  7126. {
  7127. IPropertyTree *l = (IPropertyTree *) *ll;
  7128. IPropertyTree *r = (IPropertyTree *) *rr;
  7129. return stricmp(l->queryName(), r->queryName());
  7130. };
  7131. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  7132. {
  7133. // Any other values in the WU that could affect generated code should be crc'ed here
  7134. IPropertyTree *tree = p->queryBranch("Debug");
  7135. if (tree)
  7136. {
  7137. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  7138. ICopyArrayOf<IPropertyTree> subs;
  7139. for(sub->first(); sub->isValid(); sub->next())
  7140. subs.append(sub->query());
  7141. subs.sort(comparePropTrees);
  7142. ForEachItemIn(idx, subs)
  7143. {
  7144. const char *name = subs.item(idx).queryName();
  7145. const char *val = subs.item(idx).queryProp(NULL);
  7146. crc = crc32(name, (size32_t)strlen(name), crc);
  7147. if (val)
  7148. crc = crc32(val, (size32_t)strlen(val), crc);
  7149. }
  7150. }
  7151. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  7152. for (plugins->first();plugins->isValid();plugins->next())
  7153. {
  7154. IConstWUPlugin &thisplugin = plugins->query();
  7155. SCMStringBuffer version;
  7156. thisplugin.getPluginVersion(version);
  7157. crc = crc32(version.str(), version.length(), crc);
  7158. }
  7159. return crc;
  7160. }
  7161. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7162. {
  7163. if (!to->hasProp(xpath) && from->hasProp(xpath))
  7164. to->setProp(xpath, from->queryProp(xpath));
  7165. }
  7166. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7167. {
  7168. if (from->hasProp(xpath))
  7169. to->setProp(xpath, from->queryProp(xpath));
  7170. }
  7171. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7172. {
  7173. IPropertyTree * match = from->getBranch(xpath);
  7174. if (match)
  7175. to->setPropTree(xpath, match);
  7176. }
  7177. IPropertyTree *CLocalWorkUnit::queryPTree() const
  7178. {
  7179. return p;
  7180. }
  7181. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  7182. {
  7183. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  7184. if (!from)
  7185. {
  7186. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  7187. if (!fl)
  7188. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  7189. from = fl->c;
  7190. }
  7191. // Need to copy the query, the results, and the graphs from the cached query.
  7192. // The cache is made before the query is executed so there is no need to clear them.
  7193. if (!cached->getCloneable())
  7194. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  7195. const IPropertyTree * fromP = from->p;
  7196. IPropertyTree *pt;
  7197. CriticalBlock block(crit);
  7198. clearCached(false);
  7199. query.clear();
  7200. updateProp(p, fromP, "@jobName");
  7201. copyTree(p, fromP, "Query");
  7202. pt = fromP->getBranch("Application/LibraryModule");
  7203. if (pt)
  7204. {
  7205. ensurePTree(p, "Application");
  7206. p->setPropTree("Application/LibraryModule", pt);
  7207. }
  7208. pt = fromP->getBranch("Application/prefix");
  7209. if (pt)
  7210. {
  7211. ensurePTree(p, "Application");
  7212. p->setPropTree("Application/prefix", pt);
  7213. }
  7214. pt = fromP->queryBranch("Debug");
  7215. if (pt)
  7216. {
  7217. IPropertyTree *curDebug = p->queryPropTree("Debug");
  7218. if (curDebug)
  7219. {
  7220. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  7221. ForEach(*elems)
  7222. {
  7223. IPropertyTree *elem = &elems->query();
  7224. if (!curDebug->hasProp(elem->queryName()))
  7225. curDebug->setPropTree(elem->queryName(),LINK(elem));
  7226. }
  7227. }
  7228. else
  7229. p->setPropTree("Debug", LINK(pt));
  7230. }
  7231. copyTree(p, fromP, "OnWarnings");
  7232. copyTree(p, fromP, "Plugins");
  7233. copyTree(p, fromP, "Libraries");
  7234. copyTree(p, fromP, "Results");
  7235. copyTree(p, fromP, "Graphs");
  7236. copyTree(p, fromP, "Workflow");
  7237. copyTree(p, fromP, "WebServicesInfo");
  7238. if (copyStats)
  7239. {
  7240. // Merge timing info from both branches
  7241. pt = fromP->getBranch("Statistics");
  7242. if (pt)
  7243. {
  7244. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  7245. mergePTree(tgtStatistics, pt);
  7246. pt->Release();
  7247. }
  7248. }
  7249. updateProp(p, fromP, "@clusterName");
  7250. updateProp(p, fromP, "allowedclusters");
  7251. updateProp(p, fromP, "@submitID");
  7252. updateProp(p, fromP, "SNAPSHOT");
  7253. setProp(p, fromP, "@eventScheduledCount");
  7254. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  7255. if (all)
  7256. {
  7257. setProp(p, fromP, "PriorityFlag");
  7258. setProp(p, fromP, "@priorityClass");
  7259. setProp(p, fromP, "@protected");
  7260. setProp(p, fromP, "@clusterName");
  7261. updateProp(p, fromP, "@scope");
  7262. }
  7263. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  7264. pt = fromP->getBranch("Variables");
  7265. if (pt)
  7266. {
  7267. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  7268. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  7269. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  7270. {
  7271. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  7272. const char *name = ptSrcVariable->queryProp("@name");
  7273. assertex(name);
  7274. StringBuffer xpath;
  7275. xpath.append("Variable[@name='").append(name).append("']");
  7276. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  7277. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  7278. merged->removeProp("Value"); // except value and status
  7279. merged->setProp("@status", "undefined");
  7280. if (!merged->getPropBool("@isScalar"))
  7281. merged->removeProp("totalRowCount");
  7282. merged->removeProp("rowCount");
  7283. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  7284. if (ptTgtVariable)
  7285. {
  7286. // copy status and Value from what is already set in target
  7287. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  7288. MemoryBuffer value;
  7289. if (ptTgtVariable->getPropBin("Value", value))
  7290. merged->setPropBin("Value", value.length(), value.toByteArray());
  7291. ptTgtVariable->removeProp(xpath.str());
  7292. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  7293. }
  7294. ptTgtVariables->addPropTree("Variable", merged);
  7295. }
  7296. pt->Release();
  7297. }
  7298. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  7299. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  7300. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  7301. p->setProp("@totalThorTime", fromP->queryProp("@totalThorTime"));
  7302. p->setProp("@hash", fromP->queryProp("@hash"));
  7303. p->setPropBool("@cloneable", true);
  7304. p->setPropBool("@isClone", true);
  7305. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  7306. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  7307. ForEach(*results)
  7308. {
  7309. CLocalWUResult result(LINK(&results->query()));
  7310. result.setResultStatus(ResultStatusUndefined);
  7311. }
  7312. copyTree(p, fromP, "usedsources"); // field usage
  7313. }
  7314. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  7315. {
  7316. StringBuffer lower;
  7317. lower.append(propname).toLowerCase();
  7318. CriticalBlock block(crit);
  7319. StringBuffer prop("Debug/");
  7320. return p->hasProp(prop.append(lower));
  7321. }
  7322. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  7323. {
  7324. StringBuffer lower;
  7325. lower.append(propname).toLowerCase();
  7326. CriticalBlock block(crit);
  7327. StringBuffer prop("Debug/");
  7328. str.set(p->queryProp(prop.append(lower).str()));
  7329. return str;
  7330. }
  7331. IStringIterator& CLocalWorkUnit::getDebugValues() const
  7332. {
  7333. return getDebugValues(NULL);
  7334. }
  7335. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  7336. {
  7337. CriticalBlock block(crit);
  7338. StringBuffer path("Debug/");
  7339. if (prop)
  7340. {
  7341. StringBuffer lower;
  7342. lower.append(prop).toLowerCase();
  7343. path.append(lower);
  7344. }
  7345. else
  7346. path.append("*");
  7347. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  7348. }
  7349. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  7350. {
  7351. StringBuffer lower;
  7352. lower.append(propname).toLowerCase();
  7353. CriticalBlock block(crit);
  7354. StringBuffer prop("Debug/");
  7355. prop.append(lower);
  7356. return p->getPropInt(prop.str(), defVal);
  7357. }
  7358. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  7359. {
  7360. StringBuffer lower;
  7361. lower.append(propname).toLowerCase();
  7362. CriticalBlock block(crit);
  7363. StringBuffer prop("Debug/");
  7364. prop.append(lower);
  7365. return p->getPropInt64(prop.str(), defVal);
  7366. }
  7367. double CLocalWorkUnit::getDebugValueReal(const char *propname, double defVal) const
  7368. {
  7369. StringBuffer lower;
  7370. lower.append(propname).toLowerCase();
  7371. CriticalBlock block(crit);
  7372. StringBuffer prop("Debug/");
  7373. prop.append(lower);
  7374. return p->getPropReal(prop.str(), defVal);
  7375. }
  7376. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  7377. {
  7378. StringBuffer lower;
  7379. lower.append(propname).toLowerCase();
  7380. CriticalBlock block(crit);
  7381. StringBuffer prop("Debug/");
  7382. prop.append(lower);
  7383. return p->getPropBool(prop.str(), defVal);
  7384. }
  7385. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  7386. {
  7387. VStringBuffer xpath("Process/%s/", type);
  7388. if (instance)
  7389. xpath.append(instance);
  7390. else
  7391. xpath.append("*");
  7392. CriticalBlock block(crit);
  7393. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  7394. {
  7395. // NB: instance unused
  7396. if (streq("EclAgent", type))
  7397. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  7398. else if (streq("Thor", type))
  7399. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  7400. VStringBuffer xpath("Debug/%s", type);
  7401. return new CStringPTreeIterator(p->getElements(xpath.str()));
  7402. }
  7403. else
  7404. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  7405. }
  7406. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  7407. {
  7408. VStringBuffer xpath("Process/%s/", type);
  7409. if (instance)
  7410. xpath.append(instance);
  7411. else
  7412. xpath.append("*");
  7413. CriticalBlock block(crit);
  7414. return p->getElements(xpath.str());
  7415. }
  7416. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  7417. {
  7418. VStringBuffer xpath("Process/%s/*", type);
  7419. CriticalBlock block(crit);
  7420. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  7421. }
  7422. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  7423. {
  7424. VStringBuffer processType("Process/%s", type);
  7425. VStringBuffer xpath("%s/%s", processType.str(), instance);
  7426. if (log)
  7427. xpath.appendf("[@log=\"%s\"]", log);
  7428. CriticalBlock block(crit);
  7429. if (!p->hasProp(xpath))
  7430. {
  7431. IPropertyTree *node = ensurePTree(p, processType.str());
  7432. node = node->addPropTree(instance);
  7433. node->setProp("@log", log);
  7434. node->setPropInt("@pid", pid);
  7435. }
  7436. }
  7437. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  7438. {
  7439. StringBuffer lower;
  7440. lower.append(propname).toLowerCase();
  7441. CriticalBlock block(crit);
  7442. StringBuffer prop("Debug/");
  7443. prop.append(lower);
  7444. if (overwrite || !p->hasProp(prop.str()))
  7445. {
  7446. // MORE - not sure this line should be needed....
  7447. p->setProp("Debug", "");
  7448. p->setProp(prop.str(), value);
  7449. }
  7450. }
  7451. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  7452. {
  7453. StringBuffer lower;
  7454. lower.append(propname).toLowerCase();
  7455. CriticalBlock block(crit);
  7456. StringBuffer prop("Debug/");
  7457. prop.append(lower);
  7458. if (overwrite || !p->hasProp(prop.str()))
  7459. {
  7460. // MORE - not sure this line should be needed....
  7461. p->setProp("Debug", "");
  7462. p->setPropInt(prop.str(), value);
  7463. }
  7464. }
  7465. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  7466. {
  7467. CriticalBlock block(crit);
  7468. // MORE - not sure this line should be needed....
  7469. p->setProp("Tracing", "");
  7470. StringBuffer prop("Tracing/");
  7471. p->setProp(prop.append(propname).str(), value);
  7472. }
  7473. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  7474. {
  7475. CriticalBlock block(crit);
  7476. StringBuffer prop("Tracing/");
  7477. p->setPropInt(prop.append(propname).str(), value);
  7478. }
  7479. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  7480. {
  7481. CriticalBlock block(crit);
  7482. VStringBuffer prop("Tracing/%s", propname);
  7483. p->setPropInt64(prop.str(), value);
  7484. }
  7485. IConstWUQuery* CLocalWorkUnit::getQuery() const
  7486. {
  7487. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7488. CriticalBlock block(crit);
  7489. if (!query)
  7490. {
  7491. IPropertyTree *s = p->getPropTree("Query");
  7492. if (s)
  7493. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  7494. }
  7495. return query.getLink();
  7496. }
  7497. IWUQuery* CLocalWorkUnit::updateQuery()
  7498. {
  7499. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7500. CriticalBlock block(crit);
  7501. if (!query)
  7502. {
  7503. IPropertyTree *s = p->queryPropTree("Query");
  7504. if (!s)
  7505. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  7506. s->Link();
  7507. query.setown(new CLocalWUQuery(s));
  7508. }
  7509. return query.getLink();
  7510. }
  7511. void CLocalWorkUnit::loadPlugins() const
  7512. {
  7513. CriticalBlock block(crit);
  7514. if (!pluginsCached)
  7515. {
  7516. assertex(plugins.length() == 0);
  7517. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  7518. for (r->first(); r->isValid(); r->next())
  7519. {
  7520. IPropertyTree *rp = &r->query();
  7521. rp->Link();
  7522. plugins.append(*new CLocalWUPlugin(rp));
  7523. }
  7524. pluginsCached = true;
  7525. }
  7526. }
  7527. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  7528. {
  7529. CriticalBlock block(crit);
  7530. loadPlugins();
  7531. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  7532. }
  7533. void CLocalWorkUnit::loadLibraries() const
  7534. {
  7535. CriticalBlock block(crit);
  7536. if (!librariesCached)
  7537. {
  7538. assertex(libraries.length() == 0);
  7539. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  7540. ForEach(*r)
  7541. {
  7542. IPropertyTree *rp = &r->query();
  7543. rp->Link();
  7544. libraries.append(*new CLocalWULibrary(rp));
  7545. }
  7546. librariesCached = true;
  7547. }
  7548. }
  7549. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  7550. {
  7551. CriticalBlock block(crit);
  7552. loadLibraries();
  7553. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  7554. }
  7555. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  7556. {
  7557. CriticalBlock block(crit);
  7558. loadLibraries();
  7559. ForEachItemIn(idx, libraries)
  7560. {
  7561. SCMStringBuffer name;
  7562. IConstWULibrary &cur = libraries.item(idx);
  7563. cur.getName(name);
  7564. if (stricmp(name.str(), search)==0)
  7565. return &OLINK(cur);
  7566. }
  7567. return NULL;
  7568. }
  7569. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7570. {
  7571. str.append("Graph ").append(graphName);
  7572. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  7573. else if (subId) str.append(" - id(").append(subId).append(")");
  7574. return str;
  7575. }
  7576. StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7577. {
  7578. if (wfid)
  7579. str.append(WorkflowScopePrefix).append(wfid).append(":");
  7580. str.append(graphName);
  7581. if (subId) str.append(":sg").append(subId);
  7582. return str;
  7583. }
  7584. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  7585. {
  7586. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  7587. unsigned len = (size32_t)strlen(label);
  7588. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  7589. return false;
  7590. graphNum = 0;
  7591. subGraphNum = 0;
  7592. subId = 0;
  7593. const char *finger = label+6;
  7594. const char *finger2 = strchr(finger, '-');
  7595. if (NULL == finger2) // just graphName
  7596. graphName.set(finger);
  7597. else
  7598. {
  7599. graphName.set(finger, (size32_t)((finger2-1)-finger));
  7600. finger = finger2+2; // skip '-' and space
  7601. finger2 = strchr(finger, ' ');
  7602. if (finger2)
  7603. {
  7604. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  7605. finger = finger2+2; // skip space and '('
  7606. finger2 = strchr(finger, ')');
  7607. if (finger2)
  7608. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7609. }
  7610. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  7611. {
  7612. finger += 3;
  7613. finger2 = strchr(finger, ')');
  7614. if (finger2)
  7615. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7616. }
  7617. }
  7618. if (graphName && !memicmp(graphName, "graph", 5))
  7619. graphNum = atoi(graphName + 5);
  7620. return true;
  7621. }
  7622. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  7623. {
  7624. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  7625. return false;
  7626. graphNum = atoi(scope + strlen(GraphScopePrefix));
  7627. subGraphId = 0;
  7628. const char * colon = strchr(scope, ':');
  7629. if (!colon)
  7630. {
  7631. graphName.set(scope);
  7632. return true;
  7633. }
  7634. const char * subgraph = colon+1;
  7635. graphName.set(scope, (size32_t)(colon - scope));
  7636. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  7637. subGraphId = atoi(subgraph+strlen(SubGraphScopePrefix));
  7638. return true;
  7639. }
  7640. 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)
  7641. {
  7642. if (!scope) scope = GLOBAL_SCOPE;
  7643. const char * kindName = queryStatisticName(kind);
  7644. StatisticMeasure measure = queryMeasure(kind);
  7645. //creator. scope and name must all be present, and must not contain semi colons.
  7646. assertex(creator && scope);
  7647. CriticalBlock block(crit);
  7648. IPropertyTree * stats = p->queryPropTree("Statistics");
  7649. if (!stats)
  7650. stats = p->addPropTree("Statistics");
  7651. IPropertyTree * statTree = NULL;
  7652. if (mergeAction != StatsMergeAppend)
  7653. {
  7654. StringBuffer xpath;
  7655. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  7656. statTree = stats->queryPropTree(xpath.str());
  7657. }
  7658. if (!statTree)
  7659. {
  7660. statTree = stats->addPropTree("Statistic");
  7661. statTree->setProp("@creator", creator);
  7662. statTree->setProp("@scope", scope);
  7663. statTree->setProp("@kind", kindName);
  7664. //These items are primarily here to facilitate filtering.
  7665. statTree->setProp("@unit", queryMeasureName(measure));
  7666. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  7667. statTree->setProp("@s", queryScopeTypeName(scopeType));
  7668. statTree->setPropInt64("@ts", getTimeStampNowValue());
  7669. if (optDescription)
  7670. statTree->setProp("@desc", optDescription);
  7671. if (statistics.cached)
  7672. statistics.append(LINK(statTree));
  7673. mergeAction = StatsMergeAppend;
  7674. }
  7675. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  7676. {
  7677. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  7678. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  7679. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  7680. if (oldMax < oldValue)
  7681. oldMax = oldValue;
  7682. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  7683. statTree->setPropInt64("@count", count + oldCount);
  7684. if (maxValue > oldMax)
  7685. statTree->setPropInt64("@max", maxValue);
  7686. }
  7687. else
  7688. {
  7689. statTree->setPropInt64("@value", value);
  7690. statTree->setPropInt64("@count", count);
  7691. if (maxValue)
  7692. statTree->setPropInt64("@max", maxValue);
  7693. else
  7694. statTree->removeProp("@max");
  7695. }
  7696. //Whenever a graph time is updated recalculate the total time spent in thor, and save it
  7697. if ((scopeType == SSTgraph) && (kind == StTimeElapsed))
  7698. {
  7699. _loadStatistics();
  7700. stat_type totalTime = 0;
  7701. ForEachItemIn(i, statistics)
  7702. {
  7703. IConstWUStatistic & cur = statistics.item(i);
  7704. if ((cur.getScopeType() == SSTgraph) && (cur.getKind() == StTimeElapsed))
  7705. totalTime += cur.getValue();
  7706. }
  7707. StringBuffer t;
  7708. formatTimeCollatable(t, totalTime, false);
  7709. p->setProp("@totalThorTime", t);
  7710. }
  7711. }
  7712. void CLocalWorkUnit::_loadStatistics() const
  7713. {
  7714. statistics.load(p,"Statistics/*");
  7715. }
  7716. bool CLocalWorkUnit::getStatistic(stat_type & value, const char * scope, StatisticKind kind) const
  7717. {
  7718. //MORE: Optimize this....
  7719. WuScopeFilter filter;
  7720. filter.addScope(scope).setIncludeNesting(0).addRequiredStat(kind).addOutputStatistic(kind).finishedFilter();
  7721. Owned<IConstWUScopeIterator> stats = &getScopeIterator(filter);
  7722. if (stats->first())
  7723. return stats->getStat(kind, value);
  7724. return false;
  7725. }
  7726. IConstWUScopeIterator & CLocalWorkUnit::getScopeIterator(const WuScopeFilter & filter) const
  7727. {
  7728. assertex(filter.isOptimized());
  7729. WuScopeSourceFlags sources = filter.sourceFlags;
  7730. Owned<CompoundStatisticsScopeIterator> compoundIter = new CompoundStatisticsScopeIterator(filter);
  7731. if (sources & SSFsearchGlobalStats)
  7732. {
  7733. CriticalBlock block(crit);
  7734. statistics.loadBranch(p,"Statistics");
  7735. Owned<IConstWUScopeIterator> localStats(new WorkUnitStatisticsScopeIterator(statistics, filter.queryIterFilter()));
  7736. compoundIter->addIter(localStats);
  7737. }
  7738. if (sources & SSFsearchGraphStats)
  7739. {
  7740. const char * wuid = p->queryName();
  7741. Owned<IConstWUScopeIterator> scopeIter(new CConstGraphProgressScopeIterator(wuid, filter.queryIterFilter(), filter.minVersion));
  7742. compoundIter->addIter(scopeIter);
  7743. }
  7744. if (sources & SSFsearchGraph)
  7745. {
  7746. Owned<IConstWUScopeIterator> graphIter(new GraphScopeIterator(this, filter.queryIterFilter()));
  7747. compoundIter->addIter(graphIter);
  7748. }
  7749. if (sources & SSFsearchWorkflow)
  7750. {
  7751. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  7752. if (iter)
  7753. {
  7754. Owned<IConstWUScopeIterator> workflowIter(new WorkflowStatisticsScopeIterator(iter));
  7755. compoundIter->addIter(workflowIter);
  7756. }
  7757. }
  7758. if (sources & SSFsearchExceptions)
  7759. {
  7760. Owned<IConstWUScopeIterator> notesIter(new NotesIterator(this,filter.queryIterFilter()));
  7761. compoundIter->addIter(notesIter);
  7762. }
  7763. return *compoundIter.getClear();
  7764. }
  7765. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  7766. {
  7767. CriticalBlock block(crit);
  7768. IConstWUPlugin *existing = getPluginByName(qname);
  7769. if (existing)
  7770. return (IWUPlugin *) existing;
  7771. if (!plugins.length())
  7772. p->addPropTree("Plugins");
  7773. IPropertyTree *pl = p->queryPropTree("Plugins");
  7774. IPropertyTree *s = pl->addPropTree("Plugin");
  7775. s->Link();
  7776. IWUPlugin* q = new CLocalWUPlugin(s);
  7777. q->Link();
  7778. plugins.append(*q);
  7779. q->setPluginName(qname);
  7780. return q;
  7781. }
  7782. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  7783. {
  7784. CriticalBlock block(crit);
  7785. loadPlugins();
  7786. ForEachItemIn(idx, plugins)
  7787. {
  7788. SCMStringBuffer name;
  7789. IConstWUPlugin &cur = plugins.item(idx);
  7790. cur.getPluginName(name);
  7791. if (stricmp(name.str(), qname)==0)
  7792. {
  7793. cur.Link();
  7794. return &cur;
  7795. }
  7796. }
  7797. return NULL;
  7798. }
  7799. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  7800. {
  7801. CriticalBlock block(crit);
  7802. IConstWULibrary *existing = getLibraryByName(qname);
  7803. if (existing)
  7804. return (IWULibrary *) existing;
  7805. if (!libraries.length())
  7806. p->addPropTree("Libraries");
  7807. IPropertyTree *pl = p->queryPropTree("Libraries");
  7808. IPropertyTree *s = pl->addPropTree("Library");
  7809. s->Link();
  7810. IWULibrary* q = new CLocalWULibrary(s);
  7811. q->Link();
  7812. libraries.append(*q);
  7813. q->setName(qname);
  7814. return q;
  7815. }
  7816. void CLocalWorkUnit::_loadExceptions() const
  7817. {
  7818. assertex(exceptions.length() == 0);
  7819. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  7820. for (r->first(); r->isValid(); r->next())
  7821. {
  7822. IPropertyTree *rp = &r->query();
  7823. rp->Link();
  7824. exceptions.append(*new CLocalWUException(rp));
  7825. }
  7826. }
  7827. void CLocalWorkUnit::loadExceptions() const
  7828. {
  7829. CriticalBlock block(crit);
  7830. if (!exceptionsCached)
  7831. {
  7832. _loadExceptions();
  7833. exceptionsCached = true;
  7834. }
  7835. }
  7836. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  7837. {
  7838. CriticalBlock block(crit);
  7839. loadExceptions();
  7840. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  7841. }
  7842. unsigned CLocalWorkUnit::getExceptionCount() const
  7843. {
  7844. CriticalBlock block(crit);
  7845. loadExceptions();
  7846. return exceptions.length();
  7847. }
  7848. void CLocalWorkUnit::clearExceptions(const char *source)
  7849. {
  7850. CriticalBlock block(crit);
  7851. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7852. loadExceptions();
  7853. ForEachItemInRev(idx, exceptions)
  7854. {
  7855. IWUException &e = exceptions.item(idx);
  7856. SCMStringBuffer s;
  7857. e.getExceptionSource(s);
  7858. if (source)
  7859. {
  7860. if (!strieq(s.s, source))
  7861. continue;
  7862. }
  7863. else
  7864. {
  7865. if (strieq(s.s, "eclcc") || strieq(s.s, "eclccserver") || strieq(s.s, "eclserver") )
  7866. break;
  7867. }
  7868. VStringBuffer xpath("Exceptions/Exception[@sequence='%d']", e.getSequence());
  7869. p->removeProp(xpath);
  7870. exceptions.remove(idx);
  7871. }
  7872. if (exceptions.length() == 0)
  7873. p->removeProp("Exceptions");
  7874. }
  7875. IWUException* CLocalWorkUnit::createException()
  7876. {
  7877. CriticalBlock block(crit);
  7878. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7879. loadExceptions();
  7880. if (!exceptions.length())
  7881. p->addPropTree("Exceptions");
  7882. IPropertyTree *r = p->queryPropTree("Exceptions");
  7883. IPropertyTree *s = r->addPropTree("Exception");
  7884. s->setPropInt("@sequence", exceptions.ordinality());
  7885. IWUException* q = new CLocalWUException(LINK(s));
  7886. exceptions.append(*LINK(q));
  7887. Owned<IJlibDateTime> now = createDateTimeNow();
  7888. SCMStringBuffer temp;
  7889. now->getString(temp);
  7890. q->setTimeStamp(temp.str());
  7891. return q;
  7892. }
  7893. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  7894. {
  7895. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7896. CriticalBlock block(crit);
  7897. if (!webServicesInfoCached)
  7898. {
  7899. assertex(!webServicesInfo);
  7900. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  7901. if (s)
  7902. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  7903. webServicesInfoCached = true;
  7904. }
  7905. return webServicesInfo.getLink();
  7906. }
  7907. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  7908. {
  7909. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7910. CriticalBlock block(crit);
  7911. if (!webServicesInfoCached)
  7912. {
  7913. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  7914. if (!s)
  7915. {
  7916. if (create)
  7917. s = p->addPropTree("WebServicesInfo");
  7918. else
  7919. return NULL;
  7920. }
  7921. s->Link();
  7922. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  7923. webServicesInfoCached = true;
  7924. }
  7925. return webServicesInfo.getLink();
  7926. }
  7927. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  7928. {
  7929. CLocalWUResult *l = (CLocalWUResult *) *ll;
  7930. CLocalWUResult *r = (CLocalWUResult *) *rr;
  7931. return l->getResultSequence() - r->getResultSequence();
  7932. }
  7933. void CLocalWorkUnit::_loadResults() const
  7934. {
  7935. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  7936. for (r->first(); r->isValid(); r->next())
  7937. {
  7938. IPropertyTree *rp = &r->query();
  7939. rp->Link();
  7940. results.append(*new CLocalWUResult(rp));
  7941. }
  7942. }
  7943. void CLocalWorkUnit::loadResults() const
  7944. {
  7945. if (!resultsCached)
  7946. {
  7947. assertex(results.length() == 0);
  7948. _loadResults();
  7949. results.sort(compareResults);
  7950. resultsCached = true;
  7951. }
  7952. }
  7953. void CLocalWorkUnit::_loadVariables() const
  7954. {
  7955. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  7956. for (r->first(); r->isValid(); r->next())
  7957. {
  7958. IPropertyTree *rp = &r->query();
  7959. rp->Link();
  7960. variables.append(*new CLocalWUResult(rp));
  7961. }
  7962. }
  7963. void CLocalWorkUnit::loadVariables() const
  7964. {
  7965. if (!variablesCached)
  7966. {
  7967. assertex(variables.length() == 0);
  7968. _loadVariables();
  7969. variablesCached = true;
  7970. }
  7971. }
  7972. void CLocalWorkUnit::_loadTemporaries() const
  7973. {
  7974. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  7975. for (r->first(); r->isValid(); r->next())
  7976. {
  7977. IPropertyTree *rp = &r->query();
  7978. rp->Link();
  7979. temporaries.append(*new CLocalWUResult(rp));
  7980. }
  7981. }
  7982. void CLocalWorkUnit::loadTemporaries() const
  7983. {
  7984. if (!temporariesCached)
  7985. {
  7986. assertex(temporaries.length() == 0);
  7987. _loadTemporaries();
  7988. temporariesCached = true;
  7989. }
  7990. }
  7991. void CLocalWorkUnit::deleteTemporaries()
  7992. {
  7993. CriticalBlock block(crit);
  7994. if (temporariesCached)
  7995. {
  7996. temporaries.kill();
  7997. temporariesCached = false;
  7998. }
  7999. p->removeProp("Temporaries");
  8000. }
  8001. IWUResult* CLocalWorkUnit::createResult()
  8002. {
  8003. CriticalBlock block(crit);
  8004. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8005. loadResults();
  8006. if (!results.length())
  8007. p->addPropTree("Results");
  8008. IPropertyTree *r = p->queryPropTree("Results");
  8009. IPropertyTree *s = r->addPropTree("Result");
  8010. s->Link();
  8011. IWUResult* q = new CLocalWUResult(s);
  8012. q->Link();
  8013. results.append(*q);
  8014. return q;
  8015. }
  8016. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  8017. {
  8018. CriticalBlock block(crit);
  8019. IConstWUResult *existing = getResultByName(qname);
  8020. if (existing)
  8021. return (IWUResult *) existing;
  8022. IWUResult* q = createResult();
  8023. q->setResultName(qname);
  8024. return q;
  8025. }
  8026. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  8027. {
  8028. CriticalBlock block(crit);
  8029. IConstWUResult *existing = getResultBySequence(seq);
  8030. if (existing)
  8031. return (IWUResult *) existing;
  8032. IWUResult* q = createResult();
  8033. q->setResultSequence(seq);
  8034. return q;
  8035. }
  8036. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  8037. {
  8038. CriticalBlock block(crit);
  8039. loadResults();
  8040. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  8041. }
  8042. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  8043. {
  8044. CriticalBlock block(crit);
  8045. loadResults();
  8046. ForEachItemIn(idx, results)
  8047. {
  8048. SCMStringBuffer name;
  8049. IConstWUResult &cur = results.item(idx);
  8050. cur.getResultName(name);
  8051. if (stricmp(name.str(), qname)==0)
  8052. {
  8053. cur.Link();
  8054. return &cur;
  8055. }
  8056. }
  8057. return NULL;
  8058. }
  8059. IConstWUResult* CLocalWorkUnit::getQueryResultByName(const char *qname) const
  8060. {
  8061. CriticalBlock block(crit);
  8062. loadResults();
  8063. ForEachItemIn(idx, results)
  8064. {
  8065. IConstWUResult &cur = results.item(idx);
  8066. if (!isSpecialResultSequence(cur.getResultSequence()))
  8067. {
  8068. SCMStringBuffer name;
  8069. cur.getResultName(name);
  8070. if (stricmp(name.str(), qname)==0)
  8071. {
  8072. cur.Link();
  8073. return &cur;
  8074. }
  8075. }
  8076. }
  8077. return NULL;
  8078. }
  8079. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  8080. {
  8081. CriticalBlock block(crit);
  8082. loadResults();
  8083. ForEachItemIn(idx, results)
  8084. {
  8085. IConstWUResult &cur = results.item(idx);
  8086. if (cur.getResultSequence() == seq)
  8087. {
  8088. cur.Link();
  8089. return &cur;
  8090. }
  8091. }
  8092. return NULL;
  8093. }
  8094. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  8095. {
  8096. CriticalBlock block(crit);
  8097. loadVariables();
  8098. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  8099. }
  8100. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  8101. {
  8102. CriticalBlock block(crit);
  8103. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8104. return getVariableByName(qname);
  8105. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  8106. return global->getVariableByName(qname);
  8107. }
  8108. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  8109. {
  8110. CriticalBlock block(crit);
  8111. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8112. return updateVariableByName(qname);
  8113. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  8114. return global->updateVariableByName(qname);
  8115. }
  8116. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  8117. {
  8118. CriticalBlock block(crit);
  8119. loadVariables();
  8120. ForEachItemIn(idx, variables)
  8121. {
  8122. SCMStringBuffer name;
  8123. IConstWUResult &cur = variables.item(idx);
  8124. cur.getResultName(name);
  8125. if (stricmp(name.str(), qname)==0)
  8126. {
  8127. cur.Link();
  8128. return &cur;
  8129. }
  8130. }
  8131. return NULL;
  8132. }
  8133. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  8134. {
  8135. CriticalBlock block(crit);
  8136. loadTemporaries();
  8137. ForEachItemIn(idx, temporaries)
  8138. {
  8139. SCMStringBuffer name;
  8140. IConstWUResult &cur = temporaries.item(idx);
  8141. cur.getResultName(name);
  8142. if (stricmp(name.str(), qname)==0)
  8143. {
  8144. cur.Link();
  8145. return &cur;
  8146. }
  8147. }
  8148. return NULL;
  8149. }
  8150. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  8151. {
  8152. CriticalBlock block(crit);
  8153. loadTemporaries();
  8154. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  8155. }
  8156. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  8157. {
  8158. CriticalBlock block(crit);
  8159. IConstWUResult *existing = getTemporaryByName(qname);
  8160. if (existing)
  8161. return (IWUResult *) existing;
  8162. IPropertyTree *vars = (temporaries.length()) ? p->queryPropTree("Temporaries") : p->addPropTree("Temporaries");
  8163. IPropertyTree *s = vars->addPropTree("Variable");
  8164. s->Link();
  8165. IWUResult* q = new CLocalWUResult(s);
  8166. q->Link();
  8167. temporaries.append(*q);
  8168. q->setResultName(qname);
  8169. q->setResultSequence(ResultSequenceInternal);
  8170. return q;
  8171. }
  8172. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  8173. {
  8174. CriticalBlock block(crit);
  8175. IConstWUResult *existing = getVariableByName(qname);
  8176. if (existing)
  8177. return (IWUResult *) existing;
  8178. if (!variables.length())
  8179. p->addPropTree("Variables");
  8180. IPropertyTree *vars = p->queryPropTree("Variables");
  8181. IPropertyTree *s = vars->addPropTree("Variable");
  8182. s->Link();
  8183. IWUResult* q = new CLocalWUResult(s);
  8184. q->Link();
  8185. variables.append(*q);
  8186. q->setResultName(qname);
  8187. q->setResultSequence(ResultSequenceStored);
  8188. return q;
  8189. }
  8190. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  8191. {
  8192. CriticalBlock block(crit);
  8193. IPropertyTree *files = p->queryPropTree("Files");
  8194. if (!files) return;
  8195. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  8196. ICopyArrayOf<IPropertyTree> toRemove;
  8197. ForEach (*iter)
  8198. {
  8199. IPropertyTree &file = iter->query();
  8200. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  8201. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  8202. bool needDelete;
  8203. switch(fileKind)
  8204. {
  8205. case WUFileTemporary:
  8206. if(graph==NULL)
  8207. needDelete = true;
  8208. else
  8209. {
  8210. const char *graphOwner = file.queryProp("@graph");
  8211. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  8212. }
  8213. break;
  8214. case WUFileJobOwned:
  8215. needDelete = ((graph==NULL) && deleteJobOwned);
  8216. break;
  8217. case WUFileOwned:
  8218. needDelete = ((graph==NULL) && deleteOwned);
  8219. break;
  8220. default:
  8221. needDelete = false;
  8222. }
  8223. if(needDelete)
  8224. {
  8225. const char *name = file.queryProp("@name");
  8226. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  8227. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  8228. toRemove.append(file);
  8229. }
  8230. }
  8231. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  8232. }
  8233. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  8234. {
  8235. IDistributedSuperFile *super = file->querySuperFile();
  8236. StringBuffer fname;
  8237. file->getLogicalName(fname);
  8238. if (fname.length())
  8239. {
  8240. StringBuffer path("File[@name=\"");
  8241. path.append(fname).append("\"]");
  8242. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  8243. if (fileTree)
  8244. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  8245. else
  8246. {
  8247. StringBuffer cluster;
  8248. file->getClusterName(0,cluster);
  8249. fileTree = createPTree();
  8250. fileTree->setProp("@name", fname.str());
  8251. fileTree->setProp("@cluster", cluster.str());
  8252. fileTree->setPropInt("@useCount", 1);
  8253. fileTree = filesRead->addPropTree("File", fileTree);
  8254. }
  8255. if (super)
  8256. {
  8257. fileTree->setPropBool("@super", true);
  8258. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  8259. ForEach (*iter)
  8260. {
  8261. IDistributedFile &file = iter->query();
  8262. StringBuffer fname;
  8263. file.getLogicalName(fname);
  8264. fileTree->addPropTree("Subfile")->setProp("@name", fname.str());
  8265. _noteFileRead(&file, filesRead);
  8266. }
  8267. }
  8268. }
  8269. }
  8270. void CLocalWorkUnit::_loadFilesRead() const
  8271. {
  8272. // Nothing to do
  8273. }
  8274. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  8275. {
  8276. if (file)
  8277. {
  8278. CriticalBlock block(crit);
  8279. IPropertyTree *files = p->queryPropTree("FilesRead");
  8280. if (!files)
  8281. files = p->addPropTree("FilesRead");
  8282. _noteFileRead(file, files);
  8283. }
  8284. }
  8285. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  8286. {
  8287. if (fieldUsage)
  8288. {
  8289. CriticalBlock block(crit);
  8290. p->addPropTree("usedsources", fieldUsage);
  8291. }
  8292. }
  8293. void CLocalWorkUnit::_loadFilesWritten() const
  8294. {
  8295. // Nothing to do
  8296. }
  8297. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8298. {
  8299. StringBuffer path("File[@name=\"");
  8300. path.append(fileName).append("\"]");
  8301. if (cluster)
  8302. path.append("[@cluster=\"").append(cluster).append("\"]");
  8303. IPropertyTree *file = files->queryPropTree(path.str());
  8304. if (file) files->removeTree(file);
  8305. file = createPTree();
  8306. file->setProp("@name", fileName);
  8307. if (cluster)
  8308. file->setProp("@cluster", cluster);
  8309. if (graphOwner)
  8310. file->setProp("@graph", graphOwner);
  8311. file->setPropInt("@kind", (unsigned)fileKind);
  8312. if (WUFileTemporary == fileKind)
  8313. file->setPropInt("@usageCount", usageCount);
  8314. files->addPropTree("File", file);
  8315. }
  8316. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8317. {
  8318. CriticalBlock block(crit);
  8319. IPropertyTree *files = p->queryPropTree("Files");
  8320. if (!files)
  8321. files = p->addPropTree("Files");
  8322. if (!clusters)
  8323. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  8324. else
  8325. {
  8326. ForEachItemIn(c, *clusters)
  8327. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  8328. }
  8329. }
  8330. void CLocalWorkUnit::releaseFile(const char *fileName)
  8331. {
  8332. StringBuffer path("File[@name=\"");
  8333. path.append(fileName).append("\"]");
  8334. CriticalBlock block(crit);
  8335. IPropertyTree *files = p->queryPropTree("Files");
  8336. if (!files) return;
  8337. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  8338. ForEach (*fiter)
  8339. {
  8340. IPropertyTree *file = &fiter->query();
  8341. unsigned usageCount = file->getPropInt("@usageCount");
  8342. if (usageCount > 1)
  8343. file->setPropInt("@usageCount", usageCount-1);
  8344. else
  8345. {
  8346. StringAttr name(file->queryProp("@name"));
  8347. files->removeTree(file);
  8348. if (!name.isEmpty()&&(1 == usageCount))
  8349. {
  8350. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  8351. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  8352. }
  8353. }
  8354. }
  8355. }
  8356. void CLocalWorkUnit::clearGraphProgress() const
  8357. {
  8358. }
  8359. void CLocalWorkUnit::resetBeforeGeneration()
  8360. {
  8361. CriticalBlock block(crit);
  8362. //Remove all associated files
  8363. Owned<IWUQuery> q = updateQuery();
  8364. q->removeAssociatedFiles();
  8365. //Remove any pre-existing workflow information
  8366. workflowIterator.clear();
  8367. p->removeProp("Workflow");
  8368. }
  8369. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  8370. {
  8371. StringBuffer path("Files/File[@name=\"");
  8372. path.append(fileName).append("\"]/@usageCount");
  8373. CriticalBlock block(crit);
  8374. return p->getPropInt(path.str());
  8375. }
  8376. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  8377. {
  8378. CriticalBlock block(crit);
  8379. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  8380. if (!fieldUsageTree)
  8381. return NULL;
  8382. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  8383. return new CConstWUFileUsageIterator(iter);
  8384. }
  8385. bool isFilenameResolved(StringBuffer& filename)
  8386. {
  8387. size32_t length = filename.length();
  8388. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  8389. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  8390. return true;
  8391. else
  8392. return false;
  8393. }
  8394. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  8395. {
  8396. bool scopeLoaded = false;
  8397. StringBuffer defaultScope;
  8398. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  8399. if (!files)
  8400. return false; // this query was not compiled with recordFieldUsage option.
  8401. ForEach(*files)
  8402. {
  8403. Owned<IConstWUFileUsage> file = files->get();
  8404. StringBuffer filename(file->queryName());
  8405. size32_t length = filename.length();
  8406. if (length == 0)
  8407. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8408. StringBuffer normalizedFilename;
  8409. // Two cases to handle:
  8410. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  8411. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  8412. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  8413. if (isFilenameResolved(filename))
  8414. {
  8415. // filename cannot be empty (i.e. empty single quotes '')
  8416. if (length == 2)
  8417. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8418. // Remove surrounding single quotes
  8419. StringAttr cleanFilename(filename.str()+1, length-2);
  8420. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  8421. // We need to load a default scope from config and prefix the filename with it.
  8422. if (cleanFilename.str()[0] != '~')
  8423. {
  8424. // loading a default scope from config is expensive, and should be only done once and be reused later.
  8425. if (!scopeLoaded)
  8426. {
  8427. //MORE: This should actually depend on the cluster that was active when the file was read!
  8428. if (!resolveFilePrefix(defaultScope, clusterName))
  8429. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  8430. scopeLoaded = true;
  8431. }
  8432. normalizedFilename.append(defaultScope.str());
  8433. normalizedFilename.append(cleanFilename.str());
  8434. }
  8435. else
  8436. {
  8437. normalizedFilename.append(cleanFilename);
  8438. }
  8439. }
  8440. else
  8441. {
  8442. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  8443. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  8444. normalizedFilename.append(filename.str());
  8445. }
  8446. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  8447. ForEach(*fields)
  8448. {
  8449. Owned<IConstWUFieldUsage> field = fields->get();
  8450. filenames.append(normalizedFilename.str());
  8451. columnnames.append(field->queryName());
  8452. }
  8453. }
  8454. return true;
  8455. }
  8456. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  8457. {
  8458. return p->getPropTree("DiskUsageStats");
  8459. }
  8460. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  8461. {
  8462. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  8463. offset_t maxNodeUsage;
  8464. if (stats)
  8465. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  8466. else
  8467. {
  8468. stats = p->addPropTree("DiskUsageStats");
  8469. maxNodeUsage = 0;
  8470. }
  8471. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  8472. {
  8473. // record all details at time of max node usage.
  8474. stats->setPropInt("@minNode", _minNode);
  8475. stats->setPropInt("@maxNode", _maxNode);
  8476. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  8477. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  8478. stats->setPropInt64("@graphId", _graphId);
  8479. if (_avgNodeUsage)
  8480. {
  8481. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  8482. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  8483. stats->setPropInt("@skewHi", _skewHi);
  8484. stats->setPropInt("@skewLo", _skewLo);
  8485. }
  8486. }
  8487. }
  8488. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  8489. {
  8490. CriticalBlock block(crit);
  8491. _loadFilesWritten();
  8492. return * p->getElements("Files/File");
  8493. }
  8494. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  8495. {
  8496. CriticalBlock block(crit);
  8497. _loadFilesRead();
  8498. return * p->getElements("FilesRead/File");
  8499. }
  8500. //=================================================================================================
  8501. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  8502. {
  8503. CriticalBlock block(crit);
  8504. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  8505. return false;
  8506. const char * currentcluster = queryClusterName();
  8507. const char *wuid = p->queryName();
  8508. StringBuffer curqname;
  8509. getClusterThorQueueName(curqname, currentcluster);
  8510. void *qi = qs->getQ(curqname.str(),wuid);
  8511. if (!qi)
  8512. return false;
  8513. setClusterName(cluster);
  8514. StringBuffer newqname;
  8515. getClusterThorQueueName(newqname, cluster);
  8516. qs->putQ(newqname.str(),wuid,qi);
  8517. return true;
  8518. }
  8519. //=================================================================================================
  8520. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  8521. {
  8522. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  8523. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  8524. ForEach(*graphIter)
  8525. {
  8526. IConstWUGraph &graph = graphIter->query();
  8527. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  8528. SCMStringBuffer gName;
  8529. graph.getName(gName);
  8530. StringBuffer xpath("Graphs/Graph[@name=\"");
  8531. xpath.append(gName.s).append("\"]/xgmml");
  8532. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  8533. if (xgmml) // don't know of any reason it shouldn't exist
  8534. {
  8535. xgmml->removeProp("graphBin");
  8536. xgmml->setPropTree("graph", graphTree.getClear());
  8537. }
  8538. }
  8539. return ret.getClear();
  8540. }
  8541. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  8542. {
  8543. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  8544. ForEach(*iter)
  8545. {
  8546. IPropertyTree &graph = iter->query();
  8547. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  8548. }
  8549. }
  8550. void CLocalWorkUnit::loadGraphs(bool heavy) const
  8551. {
  8552. if (graphsCached < (heavy ? 2 : 1))
  8553. {
  8554. graphs.kill();
  8555. _loadGraphs(heavy);
  8556. graphsCached = (heavy ? 2 : 1);
  8557. }
  8558. }
  8559. EnumMapping graphTypes[] = {
  8560. { GraphTypeAny, "unknown" },
  8561. { GraphTypeProgress, "progress" },
  8562. { GraphTypeEcl, "ECL" },
  8563. { GraphTypeActivities, "activities" },
  8564. { GraphTypeSubProgress, "subgraph" },
  8565. { GraphTypeSize, NULL },
  8566. };
  8567. WUGraphType getGraphTypeFromString(const char* type)
  8568. {
  8569. return (WUGraphType) getEnum(type, graphTypes);
  8570. }
  8571. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  8572. {
  8573. wuidVersion = owner.getWuidVersion();
  8574. }
  8575. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  8576. {
  8577. str.set(p->queryProp("@name"));
  8578. return str;
  8579. }
  8580. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  8581. {
  8582. if (wuidVersion >= 2)
  8583. {
  8584. str.set(p->queryProp("@label"));
  8585. return str;
  8586. }
  8587. else
  8588. {
  8589. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  8590. str.set(xgmml->queryProp("@label"));
  8591. return str;
  8592. }
  8593. }
  8594. WUGraphState CLocalWUGraph::getState() const
  8595. {
  8596. return owner.queryGraphState(p->queryProp("@name"));
  8597. }
  8598. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  8599. {
  8600. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  8601. if (xgmml)
  8602. {
  8603. StringBuffer x;
  8604. toXML(xgmml, x);
  8605. str.set(x.str());
  8606. }
  8607. return str;
  8608. }
  8609. unsigned CLocalWorkUnit::getGraphCount() const
  8610. {
  8611. CriticalBlock block(crit);
  8612. if (p->hasProp("Graphs"))
  8613. {
  8614. return p->queryPropTree("Graphs")->numChildren();
  8615. }
  8616. return 0;
  8617. }
  8618. unsigned CLocalWorkUnit::getSourceFileCount() const
  8619. {
  8620. CriticalBlock block(crit);
  8621. _loadFilesRead();
  8622. if (p->hasProp("FilesRead"))
  8623. {
  8624. return p->queryPropTree("FilesRead")->numChildren();
  8625. }
  8626. return 0;
  8627. }
  8628. unsigned CLocalWorkUnit::getResultCount() const
  8629. {
  8630. CriticalBlock block(crit);
  8631. if (p->hasProp("Results"))
  8632. {
  8633. return p->queryPropTree("Results")->numChildren();
  8634. }
  8635. return 0;
  8636. }
  8637. unsigned CLocalWorkUnit::getVariableCount() const
  8638. {
  8639. CriticalBlock block(crit);
  8640. if (p->hasProp("Variables"))
  8641. {
  8642. return p->queryPropTree("Variables")->numChildren();
  8643. }
  8644. return 0;
  8645. }
  8646. unsigned CLocalWorkUnit::getApplicationValueCount() const
  8647. {
  8648. CriticalBlock block(crit);
  8649. if (p->hasProp("Application"))
  8650. {
  8651. return p->queryPropTree("Application")->numChildren();
  8652. }
  8653. return 0;
  8654. }
  8655. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent, bool hidePasswords)
  8656. {
  8657. appendXMLOpenTag(s, name, NULL, false);
  8658. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  8659. if (attrs->first())
  8660. {
  8661. unsigned attributeindent = indent + (size32_t) strlen(name);
  8662. unsigned count = attrs->count();
  8663. bool doindent = false;
  8664. ForEach(*attrs)
  8665. {
  8666. if (hidePasswords && streq(attrs->queryName(), "@token"))
  8667. continue;
  8668. #ifndef _DEBUG
  8669. if (hidePasswords && streq(attrs->queryName(), "@distributedAccessToken"))
  8670. continue;
  8671. #endif
  8672. if (doindent)
  8673. s.append('\n').appendN(attributeindent, ' ');
  8674. else if (count > 3)
  8675. doindent = true;
  8676. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  8677. }
  8678. }
  8679. s.append('>');
  8680. return s;
  8681. }
  8682. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  8683. {
  8684. CriticalBlock block(crit);
  8685. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  8686. if (!paramTree)
  8687. return str;
  8688. StringBuffer xml;
  8689. if (!hidePasswords)
  8690. toXML(paramTree, xml);
  8691. else
  8692. {
  8693. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0, false).append('\n');
  8694. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  8695. ForEach(*elems)
  8696. {
  8697. const char *paramname = elems->query().queryName();
  8698. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8699. if (p->getPropBool(xpath))
  8700. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  8701. else
  8702. toXML(&elems->query(), xml, 2);
  8703. }
  8704. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  8705. }
  8706. str.set(xml);
  8707. return str;
  8708. }
  8709. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  8710. {
  8711. CriticalBlock block(crit);
  8712. return p->getPropTree("Parameters");
  8713. }
  8714. void CLocalWorkUnit::setXmlParams(const char *params)
  8715. {
  8716. CriticalBlock block(crit);
  8717. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  8718. }
  8719. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  8720. {
  8721. CriticalBlock block(crit);
  8722. p->setPropTree("Parameters", tree);
  8723. }
  8724. unsigned __int64 CLocalWorkUnit::getHash() const
  8725. {
  8726. CriticalBlock block(crit);
  8727. return p->getPropInt64("@hash");
  8728. }
  8729. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  8730. {
  8731. CriticalBlock block(crit);
  8732. p->setPropInt64("@hash", hash);
  8733. }
  8734. // getGraphs / getGraphsMeta
  8735. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  8736. // If a type other than any is requested, a postfilter is needed.
  8737. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  8738. {
  8739. WUGraphType type;
  8740. Owned<T> base;
  8741. bool match()
  8742. {
  8743. return base->query().getType()==type;
  8744. }
  8745. public:
  8746. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  8747. : base(_base), type(_type)
  8748. {
  8749. }
  8750. bool first()
  8751. {
  8752. if (!base->first())
  8753. return false;
  8754. if (match())
  8755. return true;
  8756. return next();
  8757. }
  8758. bool next()
  8759. {
  8760. while (base->next())
  8761. if (match())
  8762. return true;
  8763. return false;
  8764. }
  8765. virtual bool isValid()
  8766. {
  8767. return base->isValid();
  8768. }
  8769. U & query()
  8770. {
  8771. return base->query();
  8772. }
  8773. };
  8774. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  8775. {
  8776. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  8777. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  8778. */
  8779. CriticalBlock block(crit);
  8780. loadGraphs(false);
  8781. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  8782. if (type!=GraphTypeAny)
  8783. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  8784. return *giter;
  8785. }
  8786. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  8787. {
  8788. CriticalBlock block(crit);
  8789. loadGraphs(true);
  8790. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  8791. if (type!=GraphTypeAny)
  8792. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  8793. return *giter;
  8794. }
  8795. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  8796. {
  8797. CriticalBlock block(crit);
  8798. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  8799. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  8800. IPTree *graph = p->queryPropTree(xpath);
  8801. if (graph)
  8802. return new CLocalWUGraph(*this, LINK(graph));
  8803. return NULL;
  8804. }
  8805. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  8806. {
  8807. CriticalBlock block(crit);
  8808. if (!graphs.length())
  8809. p->addPropTree("Graphs");
  8810. IPropertyTree *r = p->queryPropTree("Graphs");
  8811. IPropertyTree *s = r->addPropTree("Graph");
  8812. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  8813. q->setName(name);
  8814. q->setLabel(label);
  8815. q->setType(type);
  8816. q->setWfid(wfid);
  8817. q->setXGMMLTree(xgmml);
  8818. graphs.append(*q);
  8819. }
  8820. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  8821. {
  8822. /* Owned<IRemoteConnection> conn = getProgressConnection();
  8823. if (conn)
  8824. {
  8825. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  8826. if (progress)
  8827. return new CConstGraphProgress(p->queryName(), graphName, progress);
  8828. }
  8829. */
  8830. return NULL;
  8831. }
  8832. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  8833. {
  8834. throwUnexpected(); // Should only be used for persisted workunits
  8835. }
  8836. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  8837. {
  8838. throwUnexpected(); // Should only be used for persisted workunits
  8839. }
  8840. void CLocalWorkUnit::setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  8841. {
  8842. throwUnexpected(); // Should only be used for persisted workunits
  8843. }
  8844. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  8845. {
  8846. throwUnexpected(); // Should only be used for persisted workunits
  8847. }
  8848. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const
  8849. {
  8850. return new CWuGraphStats(LINK(p), creatorType, creator, _wfid, graphName, subgraph);
  8851. }
  8852. void CLocalWUGraph::setName(const char *str)
  8853. {
  8854. p->setProp("@name", str);
  8855. }
  8856. void CLocalWUGraph::setLabel(const char *str)
  8857. {
  8858. p->setProp("@label", str);
  8859. }
  8860. void CLocalWUGraph::setWfid(unsigned wfid)
  8861. {
  8862. p->setPropInt("@wfid", wfid);
  8863. }
  8864. void CLocalWUGraph::setXGMML(const char *str)
  8865. {
  8866. setXGMMLTree(createPTreeFromXMLString(str,ipt_lowmem));
  8867. }
  8868. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  8869. {
  8870. assertex(strcmp(_graph->queryName(), "graph")==0);
  8871. IPropertyTree *xgmml = p->setPropTree("xgmml");
  8872. MemoryBuffer mb;
  8873. _graph->serialize(mb);
  8874. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  8875. // Cassandra workunit code actually lzw compresses the parent anyway
  8876. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  8877. graph.setown(_graph);
  8878. }
  8879. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  8880. {
  8881. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  8882. ForEach (*aIter)
  8883. {
  8884. const char *aName = aIter->queryName()+1;
  8885. if (0 != stricmp("id", aName)) // "id" reserved.
  8886. {
  8887. IPropertyTree *att = targetNode.addPropTree("att");
  8888. att->setProp("@name", aName);
  8889. att->setProp("@value", aIter->queryValue());
  8890. }
  8891. }
  8892. }
  8893. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  8894. {
  8895. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  8896. if (!graphNode) return;
  8897. unsigned nodeId = rootNode.getPropInt("@id");
  8898. StringBuffer progressNodePath("node[@id=\"");
  8899. progressNodePath.append(nodeId).append("\"]");
  8900. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  8901. if (progressNode)
  8902. {
  8903. expandAttributes(*graphNode, *progressNode);
  8904. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  8905. ForEach (*edges)
  8906. {
  8907. IPropertyTree &edge = edges->query();
  8908. StringBuffer edgePath("edge[@id=\"");
  8909. edgePath.append(edge.queryProp("@id")).append("\"]");
  8910. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  8911. if (graphEdge)
  8912. {
  8913. if (progressV < 1)
  8914. mergePTree(graphEdge, &edge);
  8915. else
  8916. { // must translate to XGMML format
  8917. expandAttributes(*graphEdge, edge);
  8918. // 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)
  8919. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  8920. ForEach (*iter)
  8921. {
  8922. IPropertyTree &t = iter->query();
  8923. IPropertyTree *att = graphEdge->addPropTree("att");
  8924. att->setProp("@name", t.queryName());
  8925. att->setProp("@value", t.queryProp(NULL));
  8926. }
  8927. }
  8928. }
  8929. }
  8930. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  8931. ForEach (*nodes)
  8932. {
  8933. IPropertyTree &node = nodes->query();
  8934. StringBuffer nodePath("node[@id=\"");
  8935. nodePath.append(node.queryProp("@id")).append("\"]");
  8936. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  8937. if (_node)
  8938. {
  8939. if (progressV < 1)
  8940. mergePTree(_node, &node);
  8941. else
  8942. { // must translate to XGMML format
  8943. expandAttributes(*_node, node);
  8944. }
  8945. }
  8946. }
  8947. }
  8948. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  8949. ForEach (*iter)
  8950. mergeProgress(iter->query(), progressTree, progressV);
  8951. }
  8952. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  8953. {
  8954. return p->getPropTree("xgmml");
  8955. }
  8956. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  8957. {
  8958. if (!graph)
  8959. {
  8960. // NB: although graphBin introduced in wuidVersion==2,
  8961. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  8962. MemoryBuffer mb;
  8963. if (p->getPropBin("xgmml/graphBin", mb))
  8964. graph.setown(createPTree(mb, ipt_lowmem));
  8965. else
  8966. graph.setown(p->getBranch("xgmml/graph"));
  8967. if (!graph)
  8968. return NULL;
  8969. }
  8970. if (!doMergeProgress)
  8971. return graph.getLink();
  8972. else
  8973. {
  8974. Owned<IPropertyTree> copy = createPTreeFromIPT(graph, ipt_lowmem);
  8975. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  8976. if (progress)
  8977. {
  8978. //MORE: Eventually this should directly access the new stats structure
  8979. unsigned progressV = progress->queryFormatVersion();
  8980. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  8981. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  8982. ForEach (*nodeIterator)
  8983. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  8984. }
  8985. return copy.getClear();
  8986. }
  8987. }
  8988. WUGraphType CLocalWUGraph::getType() const
  8989. {
  8990. return (WUGraphType) getEnum(p, "@type", graphTypes);
  8991. }
  8992. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  8993. {
  8994. str.set(p->queryProp("@type"));
  8995. if (!str.length())
  8996. str.set("unknown");
  8997. return str;
  8998. }
  8999. unsigned CLocalWUGraph::getWfid() const
  9000. {
  9001. return p->getPropInt("@wfid", 0);
  9002. }
  9003. void CLocalWUGraph::setType(WUGraphType _type)
  9004. {
  9005. setEnum(p, "@type", _type, graphTypes);
  9006. }
  9007. //=================================================================================================
  9008. EnumMapping queryFileTypes[] = {
  9009. { FileTypeCpp, "cpp" },
  9010. { FileTypeDll, "dll" },
  9011. { FileTypeResText, "res" },
  9012. { FileTypeHintXml, "hint" },
  9013. { FileTypeXml, "xml" },
  9014. { FileTypeLog, "log" },
  9015. { FileTypeSize, NULL },
  9016. };
  9017. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  9018. {
  9019. }
  9020. WUFileType CLocalWUAssociated::getType() const
  9021. {
  9022. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  9023. }
  9024. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  9025. {
  9026. str.set(p->queryProp("@desc"));
  9027. return str;
  9028. }
  9029. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  9030. {
  9031. str.set(p->queryProp("@ip"));
  9032. return str;
  9033. }
  9034. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  9035. {
  9036. str.set(p->queryProp("@filename"));
  9037. return str;
  9038. }
  9039. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  9040. {
  9041. str.set(pathTail(p->queryProp("@filename")));
  9042. return str;
  9043. }
  9044. unsigned CLocalWUAssociated::getCrc() const
  9045. {
  9046. return p->getPropInt("@crc", 0);
  9047. }
  9048. unsigned CLocalWUAssociated::getMinActivityId() const
  9049. {
  9050. return p->getPropInt("@minActivity", 0);
  9051. }
  9052. unsigned CLocalWUAssociated::getMaxActivityId() const
  9053. {
  9054. return p->getPropInt("@maxActivity", 0);
  9055. }
  9056. //=================================================================================================
  9057. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  9058. {
  9059. associatedCached = false;
  9060. }
  9061. EnumMapping queryTypes[] = {
  9062. { QueryTypeUnknown, "unknown" },
  9063. { QueryTypeEcl, "ECL" },
  9064. { QueryTypeSql, "SQL" },
  9065. { QueryTypeXml, "XML" },
  9066. { QueryTypeAttribute, "Attribute" },
  9067. { QueryTypeSize, NULL },
  9068. };
  9069. WUQueryType CLocalWUQuery::getQueryType() const
  9070. {
  9071. return (WUQueryType) getEnum(p, "@type", queryTypes);
  9072. }
  9073. void CLocalWUQuery::setQueryType(WUQueryType qt)
  9074. {
  9075. setEnum(p, "@type", qt, queryTypes);
  9076. }
  9077. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  9078. {
  9079. const char *text = p->queryProp("Text");
  9080. if (!text)
  9081. text = p->queryProp("ShortText");
  9082. str.set(text);
  9083. return str;
  9084. }
  9085. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  9086. {
  9087. const char * text = p->queryProp("ShortText");
  9088. if (text)
  9089. str.set(text);
  9090. else
  9091. {
  9092. text = p->queryProp("Text");
  9093. if (isArchiveQuery(text))
  9094. {
  9095. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9096. const char * path = xml->queryProp("Query/@attributePath");
  9097. if (path)
  9098. {
  9099. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9100. if (resolved)
  9101. str.set(resolved->queryProp(NULL));
  9102. }
  9103. else
  9104. str.set(xml->queryProp("Query"));
  9105. }
  9106. else
  9107. str.set(text);
  9108. }
  9109. return str;
  9110. }
  9111. bool CLocalWUQuery::isArchive() const
  9112. {
  9113. if (p->hasProp("@isArchive"))
  9114. return p->getPropBool("@isArchive");
  9115. const char *text = p->queryProp("Text");
  9116. return isArchiveQuery(text);
  9117. }
  9118. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  9119. {
  9120. str.set(p->queryProp("@name"));
  9121. return str;
  9122. }
  9123. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  9124. {
  9125. str.set(p->queryProp("@main"));
  9126. return str;
  9127. }
  9128. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  9129. {
  9130. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9131. if (entry)
  9132. entry->getNameTail(str);
  9133. return str;
  9134. }
  9135. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  9136. {
  9137. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  9138. if (entry)
  9139. entry->getName(str);
  9140. return str;
  9141. }
  9142. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  9143. {
  9144. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  9145. if (entry)
  9146. entry->getName(str);
  9147. return str;
  9148. }
  9149. unsigned CLocalWUQuery::getQueryDllCrc() const
  9150. {
  9151. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9152. if (entry)
  9153. return entry->getCrc();
  9154. return 0;
  9155. }
  9156. void CLocalWUQuery::setQueryText(const char *text)
  9157. {
  9158. bool isArchive = isArchiveQuery(text);
  9159. if (isArchive)
  9160. {
  9161. p->setProp("Text", text);
  9162. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9163. const char * path = xml->queryProp("Query/@attributePath");
  9164. if (path)
  9165. {
  9166. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9167. if (resolved)
  9168. p->setProp("ShortText", resolved->queryProp(NULL));
  9169. }
  9170. else
  9171. p->setProp("ShortText", xml->queryProp("Query"));
  9172. }
  9173. else
  9174. {
  9175. p->setProp("Text", text); // At some point in the future we may be able to remove this,
  9176. // but as long as there may be new workunits compiled by old systems, we can't
  9177. p->setProp("ShortText", text);
  9178. }
  9179. p->setPropBool("@isArchive", isArchive);
  9180. if (isArchive)
  9181. p->setPropBool("@hasArchive", true); //preserved if setQueryText is called multiple times. Should setting this be more explicit?
  9182. }
  9183. void CLocalWUQuery::setQueryName(const char *qname)
  9184. {
  9185. p->setProp("@name", qname);
  9186. }
  9187. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  9188. {
  9189. p->setProp("@main", str);
  9190. }
  9191. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  9192. {
  9193. CriticalBlock block(crit);
  9194. loadAssociated();
  9195. StringBuffer xpath;
  9196. xpath.append("Associated/File[@filename=\"").append(name).append("\"]");
  9197. if (p->hasProp(xpath))
  9198. return;
  9199. if (!associated.length())
  9200. p->addPropTree("Associated");
  9201. IPropertyTree *pl = p->queryPropTree("Associated");
  9202. IPropertyTree *s = pl->addPropTree("File");
  9203. setEnum(s, "@type", type, queryFileTypes);
  9204. s->setProp("@filename", name);
  9205. s->setProp("@ip", ip);
  9206. s->setProp("@desc", desc);
  9207. if (crc)
  9208. s->setPropInt("@crc", crc);
  9209. if (minActivity)
  9210. s->setPropInt("@minActivity", minActivity);
  9211. if (maxActivity)
  9212. s->setPropInt("@maxActivity", maxActivity);
  9213. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  9214. associated.append(*q);
  9215. }
  9216. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  9217. {
  9218. CriticalBlock block(crit);
  9219. associatedCached = false;
  9220. associated.kill();
  9221. StringBuffer xpath;
  9222. xpath.append("Associated/File");
  9223. if (type)
  9224. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  9225. if (name)
  9226. xpath.append("[@filename=\"").append(name).append("\"]");
  9227. if (desc)
  9228. xpath.append("[@desc=\"").append(desc).append("\"]");
  9229. p->removeProp(xpath.str());
  9230. }
  9231. void CLocalWUQuery::removeAssociatedFiles()
  9232. {
  9233. associatedCached = false;
  9234. associated.kill();
  9235. p->removeProp("Associated");
  9236. }
  9237. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  9238. {
  9239. CriticalBlock block(crit);
  9240. loadAssociated();
  9241. ForEachItemIn(idx, associated)
  9242. {
  9243. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  9244. if (cur.getType() == type)
  9245. {
  9246. if (index-- == 0)
  9247. return &OLINK(cur);
  9248. }
  9249. }
  9250. return NULL;
  9251. }
  9252. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  9253. {
  9254. const char * name = p->queryProp(propname);
  9255. if (name)
  9256. {
  9257. IPropertyTree *s = createPTree("File");
  9258. setEnum(s, "@type", type, queryFileTypes);
  9259. s->setProp("@filename", name);
  9260. if (crc)
  9261. s->setPropInt("@crc", crc);
  9262. associated.append(*new CLocalWUAssociated(s));
  9263. }
  9264. }
  9265. void CLocalWUQuery::loadAssociated() const
  9266. {
  9267. CriticalBlock block(crit);
  9268. if (!associatedCached)
  9269. {
  9270. assertex(associated.length() == 0);
  9271. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  9272. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  9273. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  9274. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  9275. for (r->first(); r->isValid(); r->next())
  9276. {
  9277. IPropertyTree *rp = &r->query();
  9278. rp->Link();
  9279. associated.append(*new CLocalWUAssociated(rp));
  9280. }
  9281. associatedCached = true;
  9282. }
  9283. }
  9284. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  9285. {
  9286. CriticalBlock block(crit);
  9287. loadAssociated();
  9288. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  9289. }
  9290. //========================================================================================
  9291. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  9292. {
  9293. }
  9294. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  9295. {
  9296. str.set(p->queryProp("@module"));
  9297. return str;
  9298. }
  9299. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  9300. {
  9301. str.set(p->queryProp("@attribute"));
  9302. return str;
  9303. }
  9304. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  9305. {
  9306. str.set(p->queryProp("@defaultName"));
  9307. return str;
  9308. }
  9309. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  9310. {
  9311. return (unsigned) p->getPropInt("@crc");
  9312. }
  9313. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  9314. {
  9315. if (!name)
  9316. {
  9317. StringBuffer ws_info;
  9318. ws_info.appendf("<%s ", p->queryName());
  9319. Owned<IAttributeIterator> attrs = p->getAttributes();
  9320. for(attrs->first(); attrs->isValid(); attrs->next())
  9321. {
  9322. const char *name = attrs->queryName()+1;
  9323. const char *value = attrs->queryValue();
  9324. ws_info.appendf("%s='%s' ", name, value);
  9325. }
  9326. ws_info.append("> \n");
  9327. Owned<IPropertyTreeIterator> info = p->getElements("*");
  9328. ForEach(*info)
  9329. {
  9330. IPropertyTree &item = info->query();
  9331. const char *name = item.queryName();
  9332. if (name)
  9333. {
  9334. MemoryBuffer mb;
  9335. bool isbin = p->isBinary(name);
  9336. if (isbin)
  9337. {
  9338. p->getPropBin(name,mb);
  9339. if (mb.length())
  9340. {
  9341. unsigned len = 0;
  9342. mb.read(len);
  9343. StringBuffer encodedString;
  9344. StringBuffer val(len, (const char *) mb.readDirect(len));
  9345. encodeXML(val, encodedString);
  9346. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  9347. }
  9348. }
  9349. else
  9350. {
  9351. StringBuffer tmp;
  9352. toXML(&item, tmp);
  9353. ws_info.append(tmp.str());
  9354. }
  9355. }
  9356. }
  9357. ws_info.appendf("</%s>", p->queryName());
  9358. str.setLen(ws_info.str(), ws_info.length());
  9359. }
  9360. else
  9361. {
  9362. MemoryBuffer mb;
  9363. p->getPropBin(name,mb);
  9364. if (mb.length())
  9365. {
  9366. unsigned len;
  9367. mb.read(len);
  9368. str.setLen((const char *) mb.readDirect(len), len);
  9369. }
  9370. }
  9371. return str;
  9372. }
  9373. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  9374. {
  9375. str.set(p->queryProp(name));
  9376. return str;
  9377. }
  9378. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  9379. {
  9380. p->setProp("@module", mname);
  9381. }
  9382. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  9383. {
  9384. p->setProp("@attribute", aname);
  9385. }
  9386. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  9387. {
  9388. p->setProp("@defaultName", dname);
  9389. }
  9390. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  9391. {
  9392. p->setPropInt("@crc", crc);
  9393. }
  9394. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  9395. {
  9396. MemoryBuffer m;
  9397. unsigned len = (size32_t)strlen(info);
  9398. serializeLPString(len, info, m);
  9399. p->setPropBin(name, m.length(), m.toByteArray());
  9400. }
  9401. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  9402. {
  9403. p->setProp(name, info);
  9404. }
  9405. //========================================================================================
  9406. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  9407. {
  9408. }
  9409. EnumMapping resultStatuses[] = {
  9410. { ResultStatusUndefined, "undefined" },
  9411. { ResultStatusCalculated, "calculated" },
  9412. { ResultStatusSupplied, "supplied" },
  9413. { ResultStatusFailed, "failed" },
  9414. { ResultStatusPartial, "partial" },
  9415. { ResultStatusSize, NULL }
  9416. };
  9417. WUResultStatus CLocalWUResult::getResultStatus() const
  9418. {
  9419. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  9420. }
  9421. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  9422. {
  9423. str.set(p->queryProp("@name"));
  9424. return str;
  9425. }
  9426. int CLocalWUResult::getResultSequence() const
  9427. {
  9428. return p->getPropInt("@sequence", -1);
  9429. }
  9430. bool CLocalWUResult::isResultScalar() const
  9431. {
  9432. return p->getPropInt("@isScalar", 1) != 0;
  9433. }
  9434. bool findSize(int size, IntArray &sizes)
  9435. {
  9436. ForEachItemIn(idx, sizes)
  9437. {
  9438. if (sizes.item(idx)==size)
  9439. return true;
  9440. }
  9441. return false;
  9442. }
  9443. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  9444. {
  9445. MemoryBuffer schema;
  9446. p->getPropBin("SchemaRaw", schema);
  9447. if (schema.length())
  9448. {
  9449. for (;;)
  9450. {
  9451. StringAttr name;
  9452. schema.read(name);
  9453. if (*schema.readDirect(0)==type_void)
  9454. break;
  9455. names.append(*new StringAttrItem(name));
  9456. types.append(*deserializeType(schema)); // MORE - nested records!
  9457. }
  9458. schema.skip(1);
  9459. if (schema.length() != schema.getPos())
  9460. {
  9461. unsigned eclLen;
  9462. schema.read(eclLen);
  9463. const char * schemaData = (const char *)schema.readDirect(eclLen);
  9464. if (eclText)
  9465. {
  9466. eclText->setLen(schemaData, eclLen);
  9467. if ((eclLen == 0) && names.ordinality())
  9468. {
  9469. const char * firstName = names.item(0).text;
  9470. StringBuffer temp;
  9471. temp.append("RECORD ");
  9472. types.item(0).getECLType(temp);
  9473. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  9474. eclText->set(temp.str());
  9475. }
  9476. }
  9477. }
  9478. }
  9479. }
  9480. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  9481. {
  9482. ForEachItemIn(idx, types)
  9483. {
  9484. StringAttrItem &name = names.item(idx);
  9485. ITypeInfo &type = types.item(idx);
  9486. unsigned size = type.getSize();
  9487. switch(type.getTypeCode())
  9488. {
  9489. case type_data:
  9490. if (size==UNKNOWN_LENGTH)
  9491. {
  9492. if (in.remaining() < sizeof(int))
  9493. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9494. in.read(size);
  9495. }
  9496. outputXmlData(size, in.readDirect(size), name.text, out);
  9497. break;
  9498. case type_string:
  9499. if (size==UNKNOWN_LENGTH)
  9500. {
  9501. if (in.remaining() < sizeof(int))
  9502. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9503. in.read(size);
  9504. }
  9505. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  9506. break;
  9507. case type_varstring:
  9508. {
  9509. if (size == UNKNOWN_LENGTH)
  9510. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  9511. const char * text = (const char *) in.readDirect(size);
  9512. outputXmlString((size32_t)strlen(text), text, name.text, out);
  9513. break;
  9514. }
  9515. case type_unicode:
  9516. {
  9517. unsigned len = type.getStringLen();
  9518. if (size==UNKNOWN_LENGTH)
  9519. in.read(len);
  9520. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  9521. }
  9522. break;
  9523. case type_utf8:
  9524. {
  9525. unsigned len = type.getStringLen();
  9526. if (size==UNKNOWN_LENGTH)
  9527. {
  9528. in.read(len);
  9529. size = rtlUtf8Size(len, in.readDirect(0));
  9530. }
  9531. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  9532. }
  9533. break;
  9534. case type_qstring:
  9535. {
  9536. unsigned len = type.getStringLen();
  9537. if (size==UNKNOWN_LENGTH)
  9538. in.read(len);
  9539. unsigned outlen;
  9540. char *outstr;
  9541. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  9542. outputXmlString(outlen, outstr, name.text, out);
  9543. free(outstr);
  9544. break;
  9545. }
  9546. case type_int:
  9547. case type_swapint:
  9548. if (type.isSigned())
  9549. {
  9550. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9551. unsigned __int64 cval8 = 0;
  9552. //MORE: I think this is wrong - swapped doesn't mean little/big/
  9553. if (type.isSwappedEndian())
  9554. {
  9555. unsigned idx = 0;
  9556. if (raw[idx] & 0x80)
  9557. cval8 = (__int64)-1;
  9558. while (size--)
  9559. cval8 = (cval8 << 8) | raw[idx++];
  9560. }
  9561. else
  9562. {
  9563. if (raw[size-1] & 0x80)
  9564. cval8 = (__int64)-1;
  9565. while (size--)
  9566. cval8 = (cval8 << 8) | raw[size];
  9567. }
  9568. outputXmlInt((__int64) cval8, name.text, out);
  9569. }
  9570. else
  9571. {
  9572. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9573. unsigned __int64 cval8 = 0;
  9574. if (type.isSwappedEndian())
  9575. {
  9576. unsigned idx = 0;
  9577. while (size--)
  9578. cval8 = (cval8 << 8) | raw[idx++];
  9579. }
  9580. else
  9581. {
  9582. while (size--)
  9583. cval8 = (cval8 << 8) | raw[size];
  9584. }
  9585. outputXmlUInt(cval8, name.text, out);
  9586. }
  9587. break;
  9588. case type_boolean:
  9589. bool cvalb;
  9590. in.read(cvalb);
  9591. outputXmlBool(cvalb, name.text, out);
  9592. break;
  9593. case type_decimal:
  9594. if (type.isSigned())
  9595. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9596. else
  9597. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9598. break;
  9599. case type_real:
  9600. double cvald;
  9601. switch(size)
  9602. {
  9603. case 4:
  9604. float cvalf;
  9605. in.read(cvalf);
  9606. cvald = cvalf;
  9607. break;
  9608. case 8:
  9609. in.read(cvald);
  9610. break;
  9611. default:
  9612. throwUnexpected();
  9613. }
  9614. outputXmlReal(cvald, name.text, out);
  9615. break;
  9616. default:
  9617. assertex(!"unexpected type in raw record");
  9618. break;
  9619. }
  9620. }
  9621. }
  9622. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  9623. {
  9624. TypeInfoArray types;
  9625. StringAttrArray names;
  9626. getSchema(types, names);
  9627. StringBuffer xml;
  9628. const char * name = p->queryProp("@name");
  9629. if (name)
  9630. xml.appendf("<Dataset name=\'%s\'>\n", name);
  9631. else
  9632. xml.append("<Dataset>\n");
  9633. if (hidePassword && p->getPropBool("Format/@password"))
  9634. {
  9635. xml.append(" <Row>");
  9636. appendXMLTag(xml, name, "****");
  9637. xml.append("</Row>\n");
  9638. }
  9639. else if (p->hasProp("Value"))
  9640. {
  9641. MemoryBuffer raw;
  9642. p->getPropBin("Value", raw);
  9643. unsigned __int64 numrows = getResultRowCount();
  9644. while (numrows--)
  9645. {
  9646. xml.append(" <Row>");
  9647. readRow(xml, raw, types, names);
  9648. xml.append("</Row>\n");
  9649. }
  9650. }
  9651. else if (p->hasProp("xmlValue"))
  9652. {
  9653. xml.append(" <Row>");
  9654. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  9655. xml.append("</Row>\n");
  9656. }
  9657. xml.append("</Dataset>\n");
  9658. str.set(xml.str());
  9659. return str;
  9660. }
  9661. IProperties *CLocalWUResult::queryResultXmlns()
  9662. {
  9663. CriticalBlock block(crit);
  9664. if (xmlns)
  9665. return xmlns;
  9666. xmlns.setown(createProperties());
  9667. Owned<IAttributeIterator> it = p->getAttributes();
  9668. unsigned prefixLen = strlen("@xmlns");
  9669. ForEach(*it)
  9670. {
  9671. const char *name = it->queryName();
  9672. if (!strncmp("@xmlns", name, prefixLen))
  9673. {
  9674. if (name[prefixLen]==':') //normal case
  9675. xmlns->setProp(name+prefixLen+1, it->queryValue());
  9676. else if (!name[prefixLen]) //special case, unprefixed namespace
  9677. xmlns->setProp("xmlns", it->queryValue());
  9678. }
  9679. }
  9680. return xmlns;
  9681. }
  9682. unsigned CLocalWUResult::getResultFetchSize() const
  9683. {
  9684. return p->getPropInt("fetchSize", 100);
  9685. }
  9686. __int64 CLocalWUResult::getResultTotalRowCount() const
  9687. {
  9688. return p->getPropInt64("totalRowCount", -1);
  9689. }
  9690. __int64 CLocalWUResult::getResultRowCount() const
  9691. {
  9692. return p->getPropInt64("rowCount", 0);
  9693. }
  9694. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  9695. {
  9696. ecl.set(p->queryProp("datasetEcl"));
  9697. defs.set(p->queryProp("datasetEclDefs"));
  9698. }
  9699. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  9700. {
  9701. val.set(p->queryProp("logicalName"));
  9702. return val;
  9703. }
  9704. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  9705. {
  9706. ecl.set(p->queryProp("keyField"));
  9707. return ecl;
  9708. }
  9709. unsigned CLocalWUResult::getResultRequestedRows() const
  9710. {
  9711. return p->getPropInt("requestedRows", 1);
  9712. }
  9713. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  9714. {
  9715. TypeInfoArray types;
  9716. StringAttrArray names;
  9717. getSchema(types, names, &str);
  9718. return str;
  9719. }
  9720. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  9721. {
  9722. str.set(p->queryProp("@recordSizeEntry"));
  9723. return str;
  9724. }
  9725. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  9726. {
  9727. str.set(p->queryProp("@transformerEntry"));
  9728. return str;
  9729. }
  9730. __int64 CLocalWUResult::getResultRowLimit() const
  9731. {
  9732. return p->getPropInt64("@rowLimit");
  9733. }
  9734. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  9735. {
  9736. str.set(p->queryProp("@tempFilename"));
  9737. return str;
  9738. }
  9739. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  9740. {
  9741. str.clear();
  9742. if (!name || !*name)
  9743. return str;
  9744. IPropertyTree *format = p->queryPropTree("Format");
  9745. if (!format)
  9746. return str;
  9747. VStringBuffer xpath("@%s", name);
  9748. str.set(format->queryProp(xpath));
  9749. return str;
  9750. }
  9751. void CLocalWUResult::getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const
  9752. {
  9753. _graph.set(p->queryProp("@graph"));
  9754. _activityId = p->getPropInt("@activity", 0);
  9755. }
  9756. void CLocalWUResult::setResultStatus(WUResultStatus status)
  9757. {
  9758. setEnum(p, "@status", status, resultStatuses);
  9759. if (status==ResultStatusUndefined)
  9760. {
  9761. p->removeProp("Value");
  9762. p->removeProp("totalRowCount");
  9763. p->removeProp("rowCount");
  9764. p->removeProp("@format");
  9765. p->removeProp("@tempFileNmae");
  9766. p->removeProp("logicalName");
  9767. }
  9768. }
  9769. void CLocalWUResult::setResultName(const char *s)
  9770. {
  9771. p->setProp("@name", s);
  9772. }
  9773. void CLocalWUResult::setResultSequence(unsigned seq)
  9774. {
  9775. p->setPropInt("@sequence", seq);
  9776. }
  9777. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  9778. {
  9779. p->setPropBin("SchemaRaw", size, schema);
  9780. }
  9781. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  9782. {
  9783. StringBuffer xpath("@xmlns");
  9784. if (prefix && *prefix)
  9785. xpath.append(':').append(prefix);
  9786. p->setProp(xpath, uri);
  9787. }
  9788. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  9789. {
  9790. if (!name || !*name)
  9791. return;
  9792. IPropertyTree *format = ensurePTree(p, "Format");
  9793. VStringBuffer xpath("@%s", name);
  9794. format->setProp(xpath, value);
  9795. }
  9796. void CLocalWUResult::setResultWriteLocation(const char * _graph, unsigned _activityId)
  9797. {
  9798. p->setProp("@graph", _graph);
  9799. p->setPropInt("@activity", _activityId);
  9800. }
  9801. void CLocalWUResult::setResultScalar(bool isScalar)
  9802. {
  9803. p->setPropInt("@isScalar", (int) isScalar);
  9804. if (isScalar)
  9805. setResultTotalRowCount(1);
  9806. }
  9807. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  9808. {
  9809. p->setPropBin("Value", len, data);
  9810. setResultStatus(ResultStatusSupplied);
  9811. setResultFormat(format);
  9812. }
  9813. void CLocalWUResult::setResultFormat(WUResultFormat format)
  9814. {
  9815. switch (format)
  9816. {
  9817. case ResultFormatXml:
  9818. p->setProp("@format","xml");
  9819. break;
  9820. case ResultFormatXmlSet:
  9821. p->setProp("@format","xmlSet");
  9822. break;
  9823. case ResultFormatCsv:
  9824. p->setProp("@format","csv");
  9825. break;
  9826. default:
  9827. p->removeProp("@format");
  9828. break;
  9829. }
  9830. }
  9831. void CLocalWUResult::setResultXML(const char *val)
  9832. {
  9833. p->setProp("xmlValue", val);
  9834. }
  9835. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  9836. {
  9837. p->appendPropBin("Value", len, data);
  9838. setResultStatus(ResultStatusPartial);
  9839. const char *existingFormat = p->queryProp("@format");
  9840. const char *formatStr = NULL;
  9841. switch (format)
  9842. {
  9843. case ResultFormatXml:
  9844. formatStr = "xml";
  9845. break;
  9846. case ResultFormatXmlSet:
  9847. formatStr = "xmlSet";
  9848. break;
  9849. case ResultFormatCsv:
  9850. formatStr = "csv";
  9851. break;
  9852. default:
  9853. existingFormat = nullptr;
  9854. p->removeProp("@format");
  9855. break;
  9856. }
  9857. if (format)
  9858. {
  9859. if (existingFormat)
  9860. {
  9861. if (0 != stricmp(formatStr, existingFormat))
  9862. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  9863. }
  9864. else
  9865. p->setProp("@format", formatStr);
  9866. }
  9867. }
  9868. void CLocalWUResult::setResultFetchSize(unsigned rows)
  9869. {
  9870. p->setPropInt("fetchSize", rows);
  9871. }
  9872. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  9873. {
  9874. p->setPropInt64("totalRowCount", rows);
  9875. }
  9876. void CLocalWUResult::setResultRowCount(__int64 rows)
  9877. {
  9878. p->setPropInt64("rowCount", rows);
  9879. }
  9880. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  9881. {
  9882. p->setProp("datasetEcl", ecl);
  9883. p->setProp("datasetEclDefs", defs);
  9884. }
  9885. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  9886. {
  9887. p->setProp("logicalName", logicalName);
  9888. }
  9889. void CLocalWUResult::setResultKeyField(const char *ecl)
  9890. {
  9891. p->setProp("keyField", ecl);
  9892. }
  9893. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  9894. {
  9895. p->setPropInt("requestedRows", rows);
  9896. }
  9897. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  9898. {
  9899. p->setProp("@recordSizeEntry", entry);
  9900. }
  9901. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  9902. {
  9903. p->setProp("@transformerEntry", entry);
  9904. }
  9905. void CLocalWUResult::setResultRowLimit(__int64 value)
  9906. {
  9907. p->setPropInt64("@rowLimit", value);
  9908. }
  9909. void CLocalWUResult::setResultFilename(const char * name)
  9910. {
  9911. p->setProp("@tempFilename", name);
  9912. }
  9913. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  9914. __int64 CLocalWUResult::getResultInt() const
  9915. {
  9916. __int64 result = 0;
  9917. MemoryBuffer s;
  9918. p->getPropBin("Value", s);
  9919. if (s.length())
  9920. s.read(result);
  9921. else
  9922. {
  9923. // NOTE - we use this rather than getPropInt64 since it handles uint64 values up to MAX_UINT better (for our purposes)
  9924. const char *val = p->queryProp("xmlValue");
  9925. if (val)
  9926. result = rtlStrToInt8(strlen(val), val);
  9927. }
  9928. return result;
  9929. }
  9930. bool CLocalWUResult::getResultBool() const
  9931. {
  9932. bool result = false;
  9933. MemoryBuffer s;
  9934. p->getPropBin("Value", s);
  9935. if (s.length())
  9936. s.read(result);
  9937. else
  9938. result = p->getPropBool("xmlValue");
  9939. return result;
  9940. }
  9941. double CLocalWUResult::getResultReal() const
  9942. {
  9943. double result = 0;
  9944. MemoryBuffer s;
  9945. p->getPropBin("Value", s);
  9946. if (s.length())
  9947. s.read(result);
  9948. else
  9949. {
  9950. const char *xmlVal = p->queryProp("xmlValue");
  9951. if (xmlVal)
  9952. result = atof(xmlVal);
  9953. }
  9954. return result;
  9955. }
  9956. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  9957. {
  9958. MemoryBuffer s;
  9959. p->getPropBin("Value", s);
  9960. if (s.length())
  9961. {
  9962. assertex(s.length() == len);
  9963. s.read(len, val);
  9964. }
  9965. else
  9966. {
  9967. const char *xmlVal = p->queryProp("xmlValue");
  9968. if (xmlVal)
  9969. {
  9970. Decimal d;
  9971. d.setString(strlen(xmlVal), xmlVal);
  9972. if (isSigned)
  9973. d.getDecimal(len, precision, val);
  9974. else
  9975. d.getUDecimal(len, precision, val);
  9976. }
  9977. else
  9978. memset(val, 0, len);
  9979. }
  9980. }
  9981. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  9982. {
  9983. if (hidePassword && p->getPropBool("@password"))
  9984. {
  9985. str.set("****");
  9986. return str;
  9987. }
  9988. MemoryBuffer s;
  9989. p->getPropBin("Value", s);
  9990. if (s.length())
  9991. {
  9992. unsigned len;
  9993. s.read(len);
  9994. str.setLen((const char *) s.readDirect(len), len);
  9995. }
  9996. else
  9997. {
  9998. p->getPropBin("xmlValue", s);
  9999. if (p->isBinary("xmlValue"))
  10000. str.setLen(s.toByteArray(), s.length());
  10001. else
  10002. {
  10003. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  10004. str.set(ascii);
  10005. rtlFree(ascii);
  10006. }
  10007. }
  10008. return str;
  10009. }
  10010. WUResultFormat CLocalWUResult::getResultFormat() const
  10011. {
  10012. const char * format = p->queryProp("@format");
  10013. if (!format)
  10014. return ResultFormatRaw;
  10015. else if (strcmp(format, "xml") == 0)
  10016. return ResultFormatXml;
  10017. else if (strcmp(format, "xmlSet") == 0)
  10018. return ResultFormatXmlSet;
  10019. else if (strcmp(format, "csv") == 0)
  10020. return ResultFormatCsv;
  10021. else
  10022. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  10023. }
  10024. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10025. {
  10026. MemoryBuffer s;
  10027. p->getPropBin("Value", s);
  10028. unsigned len = s.length();
  10029. if (len)
  10030. {
  10031. WUResultFormat format = getResultFormat();
  10032. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  10033. {
  10034. if (!xmlTransformer)
  10035. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  10036. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  10037. }
  10038. else if (format == ResultFormatCsv)
  10039. {
  10040. if (!csvTransformer)
  10041. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  10042. csvTransformer->transform(data, len, s.readDirect(len), true);
  10043. }
  10044. else
  10045. data.setLen(s.readDirect(len), len);
  10046. }
  10047. else
  10048. data.clear();
  10049. return data;
  10050. }
  10051. unsigned CLocalWUResult::getResultHash() const
  10052. {
  10053. MemoryBuffer s;
  10054. p->getPropBin("Value", s);
  10055. unsigned len = s.length();
  10056. const byte * data = (const byte *)s.toByteArray();
  10057. return ~hashc(data, len, ~0);
  10058. }
  10059. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  10060. {
  10061. MemoryBuffer s;
  10062. p->getPropBin("Value", s);
  10063. if (s.length())
  10064. {
  10065. unsigned len;
  10066. s.read(len);
  10067. data.setLen(s.readDirect(len*2), len*2);
  10068. }
  10069. else
  10070. {
  10071. StringBuffer utf8;
  10072. if (p->getProp("xmlValue", utf8))
  10073. {
  10074. unsigned outlen;
  10075. UChar *out;
  10076. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  10077. data.setLen(out, outlen*2);
  10078. rtlFree(out);
  10079. }
  10080. else
  10081. data.clear();
  10082. }
  10083. return data;
  10084. }
  10085. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10086. {
  10087. WUResultFormat format = getResultFormat();
  10088. if (format == ResultFormatRaw)
  10089. {
  10090. //MORE: This should not load the whole property...
  10091. MemoryBuffer s;
  10092. p->getPropBin("Value", s);
  10093. return s.length();
  10094. }
  10095. else
  10096. {
  10097. MemoryBuffer temp;
  10098. MemoryBuffer2IDataVal adaptor(temp);
  10099. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10100. return temp.length();
  10101. }
  10102. }
  10103. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10104. {
  10105. WUResultFormat format = getResultFormat();
  10106. if (format != ResultFormatRaw)
  10107. {
  10108. MemoryBuffer temp;
  10109. MemoryBuffer2IDataVal adaptor(temp);
  10110. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10111. unsigned len = temp.length();
  10112. if (from > len) from = len;
  10113. if (from + length > len) length = len - from;
  10114. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  10115. return data;
  10116. }
  10117. else
  10118. {
  10119. //MORE: This should not load the whole property, and should be different from the code above...
  10120. MemoryBuffer s;
  10121. p->getPropBin("Value", s);
  10122. unsigned len = s.length();
  10123. if (from > len) from = len;
  10124. if (from + length > len) length = len - from;
  10125. data.setLen(s.readDirect(len) + from, (size32_t)length);
  10126. return data;
  10127. }
  10128. }
  10129. bool CLocalWUResult::getResultIsAll() const
  10130. {
  10131. return p->getPropBool("@isAll", false);
  10132. }
  10133. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  10134. void CLocalWUResult::setResultInt(__int64 val)
  10135. {
  10136. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  10137. MemoryBuffer m;
  10138. serializeInt8(val, m);
  10139. p->setPropBin("Value", m.length(), m.toByteArray());
  10140. setResultRowCount(1);
  10141. setResultTotalRowCount(1);
  10142. }
  10143. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  10144. {
  10145. setResultInt((__int64) val);
  10146. }
  10147. void CLocalWUResult::setResultReal(double val)
  10148. {
  10149. // Note: we always serialize scalar real results as real8, and schema must reflect this
  10150. MemoryBuffer m;
  10151. serializeReal8(val, m);
  10152. p->setPropBin("Value", m.length(), m.toByteArray());
  10153. setResultRowCount(1);
  10154. setResultTotalRowCount(1);
  10155. }
  10156. void CLocalWUResult::setResultBool(bool val)
  10157. {
  10158. MemoryBuffer m;
  10159. serializeBool(val, m);
  10160. p->setPropBin("Value", m.length(), m.toByteArray());
  10161. setResultRowCount(1);
  10162. setResultTotalRowCount(1);
  10163. }
  10164. void CLocalWUResult::setResultString(const char *val, unsigned len)
  10165. {
  10166. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10167. MemoryBuffer m;
  10168. serializeLPString(len, val, m);
  10169. p->setPropBin("Value", m.length(), m.toByteArray());
  10170. setResultRowCount(1);
  10171. setResultTotalRowCount(1);
  10172. }
  10173. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  10174. {
  10175. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10176. MemoryBuffer m;
  10177. m.append(len).append(len*2, val);
  10178. p->setPropBin("Value", m.length(), m.toByteArray());
  10179. setResultRowCount(1);
  10180. setResultTotalRowCount(1);
  10181. }
  10182. void CLocalWUResult::setResultData(const void *val, unsigned len)
  10183. {
  10184. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  10185. MemoryBuffer m;
  10186. serializeLPString(len, (const char *)val, m);
  10187. p->setPropBin("Value", m.length(), m.toByteArray());
  10188. setResultRowCount(1);
  10189. setResultTotalRowCount(1);
  10190. }
  10191. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  10192. {
  10193. // Note: serialized as data but with length known from schema
  10194. MemoryBuffer m;
  10195. serializeFixedData(len, val, m);
  10196. p->setPropBin("Value", m.length(), m.toByteArray());
  10197. setResultRowCount(1);
  10198. setResultTotalRowCount(1);
  10199. }
  10200. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  10201. {
  10202. p->setPropBin("Value", len, data);
  10203. setResultRowCount(1);
  10204. setResultTotalRowCount(1);
  10205. setResultFormat(ResultFormatRaw);
  10206. }
  10207. void CLocalWUResult::setResultIsAll(bool value)
  10208. {
  10209. p->setPropBool("@isAll", value);
  10210. }
  10211. //==========================================================================================
  10212. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  10213. {
  10214. }
  10215. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  10216. {
  10217. str.set(p->queryProp("@dllname"));
  10218. return str;
  10219. }
  10220. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  10221. {
  10222. str.set(p->queryProp("@version"));
  10223. return str;
  10224. }
  10225. void CLocalWUPlugin::setPluginName(const char *str)
  10226. {
  10227. p->setProp("@dllname", str);
  10228. }
  10229. void CLocalWUPlugin::setPluginVersion(const char *str)
  10230. {
  10231. p->setProp("@version", str);
  10232. }
  10233. //==========================================================================================
  10234. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  10235. {
  10236. }
  10237. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  10238. {
  10239. str.set(p->queryProp("@name"));
  10240. return str;
  10241. }
  10242. void CLocalWULibrary::setName(const char *str)
  10243. {
  10244. p->setProp("@name", str);
  10245. }
  10246. //==========================================================================================
  10247. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  10248. {
  10249. }
  10250. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  10251. {
  10252. str.set(p->queryProp("@source"));
  10253. return str;
  10254. }
  10255. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  10256. {
  10257. str.set(p->queryProp(NULL));
  10258. return str;
  10259. }
  10260. unsigned CLocalWUException::getExceptionCode() const
  10261. {
  10262. return p->getPropInt("@code", 0);
  10263. }
  10264. ErrorSeverity CLocalWUException::getSeverity() const
  10265. {
  10266. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  10267. }
  10268. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  10269. {
  10270. dt.set(p->queryProp("@time"));
  10271. return dt;
  10272. }
  10273. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  10274. {
  10275. str.set(p->queryProp("@filename"));
  10276. return str;
  10277. }
  10278. unsigned CLocalWUException::getExceptionLineNo() const
  10279. {
  10280. return p->getPropInt("@row", 0);
  10281. }
  10282. unsigned CLocalWUException::getExceptionColumn() const
  10283. {
  10284. return p->getPropInt("@col", 0);
  10285. }
  10286. unsigned CLocalWUException::getActivityId() const
  10287. {
  10288. const char * scope = queryScope();
  10289. if (scope)
  10290. {
  10291. const char * colon = strrchr(scope, ':');
  10292. if (colon && hasPrefix(colon+1, ActivityScopePrefix, true))
  10293. return atoi(colon+1+strlen(ActivityScopePrefix));
  10294. }
  10295. return p->getPropInt("@activity", 0);
  10296. }
  10297. unsigned CLocalWUException::getSequence() const
  10298. {
  10299. return p->getPropInt("@sequence", 0);
  10300. }
  10301. const char * CLocalWUException::queryScope() const
  10302. {
  10303. return p->queryProp("@scope");
  10304. }
  10305. unsigned CLocalWUException::getPriority() const
  10306. {
  10307. return p->getPropInt("@prio", 0);
  10308. }
  10309. void CLocalWUException::setExceptionSource(const char *str)
  10310. {
  10311. p->setProp("@source", str);
  10312. }
  10313. void CLocalWUException::setExceptionMessage(const char *str)
  10314. {
  10315. p->setProp(NULL, str);
  10316. }
  10317. void CLocalWUException::setExceptionCode(unsigned code)
  10318. {
  10319. p->setPropInt("@code", code);
  10320. }
  10321. void CLocalWUException::setSeverity(ErrorSeverity level)
  10322. {
  10323. p->setPropInt("@severity", level);
  10324. }
  10325. void CLocalWUException::setTimeStamp(const char *str)
  10326. {
  10327. p->setProp("@time", str);
  10328. }
  10329. void CLocalWUException::setExceptionFileName(const char *str)
  10330. {
  10331. p->setProp("@filename", str);
  10332. }
  10333. void CLocalWUException::setExceptionLineNo(unsigned r)
  10334. {
  10335. p->setPropInt("@row", r);
  10336. }
  10337. void CLocalWUException::setExceptionColumn(unsigned c)
  10338. {
  10339. p->setPropInt("@col", c);
  10340. }
  10341. void CLocalWUException::setActivityId(unsigned _id)
  10342. {
  10343. p->setPropInt("@activity", _id);
  10344. }
  10345. void CLocalWUException::setScope(const char * _scope)
  10346. {
  10347. p->setProp("@scope", _scope);
  10348. }
  10349. void CLocalWUException::setPriority(unsigned _priority)
  10350. {
  10351. p->setPropInt("@prio", _priority);
  10352. }
  10353. //==========================================================================================
  10354. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  10355. {
  10356. StringAttrBuilder propPath(prop);
  10357. propPath.append("*[").append(child).append("]");
  10358. }
  10359. const char * CLocalWUAppValue::queryApplication() const
  10360. {
  10361. return p->queryName();
  10362. }
  10363. const char * CLocalWUAppValue::queryName() const
  10364. {
  10365. IPropertyTree* val=p->queryPropTree(prop.str());
  10366. if(val)
  10367. return val->queryName();
  10368. return ""; // Should not happen in normal usage
  10369. }
  10370. const char * CLocalWUAppValue::queryValue() const
  10371. {
  10372. return p->queryProp(prop.str());
  10373. }
  10374. //==========================================================================================
  10375. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  10376. {
  10377. }
  10378. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  10379. {
  10380. const char * creator = p->queryProp("@creator");
  10381. str.set(creator);
  10382. return str;
  10383. }
  10384. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  10385. {
  10386. const char * desc = p->queryProp("@desc");
  10387. if (desc)
  10388. {
  10389. str.set(desc); // legacy and in case it is overridden
  10390. }
  10391. else if (createDefault)
  10392. {
  10393. StatisticKind kind = getKind();
  10394. assertex(kind != StKindNone);
  10395. const char * scope = p->queryProp("@scope");
  10396. assertex(scope);
  10397. //Clean up the format of the scope when converting it to a description
  10398. StringBuffer descriptionText;
  10399. if (isGlobalScope(scope))
  10400. {
  10401. const char * creator = p->queryProp("@creator");
  10402. descriptionText.append(creator).append(":");
  10403. queryLongStatisticName(descriptionText, kind);
  10404. }
  10405. else
  10406. {
  10407. for (;;)
  10408. {
  10409. char c = *scope++;
  10410. if (!c)
  10411. break;
  10412. if (c == ':')
  10413. descriptionText.append(": ");
  10414. else
  10415. descriptionText.append(c);
  10416. }
  10417. if (kind != StTimeElapsed)
  10418. queryLongStatisticName(descriptionText.append(": "), kind);
  10419. }
  10420. str.set(descriptionText);
  10421. }
  10422. else
  10423. str.clear();
  10424. return str;
  10425. }
  10426. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  10427. {
  10428. StringBuffer formatted;
  10429. formatStatistic(formatted, getValue(), getMeasure());
  10430. str.set(formatted);
  10431. return str;
  10432. }
  10433. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  10434. {
  10435. return queryCreatorType(p->queryProp("@c"), SCTnone);
  10436. }
  10437. StatisticScopeType CLocalWUStatistic::getScopeType() const
  10438. {
  10439. return queryScopeType(p->queryProp("@s"), SSTnone);
  10440. }
  10441. StatisticKind CLocalWUStatistic::getKind() const
  10442. {
  10443. return queryStatisticKind(p->queryProp("@kind"), StKindNone);
  10444. }
  10445. const char * CLocalWUStatistic::queryScope() const
  10446. {
  10447. const char * scope = p->queryProp("@scope");
  10448. if (!scope || streq(scope, LEGACY_GLOBAL_SCOPE))
  10449. scope = GLOBAL_SCOPE;
  10450. return scope;
  10451. }
  10452. StatisticMeasure CLocalWUStatistic::getMeasure() const
  10453. {
  10454. return queryMeasure(p->queryProp("@unit"), SMeasureNone);
  10455. }
  10456. unsigned __int64 CLocalWUStatistic::getValue() const
  10457. {
  10458. return p->getPropInt64("@value", 0);
  10459. }
  10460. unsigned __int64 CLocalWUStatistic::getCount() const
  10461. {
  10462. return p->getPropInt64("@count", 0);
  10463. }
  10464. unsigned __int64 CLocalWUStatistic::getMax() const
  10465. {
  10466. return p->getPropInt64("@max", 0);
  10467. }
  10468. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  10469. {
  10470. return p->getPropInt64("@ts", 0);
  10471. }
  10472. //==========================================================================================
  10473. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  10474. {
  10475. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  10476. if (xml)
  10477. cw->loadPTree(createPTreeFromXMLString(xml, ipt_lowmem));
  10478. else
  10479. {
  10480. Owned<IPropertyTree> p = createPTree("W_LOCAL", ipt_lowmem);
  10481. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  10482. cw->loadPTree(p.getClear());
  10483. }
  10484. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  10485. return ret;
  10486. }
  10487. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  10488. {
  10489. const char *name = p->queryName();
  10490. if (!name)
  10491. name = "__unnamed__";
  10492. StringBuffer temp;
  10493. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1, true));
  10494. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  10495. ForEach(*elems)
  10496. {
  10497. IPropertyTree &elem = elems->query();
  10498. if (streq(elem.queryName(), "Parameters"))
  10499. {
  10500. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2, false).append('\n'));
  10501. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  10502. ForEach(*params)
  10503. {
  10504. IPropertyTree &param = params->query();
  10505. const char *paramname = param.queryName();
  10506. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  10507. if (p->getPropBool(xpath))
  10508. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  10509. else
  10510. {
  10511. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10512. }
  10513. }
  10514. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  10515. }
  10516. else if (streq(elem.queryName(), "Variables"))
  10517. {
  10518. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2, false).append('\n'));
  10519. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  10520. ForEach(*vars)
  10521. {
  10522. Owned<IPropertyTree> var = LINK(&vars->query());
  10523. if (var->getPropBool("Format/@password"))
  10524. {
  10525. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  10526. var->removeProp("Value");
  10527. var->removeProp("xmlValue");
  10528. }
  10529. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10530. }
  10531. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  10532. }
  10533. else
  10534. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  10535. }
  10536. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  10537. }
  10538. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  10539. {
  10540. class CAdapter : public CInterface, implements IIOStream
  10541. {
  10542. StringBuffer &out;
  10543. public:
  10544. IMPLEMENT_IINTERFACE;
  10545. CAdapter(StringBuffer &_out) : out(_out) { }
  10546. virtual void flush() { }
  10547. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  10548. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  10549. } adapter(str);
  10550. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  10551. return str;
  10552. }
  10553. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  10554. {
  10555. OwnedIFile ifile = createIFile(filename);
  10556. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  10557. Owned<IIOStream> stream = createIOStream(ifileio);
  10558. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  10559. }
  10560. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  10561. {
  10562. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  10563. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10564. if (ewu)
  10565. {
  10566. Linked<IPropertyTree> p;
  10567. if (unpack||includeProgress)
  10568. p.setown(ewu->getUnpackedTree(includeProgress));
  10569. else
  10570. p.set(ewu->queryPTree());
  10571. if (hidePasswords)
  10572. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  10573. else
  10574. return toXML(p, str, 0, XML_Format|XML_SortTags);
  10575. }
  10576. else
  10577. return str.append("Unrecognized workunit format");
  10578. }
  10579. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool regressionTest)
  10580. {
  10581. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10582. if (ewu)
  10583. {
  10584. Linked<IPropertyTree> p;
  10585. if (unpack||includeProgress)
  10586. p.setown(ewu->getUnpackedTree(includeProgress));
  10587. else if (regressionTest)
  10588. p.setown(createPTreeFromIPT(ewu->queryPTree()));
  10589. else
  10590. p.set(ewu->queryPTree());
  10591. if (hidePasswords)
  10592. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  10593. if (regressionTest)
  10594. {
  10595. //This removes any items from the xml that will vary from run to run, so they can be binary compared from run to run
  10596. //The following attributes change with the build. Simpler to remove rather than needing to updated each build
  10597. p->removeProp("@buildVersion");
  10598. p->removeProp("@eclVersion");
  10599. p->removeProp("@hash");
  10600. //Remove statistics, and extract them to a separate file
  10601. IPropertyTree * stats = p->queryPropTree("Statistics");
  10602. if (stats)
  10603. {
  10604. StringBuffer statsFilename;
  10605. statsFilename.append(filename).append(".stats");
  10606. saveXML(statsFilename, stats, 0, (XML_Format|XML_SortTags|extraXmlFlags) & ~XML_LineBreakAttributes);
  10607. p->removeProp("Statistics");
  10608. }
  10609. //Now remove timestamps from exceptions
  10610. Owned<IPropertyTreeIterator> elems = p->getElements("Exceptions/Exception", iptiter_sort);
  10611. ForEach(*elems)
  10612. {
  10613. IPropertyTree &elem = elems->query();
  10614. elem.removeProp("@time");
  10615. }
  10616. }
  10617. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  10618. }
  10619. else
  10620. throw makeStringException(0, "Unrecognized workunit format");
  10621. }
  10622. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  10623. {
  10624. MemoryBuffer buffer;
  10625. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  10626. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  10627. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  10628. assertex(workunit);
  10629. StringAttr clusterName(workunit->queryClusterName());
  10630. if (!clusterName.length())
  10631. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  10632. workunit->commit();
  10633. workunit.clear();
  10634. StringBuffer serverQueue;
  10635. getClusterEclCCServerQueueName(serverQueue, clusterName);
  10636. assertex(serverQueue.length());
  10637. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  10638. if (!queue.get())
  10639. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  10640. IJobQueueItem *item = createJobQueueItem(wuid);
  10641. queue->enqueue(item);
  10642. }
  10643. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  10644. {
  10645. StringBuffer xpath("/WorkUnitAborts/");
  10646. xpath.append(wuid);
  10647. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  10648. acon->queryRoot()->setPropInt(NULL, 1);
  10649. }
  10650. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10651. {
  10652. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10653. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  10654. }
  10655. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10656. {
  10657. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10658. return;
  10659. abortWorkUnit(wuid);
  10660. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  10661. if(!cw)
  10662. return;
  10663. WorkunitUpdate wu(&cw->lock());
  10664. const char *abortBy = secuser.getName();
  10665. if (abortBy && *abortBy)
  10666. wu->setTracingValue("AbortBy", abortBy);
  10667. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  10668. }
  10669. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10670. {
  10671. if (secmgr && secuser)
  10672. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  10673. if (secuser)
  10674. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  10675. submitWorkUnit(wuid, "", "");
  10676. }
  10677. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10678. {
  10679. if (secmgr && secuser)
  10680. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  10681. abortWorkUnit(wuid);
  10682. }
  10683. bool CLocalWorkUnit::hasWorkflow() const
  10684. {
  10685. return p->hasProp("Workflow");
  10686. }
  10687. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  10688. {
  10689. CriticalBlock block(crit);
  10690. if (p->hasProp("@eventScheduledCount"))
  10691. return p->getPropInt("@eventScheduledCount", 0);
  10692. else
  10693. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  10694. }
  10695. void CLocalWorkUnit::incEventScheduledCount()
  10696. {
  10697. CriticalBlock block(crit);
  10698. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  10699. }
  10700. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  10701. {
  10702. CriticalBlock block(crit);
  10703. return p->queryPropTree("Workflow");
  10704. }
  10705. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  10706. {
  10707. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10708. CriticalBlock block(crit);
  10709. if(!workflowIteratorCached)
  10710. {
  10711. assertex(!workflowIterator);
  10712. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  10713. if(s)
  10714. workflowIterator.setown(createWorkflowItemIterator(s));
  10715. workflowIteratorCached = true;
  10716. }
  10717. return workflowIterator.getLink();
  10718. }
  10719. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  10720. {
  10721. unsigned count = 0;
  10722. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10723. for(iter->first(); iter->isValid(); iter->next())
  10724. count++;
  10725. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  10726. for(iter->first(); iter->isValid(); iter->next())
  10727. array->addClone(iter->query());
  10728. return array.getLink();
  10729. }
  10730. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  10731. {
  10732. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10733. CriticalBlock block(crit);
  10734. workflowIterator.clear();
  10735. workflowIteratorCached = false;
  10736. IPropertyTree * s = p->queryPropTree("Workflow");
  10737. if(!s)
  10738. s = p->addPropTree("Workflow");
  10739. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  10740. }
  10741. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  10742. {
  10743. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10744. CriticalBlock block(crit);
  10745. if(!workflowIterator)
  10746. {
  10747. IPropertyTree * s = p->queryPropTree("Workflow");
  10748. if(!s)
  10749. s = p->addPropTree("Workflow");
  10750. workflowIterator.setown(createWorkflowItemIterator(s));
  10751. workflowIteratorCached = true;
  10752. }
  10753. return workflowIterator.getLink();
  10754. }
  10755. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  10756. {
  10757. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10758. Owned<IWorkflowItem> item;
  10759. for(iter->first(); iter->isValid(); iter->next())
  10760. {
  10761. item.setown(iter->get());
  10762. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  10763. }
  10764. workflowIterator.clear();
  10765. workflowIteratorCached = false;
  10766. }
  10767. void CLocalWorkUnit::resetWorkflow()
  10768. {
  10769. if (hasWorkflow())
  10770. {
  10771. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10772. Owned<IWorkflowItem> wf;
  10773. for(iter->first(); iter->isValid(); iter->next())
  10774. {
  10775. wf.setown(iter->get());
  10776. wf->reset();
  10777. }
  10778. workflowIterator.clear();
  10779. workflowIteratorCached = false;
  10780. }
  10781. }
  10782. void CLocalWorkUnit::schedule()
  10783. {
  10784. CriticalBlock block(crit);
  10785. if(queryEventScheduledCount() == 0) return;
  10786. switch(getState())
  10787. {
  10788. case WUStateCompleted:
  10789. setState(WUStateWait);
  10790. break;
  10791. case WUStateFailed:
  10792. case WUStateArchived:
  10793. case WUStateAborting:
  10794. case WUStateAborted:
  10795. case WUStateScheduled:
  10796. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  10797. }
  10798. StringBuffer rootPath;
  10799. rootPath.append("/Schedule/").append(queryClusterName());
  10800. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10801. Owned<IPropertyTree> root = conn->getRoot();
  10802. if(!root->hasChildren())
  10803. {
  10804. StringBuffer addPath;
  10805. addPath.append("/Schedulers/").append(queryClusterName());
  10806. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10807. }
  10808. char const * wuid = p->queryName();
  10809. StringBuffer xpath("*/*/");
  10810. ncnameEscape(wuid, xpath);
  10811. bool more;
  10812. do more = root->removeProp(xpath.str()); while(more);
  10813. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10814. Owned<IWorkflowEvent> event;
  10815. Owned<IPropertyTree> branch1, branch2;
  10816. for(iter->first(); iter->isValid(); iter->next())
  10817. {
  10818. event.setown(iter->query()->getScheduleEvent());
  10819. if(!event) continue;
  10820. ncnameEscape(event->queryName(), xpath.clear());
  10821. ensurePTree(root, xpath.str());
  10822. branch1.setown(root->getPropTree(xpath.str()));
  10823. ncnameEscape(event->queryText(), xpath.clear());
  10824. ensurePTree(branch1, xpath.str());
  10825. branch2.setown(branch1->getPropTree(xpath.str()));
  10826. ncnameEscape(wuid, xpath.clear());
  10827. ensurePTree(branch2, xpath.str());
  10828. }
  10829. }
  10830. void CLocalWorkUnit::deschedule()
  10831. {
  10832. if(queryEventScheduledCount() == 0) return;
  10833. if(getState() == WUStateWait)
  10834. setState(WUStateCompleted);
  10835. doDescheduleWorkkunit(p->queryName());
  10836. }
  10837. EnumMapping localFileUploadTypes[] = {
  10838. { UploadTypeFileSpray, "FileSpray" },
  10839. { UploadTypeWUResult, "WUResult" },
  10840. { UploadTypeWUResultCsv, "WUResultCsv" },
  10841. { UploadTypeWUResultXml, "WUResultXml" },
  10842. { UploadTypeSize, NULL }
  10843. };
  10844. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  10845. {
  10846. public:
  10847. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  10848. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10849. {
  10850. tree.setown(createPTree());
  10851. tree->setPropInt("@id", id);
  10852. setEnum(tree, "@type", type, localFileUploadTypes);
  10853. tree->setProp("@source", source);
  10854. tree->setProp("@destination", destination);
  10855. if (eventTag)
  10856. tree->setProp("@eventTag", eventTag);
  10857. }
  10858. IMPLEMENT_IINTERFACE;
  10859. IPropertyTree * getTree() { return tree.getLink(); }
  10860. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  10861. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  10862. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  10863. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  10864. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  10865. private:
  10866. Owned<IPropertyTree> tree;
  10867. };
  10868. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  10869. {
  10870. public:
  10871. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  10872. IMPLEMENT_IINTERFACE;
  10873. bool first() { return iter->first(); }
  10874. bool isValid() { return iter->isValid(); }
  10875. bool next() { return iter->next(); }
  10876. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  10877. private:
  10878. Owned<IPropertyTree> tree;
  10879. Owned<IPropertyTreeIterator> iter;
  10880. };
  10881. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  10882. {
  10883. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10884. CriticalBlock block(crit);
  10885. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  10886. if(s)
  10887. return new CLocalFileUploadIterator(s.getClear());
  10888. else
  10889. return NULL;
  10890. }
  10891. bool CLocalWorkUnit::requiresLocalFileUpload() const
  10892. {
  10893. SCMStringBuffer dest;
  10894. Owned<IConstWUResult> result;
  10895. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  10896. if(!iter)
  10897. return false;
  10898. for(iter->first(); iter->isValid(); iter->next())
  10899. {
  10900. Owned<IConstLocalFileUpload> upload(iter->get());
  10901. switch(upload->queryType())
  10902. {
  10903. case UploadTypeWUResult:
  10904. case UploadTypeWUResultCsv:
  10905. case UploadTypeWUResultXml:
  10906. upload->getDestination(dest);
  10907. result.setown(getResultByName(dest.str()));
  10908. if(!result)
  10909. return true;
  10910. break;
  10911. default:
  10912. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  10913. }
  10914. }
  10915. return false;
  10916. }
  10917. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10918. {
  10919. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10920. CriticalBlock block(crit);
  10921. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  10922. if(!s)
  10923. s = p->addPropTree("LocalFileUploads");
  10924. unsigned id = s->numChildren();
  10925. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  10926. s->addPropTree("LocalFileUpload", upload->getTree());
  10927. return id;
  10928. }
  10929. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  10930. {
  10931. CriticalBlock block(crit);
  10932. str.set(p->queryProp("Tracing/AbortBy"));
  10933. return str;
  10934. }
  10935. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  10936. {
  10937. CriticalBlock block(crit);
  10938. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  10939. }
  10940. #if 0
  10941. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  10942. {
  10943. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  10944. unsigned deps = 0;
  10945. Owned<IWorkflowDependencyIterator> diter;
  10946. switch(cwf->queryWfid())
  10947. {
  10948. case 1:
  10949. assertex(!cwf->isScheduled());
  10950. assertex(cwf->queryType() == WFTypeNormal);
  10951. assertex(cwf->queryState() == WFStateNull);
  10952. diter.setown(cwf->getDependencies());
  10953. for(diter->first(); diter->isValid(); diter->next())
  10954. deps++;
  10955. assertex(deps==0);
  10956. okay[0] = true;
  10957. break;
  10958. case 2:
  10959. assertex(!cwf->isScheduled());
  10960. assertex(cwf->queryType() == WFTypeRecovery);
  10961. assertex(cwf->queryState() == WFStateSkip);
  10962. okay[1] = true;
  10963. break;
  10964. case 3:
  10965. assertex(cwf->queryContingencyFor() == 4);
  10966. okay[2] = true;
  10967. break;
  10968. case 4:
  10969. assertex(cwf->isScheduled());
  10970. assertex(cwf->queryType() == WFTypeNormal);
  10971. assertex(cwf->queryState() == WFStateReqd);
  10972. assertex(cwf->querySuccess() == 0);
  10973. assertex(cwf->queryFailure() == 3);
  10974. assertex(cwf->queryRecovery() == 2);
  10975. assertex(cwf->queryRetriesAllowed() == 10);
  10976. assertex(cwf->queryRetriesRemaining() == 10);
  10977. diter.setown(cwf->getDependencies());
  10978. for(diter->first(); diter->isValid(); diter->next())
  10979. {
  10980. dep[diter->query()-1] = true;
  10981. deps++;
  10982. }
  10983. assertex(deps==2);
  10984. assertex(dep[0]);
  10985. assertex(dep[1]);
  10986. okay[3] = true;
  10987. break;
  10988. case 5:
  10989. assertex(cwf->isScheduled());
  10990. assertex(!cwf->isScheduledNow());
  10991. assertex(cwf->querySchedulePriority() == 75);
  10992. assertex(cwf->queryScheduleCount() == 5);
  10993. assertex(cwf->queryScheduleCountRemaining() == 5);
  10994. okay[4] = true;
  10995. break;
  10996. case 6:
  10997. assertex(cwf->isScheduled());
  10998. assertex(!cwf->isScheduledNow());
  10999. assertex(cwf->querySchedulePriority() == 25);
  11000. assertex(!cwf->hasScheduleCount());
  11001. okay[5] = true;
  11002. break;
  11003. default:
  11004. assertex(!"unknown wfid in test");
  11005. }
  11006. }
  11007. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  11008. {
  11009. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  11010. switch(rwf->queryWfid())
  11011. {
  11012. case 1:
  11013. case 2:
  11014. case 3:
  11015. okay[rwf->queryWfid()-1] = true;
  11016. break;
  11017. case 4:
  11018. {
  11019. unsigned tries = 0;
  11020. while(rwf->testAndDecRetries())
  11021. tries++;
  11022. assertex(tries == 10);
  11023. assertex(rwf->queryRetriesRemaining() == 0);
  11024. rwf->setState(WFStateFail);
  11025. assertex(rwf->queryState() == WFStateFail);
  11026. rwf->reset();
  11027. assertex(rwf->queryRetriesRemaining() == 10);
  11028. assertex(rwf->queryState() == WFStateReqd);
  11029. }
  11030. okay[3] = true;
  11031. break;
  11032. case 5:
  11033. {
  11034. assertex(rwf->queryScheduleCountRemaining() == 5);
  11035. unsigned count = 0;
  11036. do count++; while(rwf->decAndTestScheduleCountRemaining());
  11037. assertex(count == 5);
  11038. assertex(rwf->queryScheduleCountRemaining() == 0);
  11039. rwf->reset();
  11040. assertex(rwf->queryScheduleCountRemaining() == 5);
  11041. }
  11042. okay[4] = true;
  11043. break;
  11044. case 6:
  11045. {
  11046. assertex(!rwf->hasScheduleCount());
  11047. unsigned count;
  11048. for(count=0; count<20; count++)
  11049. assertex(rwf->decAndTestScheduleCountRemaining());
  11050. }
  11051. okay[5] = true;
  11052. break;
  11053. default:
  11054. assertex(!"unknown wfid in test");
  11055. }
  11056. }
  11057. void testWorkflow()
  11058. {
  11059. DBGLOG("workunit.cpp : testWorkflow");
  11060. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  11061. Owned<IWorkflowItem> wf;
  11062. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  11063. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  11064. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  11065. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  11066. wf->setScheduledNow();
  11067. wf->addDependency(1);
  11068. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  11069. wf->setScheduledOn("test", "foo*");
  11070. wf->setSchedulePriority(75);
  11071. wf->setScheduleCount(5);
  11072. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  11073. wf->setScheduledOn("test", "bar*");
  11074. wf->setSchedulePriority(25);
  11075. unsigned const n = 6;
  11076. bool okay[n];
  11077. bool dep[n];
  11078. unsigned i;
  11079. for(i=0; i<n; i++)
  11080. okay[i] = dep[i] = 0;
  11081. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  11082. for(citer->first(); citer->isValid(); citer->next())
  11083. testConstWorkflow(citer->query(), okay, dep);
  11084. for(i=0; i<n; i++)
  11085. {
  11086. assertex(okay[i]);
  11087. okay[i] = false;
  11088. }
  11089. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  11090. for(miter->first(); miter->isValid(); miter->next())
  11091. {
  11092. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  11093. testRuntimeWorkflow(rwf, okay);
  11094. }
  11095. for(i=0; i<n; i++)
  11096. {
  11097. assertex(okay[i]);
  11098. okay[i] = dep[i] = false;
  11099. }
  11100. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  11101. unsigned wfid;
  11102. for(wfid = 1; array->isValid(wfid); wfid++)
  11103. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  11104. for(i=0; i<n; i++)
  11105. {
  11106. assertex(okay[i]);
  11107. okay[i] = false;
  11108. }
  11109. for(wfid = 1; array->isValid(wfid); wfid++)
  11110. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  11111. for(i=0; i<n; i++)
  11112. {
  11113. assertex(okay[i]);
  11114. okay[i] = false;
  11115. }
  11116. }
  11117. #endif
  11118. //------------------------------------------------------------------------------------------
  11119. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, std::list<WUState> expectedStates)
  11120. {
  11121. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, expectedStates);
  11122. }
  11123. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, std::list<WUState> expectedStates)
  11124. {
  11125. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  11126. return waitForWorkUnitToComplete(wuid, timeout, expectedStates);
  11127. return WUStateUnknown;
  11128. }
  11129. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  11130. {
  11131. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, { WUStateWait }))
  11132. {
  11133. case WUStateCompiled:
  11134. case WUStateCompleted:
  11135. case WUStateWait:
  11136. case WUStateUploadingFiles:
  11137. return true;
  11138. default:
  11139. return false;
  11140. }
  11141. }
  11142. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  11143. {
  11144. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  11145. return waitForWorkUnitToCompile(wuid, timeout);
  11146. return false;
  11147. }
  11148. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  11149. {
  11150. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  11151. {
  11152. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  11153. SCMStringBuffer ip;
  11154. unsigned port;
  11155. try
  11156. {
  11157. port = wu->getDebugAgentListenerPort();
  11158. wu->getDebugAgentListenerIP(ip);
  11159. SocketEndpoint debugEP(ip.str(), port);
  11160. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  11161. unsigned len = (size32_t)strlen(command);
  11162. unsigned revlen = len;
  11163. _WINREV(revlen);
  11164. socket->write(&revlen, sizeof(revlen));
  11165. socket->write(command, len);
  11166. for (;;)
  11167. {
  11168. socket->read(&len, sizeof(len));
  11169. _WINREV(len);
  11170. if (len == 0)
  11171. break;
  11172. if (len & 0x80000000)
  11173. {
  11174. throwUnexpected();
  11175. }
  11176. char * mem = (char*) response.reserve(len);
  11177. socket->read(mem, len);
  11178. }
  11179. return true;
  11180. }
  11181. catch (IException *E)
  11182. {
  11183. VStringBuffer msg("In secDebugWorkunit wuid %s port %d ip %s command %s", wuid, port, ip.str(), command);
  11184. EXCLOG(E, msg.str());
  11185. throw;
  11186. }
  11187. }
  11188. return false;
  11189. }
  11190. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  11191. {
  11192. TypeInfoArray types;
  11193. StringAttrArray names;
  11194. r->getSchema(types, names, NULL);
  11195. if (types.ordinality()==1)
  11196. type.set(&types.item(0));
  11197. }
  11198. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  11199. {
  11200. if (!r->isResultScalar())
  11201. return false;
  11202. if (!curVal.hasChildren())
  11203. return true;
  11204. getSimpleResultType(r, type);
  11205. return type && type->isScalar();
  11206. }
  11207. void updateSuppliedXmlParams(IWorkUnit * w)
  11208. {
  11209. Owned<const IPropertyTree> params = w->getXmlParams();
  11210. if (!params)
  11211. return;
  11212. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  11213. ForEach(*elems)
  11214. {
  11215. IPropertyTree & curVal = elems->query();
  11216. const char *name = curVal.queryName();
  11217. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  11218. if (r)
  11219. {
  11220. Owned<ITypeInfo> type;
  11221. StringBuffer s;
  11222. if (isSuppliedParamScalar(r, curVal, type))
  11223. {
  11224. curVal.getProp(".", s);
  11225. r->setResultXML(s);
  11226. r->setResultStatus(ResultStatusSupplied);
  11227. }
  11228. else
  11229. {
  11230. toXML(&curVal, s);
  11231. if (!type)
  11232. getSimpleResultType(r, type);
  11233. bool isSet = (type && type->getTypeCode()==type_set);
  11234. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  11235. }
  11236. }
  11237. else
  11238. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  11239. }
  11240. }
  11241. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  11242. {
  11243. switch ((int)sequence)
  11244. {
  11245. case ResultSequenceStored:
  11246. return w->updateVariableByName(name);
  11247. case ResultSequencePersist:
  11248. return w->updateGlobalByName(name);
  11249. case ResultSequenceInternal:
  11250. case ResultSequenceOnce:
  11251. return w->updateTemporaryByName(name);
  11252. default:
  11253. return w->updateResultBySequence(sequence);
  11254. }
  11255. }
  11256. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  11257. {
  11258. switch ((int)sequence)
  11259. {
  11260. case ResultSequenceStored:
  11261. return w->getVariableByName(name);
  11262. case ResultSequencePersist:
  11263. return w->getGlobalByName(name);
  11264. case ResultSequenceInternal:
  11265. case ResultSequenceOnce:
  11266. return w->getTemporaryByName(name);
  11267. default:
  11268. if (name && name[0])
  11269. return w->getResultByName(name);//name takes precedence over sequence
  11270. else
  11271. return w->getResultBySequence(sequence);
  11272. }
  11273. }
  11274. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  11275. {
  11276. if (wuid) {
  11277. char prefchar;
  11278. unsigned year,month,day,hour,min,sec;
  11279. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  11280. time.set(year, month, day, hour, min, sec, 0, true);
  11281. // time.setDate(year, month, day);
  11282. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  11283. return true;
  11284. }
  11285. }
  11286. return false;
  11287. }
  11288. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  11289. {
  11290. return (WUState) getEnum(state, states);
  11291. }
  11292. constexpr LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  11293. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  11294. {
  11295. public:
  11296. CWorkflowScheduleConnection(char const * wuid)
  11297. {
  11298. basexpath.append("/WorkflowSchedule/").append(wuid);
  11299. flagxpath.append(basexpath.str()).append("/Active");
  11300. }
  11301. IMPLEMENT_IINTERFACE;
  11302. virtual void lock()
  11303. {
  11304. LOG(MCschedconn, "Locking base schedule connection");
  11305. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  11306. if(!baseconn)
  11307. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  11308. }
  11309. virtual void unlock()
  11310. {
  11311. LOG(MCschedconn, "Unlocking base schedule connection");
  11312. baseconn.clear();
  11313. }
  11314. virtual void setActive()
  11315. {
  11316. LOG(MCschedconn, "Setting active flag in schedule connection");
  11317. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  11318. if(!flagconn)
  11319. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  11320. }
  11321. virtual void resetActive()
  11322. {
  11323. LOG(MCschedconn, "Resetting active flag in schedule connection");
  11324. flagconn.clear();
  11325. }
  11326. virtual bool queryActive()
  11327. {
  11328. return baseconn->queryRoot()->hasProp("Active");
  11329. }
  11330. virtual bool pull(IWorkflowItemArray * workflow)
  11331. {
  11332. assertex(baseconn);
  11333. Owned<IPropertyTree> root = baseconn->getRoot();
  11334. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  11335. if(!eventQueue) return false;
  11336. if(!eventQueue->hasProp("Item")) return false;
  11337. {
  11338. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  11339. Owned<IPropertyTree> eventItem;
  11340. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  11341. Owned<IRuntimeWorkflowItem> wfItem;
  11342. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  11343. {
  11344. eventItem.setown(&eventItems->get());
  11345. const char * eventName = eventItem->queryProp("@name");
  11346. const char * eventText = eventItem->queryProp("@text");
  11347. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  11348. {
  11349. wfItem.setown(wfItems->get());
  11350. if(wfItem->queryState() != WFStateWait)
  11351. continue;
  11352. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  11353. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  11354. continue;
  11355. wfItem->setEvent(eventName, eventText);
  11356. wfItem->setState(WFStateReqd);
  11357. resetDependentsState(workflow, *wfItem);
  11358. }
  11359. }
  11360. }
  11361. bool more;
  11362. do
  11363. more = eventQueue->removeProp("Item");
  11364. while(more);
  11365. return true;
  11366. }
  11367. virtual void push(char const * name, char const * text)
  11368. {
  11369. assertex(baseconn);
  11370. Owned<IPropertyTree> root = baseconn->getRoot();
  11371. IPropertyTree *eventQueue = ensurePTree(root, "EventQueue");
  11372. IPropertyTree *eventItem = eventQueue->addPropTree("Item");
  11373. eventItem->setProp("@name", name);
  11374. eventItem->setProp("@text", text);
  11375. }
  11376. virtual void remove()
  11377. {
  11378. if (baseconn)
  11379. {
  11380. baseconn->close(true);
  11381. baseconn.clear();
  11382. }
  11383. }
  11384. private:
  11385. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  11386. {
  11387. if (wfid)
  11388. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  11389. }
  11390. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11391. {
  11392. switch(item.queryState())
  11393. {
  11394. case WFStateDone:
  11395. case WFStateFail:
  11396. {
  11397. item.setState(WFStateNull);
  11398. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  11399. resetDependentsState(workflow, item);
  11400. break;
  11401. }
  11402. }
  11403. }
  11404. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11405. {
  11406. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  11407. for(iter->first(); iter->isValid(); iter->next())
  11408. {
  11409. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  11410. resetItemStateAndDependents(workflow, dep);
  11411. }
  11412. }
  11413. private:
  11414. StringBuffer basexpath;
  11415. StringBuffer flagxpath;
  11416. Owned<IRemoteConnection> baseconn;
  11417. Owned<IRemoteConnection> flagconn;
  11418. };
  11419. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  11420. {
  11421. return new CWorkflowScheduleConnection(wuid);
  11422. }
  11423. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  11424. {
  11425. return QUERYINTERFACE(wu, IExtendedWUInterface);
  11426. }
  11427. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  11428. {
  11429. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  11430. }
  11431. 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)
  11432. {
  11433. Owned<IWUException> we = wu->createException();
  11434. we->setSeverity(severity);
  11435. we->setExceptionMessage(text);
  11436. if (source)
  11437. we->setExceptionSource(source);
  11438. if (code)
  11439. we->setExceptionCode(code);
  11440. if (filename)
  11441. we->setExceptionFileName(filename);
  11442. if (lineno)
  11443. {
  11444. we->setExceptionLineNo(lineno);
  11445. if (column)
  11446. we->setExceptionColumn(lineno);
  11447. }
  11448. if (activity)
  11449. we->setActivityId(activity);
  11450. }
  11451. const char * skipLeadingXml(const char * text)
  11452. {
  11453. if (!text)
  11454. return NULL;
  11455. //skip utf8 BOM, probably excessive
  11456. if (memcmp(text, UTF8_BOM, 3) == 0)
  11457. text += 3;
  11458. for (;;)
  11459. {
  11460. if (isspace(*text))
  11461. text++;
  11462. else if (text[0] == '<' && text[1] == '?')
  11463. {
  11464. text += 2;
  11465. for (;;)
  11466. {
  11467. if (!*text) break;
  11468. if (text[0] == '?' && text[1] == '>')
  11469. {
  11470. text += 2;
  11471. break;
  11472. }
  11473. text++;
  11474. }
  11475. }
  11476. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  11477. {
  11478. text += 4;
  11479. for (;;)
  11480. {
  11481. if (!*text) break;
  11482. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  11483. {
  11484. text += 3;
  11485. break;
  11486. }
  11487. text++;
  11488. }
  11489. }
  11490. else
  11491. break;
  11492. }
  11493. return text;
  11494. }
  11495. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  11496. {
  11497. text = skipLeadingXml(text);
  11498. if (!text)
  11499. return false;
  11500. const char * archivePrefix = "<Archive";
  11501. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  11502. }
  11503. extern WORKUNIT_API bool isQueryManifest(const char * text)
  11504. {
  11505. text = skipLeadingXml(text);
  11506. if (!text)
  11507. return false;
  11508. const char * manifestPrefix = "<Manifest";
  11509. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  11510. }
  11511. //------------------------------------------------------------------------------
  11512. // Named Alias helper function
  11513. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  11514. {
  11515. StringBuffer xpath;
  11516. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  11517. return queryRegistry->getPropTree(xpath);
  11518. }
  11519. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  11520. {
  11521. StringBuffer xpath;
  11522. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  11523. return queryRegistry->getPropTree(xpath);
  11524. }
  11525. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  11526. {
  11527. StringBuffer lcId(id);
  11528. lcId.toLowerCase();
  11529. StringBuffer xpath;
  11530. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  11531. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11532. ForEach(*iter)
  11533. {
  11534. queryRegistry->removeProp(xpath.str());
  11535. }
  11536. }
  11537. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  11538. {
  11539. StringBuffer lcName(name);
  11540. lcName.toLowerCase();
  11541. StringBuffer xpath;
  11542. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  11543. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11544. unsigned seq = 1;
  11545. ForEach(*iter)
  11546. {
  11547. IPropertyTree &item = iter->query();
  11548. const char *thisWuid = item.queryProp("@wuid");
  11549. if (strieq(wuid, thisWuid))
  11550. return &item;
  11551. unsigned thisSeq = item.getPropInt("@seq");
  11552. if (thisSeq >= seq)
  11553. seq = thisSeq + 1;
  11554. }
  11555. StringBuffer id;
  11556. id.append(lcName).append(".").append(seq);
  11557. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive|ipt_lowmem);
  11558. newEntry->setProp("@name", lcName);
  11559. newEntry->setProp("@wuid", wuid);
  11560. newEntry->setProp("@dll", dll);
  11561. newEntry->setProp("@id", id);
  11562. newEntry->setPropInt("@seq", seq);
  11563. if (library)
  11564. newEntry->setPropBool("@isLibrary", true);
  11565. if (userid && *userid)
  11566. newEntry->setProp("@publishedBy", userid);
  11567. if (snapshot && *snapshot)
  11568. newEntry->setProp("@snapshot", snapshot);
  11569. return queryRegistry->addPropTree("Query", newEntry);
  11570. }
  11571. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11572. {
  11573. StringBuffer lcId(id);
  11574. lcId.toLowerCase();
  11575. clearAliases(queryRegistry, lcId);
  11576. StringBuffer xpath;
  11577. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11578. queryRegistry->removeProp(xpath);
  11579. }
  11580. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  11581. {
  11582. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  11583. if (!match)
  11584. return;
  11585. clearAliases(queryRegistry, match->queryProp("@id"));
  11586. queryRegistry->removeTree(match);
  11587. }
  11588. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  11589. {
  11590. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  11591. if (!match)
  11592. return;
  11593. clearAliases(queryRegistry, match->queryProp("@id"));
  11594. queryRegistry->removeTree(match);
  11595. }
  11596. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11597. {
  11598. clearAliases(queryRegistry, id);
  11599. }
  11600. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  11601. {
  11602. StringBuffer lcName(name);
  11603. lcName.toLowerCase();
  11604. StringBuffer xpath;
  11605. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  11606. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  11607. if (!match)
  11608. {
  11609. match = queryRegistry->addPropTree("Alias");
  11610. match->setProp("@name", lcName);
  11611. }
  11612. match->setProp("@id", value);
  11613. }
  11614. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  11615. {
  11616. if (!queryRegistry || !queryid)
  11617. return NULL;
  11618. StringBuffer xpath;
  11619. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  11620. return queryRegistry->getPropTree(xpath);
  11621. }
  11622. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  11623. {
  11624. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11625. return getQueryById(queryRegistry, queryid);
  11626. }
  11627. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  11628. {
  11629. if (!queryRegistry || !alias)
  11630. return NULL;
  11631. StringBuffer xpath;
  11632. unsigned cnt = 0;
  11633. StringBuffer lc(alias);
  11634. const char * search = lc.toLowerCase().str();
  11635. for (;;)
  11636. {
  11637. xpath.set("Alias[@name='").append(search).append("']/@id");
  11638. const char * queryId = queryRegistry->queryProp(xpath);
  11639. if (!queryId)
  11640. break;
  11641. //Check for too many alias indirections.
  11642. if (cnt++ > 10)
  11643. return NULL;
  11644. search = lc.set(queryId).toLowerCase().str();
  11645. }
  11646. return getQueryById(queryRegistry, search);
  11647. }
  11648. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  11649. {
  11650. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11651. return resolveQueryAlias(queryRegistry, alias);
  11652. }
  11653. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  11654. {
  11655. StringBuffer lcId(id);
  11656. lcId.toLowerCase();
  11657. StringBuffer xpath;
  11658. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11659. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11660. if (tree)
  11661. {
  11662. if (tree->getPropBool("@suspended", false) == suspend)
  11663. return;
  11664. if (suspend)
  11665. {
  11666. tree->addPropBool("@suspended", true);
  11667. if (userid && *userid)
  11668. tree->addProp("@suspendedBy", userid);
  11669. }
  11670. else
  11671. {
  11672. tree->removeProp("@suspended");
  11673. tree->removeProp("@suspendedBy");
  11674. }
  11675. }
  11676. else
  11677. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  11678. }
  11679. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  11680. {
  11681. if (queryComment)
  11682. {
  11683. StringBuffer lcId(id);
  11684. lcId.toLowerCase();
  11685. StringBuffer xpath;
  11686. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11687. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11688. if (tree)
  11689. tree->setProp("@queryComment", queryComment);
  11690. else
  11691. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  11692. }
  11693. }
  11694. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  11695. {
  11696. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  11697. if (conn)
  11698. return conn->getRoot();
  11699. else
  11700. return NULL;
  11701. }
  11702. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  11703. {
  11704. if (!queryTree || !libraries)
  11705. return;
  11706. if (queryTree->hasProp("@libCount")) //already added
  11707. return;
  11708. unsigned libCount=0;
  11709. ForEach(*libraries)
  11710. {
  11711. IConstWULibrary &library = libraries->query();
  11712. SCMStringBuffer libname;
  11713. if (!library.getName(libname).length())
  11714. continue;
  11715. queryTree->addProp("Library", libname.str());
  11716. libCount++;
  11717. }
  11718. queryTree->setPropInt("@libCount", libCount);
  11719. }
  11720. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  11721. {
  11722. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  11723. checkAddLibrariesToQueryEntry(queryTree, libraries);
  11724. }
  11725. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  11726. {
  11727. //Only lock the branch for the target we're interested in.
  11728. StringBuffer xpath;
  11729. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  11730. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11731. if (conn)
  11732. return conn->getRoot();
  11733. if (readonly)
  11734. return NULL;
  11735. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  11736. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11737. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  11738. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11739. if (conn)
  11740. return conn->getRoot();
  11741. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11742. if (!conn)
  11743. throwUnexpected();
  11744. IPropertyTree * root = conn->queryRoot();
  11745. root->setProp("@id",wsEclId);
  11746. conn->commit();
  11747. return LINK(root);
  11748. }
  11749. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  11750. {
  11751. StringBuffer xpath;
  11752. StringBuffer lcName(name);
  11753. lcName.toLowerCase();
  11754. // see if "name" already exists
  11755. xpath.append("Package[@id='").append(name).append("']");
  11756. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  11757. if (pkgTree)
  11758. {
  11759. if (overWrite)
  11760. packageRegistry->removeTree(pkgTree);
  11761. else
  11762. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  11763. }
  11764. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  11765. tree->setProp("@id", lcName);
  11766. return tree;
  11767. }
  11768. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  11769. {
  11770. StringBuffer lcId(id);
  11771. lcId.toLowerCase();
  11772. StringBuffer xpath;
  11773. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  11774. packageRegistry->removeProp(xpath);
  11775. }
  11776. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  11777. {
  11778. //Only lock the branch for the target we're interested in.
  11779. StringBuffer xpath;
  11780. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  11781. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11782. if (conn)
  11783. return conn->getRoot();
  11784. if (readonly)
  11785. return NULL;
  11786. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  11787. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11788. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  11789. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11790. if (conn)
  11791. return conn->getRoot();
  11792. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11793. if (!conn)
  11794. throwUnexpected();
  11795. IPropertyTree* root = conn->queryRoot();
  11796. root->setProp("@id",wsEclId);
  11797. conn->commit();
  11798. return LINK(root);
  11799. }
  11800. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11801. {
  11802. StringBuffer cleanQueryName;
  11803. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11804. SCMStringBuffer dllName;
  11805. Owned<IConstWUQuery> q = workunit->getQuery();
  11806. q->getQueryDllName(dllName);
  11807. if (!dllName.length())
  11808. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  11809. StringBuffer currentTargetClusterType;
  11810. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  11811. SCMStringBuffer targetClusterType;
  11812. workunit->getDebugValue("targetclustertype", targetClusterType);
  11813. SCMStringBuffer snapshot;
  11814. workunit->getSnapshot(snapshot);
  11815. if (currentTargetClusterType.length() < 1)
  11816. {
  11817. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  11818. }
  11819. else
  11820. {
  11821. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  11822. {
  11823. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  11824. }
  11825. }
  11826. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  11827. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  11828. checkAddLibrariesToQueryEntry(newEntry, libraries);
  11829. newQueryId.append(newEntry->queryProp("@id"));
  11830. workunit->setIsQueryService(true); //will check querysets before delete
  11831. workunit->commit();
  11832. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  11833. }
  11834. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  11835. {
  11836. StringBuffer cleanQueryName;
  11837. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11838. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  11839. {
  11840. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  11841. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11842. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  11843. {
  11844. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  11845. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  11846. else
  11847. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  11848. }
  11849. }
  11850. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  11851. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11852. }
  11853. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11854. {
  11855. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11856. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  11857. }
  11858. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  11859. {
  11860. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11861. StringBuffer xpath;
  11862. xpath.appendf("Alias[@name='%s']", alias);
  11863. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  11864. return queryRegistry->removeTree(t);
  11865. }
  11866. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  11867. {
  11868. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11869. setQueryAlias(queryRegistry, alias, id);
  11870. }
  11871. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  11872. {
  11873. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11874. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  11875. }
  11876. void deleteQuerySetQuery(const char *querySetName, const char *id)
  11877. {
  11878. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11879. removeNamedQuery(queryRegistry, id);
  11880. }
  11881. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  11882. {
  11883. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11884. clearAliases(queryRegistry, id);
  11885. }
  11886. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  11887. {
  11888. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11889. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  11890. }
  11891. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  11892. {
  11893. if (!queryRegistry)
  11894. return NULL;
  11895. StringBuffer xpath;
  11896. xpath.appendf("Query[@wuid='%s']", wuid);
  11897. if (queryName && *queryName)
  11898. xpath.appendf("[@name='%s']", queryName);
  11899. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  11900. if (q)
  11901. {
  11902. id.set(q->queryProp("@id"));
  11903. }
  11904. return id.str();
  11905. }
  11906. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  11907. {
  11908. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11909. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  11910. }
  11911. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  11912. {
  11913. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  11914. ForEach(*wulibraries)
  11915. {
  11916. SCMStringBuffer libname;
  11917. IConstWULibrary &wulibrary = wulibraries->query();
  11918. wulibrary.getName(libname);
  11919. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  11920. continue;
  11921. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  11922. if (query && query->getPropBool("@isLibrary"))
  11923. {
  11924. const char *wuid = query->queryProp("@wuid");
  11925. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  11926. if (libcw)
  11927. {
  11928. names.appendUniq(libname.str());
  11929. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  11930. continue;
  11931. }
  11932. }
  11933. unresolved.appendUniq(libname.str());
  11934. }
  11935. }
  11936. bool looksLikeAWuid(const char * wuid, const char firstChar)
  11937. {
  11938. if (!wuid)
  11939. return false;
  11940. if (wuid[0] != firstChar)
  11941. return false;
  11942. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  11943. return false;
  11944. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  11945. return false;
  11946. return (wuid[9]=='-');
  11947. }
  11948. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  11949. {
  11950. IPropertyTree * module = archive;
  11951. const char * dot = strrchr(path, '.');
  11952. StringBuffer xpath;
  11953. if (dot)
  11954. {
  11955. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  11956. module = archive->queryPropTree(xpath);
  11957. path = dot+1;
  11958. }
  11959. else
  11960. module = archive->queryPropTree("Module[@key='']");
  11961. if (!module)
  11962. return NULL;
  11963. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  11964. return module->queryPropTree(xpath);
  11965. }
  11966. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  11967. {
  11968. StringBuffer fullPathName;
  11969. makeAbsolutePath(name, fullPathName);
  11970. if (isContainerized())
  11971. {
  11972. const char *dllserver_root = getenv("HPCC_DLLSERVER_PATH");
  11973. assertex(dllserver_root != nullptr);
  11974. StringBuffer destPathName(dllserver_root);
  11975. addNonEmptyPathSepChar(destPathName);
  11976. splitFilename(fullPathName.str(), nullptr, nullptr, &destPathName, &destPathName);
  11977. OwnedIFile source = createIFile(fullPathName);
  11978. OwnedIFile target = createIFile(destPathName);
  11979. if (!target->exists())
  11980. {
  11981. source->copyTo(target, 0, NULL, true);
  11982. }
  11983. query->addAssociatedFile(type, destPathName, "localhost", description, crc, minActivity, maxActivity);
  11984. // Should we delete the local files? May not matter...
  11985. }
  11986. else
  11987. {
  11988. StringBuffer hostname;
  11989. queryHostIP().getIpText(hostname);
  11990. query->addAssociatedFile(type, fullPathName, hostname, description, crc, minActivity, maxActivity);
  11991. }
  11992. }
  11993. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  11994. {
  11995. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  11996. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  11997. if(workunit)
  11998. workunit->deschedule();
  11999. else
  12000. doDescheduleWorkkunit(wuid);
  12001. }
  12002. extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid)
  12003. {
  12004. StringBuffer scopestr;
  12005. if (wfid && scope && *scope)
  12006. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12007. else
  12008. scopestr.set(scope);
  12009. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, description, value, 1, 0, StatsMergeReplace);
  12010. }
  12011. class WuTimingUpdater : implements ITimeReportInfo
  12012. {
  12013. public:
  12014. WuTimingUpdater(IWorkUnit * _wu, StatisticScopeType _scopeType, StatisticKind _kind)
  12015. : wu(_wu), scopeType(_scopeType), kind(_kind)
  12016. { }
  12017. virtual void report(const char * scope, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  12018. {
  12019. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, nullptr, totaltime, count, maxtime, StatsMergeReplace);
  12020. }
  12021. protected:
  12022. IWorkUnit * wu;
  12023. StatisticScopeType scopeType;
  12024. StatisticKind kind;
  12025. };
  12026. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  12027. {
  12028. WuTimingUpdater target(wu, SSTsection, StTimeTotalExecute);
  12029. timer->report(target);
  12030. }
  12031. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer)
  12032. {
  12033. WuTimingUpdater target(wu, scopeType, kind);
  12034. timer->report(target);
  12035. }
  12036. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid)
  12037. {
  12038. StringBuffer scopestr;
  12039. if (wfid && scope && *scope)
  12040. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12041. else
  12042. scopestr.set(scope);
  12043. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  12044. }
  12045. extern WORKUNIT_API cost_type calculateThorCost(unsigned __int64 ms, unsigned clusterWidth)
  12046. {
  12047. IPropertyTree *costs = queryCostsConfiguration();
  12048. if (costs)
  12049. {
  12050. cost_type thor_master_rate = money2cost_type(costs->getPropReal("thor/@master"));
  12051. cost_type thor_slave_rate = money2cost_type(costs->getPropReal("thor/@slave"));
  12052. return calcCost(thor_master_rate, ms) + calcCost(thor_slave_rate, ms) * clusterWidth;
  12053. }
  12054. return 0;
  12055. }
  12056. void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search)
  12057. {
  12058. SimpleReferenceAggregator aggregator(search, result);
  12059. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  12060. ForEach(*it)
  12061. it->playProperties(aggregator);
  12062. }
  12063. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  12064. {
  12065. public:
  12066. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  12067. virtual void beginScope(const StatsScopeId & id)
  12068. {
  12069. prevLenStack.append(scope.length());
  12070. if (scope.length())
  12071. scope.append(":");
  12072. id.getScopeText(scope);
  12073. scopeTypeStack.append(id.queryScopeType());
  12074. }
  12075. virtual void beginSubGraphScope(unsigned id)
  12076. {
  12077. StatsScopeId scopeId(SSTsubgraph, id);
  12078. beginScope(scopeId);
  12079. }
  12080. virtual void beginActivityScope(unsigned id)
  12081. {
  12082. StatsScopeId scopeId(SSTactivity, id);
  12083. beginScope(scopeId);
  12084. }
  12085. virtual void beginEdgeScope(unsigned id, unsigned oid)
  12086. {
  12087. StatsScopeId scopeId(SSTedge, id, oid);
  12088. beginScope(scopeId);
  12089. }
  12090. virtual void beginChildGraphScope(unsigned id)
  12091. {
  12092. StatsScopeId scopeId(SSTchildgraph, id);
  12093. beginScope(scopeId);
  12094. }
  12095. virtual void endScope()
  12096. {
  12097. scope.setLength(prevLenStack.popGet());
  12098. scopeTypeStack.pop();
  12099. }
  12100. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  12101. {
  12102. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12103. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  12104. }
  12105. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  12106. {
  12107. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12108. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  12109. }
  12110. virtual IStatisticCollection * getResult()
  12111. {
  12112. return NULL;
  12113. }
  12114. protected:
  12115. Linked<IWorkUnit> wu;
  12116. StringBuffer scope;
  12117. UnsignedArray prevLenStack;
  12118. UnsignedArray scopeTypeStack;
  12119. };
  12120. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  12121. {
  12122. return new GlobalStatisticGatherer(wu);
  12123. }
  12124. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  12125. {
  12126. if (!wuid || !*wuid)
  12127. return NULL;
  12128. VStringBuffer path("/GraphProgress/%s", wuid);
  12129. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  12130. if (conn)
  12131. return conn->getRoot();
  12132. else
  12133. return NULL;
  12134. }
  12135. void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp)
  12136. {
  12137. ErrorSeverity wuSeverity = SeverityInformation;
  12138. ErrorSeverity severity = error->getSeverity();
  12139. switch (severity)
  12140. {
  12141. case SeverityIgnore:
  12142. return;
  12143. case SeverityInformation:
  12144. break;
  12145. case SeverityWarning:
  12146. wuSeverity = SeverityWarning;
  12147. break;
  12148. case SeverityError:
  12149. case SeverityFatal:
  12150. wuSeverity = SeverityError;
  12151. break;
  12152. }
  12153. Owned<IWUException> exception = wu->createException();
  12154. exception->setSeverity(wuSeverity);
  12155. StringBuffer msg;
  12156. exception->setExceptionCode(error->errorCode());
  12157. exception->setExceptionMessage(error->errorMessage(msg).str());
  12158. const char * source = queryCreatorTypeName(queryStatisticsComponentType());
  12159. exception->setExceptionSource(source);
  12160. exception->setExceptionFileName(error->getFilename());
  12161. exception->setExceptionLineNo(error->getLine());
  12162. exception->setExceptionColumn(error->getColumn());
  12163. if (removeTimeStamp)
  12164. exception->setTimeStamp(nullptr);
  12165. if (error->getActivity())
  12166. exception->setActivityId(error->getActivity());
  12167. if (error->queryScope())
  12168. exception->setScope(error->queryScope());
  12169. }
  12170. IError * WorkUnitErrorReceiver::mapError(IError * error)
  12171. {
  12172. return LINK(error);
  12173. }
  12174. void WorkUnitErrorReceiver::report(IError* eclError)
  12175. {
  12176. addWorkunitException(wu, eclError, removeTimeStamp);
  12177. }
  12178. size32_t WorkUnitErrorReceiver::errCount()
  12179. {
  12180. unsigned count = 0;
  12181. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12182. ForEach(*exceptions)
  12183. if (exceptions->query().getSeverity() == SeverityError)
  12184. count++;
  12185. return count;
  12186. }
  12187. size32_t WorkUnitErrorReceiver::warnCount()
  12188. {
  12189. unsigned count = 0;
  12190. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12191. ForEach(*exceptions)
  12192. if (exceptions->query().getSeverity() == SeverityWarning)
  12193. count++;
  12194. return count;
  12195. }
  12196. bool isValidPriorityValue(const char *priority)
  12197. {
  12198. if (isEmptyString(priority))
  12199. return false;
  12200. if (strieq("SLA", priority) || strieq("LOW", priority) || strieq("HIGH", priority) || strieq("NONE", priority))
  12201. return true;
  12202. return false;
  12203. }
  12204. bool isValidMemoryValue(const char *memoryUnit)
  12205. {
  12206. if (isEmptyString(memoryUnit) || !isdigit(*memoryUnit))
  12207. return false;
  12208. while (isdigit(*++memoryUnit));
  12209. if (!*memoryUnit)
  12210. return true;
  12211. switch (toupper(*memoryUnit++))
  12212. {
  12213. case 'E':
  12214. case 'P':
  12215. case 'T':
  12216. case 'G':
  12217. case 'M':
  12218. case 'K':
  12219. if (!*memoryUnit || strieq("B", memoryUnit))
  12220. return true;
  12221. break;
  12222. case 'B':
  12223. if (!*memoryUnit)
  12224. return true;
  12225. break;
  12226. }
  12227. return false;
  12228. }
  12229. // used by eclagent and roxie
  12230. #define ABORT_POLL_PERIOD (5*1000)
  12231. void executeThorGraph(const char * graphName, IConstWorkUnit &workunit, const IPropertyTree &config)
  12232. {
  12233. unsigned timelimit = workunit.getDebugValueInt("thorConnectTimeout", config.getPropInt("@thorConnectTimeout", 60));
  12234. StringAttr wuid(workunit.queryWuid());
  12235. #ifdef _CONTAINERIZED
  12236. // NB: If a single agent were to want to launch >1 Thor, then the threading could be in the workflow above this call.
  12237. {
  12238. Owned<IWorkUnit> w = &workunit.lock();
  12239. w->setState(WUStateBlocked);
  12240. }
  12241. WUState state = WUStateUnknown;
  12242. if (config.hasProp("@queue"))
  12243. {
  12244. bool multiJobLinger = config.getPropBool("@multiJobLinger");
  12245. if (executeGraphOnLingeringThor(workunit, graphName, multiJobLinger ? config.queryProp("@queue") : nullptr))
  12246. PROGLOG("Existing lingering Thor handled graph: %s", graphName);
  12247. else
  12248. {
  12249. VStringBuffer queueName("%s.thor", config.queryProp("@queue"));
  12250. DBGLOG("Queueing wuid=%s, graph=%s, on queue=%s, timelimit=%u seconds", wuid.str(), graphName, queueName.str(), timelimit);
  12251. Owned<IJobQueue> queue = createJobQueue(queueName);
  12252. VStringBuffer jobName("%s/%s", wuid.get(), graphName);
  12253. IJobQueueItem *item = createJobQueueItem(jobName);
  12254. queue->enqueue(item);
  12255. }
  12256. // NB: overall max runtime if guillotine set handled by abortmonitor
  12257. unsigned runningTimeLimit = workunit.getDebugValueInt("maxRunTime", 0);
  12258. runningTimeLimit = runningTimeLimit ? runningTimeLimit : INFINITE;
  12259. std::list<WUState> expectedStates = { WUStateRunning, WUStateWait };
  12260. for (unsigned i=0; i<2; i++)
  12261. {
  12262. WUState state = waitForWorkUnitToComplete(wuid, timelimit*1000, expectedStates);
  12263. DBGLOG("Got state: %s", getWorkunitStateStr(state));
  12264. if (WUStateWait == state) // already finished
  12265. break;
  12266. else if ((INFINITE != timelimit) && (WUStateUnknown == state))
  12267. throw makeStringExceptionV(0, "Query %s failed to start within specified timelimit (%u) seconds", wuid.str(), timelimit);
  12268. else
  12269. {
  12270. auto it = std::find(expectedStates.begin(), expectedStates.end(), state);
  12271. if (it == expectedStates.end())
  12272. throw makeStringExceptionV(0, "Query %s failed, state: %s", wuid.str(), getWorkunitStateStr(state));
  12273. }
  12274. timelimit = runningTimeLimit;
  12275. expectedStates = { WUStateWait };
  12276. }
  12277. }
  12278. else
  12279. {
  12280. VStringBuffer job("%s-%s", wuid.str(), graphName);
  12281. runK8sJob("thormaster", wuid, job, queryComponentConfig().getPropBool("@deleteJobs", true), { { "graphName", graphName} });
  12282. }
  12283. /* In k8s, Thor feeds back the terminating exception via the workunit.
  12284. * (in bare-metal it is returned via a socket the agent connect to Thor with)
  12285. */
  12286. workunit.forceReload();
  12287. if (workunit.getExceptionCount())
  12288. {
  12289. Owned<IConstWUExceptionIterator> iter = &workunit.getExceptions();
  12290. ForEach(*iter)
  12291. {
  12292. IConstWUException &e = iter->query();
  12293. SCMStringBuffer str;
  12294. e.getExceptionSource(str);
  12295. if (streq("thormasterexception", str.s))
  12296. {
  12297. str.clear();
  12298. e.getExceptionMessage(str);
  12299. unsigned errCode = e.getExceptionCode();
  12300. {
  12301. /* Clear the feedback exception (consume it),
  12302. * so that any future re-submissions of this workunit (e.g. due to workflow)
  12303. * don't see it again.
  12304. */
  12305. Owned<IWorkUnit> w = &workunit.lock();
  12306. w->clearExceptions("thormasterexception");
  12307. }
  12308. throw makeStringException(errCode, str.str());
  12309. }
  12310. }
  12311. }
  12312. else
  12313. {
  12314. Owned<IWorkUnit> w = &workunit.lock();
  12315. WUState state = w->getState();
  12316. if (WUStateFailed == state)
  12317. throw makeStringException(0, "Workunit failed");
  12318. }
  12319. {
  12320. Owned<IWorkUnit> w = &workunit.lock();
  12321. w->setState(WUStateRunning);
  12322. }
  12323. #else
  12324. StringAttr owner(workunit.queryUser());
  12325. StringAttr cluster(workunit.queryClusterName());
  12326. int priority = workunit.getPriorityValue();
  12327. Owned<IConstWUClusterInfo> c = getTargetClusterInfo(cluster);
  12328. if (!c)
  12329. throw MakeStringException(0, "Invalid thor cluster %s", cluster.str());
  12330. SCMStringBuffer queueName;
  12331. c->getThorQueue(queueName);
  12332. Owned<IJobQueue> jq = createJobQueue(queueName.str());
  12333. bool resubmit;
  12334. Owned<IWorkUnitFactory> wuFactory = getWorkUnitFactory();
  12335. do // loop if pause interrupted graph and needs resubmitting on resume
  12336. {
  12337. resubmit = false; // set if job interrupted in thor
  12338. if (WUStatePaused == workunit.getState()) // check initial state - and wait if paused
  12339. {
  12340. for (;;)
  12341. {
  12342. WUAction action = wuFactory->waitForWorkUnitAction(wuid, workunit.getAction());
  12343. if (action == WUActionUnknown)
  12344. throw new WorkflowException(0, "Workunit aborting", 0, WorkflowException::ABORT, MSGAUD_user);
  12345. if (action != WUActionPause && action != WUActionPauseNow)
  12346. break;
  12347. }
  12348. }
  12349. {
  12350. Owned<IWorkUnit> w = &workunit.lock();
  12351. w->setState(WUStateBlocked);
  12352. }
  12353. class cPollThread: public Thread // MORE - why do we ned a thread here?
  12354. {
  12355. Semaphore sem;
  12356. bool stopped;
  12357. IJobQueue *jq;
  12358. IConstWorkUnit *wu;
  12359. public:
  12360. bool timedout;
  12361. CTimeMon tm;
  12362. cPollThread(IJobQueue *_jq, IConstWorkUnit *_wu, unsigned timelimit)
  12363. : tm(timelimit)
  12364. {
  12365. stopped = false;
  12366. jq = _jq;
  12367. wu = _wu;
  12368. timedout = false;
  12369. }
  12370. ~cPollThread()
  12371. {
  12372. stop();
  12373. }
  12374. int run()
  12375. {
  12376. while (!stopped) {
  12377. sem.wait(ABORT_POLL_PERIOD);
  12378. if (stopped)
  12379. break;
  12380. if (tm.timedout()) {
  12381. timedout = true;
  12382. stopped = true;
  12383. jq->cancelInitiateConversation();
  12384. }
  12385. else if (wu->aborting()) {
  12386. stopped = true;
  12387. jq->cancelInitiateConversation();
  12388. }
  12389. }
  12390. return 0;
  12391. }
  12392. void stop()
  12393. {
  12394. stopped = true;
  12395. sem.signal();
  12396. }
  12397. } pollthread(jq, &workunit, timelimit*1000);
  12398. pollthread.start();
  12399. PROGLOG("Enqueuing on %s to run wuid=%s, graph=%s, timelimit=%d seconds, priority=%d", queueName.str(), wuid.str(), graphName, timelimit, priority);
  12400. IJobQueueItem* item = createJobQueueItem(wuid.str());
  12401. item->setOwner(owner.str());
  12402. item->setPriority(priority);
  12403. Owned<IConversation> conversation = jq->initiateConversation(item);
  12404. bool got = conversation.get()!=NULL;
  12405. pollthread.stop();
  12406. pollthread.join();
  12407. if (!got)
  12408. {
  12409. if (pollthread.timedout)
  12410. throw MakeStringException(0, "Query %s failed to start within specified timelimit (%d) seconds", wuid.str(), timelimit);
  12411. throw MakeStringException(0, "Query %s cancelled (1)",wuid.str());
  12412. }
  12413. // get the thor ep from whoever picked up
  12414. SocketEndpoint thorMaster;
  12415. MemoryBuffer msg;
  12416. if (!conversation->recv(msg,1000*60))
  12417. throw MakeStringException(0, "Query %s cancelled (2)",wuid.str());
  12418. thorMaster.deserialize(msg);
  12419. msg.clear().append(graphName);
  12420. SocketEndpoint myep;
  12421. myep.setLocalHost(0);
  12422. myep.serialize(msg); // only used for tracing
  12423. if (!conversation->send(msg)) {
  12424. StringBuffer s("Failed to send query to Thor on ");
  12425. thorMaster.getUrlStr(s);
  12426. throw MakeStringExceptionDirect(-1, s.str()); // maybe retry?
  12427. }
  12428. StringBuffer eps;
  12429. PROGLOG("Thor on %s running %s",thorMaster.getUrlStr(eps).str(),wuid.str());
  12430. MemoryBuffer reply;
  12431. try
  12432. {
  12433. if (!conversation->recv(reply,INFINITE))
  12434. {
  12435. StringBuffer s("Failed to receive reply from thor ");
  12436. thorMaster.getUrlStr(s);
  12437. throw MakeStringExceptionDirect(-1, s.str());
  12438. }
  12439. }
  12440. catch (IException *e)
  12441. {
  12442. StringBuffer s("Failed to receive reply from thor ");
  12443. thorMaster.getUrlStr(s);
  12444. s.append("; (").append(e->errorCode()).append(", ");
  12445. e->errorMessage(s).append(")");
  12446. e->Release();
  12447. throw MakeStringExceptionDirect(-1, s.str());
  12448. }
  12449. unsigned replyCode;
  12450. reply.read(replyCode);
  12451. switch ((ThorReplyCodes) replyCode)
  12452. {
  12453. case DAMP_THOR_REPLY_PAUSED:
  12454. {
  12455. bool isException;
  12456. reply.read(isException);
  12457. if (isException)
  12458. {
  12459. Owned<IException> e = deserializeException(reply);
  12460. VStringBuffer str("Pausing job %s caused exception", wuid.get());
  12461. EXCLOG(e, str.str());
  12462. }
  12463. Owned<IWorkUnit> w = &workunit.lock();
  12464. w->setState(WUStatePaused); // will trigger executeThorGraph to pause next time around.
  12465. WUAction action = w->getAction();
  12466. switch (action)
  12467. {
  12468. case WUActionPause:
  12469. case WUActionPauseNow:
  12470. w->setAction(WUActionUnknown);
  12471. }
  12472. resubmit = true; // JCSMORE - all subgraph _could_ be done, thor will check though and not rerun
  12473. break;
  12474. }
  12475. case DAMP_THOR_REPLY_GOOD:
  12476. break;
  12477. case DAMP_THOR_REPLY_ERROR:
  12478. {
  12479. throw deserializeException(reply);
  12480. }
  12481. case DAMP_THOR_REPLY_ABORT:
  12482. {
  12483. Owned<IException> e = deserializeException(reply);
  12484. StringBuffer msg;
  12485. e->errorMessage(msg);
  12486. throw new WorkflowException(e->errorCode(), msg.str(), 0, WorkflowException::ABORT, MSGAUD_user);
  12487. }
  12488. default:
  12489. throwUnexpected();
  12490. }
  12491. workunit.forceReload();
  12492. }
  12493. while (resubmit); // if pause interrupted job (i.e. with pausenow action), resubmit graph
  12494. #endif
  12495. }
  12496. #ifdef _CONTAINERIZED
  12497. bool executeGraphOnLingeringThor(IConstWorkUnit &workunit, const char *graphName, const char *multiJobLingerQueueName)
  12498. {
  12499. // check if lingering thor instance is up.
  12500. // Returns true if successfully submitted graph to a lingering Thor.
  12501. /* If code was dependent on reading a workunit in parallel, the whole area of
  12502. * workunit locking and reading will need revisiting, because at the moment the
  12503. * workunit reading code does not lock at all.
  12504. *
  12505. * Either,
  12506. * 1) multiJobThorLinger is set, meaning Thor instances will wait for any job's graph.
  12507. * OR
  12508. * 2) if not set, the Thor will wait for graphs from same job only, and will be
  12509. * notified to quit by the agent, when the last graph is complete.
  12510. *
  12511. * This code is called from the client (agent) when it wants to execute a Thor graph.
  12512. * This function checks to see if there any registered lingering Thor instances available.
  12513. *
  12514. * Lingering Thor's register when they are idle either with the workunit itself in
  12515. * the case of [2], or with a Dali psuedo queue (a branch under /Status/ThorLinger),
  12516. * in the case of [1]
  12517. * If they have not been contacted within the 'lingerPeriod' they shutdown and remove
  12518. * their registered instance from the queue.
  12519. *
  12520. * The client will attempt to find a lingering Thor in either the workunit or a global
  12521. * named dali queue (depending on the configuration), it will then remove that entry,
  12522. * and attempt to post the graph to that lingering Thor. If the Thor acknowledges the
  12523. * request, this function exits with success. If it it fails, or there are no more
  12524. * lingering Thor instances, it returns with false to indicate that the graph was not
  12525. * submitted to a lingering Thor.
  12526. * The client should then queue the wuid/graph normally, which will invoke a new Thor
  12527. * instance.
  12528. */
  12529. try
  12530. {
  12531. if (multiJobLingerQueueName && graphName)
  12532. {
  12533. // check a Dali queue for idle spare Thor's
  12534. DBGLOG("Checking multi job lingering queue: %s", multiJobLingerQueueName);
  12535. VStringBuffer xpath("/Status/ThorLinger/%s", multiJobLingerQueueName);
  12536. while (true)
  12537. {
  12538. Owned<IRemoteConnection> conn = querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE, 5*60*1000);
  12539. if (!conn)
  12540. break;
  12541. IPropertyTree *root = conn->queryRoot();
  12542. if (0 == root->numChildren())
  12543. break;
  12544. IPropertyTree *entry = root->queryPropTree("Thor*[1]");
  12545. const char *entryName = entry->queryName();
  12546. // get available instance and remove it
  12547. VStringBuffer entryXPath("%s/%s", xpath.str(), entryName);
  12548. Owned<IRemoteConnection> lingerInstanceConn = querySDS().connect(entryXPath, myProcessSession(), RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, 5*1000);
  12549. if (lingerInstanceConn)
  12550. {
  12551. StringBuffer instanceName;
  12552. lingerInstanceConn->queryRoot()->getProp(nullptr, instanceName);
  12553. lingerInstanceConn->close(true);
  12554. lingerInstanceConn.clear();
  12555. conn.clear();
  12556. Owned<INode> masterNode = createINode(instanceName);
  12557. CMessageBuffer msg;
  12558. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName);
  12559. msg.append(jobStr);
  12560. bool success = queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000);
  12561. DBGLOG("Found lingering Thor: %s, submitted: %s, success: %s", instanceName.str(), jobStr.str(), boolToStr(success));
  12562. if (success)
  12563. {
  12564. bool ok;
  12565. msg.read(ok);
  12566. return true;
  12567. }
  12568. }
  12569. }
  12570. }
  12571. else
  12572. {
  12573. /* NB: forcing a reload here to ensure Debug values are recent.
  12574. * Could be improved by refreshing only the specific area of interest (i.e. Debug/ in this case).
  12575. * The area of persisting a non-locked connection to workunits should be resivisted..
  12576. */
  12577. workunit.forceReload();
  12578. Owned<IStringIterator> iter = &workunit.getDebugValues("thorinstance_*");
  12579. ForEach(*iter)
  12580. {
  12581. /* NB: Thor's set their running endpoint into Debug values of workunit
  12582. * Check to see if workunit has any Thor's available lingering instances.
  12583. */
  12584. SCMStringBuffer thorInstance;
  12585. iter->str(thorInstance);
  12586. SCMStringBuffer thorInstanceValue;
  12587. if (workunit.getDebugValueBool(thorInstance.s, false))
  12588. {
  12589. {
  12590. Owned<IWorkUnit> w = &workunit.lock();
  12591. w->setDebugValue(thorInstance.s, "0", true);
  12592. }
  12593. /* NB: there's a window where Thor could shutdown here.
  12594. * In that case, the sendRecv will fail and it will fall through to queueing.
  12595. */
  12596. const char *instanceName = strchr(thorInstance.str(), '_') + 1;
  12597. Owned<INode> masterNode = createINode(instanceName);
  12598. CMessageBuffer msg;
  12599. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName?graphName:"");
  12600. msg.append(jobStr);
  12601. if (queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000))
  12602. {
  12603. bool ok;
  12604. msg.read(ok);
  12605. if (graphName) // if graphName==nullptr, then continue around to look at others
  12606. {
  12607. if (ok)
  12608. return true;
  12609. }
  12610. }
  12611. }
  12612. }
  12613. }
  12614. }
  12615. catch (IException *e)
  12616. {
  12617. EXCLOG(e, "executeGraphOnLingeringThor");
  12618. e->Release();
  12619. }
  12620. return false;
  12621. }
  12622. static void setResources(StringBuffer &jobYaml, const IConstWorkUnit *workunit, const char *process)
  12623. {
  12624. StringBuffer s;
  12625. unsigned memRequest = workunit->getDebugValueInt(s.clear().appendf("%s-memRequest", process), 0);
  12626. unsigned memLimit = workunit->getDebugValueInt(s.clear().appendf("%s-memLimit", process), 0);
  12627. if (memLimit && memLimit < memRequest)
  12628. memLimit = memRequest;
  12629. if (memRequest)
  12630. jobYaml.replaceString("#request-memory", s.clear().appendf("memory: \"%uMi\"", memRequest));
  12631. if (memLimit)
  12632. jobYaml.replaceString("#limit-memory", s.clear().appendf("memory: \"%uMi\"", memLimit));
  12633. unsigned cpuRequest = workunit->getDebugValueInt(s.clear().appendf("%s-cpuRequest", process), 0);
  12634. unsigned cpuLimit = workunit->getDebugValueInt(s.clear().appendf("%s-cpuLimit", process), 0);
  12635. if (cpuLimit && cpuLimit < cpuRequest)
  12636. cpuLimit = cpuRequest;
  12637. if (cpuRequest)
  12638. jobYaml.replaceString("#request-cpu", s.clear().appendf("cpu: \"%um\"", cpuRequest));
  12639. if (cpuLimit)
  12640. jobYaml.replaceString("#limit-cpu", s.clear().appendf("cpu: \"%um\"", cpuLimit));
  12641. }
  12642. void deleteK8sJob(const char *componentName, const char *job)
  12643. {
  12644. VStringBuffer jobname("%s-%s", componentName, job);
  12645. jobname.toLowerCase();
  12646. VStringBuffer deleteJob("kubectl delete job/%s", jobname.str());
  12647. StringBuffer output, error;
  12648. bool ret = runExternalCommand(componentName, output, error, deleteJob.str(), nullptr);
  12649. DBGLOG("kubectl delete output: %s", output.str());
  12650. if (error.length())
  12651. DBGLOG("kubectl delete error: %s", error.str());
  12652. if (ret)
  12653. throw makeStringException(0, "Failed to run kubectl delete");
  12654. }
  12655. void waitK8sJob(const char *componentName, const char *job)
  12656. {
  12657. VStringBuffer jobname("%s-%s", componentName, job);
  12658. jobname.toLowerCase();
  12659. VStringBuffer waitJob("kubectl get jobs %s -o jsonpath={.status.active}", jobname.str());
  12660. VStringBuffer getScheduleStatus("kubectl get pods --selector=job-name=%s --output=jsonpath={.items[*].status.conditions[?(@.type=='PodScheduled')].status}", jobname.str());
  12661. VStringBuffer checkJobExitCode("kubectl get pods --selector=job-name=%s --output=jsonpath={.items[*].status.containerStatuses[?(@.name==\"%s\")].state.terminated.exitCode}", jobname.str(), jobname.str());
  12662. unsigned delay = 100;
  12663. unsigned start = msTick();
  12664. unsigned pendingTimeout = 10000;
  12665. for (;;)
  12666. {
  12667. StringBuffer output, error;
  12668. unsigned ret = runExternalCommand(nullptr, output, error, waitJob.str(), nullptr);
  12669. if (ret || error.length())
  12670. throw makeStringExceptionV(0, "Failed to run %s: error %u: %s", waitJob.str(), ret, error.str());
  12671. if (!streq(output, "1")) // status.active value
  12672. {
  12673. // Job is no longer active - we can terminate
  12674. DBGLOG("kubectl jobs output: %s", output.str());
  12675. unsigned ret = runExternalCommand(nullptr, output.clear(), error.clear(), checkJobExitCode.str(), nullptr);
  12676. if (ret || error.length())
  12677. throw makeStringExceptionV(0, "Failed to run %s: error %u: %s", checkJobExitCode.str(), ret, error.str());
  12678. if (!streq(output, "0")) // state.terminated.exitCode
  12679. throw makeStringExceptionV(0, "Failed to run %s: pod exited with error: %s", jobname.str(), output.str());
  12680. break;
  12681. }
  12682. ret = runExternalCommand(nullptr, output.clear(), error.clear(), getScheduleStatus.str(), nullptr);
  12683. if (error.length())
  12684. {
  12685. DBGLOG("kubectl get schedule status error: %s", error.str());
  12686. break;
  12687. }
  12688. // Check whether pod has been scheduled yet - if resources are not available pods may block indefinitely waiting to be scheduled, and
  12689. // we would prefer them to fail instead.
  12690. bool pending = streq(output, "False");
  12691. if (pending && msTick()-start > pendingTimeout)
  12692. {
  12693. VStringBuffer getReason("kubectl get pods --selector=job-name=%s \"--output=jsonpath={range .items[*].status.conditions[?(@.type=='PodScheduled')]}{.reason}{': '}{.message}{end}\"", jobname.str());
  12694. runExternalCommand(componentName, output.clear(), error.clear(), getReason.str(), nullptr);
  12695. throw makeStringExceptionV(0, "Failed to run %s - pod not scheduled after %d ms: %s ", jobname.str(), pendingTimeout, output.str());
  12696. }
  12697. MilliSleep(delay);
  12698. if (delay < 10000)
  12699. delay = delay * 2;
  12700. }
  12701. }
  12702. void launchK8sJob(const char *componentName, const char *wuid, const char *job, const std::list<std::pair<std::string, std::string>> &extraParams)
  12703. {
  12704. VStringBuffer jobname("%s-%s", componentName, job);
  12705. jobname.toLowerCase();
  12706. VStringBuffer jobSpecFilename("/etc/config/%s-jobspec.yaml", componentName);
  12707. StringBuffer jobYaml;
  12708. jobYaml.loadFile(jobSpecFilename, false);
  12709. jobYaml.replaceString("%jobname", jobname.str());
  12710. VStringBuffer args("\"--workunit=%s\"", wuid);
  12711. for (const auto &p: extraParams)
  12712. {
  12713. if ('%' == p.first[0]) // jobspec substituion
  12714. jobYaml.replaceString(p.first.c_str(), p.second.c_str());
  12715. else
  12716. args.append(',').newline().append("\"--").append(p.first.c_str()).append('=').append(p.second.c_str()).append("\"");
  12717. }
  12718. jobYaml.replaceString("%args", args.str());
  12719. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  12720. if (factory)
  12721. {
  12722. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(wuid);
  12723. if (workunit)
  12724. setResources(jobYaml, workunit, componentName);
  12725. }
  12726. StringBuffer output, error;
  12727. unsigned ret = runExternalCommand(componentName, output, error, "kubectl replace --force -f -", jobYaml.str());
  12728. DBGLOG("kubectl output: %s", output.str());
  12729. if (error.length())
  12730. DBGLOG("kubectl error: %s", error.str());
  12731. if (ret)
  12732. {
  12733. DBGLOG("Using job yaml %s", jobYaml.str());
  12734. throw makeStringException(0, "Failed to start kubectl job");
  12735. }
  12736. }
  12737. void runK8sJob(const char *componentName, const char *wuid, const char *job, bool del, const std::list<std::pair<std::string, std::string>> &extraParams)
  12738. {
  12739. launchK8sJob(componentName, wuid, job, extraParams);
  12740. waitK8sJob(componentName, job);
  12741. if (del)
  12742. deleteK8sJob(componentName, job);
  12743. }
  12744. #endif