workunit.cpp 338 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362
  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 "jlib.hpp"
  14. #include "workunit.hpp"
  15. #include "jprop.hpp"
  16. #include "jmisc.hpp"
  17. #include "jexcept.hpp"
  18. #include "jiter.ipp"
  19. #include "jptree.hpp"
  20. #include "jtime.ipp"
  21. #include "jencrypt.hpp"
  22. #include "junicode.hpp"
  23. #include "jlzw.hpp"
  24. #include "jregexp.hpp"
  25. #include "eclrtl.hpp"
  26. #include "deftype.hpp"
  27. #include <time.h>
  28. #include "mpbase.hpp"
  29. #include "daclient.hpp"
  30. #include "dadfs.hpp"
  31. #include "dafdesc.hpp"
  32. #include "dasds.hpp"
  33. #include "danqs.hpp"
  34. #include "dautils.hpp"
  35. #include "dllserver.hpp"
  36. #include "thorplugin.hpp"
  37. #include "thorhelper.hpp"
  38. #include "workflow.hpp"
  39. #include "nbcd.hpp"
  40. #include "seclib.hpp"
  41. #include "wuerror.hpp"
  42. #include "wujobq.hpp"
  43. #include "environment.hpp"
  44. #include "workunit.ipp"
  45. static int workUnitTraceLevel = 1;
  46. static StringBuffer &getXPath(StringBuffer &wuRoot, const char *wuid)
  47. {
  48. // MORE - can fold in the date
  49. return wuRoot.append("/WorkUnits/").append(wuid);
  50. }
  51. //To be called by eclserver, but esp etc. won't know, so we need to store it.
  52. static StringBuffer & appendLibrarySuffix(StringBuffer & suffix)
  53. {
  54. #ifdef _WIN32
  55. suffix.append("W");
  56. #else
  57. suffix.append("L");
  58. #endif
  59. #ifdef __64BIT__
  60. suffix.append("64");
  61. #else
  62. suffix.append("32");
  63. #endif
  64. return suffix;
  65. }
  66. typedef MapStringTo<bool> UniqueScopes;
  67. static void wuAccessError(const char *username, const char *action, const char *wuscope, const char *wuid, bool excpt, bool log)
  68. {
  69. StringBuffer err;
  70. err.append("Workunit Access Denied - action: ").append(action).append(" user:").append(username ? username : "<Unknown>");
  71. if (wuid)
  72. err.append(" workunit:").append(wuid);
  73. if (wuscope)
  74. err.append(" scope:").append(wuscope);
  75. //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
  76. SYSLOG(AUDIT_TYPE_ACCESS_FAILURE, err.str());
  77. if (log)
  78. LOG(MCuserError, "%s", err.str());
  79. if (excpt)
  80. throw MakeStringException(WUERR_AccessError, "%s", err.str());
  81. }
  82. static bool checkWuScopeSecAccess(const char *wuscope, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  83. {
  84. if (!secmgr || !secuser)
  85. return true;
  86. bool ret = secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, wuscope)>=required;
  87. if (!ret && (log || excpt))
  88. wuAccessError(secuser->getName(), action, wuscope, NULL, excpt, log);
  89. return ret;
  90. }
  91. static bool checkWuScopeListSecAccess(const char *wuscope, ISecResourceList *scopes, int required, const char *action, bool excpt, bool log)
  92. {
  93. if (!scopes)
  94. return true;
  95. bool ret=true;
  96. if (wuscope)
  97. {
  98. Owned<ISecResource> res=scopes->getResource(wuscope);
  99. if (!res || res->getAccessFlags()<required)
  100. ret=false;
  101. }
  102. else
  103. {
  104. for (int seq=0; ret && seq<scopes->count(); seq++)
  105. {
  106. ISecResource *res=scopes->queryResource(seq);
  107. if (res && res->getAccessFlags()<required)
  108. return false;
  109. }
  110. }
  111. if (!ret && (log || excpt))
  112. wuAccessError(NULL, action, wuscope, NULL, excpt, log);
  113. return ret;
  114. }
  115. static bool checkWuSecAccess(IConstWorkUnit &cw, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  116. {
  117. if (!secmgr || !secuser)
  118. return true;
  119. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw.queryWuScope())>=required;
  120. if (!ret && (log || excpt))
  121. {
  122. wuAccessError(secuser->getName(), action, cw.queryWuScope(), cw.queryWuid(), excpt, log);
  123. }
  124. return ret;
  125. }
  126. static bool checkWuSecAccess(const char *wuid, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  127. {
  128. StringBuffer wuRoot;
  129. Owned<IRemoteConnection> conn = querySDS().connect(getXPath(wuRoot, wuid).str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  130. if (conn)
  131. {
  132. Owned<IPropertyTree> ptree=conn->getRoot();
  133. return checkWuScopeSecAccess(ptree->queryProp("@scope"), secmgr, secuser, required, action, excpt, log);
  134. }
  135. if (log || excpt)
  136. wuAccessError(secuser ? secuser->getName() : NULL, action, "Unknown", NULL, excpt, log);
  137. return false;
  138. }
  139. void doDescheduleWorkkunit(char const * wuid)
  140. {
  141. StringBuffer xpath;
  142. xpath.append("*/*/*/");
  143. ncnameEscape(wuid, xpath);
  144. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  145. if(!conn) return;
  146. Owned<IPropertyTree> root = conn->getRoot();
  147. bool more;
  148. do more = root->removeProp(xpath.str()); while(more);
  149. }
  150. //======================================================
  151. /*
  152. * Graph progress support
  153. */
  154. CWuGraphStats::CWuGraphStats(IPropertyTree *_progress, StatisticCreatorType _creatorType, const char * _creator, const char * _rootScope, unsigned _id)
  155. : progress(_progress), creatorType(_creatorType), creator(_creator), id(_id)
  156. {
  157. StatisticScopeType scopeType = SSTgraph;
  158. StatsScopeId rootScopeId;
  159. verifyex(rootScopeId.setScopeText(_rootScope));
  160. collector.setown(createStatisticsGatherer(_creatorType, _creator, rootScopeId));
  161. }
  162. void CWuGraphStats::beforeDispose()
  163. {
  164. Owned<IStatisticCollection> stats = collector->getResult();
  165. MemoryBuffer compressed;
  166. {
  167. MemoryBuffer serialized;
  168. serializeStatisticCollection(serialized, stats);
  169. compressToBuffer(compressed, serialized.length(), serialized.toByteArray());
  170. }
  171. unsigned minActivity = 0;
  172. unsigned maxActivity = 0;
  173. stats->getMinMaxActivity(minActivity, maxActivity);
  174. StringBuffer tag;
  175. tag.append("sg").append(id);
  176. IPropertyTree * subgraph = createPTree(tag);
  177. subgraph->setProp("@c", queryCreatorTypeName(creatorType));
  178. subgraph->setProp("@creator", creator);
  179. subgraph->setPropInt("@minActivity", minActivity);
  180. subgraph->setPropInt("@maxActivity", maxActivity);
  181. //Replace the particular subgraph statistics added by this creator
  182. StringBuffer qualified(tag);
  183. qualified.append("[@creator='").append(creator).append("']");
  184. progress->removeProp(qualified);
  185. subgraph = progress->addPropTree(tag, subgraph);
  186. subgraph->setPropBin("Stats", compressed.length(), compressed.toByteArray());
  187. if (!progress->getPropBool("@stats", false))
  188. progress->setPropBool("@stats", true);
  189. }
  190. IStatisticGatherer & CWuGraphStats::queryStatsBuilder()
  191. {
  192. return *collector;
  193. }
  194. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  195. {
  196. public:
  197. IMPLEMENT_IINTERFACE;
  198. CConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress) : wuid(_wuid), graphName(_graphName), progress(_progress)
  199. {
  200. if (!progress)
  201. progress.setown(createPTree());
  202. formatVersion = progress->getPropInt("@format", PROGRESS_FORMAT_V);
  203. }
  204. virtual IPropertyTree * getProgressTree()
  205. {
  206. if (progress->getPropBool("@stats"))
  207. return createProcessTreeFromStats(); // Should we cache that?
  208. return LINK(progress);
  209. }
  210. virtual unsigned queryFormatVersion()
  211. {
  212. return formatVersion;
  213. }
  214. protected:
  215. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  216. {
  217. formatVersion = PROGRESS_FORMAT_V;
  218. }
  219. static void expandStats(IPropertyTree * target, IStatisticCollection & collection)
  220. {
  221. StringBuffer formattedValue;
  222. unsigned numStats = collection.getNumStatistics();
  223. for (unsigned i=0; i < numStats; i++)
  224. {
  225. StatisticKind kind;
  226. unsigned __int64 value;
  227. collection.getStatistic(kind, value, i);
  228. formatStatistic(formattedValue.clear(), value, kind);
  229. //Until 6.0 generate the backward compatible tag name
  230. const char * legacyTreeTag = queryLegacyTreeTag(kind);
  231. if (legacyTreeTag)
  232. {
  233. StatisticMeasure measure = queryMeasure(kind);
  234. if (measure == SMeasureSkew)
  235. {
  236. //Minimum stats were always output as +ve numbers
  237. if (queryStatsVariant(kind) == StSkewMin)
  238. value = -value;
  239. target->setPropInt64(legacyTreeTag, value/100);
  240. }
  241. else if (measure == SMeasureTimeNs)
  242. {
  243. //Legacy timings are in ms => scale
  244. target->setPropInt64(legacyTreeTag, value/1000000);
  245. }
  246. else
  247. target->setProp(legacyTreeTag, formattedValue);
  248. }
  249. //Unconditionally output in the new format.
  250. target->setProp(queryTreeTag(kind), formattedValue);
  251. }
  252. }
  253. void expandProcessTreeFromStats(IPropertyTree * rootTarget, IPropertyTree * target, IStatisticCollection * collection)
  254. {
  255. expandStats(target, *collection);
  256. StringBuffer scopeName;
  257. Owned<IStatisticCollectionIterator> activityIter = &collection->getScopes(NULL);
  258. ForEach(*activityIter)
  259. {
  260. IStatisticCollection & cur = activityIter->query();
  261. cur.getScope(scopeName.clear());
  262. const char * id = scopeName.str();
  263. const char * tag;
  264. IPropertyTree * curTarget = target;
  265. switch (cur.queryScopeType())
  266. {
  267. case SSTedge:
  268. tag = "edge";
  269. id += strlen(EdgeScopePrefix);
  270. break;
  271. case SSTactivity:
  272. tag = "node";
  273. id += strlen(ActivityScopePrefix);
  274. break;
  275. case SSTsubgraph:
  276. //All subgraphs are added a root elements in the progress tree
  277. curTarget = rootTarget;
  278. tag = "node";
  279. id += strlen(SubGraphScopePrefix);
  280. break;
  281. default:
  282. throwUnexpected();
  283. }
  284. IPropertyTree * next = curTarget->addPropTree(tag, createPTree());
  285. next->setProp("@id", id);
  286. expandProcessTreeFromStats(rootTarget, next, &cur);
  287. }
  288. }
  289. IPropertyTree * createProcessTreeFromStats()
  290. {
  291. MemoryBuffer compressed;
  292. MemoryBuffer serialized;
  293. Owned<IPropertyTree> progressTree = createPTree();
  294. Owned<IPropertyTreeIterator> iter = progress->getElements("sg*");
  295. ForEach(*iter)
  296. {
  297. IPropertyTree & curSubGraph = iter->query();
  298. curSubGraph.getPropBin("Stats", compressed.clear());
  299. //Protect against updates that delete the stats while we are iterating
  300. if (compressed.length())
  301. {
  302. decompressToBuffer(serialized.clear(), compressed);
  303. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  304. expandProcessTreeFromStats(progressTree, progressTree, collection);
  305. }
  306. }
  307. return progressTree.getClear();
  308. }
  309. protected:
  310. Linked<IPropertyTree> progress;
  311. StringAttr wuid, graphName;
  312. unsigned formatVersion;
  313. };
  314. extern WORKUNIT_API IConstWUGraphProgress *createConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress)
  315. {
  316. return new CConstGraphProgress(_wuid, _graphName, _progress);
  317. }
  318. //--------------------------------------------------------------------------------------------------------------------
  319. class ExtractedStatistic : public CInterfaceOf<IConstWUStatistic>
  320. {
  321. public:
  322. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const
  323. {
  324. if (!description && createDefault)
  325. {
  326. switch (kind)
  327. {
  328. case StTimeElapsed:
  329. {
  330. if (scopeType != SSTsubgraph)
  331. break;
  332. //Create a default description for a root subgraph
  333. const char * colon = strchr(scope, ':');
  334. if (!colon)
  335. break;
  336. const char * subgraph = colon+1;
  337. //Check for nested subgraph
  338. if (strchr(subgraph, ':'))
  339. break;
  340. assertex(strncmp(subgraph, SubGraphScopePrefix, strlen(SubGraphScopePrefix)) == 0);
  341. StringAttr graphname;
  342. graphname.set(scope, colon - scope);
  343. unsigned subId = atoi(subgraph + strlen(SubGraphScopePrefix));
  344. StringBuffer desc;
  345. formatGraphTimerLabel(desc, graphname, 0, subId);
  346. str.set(desc);
  347. return str;
  348. }
  349. }
  350. }
  351. str.set(description);
  352. return str;
  353. }
  354. virtual IStringVal & getCreator(IStringVal & str) const
  355. {
  356. str.set(creator);
  357. return str;
  358. }
  359. virtual IStringVal & getScope(IStringVal & str) const
  360. {
  361. str.set(scope);
  362. return str;
  363. }
  364. virtual IStringVal & getFormattedValue(IStringVal & str) const
  365. {
  366. StringBuffer formatted;
  367. formatStatistic(formatted, value, measure);
  368. str.set(formatted);
  369. return str;
  370. }
  371. virtual StatisticMeasure getMeasure() const
  372. {
  373. return measure;
  374. }
  375. virtual StatisticKind getKind() const
  376. {
  377. return kind;
  378. }
  379. virtual StatisticCreatorType getCreatorType() const
  380. {
  381. return creatorType;
  382. }
  383. virtual StatisticScopeType getScopeType() const
  384. {
  385. return scopeType;
  386. }
  387. virtual unsigned __int64 getValue() const
  388. {
  389. return value;
  390. }
  391. virtual unsigned __int64 getCount() const
  392. {
  393. return count;
  394. }
  395. virtual unsigned __int64 getMax() const
  396. {
  397. return max;
  398. }
  399. virtual unsigned __int64 getTimestamp() const
  400. {
  401. return timeStamp;
  402. }
  403. virtual bool matches(const IStatisticsFilter * filter) const
  404. {
  405. return filter->matches(creatorType, creator, scopeType, scope, measure, kind);
  406. }
  407. public:
  408. StringAttr creator;
  409. StringAttr description;
  410. StringBuffer scope;
  411. StatisticMeasure measure;
  412. StatisticKind kind;
  413. StatisticCreatorType creatorType;
  414. StatisticScopeType scopeType;
  415. unsigned __int64 value;
  416. unsigned __int64 count;
  417. unsigned __int64 max;
  418. unsigned __int64 timeStamp;
  419. };
  420. class CConstGraphProgressStatisticsIterator : public CInterfaceOf<IConstWUStatisticIterator>
  421. {
  422. public:
  423. CConstGraphProgressStatisticsIterator(const char * wuid, const IStatisticsFilter * _filter) : filter(_filter)
  424. {
  425. if (filter)
  426. scopes.appendList(filter->queryScope(), ":");
  427. const char * searchGraph = "*";
  428. if (scopes.ordinality())
  429. searchGraph = scopes.item(0);
  430. rootPath.append("/GraphProgress/").append(wuid).append('/');
  431. bool singleGraph = false;
  432. if (!containsWildcard(searchGraph))
  433. {
  434. rootPath.append(searchGraph).append("/");
  435. singleGraph = true;
  436. }
  437. //Don't lock the statistics while we iterate - any partial updates must not cause problems
  438. if (daliClientActive())
  439. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_NONE, SDS_LOCK_TIMEOUT));
  440. if (conn && !singleGraph)
  441. graphIter.setown(conn->queryRoot()->getElements("*"));
  442. curStat.setown(new ExtractedStatistic);
  443. //These are currently constant for all graph statistics instances
  444. curStat->count = 1;
  445. curStat->max = 0;
  446. valid = false;
  447. }
  448. virtual IConstWUStatistic & query()
  449. {
  450. return *curStat;
  451. }
  452. virtual bool first()
  453. {
  454. valid = false;
  455. if (!conn)
  456. return false;
  457. if (graphIter && !graphIter->first())
  458. return false;
  459. ensureUniqueStatistic();
  460. if (!firstSubGraph())
  461. return false;
  462. valid = true;
  463. return true;
  464. }
  465. virtual bool next()
  466. {
  467. ensureUniqueStatistic();
  468. if (!nextStatistic())
  469. {
  470. if (!nextSubGraph())
  471. {
  472. if (!nextGraph())
  473. {
  474. valid = false;
  475. return false;
  476. }
  477. }
  478. }
  479. return true;
  480. }
  481. virtual bool isValid()
  482. {
  483. return valid;
  484. }
  485. protected:
  486. bool firstSubGraph()
  487. {
  488. IPropertyTree & graphNode = graphIter ? graphIter->query() : *conn->queryRoot();
  489. const char * xpath = "sg*";
  490. StringBuffer childXpath;
  491. if (scopes.isItem(1))
  492. {
  493. const char * scope1 = scopes.item(1);
  494. if (strnicmp(scope1, "sg", 2) == 0)
  495. {
  496. childXpath.append(scope1);
  497. xpath = childXpath.str();
  498. }
  499. }
  500. subgraphIter.setown(graphNode.getElements(xpath));
  501. if (!subgraphIter)
  502. subgraphIter.setown(graphNode.getElements("sg0"));
  503. if (!subgraphIter->first())
  504. return false;
  505. if (firstStat())
  506. return true;
  507. return nextSubGraph();
  508. }
  509. bool nextSubGraph()
  510. {
  511. loop
  512. {
  513. if (!subgraphIter->next())
  514. return false;
  515. if (firstStat())
  516. return true;
  517. }
  518. }
  519. bool nextGraph()
  520. {
  521. if (!graphIter)
  522. return false;
  523. loop
  524. {
  525. if (!graphIter->next())
  526. return false;
  527. if (firstSubGraph())
  528. return true;
  529. }
  530. }
  531. bool firstStat()
  532. {
  533. IPropertyTree & curSubGraph = subgraphIter->query();
  534. if (!checkSubGraph())
  535. return false;
  536. curSubGraph.getPropBin("Stats", compressed.clear());
  537. //Don't crash on old format progress...
  538. if (compressed.length() == 0)
  539. return false;
  540. decompressToBuffer(serialized.clear(), compressed);
  541. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  542. curStat->timeStamp = collection->queryWhenCreated();
  543. return beginCollection(*collection);
  544. }
  545. bool beginCollection(IStatisticCollection & collection)
  546. {
  547. collections.append(OLINK(collection));
  548. numStats = collection.getNumStatistics();
  549. curStatIndex = 0;
  550. if (checkScope())
  551. {
  552. if (curStatIndex < numStats)
  553. {
  554. if (checkStatistic())
  555. return true;
  556. return nextStatistic();
  557. }
  558. }
  559. return nextChildScope();
  560. }
  561. bool nextStatistic()
  562. {
  563. //Finish iterating the statistics at this level.
  564. while (++curStatIndex < numStats)
  565. {
  566. if (checkStatistic())
  567. return true;
  568. }
  569. return nextChildScope();
  570. }
  571. bool nextChildScope()
  572. {
  573. loop
  574. {
  575. if (collections.ordinality() == 0)
  576. return false;
  577. IStatisticCollection * curCollection = &collections.tos();
  578. if (childIterators.ordinality() < collections.ordinality())
  579. {
  580. if (!filter || filter->recurseChildScopes(curStat->scopeType, curStat->scope))
  581. {
  582. //Start iterating the children for the current collection
  583. childIterators.append(curCollection->getScopes(NULL));
  584. if (!childIterators.tos().first())
  585. {
  586. finishCollection();
  587. continue;
  588. }
  589. }
  590. else
  591. {
  592. //Don't walk the child scopes
  593. collections.pop();
  594. continue;
  595. }
  596. }
  597. else if (!childIterators.tos().next())
  598. {
  599. finishCollection();
  600. continue;
  601. }
  602. if (beginCollection(childIterators.tos().query()))
  603. return true;
  604. }
  605. }
  606. void finishCollection()
  607. {
  608. collections.pop();
  609. childIterators.pop();
  610. }
  611. bool checkSubGraph()
  612. {
  613. if (!filter)
  614. return true;
  615. IPropertyTree & curSubGraph = subgraphIter->query();
  616. curStat->creatorType = queryCreatorType(curSubGraph.queryProp("@c"));
  617. curStat->creator.set(curSubGraph.queryProp("@creator"));
  618. return filter->matches(curStat->creatorType, curStat->creator, SSTall, NULL, SMeasureAll, StKindAll);
  619. }
  620. bool checkScope()
  621. {
  622. if (!filter)
  623. return true;
  624. IStatisticCollection * collection = &collections.tos();
  625. curStat->scopeType = collection->queryScopeType();
  626. collection->getFullScope(curStat->scope.clear());
  627. return filter->matches(SCTall, NULL, curStat->scopeType, curStat->scope, SMeasureAll, StKindAll);
  628. }
  629. bool checkStatistic()
  630. {
  631. IStatisticCollection & collection = collections.tos();
  632. collection.getStatistic(curStat->kind, curStat->value, curStatIndex);
  633. curStat->measure = queryMeasure(curStat->kind);
  634. if (!filter)
  635. return true;
  636. if (!filter->matches(SCTall, NULL, SSTall, NULL, curStat->measure, curStat->kind))
  637. return false;
  638. return true;
  639. }
  640. void ensureUniqueStatistic()
  641. {
  642. //If something else has linked this statistic, clone a unique one.
  643. if (curStat->IsShared())
  644. curStat.setown(new ExtractedStatistic(*curStat));
  645. }
  646. private:
  647. Owned<IRemoteConnection> conn;
  648. Owned<ExtractedStatistic> curStat;
  649. const IStatisticsFilter * filter;
  650. StringArray scopes;
  651. StringBuffer rootPath;
  652. Owned<IPropertyTreeIterator> graphIter;
  653. Owned<IPropertyTreeIterator> subgraphIter;
  654. IArrayOf<IStatisticCollection> collections;
  655. IArrayOf<IStatisticCollectionIterator> childIterators;
  656. MemoryBuffer compressed;
  657. MemoryBuffer serialized;
  658. unsigned numStats;
  659. unsigned curStatIndex;
  660. bool valid;
  661. };
  662. //--------------------------------------------------------------------------------------------------------------------
  663. mapEnums states[] = {
  664. { WUStateUnknown, "unknown" },
  665. { WUStateCompiled, "compiled" },
  666. { WUStateRunning, "running" },
  667. { WUStateCompleted, "completed" },
  668. { WUStateFailed, "failed" },
  669. { WUStateArchived, "archived" },
  670. { WUStateAborting, "aborting" },
  671. { WUStateAborted, "aborted" },
  672. { WUStateBlocked, "blocked" },
  673. { WUStateSubmitted, "submitted" },
  674. { WUStateScheduled, "scheduled" },
  675. { WUStateCompiling, "compiling" },
  676. { WUStateWait, "wait" },
  677. { WUStateUploadingFiles, "uploading_files" },
  678. { WUStateDebugPaused, "debugging" },
  679. { WUStateDebugRunning, "debug_running" },
  680. { WUStatePaused, "paused" },
  681. { WUStateSize, NULL }
  682. };
  683. mapEnums actions[] = {
  684. { WUActionUnknown, "unknown" },
  685. { WUActionCompile, "compile" },
  686. { WUActionCheck, "check" },
  687. { WUActionRun, "run" },
  688. { WUActionExecuteExisting, "execute" },
  689. { WUActionPause, "pause" },
  690. { WUActionPauseNow, "pausenow" },
  691. { WUActionResume, "resume" },
  692. { WUActionSize, NULL },
  693. };
  694. mapEnums priorityClasses[] = {
  695. { PriorityClassUnknown, "unknown" },
  696. { PriorityClassLow, "low" },
  697. { PriorityClassNormal, "normal" },
  698. { PriorityClassHigh, "high" },
  699. { PriorityClassSize, NULL },
  700. };
  701. const char * getWorkunitStateStr(WUState state)
  702. {
  703. dbgassertex(state < WUStateSize);
  704. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  705. }
  706. void setEnum(IPropertyTree *p, const char *propname, int value, const mapEnums *map)
  707. {
  708. const char *defval = map->str;
  709. while (map->str)
  710. {
  711. if (value==map->val)
  712. {
  713. p->setProp(propname, map->str);
  714. return;
  715. }
  716. map++;
  717. }
  718. assertex(!"Unexpected value in setEnum");
  719. p->setProp(propname, defval);
  720. }
  721. static int getEnum(const char *v, const mapEnums *map)
  722. {
  723. if (v)
  724. {
  725. while (map->str)
  726. {
  727. if (stricmp(v, map->str)==0)
  728. return map->val;
  729. map++;
  730. }
  731. assertex(!"Unexpected value in getEnum");
  732. }
  733. return 0;
  734. }
  735. static int getEnum(const IPropertyTree *p, const char *propname, const mapEnums *map)
  736. {
  737. return getEnum(p->queryProp(propname),map);
  738. }
  739. const char * getWorkunitActionStr(WUAction action)
  740. {
  741. return getEnumText(action, actions);
  742. }
  743. WUAction getWorkunitAction(const char *actionStr)
  744. {
  745. return (WUAction) getEnum(actionStr, actions);
  746. }
  747. //==========================================================================================
  748. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  749. {
  750. public:
  751. CLightweightWorkunitInfo(IPropertyTree &p)
  752. {
  753. wuid.set(p.queryName());
  754. user.set(p.queryProp("@submitID"));
  755. jobName.set(p.queryProp("@jobName"));
  756. clusterName.set(p.queryProp("@clusterName"));
  757. timeScheduled.set(p.queryProp("@timeScheduled"));
  758. state = (WUState) getEnum(&p, "@state", states);
  759. action = (WUAction) getEnum(&p, "Action", actions);
  760. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  761. priorityLevel = calcPriorityValue(&p);
  762. wuscope.set(p.queryProp("@scope"));
  763. appvalues.load(&p,"Application/*");
  764. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  765. _isProtected = p.getPropBool("@protected", false);
  766. }
  767. virtual const char *queryWuid() const { return wuid.str(); }
  768. virtual const char *queryUser() const { return user.str(); }
  769. virtual const char *queryJobName() const { return jobName.str(); }
  770. virtual const char *queryClusterName() const { return clusterName.str(); }
  771. virtual const char *queryWuScope() const { return wuscope.str(); }
  772. virtual WUState getState() const { return state; }
  773. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  774. virtual WUAction getAction() const { return action; }
  775. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  776. virtual WUPriorityClass getPriority() const { return priority; }
  777. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  778. virtual int getPriorityLevel() const { return priorityLevel; }
  779. virtual bool isProtected() const { return _isProtected; }
  780. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  781. {
  782. if (timeScheduled.length())
  783. val.setGmtString(timeScheduled.str());
  784. return val;
  785. }
  786. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  787. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  788. protected:
  789. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  790. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  791. unsigned totalThorTime;
  792. WUState state;
  793. WUAction action;
  794. WUPriorityClass priority;
  795. int priorityLevel;
  796. bool _isProtected;
  797. };
  798. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  799. {
  800. return new CLightweightWorkunitInfo(p);
  801. }
  802. class CDaliWuGraphStats : public CWuGraphStats
  803. {
  804. public:
  805. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, const char * _rootScope, unsigned _id)
  806. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _rootScope, _id), conn(_conn)
  807. {
  808. }
  809. protected:
  810. Owned<IRemoteConnection> conn;
  811. };
  812. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  813. {
  814. abortId = 0;
  815. stateId = 0;
  816. actionId = 0;
  817. assertex((flags & ~SubscribeOptionAbort) == 0);
  818. if (flags & SubscribeOptionAbort)
  819. {
  820. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  821. abortId = querySDS().subscribe(xpath.str(), *this);
  822. }
  823. }
  824. CWorkUnitWatcher::~CWorkUnitWatcher()
  825. {
  826. assertex(abortId==0 && stateId==0 && actionId==0);
  827. }
  828. void CWorkUnitWatcher::unsubscribe()
  829. {
  830. CriticalBlock b(crit);
  831. if (abortId)
  832. querySDS().unsubscribe(abortId);
  833. if (stateId)
  834. querySDS().unsubscribe(stateId);
  835. if (actionId)
  836. querySDS().unsubscribe(actionId);
  837. abortId = 0;
  838. stateId = 0;
  839. actionId = 0;
  840. }
  841. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  842. {
  843. CriticalBlock b(crit);
  844. if (id==stateId)
  845. subscriber->notify(SubscribeOptionState);
  846. else if (id==actionId)
  847. subscriber->notify(SubscribeOptionAction);
  848. else if (id==abortId)
  849. subscriber->notify(SubscribeOptionAbort);
  850. }
  851. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  852. {
  853. public:
  854. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  855. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  856. {
  857. if (flags & SubscribeOptionState)
  858. {
  859. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  860. stateId = querySDS().subscribe(xpath.str(), *this);
  861. }
  862. if (flags & SubscribeOptionAction)
  863. {
  864. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  865. actionId = querySDS().subscribe(xpath.str(), *this);
  866. }
  867. }
  868. };
  869. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  870. {
  871. CriticalBlock block(crit);
  872. assertex(options==SubscribeOptionAbort);
  873. if (!abortWatcher)
  874. {
  875. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  876. abortDirty = true;
  877. }
  878. }
  879. void CPersistedWorkUnit::unsubscribe()
  880. {
  881. CriticalBlock block(crit);
  882. if (abortWatcher)
  883. {
  884. abortWatcher->unsubscribe();
  885. abortWatcher.clear();
  886. }
  887. }
  888. bool CPersistedWorkUnit::aborting() const
  889. {
  890. CriticalBlock block(crit);
  891. if (abortDirty)
  892. {
  893. StringBuffer apath;
  894. apath.append("/WorkUnitAborts/").append(p->queryName());
  895. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  896. if (acon)
  897. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  898. else
  899. abortState = false;
  900. abortDirty = false;
  901. }
  902. return abortState;
  903. }
  904. class CDaliWorkUnit : public CPersistedWorkUnit
  905. {
  906. public:
  907. IMPLEMENT_IINTERFACE;
  908. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  909. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  910. {
  911. loadPTree(connection->getRoot());
  912. }
  913. ~CDaliWorkUnit()
  914. {
  915. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  916. // We use the beforeDispose() in base class to help ensure this
  917. p.clear();
  918. }
  919. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  920. {
  921. Owned<IRemoteConnection> conn = getProgressConnection();
  922. if (conn)
  923. {
  924. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  925. if (progress)
  926. return new CConstGraphProgress(p->queryName(), graphName, progress);
  927. }
  928. return NULL;
  929. }
  930. virtual WUGraphState queryGraphState(const char *graphName) const
  931. {
  932. Owned<IRemoteConnection> conn = getProgressConnection();
  933. if (conn)
  934. {
  935. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  936. if (progress)
  937. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  938. }
  939. return WUGraphUnknown;
  940. }
  941. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  942. {
  943. Owned<IRemoteConnection> conn = getProgressConnection();
  944. if (conn)
  945. {
  946. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  947. if (progress)
  948. {
  949. StringBuffer path;
  950. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  951. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  952. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  953. }
  954. }
  955. return WUGraphUnknown;
  956. }
  957. virtual void clearGraphProgress() const
  958. {
  959. CriticalBlock block(crit);
  960. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  961. StringBuffer path("/GraphProgress/");
  962. path.append(p->queryName());
  963. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  964. if (delconn)
  965. delconn->close(true);
  966. }
  967. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  968. {
  969. Owned<IRemoteConnection> conn = getProgressConnection();
  970. if (!conn)
  971. return false;
  972. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  973. if (name)
  974. {
  975. graphName.set(name);
  976. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  977. return true;
  978. }
  979. else
  980. return false;
  981. }
  982. virtual void forceReload()
  983. {
  984. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  985. CriticalBlock block(crit);
  986. clearCached(true);
  987. connection->reload();
  988. progressConnection.clear();
  989. abortDirty = true;
  990. p.setown(connection->getRoot());
  991. }
  992. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  993. {
  994. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  995. clearGraphProgress();
  996. connection->close(true);
  997. connection.clear();
  998. }
  999. virtual void commit()
  1000. {
  1001. CPersistedWorkUnit::commit();
  1002. if (connection)
  1003. connection->commit();
  1004. }
  1005. virtual void _lockRemote()
  1006. {
  1007. StringBuffer wuRoot;
  1008. getXPath(wuRoot, p->queryName());
  1009. if (connection)
  1010. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  1011. else
  1012. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  1013. if (!connection)
  1014. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  1015. clearCached(true);
  1016. p.setown(connection->getRoot());
  1017. }
  1018. virtual void _unlockRemote()
  1019. {
  1020. if (connection)
  1021. {
  1022. try
  1023. {
  1024. try
  1025. {
  1026. connection->commit();
  1027. }
  1028. catch (IException *e)
  1029. {
  1030. EXCLOG(e, "Error during workunit commit");
  1031. connection->rollback();
  1032. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  1033. throw;
  1034. }
  1035. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  1036. }
  1037. catch (IException *E)
  1038. {
  1039. StringBuffer s;
  1040. PrintLog("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  1041. throw;
  1042. }
  1043. }
  1044. }
  1045. virtual void setGraphState(const char *graphName, WUGraphState state) const
  1046. {
  1047. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName);
  1048. conn->queryRoot()->setPropInt("@_state", state);
  1049. }
  1050. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  1051. {
  1052. CriticalBlock block(crit);
  1053. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  1054. VStringBuffer path("/GraphProgress/%s", queryWuid());
  1055. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  1056. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  1057. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  1058. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  1059. IPropertyTree *node = progress->queryPropTree(path.str());
  1060. if (!node)
  1061. {
  1062. node = progress->addPropTree("node", createPTree());
  1063. node->setPropInt64("@id", nodeId);
  1064. }
  1065. node->setPropInt("@_state", (unsigned)state);
  1066. switch (state)
  1067. {
  1068. case WUGraphRunning:
  1069. {
  1070. IPropertyTree *running = conn->queryRoot()->setPropTree("Running", createPTree());
  1071. running->setProp("@graph", graphName);
  1072. running->setPropInt64("@subId", nodeId);
  1073. break;
  1074. }
  1075. case WUGraphComplete:
  1076. {
  1077. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  1078. break;
  1079. }
  1080. }
  1081. }
  1082. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned subgraph) const
  1083. {
  1084. return new CDaliWuGraphStats(getWritableProgressConnection(graphName), creatorType, creator, graphName, subgraph);
  1085. }
  1086. protected:
  1087. IRemoteConnection *getProgressConnection() const
  1088. {
  1089. CriticalBlock block(crit);
  1090. if (!progressConnection)
  1091. {
  1092. VStringBuffer path("/GraphProgress/%s", queryWuid());
  1093. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  1094. }
  1095. return progressConnection.getLink();
  1096. }
  1097. IRemoteConnection *getWritableProgressConnection(const char *graphName) const
  1098. {
  1099. CriticalBlock block(crit);
  1100. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  1101. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  1102. return querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  1103. }
  1104. IPropertyTree *getGraphProgressTree() const
  1105. {
  1106. Owned<IRemoteConnection> conn = getProgressConnection();
  1107. if (conn)
  1108. {
  1109. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  1110. mergePTree(tmp,conn->queryRoot());
  1111. return tmp.getClear();
  1112. }
  1113. return NULL;
  1114. }
  1115. Owned<IRemoteConnection> connection;
  1116. mutable Owned<IRemoteConnection> progressConnection;
  1117. };
  1118. class CLockedWorkUnit : public CInterface, implements ILocalWorkUnit, implements IExtendedWUInterface
  1119. {
  1120. public:
  1121. Owned<CLocalWorkUnit> c;
  1122. IMPLEMENT_IINTERFACE;
  1123. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  1124. ~CLockedWorkUnit()
  1125. {
  1126. if (workUnitTraceLevel > 1)
  1127. PrintLog("Releasing locked workunit %s", queryWuid());
  1128. if (c)
  1129. c->unlockRemote();
  1130. }
  1131. virtual IConstWorkUnit * unlock()
  1132. {
  1133. c->unlockRemote();
  1134. return c.getClear();
  1135. }
  1136. virtual bool aborting() const
  1137. { return c->aborting(); }
  1138. virtual void forceReload()
  1139. { UNIMPLEMENTED; }
  1140. virtual WUAction getAction() const
  1141. { return c->getAction(); }
  1142. virtual const char *queryActionDesc() const
  1143. { return c->queryActionDesc(); }
  1144. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  1145. { return c->getApplicationValue(application, propname, str); }
  1146. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  1147. { return c->getApplicationValueInt(application, propname, defVal); }
  1148. virtual IConstWUAppValueIterator & getApplicationValues() const
  1149. { return c->getApplicationValues(); }
  1150. virtual bool hasWorkflow() const
  1151. { return c->hasWorkflow(); }
  1152. virtual unsigned queryEventScheduledCount() const
  1153. { return c->queryEventScheduledCount(); }
  1154. virtual IPropertyTree * queryWorkflowTree() const
  1155. { return c->queryWorkflowTree(); }
  1156. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  1157. { return c->getWorkflowItems(); }
  1158. virtual IWorkflowItemArray * getWorkflowClone() const
  1159. { return c->getWorkflowClone(); }
  1160. virtual bool requiresLocalFileUpload() const
  1161. { return c->requiresLocalFileUpload(); }
  1162. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  1163. { return c->getLocalFileUploads(); }
  1164. virtual bool getIsQueryService() const
  1165. { return c->getIsQueryService(); }
  1166. virtual bool getCloneable() const
  1167. { return c->getCloneable(); }
  1168. virtual IUserDescriptor * queryUserDescriptor() const
  1169. { return c->queryUserDescriptor(); }
  1170. virtual const char *queryClusterName() const
  1171. { return c->queryClusterName(); }
  1172. virtual unsigned getCodeVersion() const
  1173. { return c->getCodeVersion(); }
  1174. virtual unsigned getWuidVersion() const
  1175. { return c->getWuidVersion(); }
  1176. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  1177. { c->getBuildVersion(buildVersion, eclVersion); }
  1178. virtual bool hasDebugValue(const char * propname) const
  1179. { return c->hasDebugValue(propname); }
  1180. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  1181. { return c->getDebugValue(propname, str); }
  1182. virtual int getDebugValueInt(const char * propname, int defVal) const
  1183. { return c->getDebugValueInt(propname, defVal); }
  1184. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  1185. { return c->getDebugValueInt64(propname, defVal); }
  1186. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  1187. { return c->getDebugValueBool(propname, defVal); }
  1188. virtual IStringIterator & getDebugValues() const
  1189. { return c->getDebugValues(NULL); }
  1190. virtual IStringIterator & getDebugValues(const char *prop) const
  1191. { return c->getDebugValues(prop); }
  1192. virtual unsigned getExceptionCount() const
  1193. { return c->getExceptionCount(); }
  1194. virtual IConstWUExceptionIterator & getExceptions() const
  1195. { return c->getExceptions(); }
  1196. virtual unsigned getGraphCount() const
  1197. { return c->getGraphCount(); }
  1198. virtual unsigned getSourceFileCount() const
  1199. { return c->getSourceFileCount(); }
  1200. virtual unsigned getResultCount() const
  1201. { return c->getResultCount(); }
  1202. virtual unsigned getVariableCount() const
  1203. { return c->getVariableCount(); }
  1204. virtual unsigned getApplicationValueCount() const
  1205. { return c->getApplicationValueCount(); }
  1206. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  1207. { return c->getGraphs(type); }
  1208. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  1209. { return c->getGraphsMeta(type); }
  1210. virtual IConstWUGraph * getGraph(const char *name) const
  1211. { return c->getGraph(name); }
  1212. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  1213. { return c->getGraphProgress(name); }
  1214. virtual const char *queryJobName() const
  1215. { return c->queryJobName(); }
  1216. virtual IConstWUPlugin * getPluginByName(const char * name) const
  1217. { return c->getPluginByName(name); }
  1218. virtual IConstWUPluginIterator & getPlugins() const
  1219. { return c->getPlugins(); }
  1220. virtual IConstWULibrary* getLibraryByName(const char *name) const
  1221. { return c->getLibraryByName(name); }
  1222. virtual IConstWULibraryIterator & getLibraries() const
  1223. { return c->getLibraries(); }
  1224. virtual WUPriorityClass getPriority() const
  1225. { return c->getPriority(); }
  1226. virtual const char *queryPriorityDesc() const
  1227. { return c->queryPriorityDesc(); }
  1228. virtual int getPriorityLevel() const
  1229. { return c->getPriorityLevel(); }
  1230. virtual int getPriorityValue() const
  1231. { return c->getPriorityValue(); }
  1232. virtual IConstWUQuery * getQuery() const
  1233. { return c->getQuery(); }
  1234. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  1235. { return c->getWebServicesInfo(); }
  1236. virtual bool getRescheduleFlag() const
  1237. { return c->getRescheduleFlag(); }
  1238. virtual IConstWUResult * getResultByName(const char * name) const
  1239. { return c->getResultByName(name); }
  1240. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  1241. { return c->getResultBySequence(seq); }
  1242. virtual unsigned getResultLimit() const
  1243. { return c->getResultLimit(); }
  1244. virtual IConstWUResultIterator & getResults() const
  1245. { return c->getResults(); }
  1246. virtual IStringVal & getScope(IStringVal & str) const
  1247. { return c->getScope(str); }
  1248. virtual IStringVal & getSecurityToken(IStringVal & str) const
  1249. { return c->getSecurityToken(str); }
  1250. virtual WUState getState() const
  1251. { return c->getState(); }
  1252. virtual IStringVal & getStateEx(IStringVal & str) const
  1253. { return c->getStateEx(str); }
  1254. virtual __int64 getAgentSession() const
  1255. { return c->getAgentSession(); }
  1256. virtual unsigned getAgentPID() const
  1257. { return c->getAgentPID(); }
  1258. virtual const char *queryStateDesc() const
  1259. { return c->queryStateDesc(); }
  1260. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  1261. { return c->getRunningGraph(graphName, subId); }
  1262. virtual IConstWUStatisticIterator & getStatistics(const IStatisticsFilter * filter) const
  1263. { return c->getStatistics(filter); }
  1264. virtual IConstWUStatistic * getStatistic(const char * creator, const char * scope, StatisticKind kind) const
  1265. { return c->getStatistic(creator, scope, kind); }
  1266. virtual IStringVal & getSnapshot(IStringVal & str) const
  1267. { return c->getSnapshot(str); }
  1268. virtual const char *queryUser() const
  1269. { return c->queryUser(); }
  1270. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  1271. { return c->getWarningSeverity(code, defaultSeverity); }
  1272. virtual const char *queryWuScope() const
  1273. { return c->queryWuScope(); }
  1274. virtual const char *queryWuid() const
  1275. { return c->queryWuid(); }
  1276. virtual IConstWUResult * getGlobalByName(const char * name) const
  1277. { return c->getGlobalByName(name); }
  1278. virtual IConstWUResult * getTemporaryByName(const char * name) const
  1279. { return c->getTemporaryByName(name); }
  1280. virtual IConstWUResultIterator & getTemporaries() const
  1281. { return c->getTemporaries(); }
  1282. virtual IConstWUResult * getVariableByName(const char * name) const
  1283. { return c->getVariableByName(name); }
  1284. virtual IConstWUResultIterator & getVariables() const
  1285. { return c->getVariables(); }
  1286. virtual bool isProtected() const
  1287. { return c->isProtected(); }
  1288. virtual bool isPausing() const
  1289. { return c->isPausing(); }
  1290. virtual IWorkUnit & lock()
  1291. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  1292. virtual bool reload()
  1293. { UNIMPLEMENTED; }
  1294. virtual void subscribe(WUSubscribeOptions options)
  1295. { c->subscribe(options); }
  1296. virtual void requestAbort()
  1297. { c->requestAbort(); }
  1298. virtual unsigned calculateHash(unsigned prevHash)
  1299. { return queryExtendedWU(c)->calculateHash(prevHash); }
  1300. virtual void copyWorkUnit(IConstWorkUnit *cached, bool all)
  1301. { queryExtendedWU(c)->copyWorkUnit(cached, all); }
  1302. virtual IPropertyTree *queryPTree() const
  1303. { return queryExtendedWU(c)->queryPTree(); }
  1304. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  1305. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  1306. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned)
  1307. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned); }
  1308. virtual unsigned queryFileUsage(const char *filename) const
  1309. { return c->queryFileUsage(filename); }
  1310. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  1311. { return c->getTimeScheduled(val); }
  1312. virtual unsigned getDebugAgentListenerPort() const
  1313. { return c->getDebugAgentListenerPort(); }
  1314. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  1315. { return c->getDebugAgentListenerIP(ip); }
  1316. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  1317. { return c->getXmlParams(params, hidePasswords); }
  1318. virtual const IPropertyTree *getXmlParams() const
  1319. { return c->getXmlParams(); }
  1320. virtual unsigned __int64 getHash() const
  1321. { return c->getHash(); }
  1322. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  1323. { return c->getLogs(type, instance); }
  1324. virtual IStringIterator *getProcesses(const char *type) const
  1325. { return c->getProcesses(type); }
  1326. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  1327. { return c->getProcesses(type, instance); }
  1328. virtual unsigned getTotalThorTime() const
  1329. { return c->getTotalThorTime(); }
  1330. virtual WUGraphState queryGraphState(const char *graphName) const
  1331. { return c->queryGraphState(graphName); }
  1332. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  1333. { return c->queryNodeState(graphName, nodeId); }
  1334. virtual void setGraphState(const char *graphName, WUGraphState state) const
  1335. { c->setGraphState(graphName, state); }
  1336. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  1337. { c->setNodeState(graphName, nodeId, state); }
  1338. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned subgraph) const
  1339. { return c->updateStats(graphName, creatorType, creator, subgraph); }
  1340. virtual void clearGraphProgress() const
  1341. { c->clearGraphProgress(); }
  1342. virtual void clearExceptions()
  1343. { c->clearExceptions(); }
  1344. virtual void commit()
  1345. { c->commit(); }
  1346. virtual IWUException * createException()
  1347. { return c->createException(); }
  1348. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  1349. { c->addProcess(type, instance, pid, log); }
  1350. virtual void protect(bool protectMode)
  1351. { c->protect(protectMode); }
  1352. virtual void setAction(WUAction action)
  1353. { c->setAction(action); }
  1354. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  1355. { c->setApplicationValue(application, propname, value, overwrite); }
  1356. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  1357. { c->setApplicationValueInt(application, propname, value, overwrite); }
  1358. virtual void incEventScheduledCount()
  1359. { c->incEventScheduledCount(); }
  1360. virtual void setIsQueryService(bool value)
  1361. { c->setIsQueryService(value); }
  1362. virtual void setCloneable(bool value)
  1363. { c->setCloneable(value); }
  1364. virtual void setIsClone(bool value)
  1365. { c->setIsClone(value); }
  1366. virtual void setClusterName(const char * value)
  1367. { c->setClusterName(value); }
  1368. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  1369. { c->setCodeVersion(version, buildVersion, eclVersion); }
  1370. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  1371. { c->setDebugValue(propname, value, overwrite); }
  1372. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  1373. { c->setDebugValueInt(propname, value, overwrite); }
  1374. virtual void setJobName(const char * value)
  1375. { c->setJobName(value); }
  1376. virtual void setPriority(WUPriorityClass cls)
  1377. { c->setPriority(cls); }
  1378. virtual void setPriorityLevel(int level)
  1379. { c->setPriorityLevel(level); }
  1380. virtual void setRescheduleFlag(bool value)
  1381. { c->setRescheduleFlag(value); }
  1382. virtual void setResultLimit(unsigned value)
  1383. { c->setResultLimit(value); }
  1384. virtual void setSecurityToken(const char *value)
  1385. { c->setSecurityToken(value); }
  1386. virtual void setState(WUState state)
  1387. { c->setState(state); }
  1388. virtual void setStateEx(const char * text)
  1389. { c->setStateEx(text); }
  1390. virtual void setAgentSession(__int64 sessionId)
  1391. { c->setAgentSession(sessionId); }
  1392. 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)
  1393. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  1394. virtual void setTracingValue(const char * propname, const char * value)
  1395. { c->setTracingValue(propname, value); }
  1396. virtual void setTracingValueInt(const char * propname, int value)
  1397. { c->setTracingValueInt(propname, value); }
  1398. virtual void setUser(const char * value)
  1399. { c->setUser(value); }
  1400. virtual void setWuScope(const char * value)
  1401. { c->setWuScope(value); }
  1402. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  1403. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  1404. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  1405. { c->syncRuntimeWorkflow(array); }
  1406. virtual IWorkflowItemIterator * updateWorkflowItems()
  1407. { return c->updateWorkflowItems(); }
  1408. virtual void resetWorkflow()
  1409. { c->resetWorkflow(); }
  1410. virtual void schedule()
  1411. { c->schedule(); }
  1412. virtual void deschedule()
  1413. { c->deschedule(); }
  1414. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  1415. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  1416. virtual IWUResult * updateGlobalByName(const char * name)
  1417. { return c->updateGlobalByName(name); }
  1418. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml)
  1419. { c->createGraph(name, label, type, xgmml); }
  1420. virtual IWUQuery * updateQuery()
  1421. { return c->updateQuery(); }
  1422. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  1423. { return c->updateWebServicesInfo(create); }
  1424. virtual IWUPlugin * updatePluginByName(const char * name)
  1425. { return c->updatePluginByName(name); }
  1426. virtual IWULibrary * updateLibraryByName(const char * name)
  1427. { return c->updateLibraryByName(name); }
  1428. virtual IWUResult * updateResultByName(const char * name)
  1429. { return c->updateResultByName(name); }
  1430. virtual IWUResult * updateResultBySequence(unsigned seq)
  1431. { return c->updateResultBySequence(seq); }
  1432. virtual IWUResult * updateTemporaryByName(const char * name)
  1433. { return c->updateTemporaryByName(name); }
  1434. virtual IWUResult * updateVariableByName(const char * name)
  1435. { return c->updateVariableByName(name); }
  1436. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  1437. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  1438. virtual void noteFileRead(IDistributedFile *file)
  1439. { c->noteFileRead(file); }
  1440. virtual void releaseFile(const char *fileName)
  1441. { c->releaseFile(fileName); }
  1442. virtual void resetBeforeGeneration()
  1443. { c->resetBeforeGeneration(); }
  1444. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  1445. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  1446. virtual void deleteTemporaries()
  1447. { c->deleteTemporaries(); }
  1448. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  1449. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  1450. virtual IPropertyTree * getDiskUsageStats()
  1451. { return c->getDiskUsageStats(); }
  1452. virtual IPropertyTreeIterator & getFileIterator() const
  1453. { return c->getFileIterator(); }
  1454. virtual IPropertyTreeIterator & getFilesReadIterator() const
  1455. { return c->getFilesReadIterator(); }
  1456. virtual void setSnapshot(const char * value)
  1457. { c->setSnapshot(value); }
  1458. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  1459. { c->setWarningSeverity(code, severity); }
  1460. virtual void setTimeScheduled(const IJlibDateTime &val)
  1461. { c->setTimeScheduled(val); }
  1462. virtual void setDebugAgentListenerPort(unsigned port)
  1463. { c->setDebugAgentListenerPort(port); }
  1464. virtual void setDebugAgentListenerIP(const char * ip)
  1465. { c->setDebugAgentListenerIP(ip); }
  1466. virtual void setXmlParams(const char *params)
  1467. { c->setXmlParams(params); }
  1468. virtual void setXmlParams(IPropertyTree *tree)
  1469. { c->setXmlParams(tree); }
  1470. virtual void setHash(unsigned __int64 hash)
  1471. { c->setHash(hash); }
  1472. // ILocalWorkUnit - used for debugging etc
  1473. virtual void serialize(MemoryBuffer &tgt)
  1474. { c->serialize(tgt); }
  1475. virtual void deserialize(MemoryBuffer &src)
  1476. { c->deserialize(src); }
  1477. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  1478. { return c->switchThorQueue(cluster,qs); }
  1479. virtual void setAllowedClusters(const char *value)
  1480. { c->setAllowedClusters(value); }
  1481. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  1482. { return c->getAllowedClusters(str); }
  1483. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  1484. { c->remoteCheckAccess(user,writeaccess); }
  1485. virtual void setAllowAutoQueueSwitch(bool val)
  1486. { c->setAllowAutoQueueSwitch(val); }
  1487. virtual bool getAllowAutoQueueSwitch() const
  1488. { return c->getAllowAutoQueueSwitch(); }
  1489. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  1490. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  1491. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  1492. { c->setResultInt(name, sequence, val); }
  1493. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  1494. { c->setResultUInt(name, sequence, val); }
  1495. virtual void setResultReal(const char *name, unsigned sequence, double val)
  1496. { c->setResultReal(name, sequence, val); }
  1497. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  1498. { c->setResultVarString(stepname, sequence, val); }
  1499. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  1500. { c->setResultVarUnicode(stepname, sequence, val); }
  1501. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  1502. { c->setResultString(stepname, sequence, len, val); }
  1503. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  1504. { c->setResultData(stepname, sequence, len, val); }
  1505. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  1506. { c->setResultRaw(name, sequence, len, val); }
  1507. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  1508. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  1509. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  1510. { c->setResultUnicode(name, sequence, len, val); }
  1511. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  1512. { c->setResultBool(name, sequence, val); }
  1513. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  1514. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  1515. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  1516. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  1517. };
  1518. class CLocalWUAssociated : public CInterface, implements IConstWUAssociatedFile
  1519. {
  1520. Owned<IPropertyTree> p;
  1521. public:
  1522. IMPLEMENT_IINTERFACE;
  1523. CLocalWUAssociated(IPropertyTree *p);
  1524. virtual WUFileType getType() const;
  1525. virtual IStringVal & getDescription(IStringVal & ret) const;
  1526. virtual IStringVal & getIp(IStringVal & ret) const;
  1527. virtual IStringVal & getName(IStringVal & ret) const;
  1528. virtual IStringVal & getNameTail(IStringVal & ret) const;
  1529. virtual unsigned getCrc() const;
  1530. };
  1531. class CLocalWUQuery : public CInterface, implements IWUQuery
  1532. {
  1533. Owned<IPropertyTree> p;
  1534. mutable IArrayOf<IConstWUAssociatedFile> associated;
  1535. mutable CriticalSection crit;
  1536. mutable bool associatedCached;
  1537. private:
  1538. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  1539. void loadAssociated() const;
  1540. public:
  1541. IMPLEMENT_IINTERFACE;
  1542. CLocalWUQuery(IPropertyTree *p);
  1543. virtual WUQueryType getQueryType() const;
  1544. virtual IStringVal& getQueryText(IStringVal &str) const;
  1545. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  1546. virtual IStringVal& getQueryName(IStringVal &str) const;
  1547. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  1548. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  1549. virtual unsigned getQueryDllCrc() const;
  1550. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  1551. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  1552. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  1553. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  1554. virtual bool isArchive() const;
  1555. virtual void setQueryType(WUQueryType qt);
  1556. virtual void setQueryText(const char *pstr);
  1557. virtual void setQueryName(const char *);
  1558. virtual void setQueryMainDefinition(const char * str);
  1559. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc);
  1560. virtual void removeAssociatedFiles();
  1561. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  1562. };
  1563. class CLocalWUWebServicesInfo : public CInterface, implements IWUWebServicesInfo
  1564. {
  1565. Owned<IPropertyTree> p;
  1566. mutable CriticalSection crit;
  1567. private:
  1568. public:
  1569. IMPLEMENT_IINTERFACE;
  1570. CLocalWUWebServicesInfo(IPropertyTree *p);
  1571. virtual IStringVal& getModuleName(IStringVal &str) const;
  1572. virtual IStringVal& getAttributeName(IStringVal &str) const;
  1573. virtual IStringVal& getDefaultName(IStringVal &str) const;
  1574. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  1575. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  1576. virtual unsigned getWebServicesCRC() const;
  1577. virtual void setModuleName(const char *);
  1578. virtual void setAttributeName(const char *);
  1579. virtual void setDefaultName(const char *);
  1580. virtual void setInfo(const char *name, const char *info);
  1581. virtual void setText(const char *name, const char *info);
  1582. virtual void setWebServicesCRC(unsigned);
  1583. };
  1584. class CLocalWUResult : public CInterface, implements IWUResult
  1585. {
  1586. friend class CLocalWorkUnit;
  1587. mutable CriticalSection crit;
  1588. Owned<IPropertyTree> p;
  1589. Owned<IProperties> xmlns;
  1590. public:
  1591. IMPLEMENT_IINTERFACE;
  1592. CLocalWUResult(IPropertyTree *props);
  1593. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  1594. virtual WUResultStatus getResultStatus() const;
  1595. virtual IStringVal& getResultName(IStringVal &str) const;
  1596. virtual int getResultSequence() const;
  1597. virtual bool isResultScalar() const;
  1598. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  1599. virtual unsigned getResultFetchSize() const;
  1600. virtual __int64 getResultTotalRowCount() const;
  1601. virtual __int64 getResultRowCount() const;
  1602. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  1603. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  1604. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  1605. virtual unsigned getResultRequestedRows() const;
  1606. virtual __int64 getResultInt() const;
  1607. virtual bool getResultBool() const;
  1608. virtual double getResultReal() const;
  1609. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  1610. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1611. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  1612. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  1613. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  1614. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1615. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1616. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  1617. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  1618. virtual __int64 getResultRowLimit() const;
  1619. virtual IStringVal& getResultFilename(IStringVal & str) const;
  1620. virtual WUResultFormat getResultFormat() const;
  1621. virtual unsigned getResultHash() const;
  1622. virtual bool getResultIsAll() const;
  1623. virtual IProperties *queryResultXmlns();
  1624. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  1625. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  1626. // interface IWUResult
  1627. virtual void setResultStatus(WUResultStatus status);
  1628. virtual void setResultName(const char *name);
  1629. virtual void setResultSequence(unsigned seq);
  1630. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  1631. virtual void setResultScalar(bool isScalar);
  1632. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  1633. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  1634. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  1635. virtual void setResultRowCount(__int64 rows);
  1636. virtual void setResultDataset(const char *ecl, const char *defs);
  1637. virtual void setResultLogicalName(const char *logicalName);
  1638. virtual void setResultKeyField(const char * name);
  1639. virtual void setResultRequestedRows(unsigned req);
  1640. virtual void setResultRecordSizeEntry(const char * val);
  1641. virtual void setResultTransformerEntry(const char * val);
  1642. virtual void setResultInt(__int64 val);
  1643. virtual void setResultReal(double val);
  1644. virtual void setResultBool(bool val);
  1645. virtual void setResultString(const char * val, unsigned length);
  1646. virtual void setResultUnicode(const void * val, unsigned length);
  1647. virtual void setResultData(const void * val, unsigned length);
  1648. virtual void setResultDecimal(const void * val, unsigned length);
  1649. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  1650. virtual void setResultRowLimit(__int64 value);
  1651. virtual void setResultFilename(const char * name);
  1652. virtual void setResultUInt(unsigned __int64 val);
  1653. virtual void setResultIsAll(bool value);
  1654. virtual void setResultFormat(WUResultFormat format);
  1655. virtual void setResultXML(const char *val);
  1656. virtual void setResultRow(unsigned len, const void * data);
  1657. virtual void setResultXmlns(const char *prefix, const char *uri);
  1658. virtual void setResultFieldOpt(const char *name, const char *value);
  1659. virtual IPropertyTree *queryPTree() { return p; }
  1660. };
  1661. class CLocalWUPlugin : public CInterface, implements IWUPlugin
  1662. {
  1663. Owned<IPropertyTree> p;
  1664. public:
  1665. IMPLEMENT_IINTERFACE;
  1666. CLocalWUPlugin(IPropertyTree *p);
  1667. virtual IStringVal& getPluginName(IStringVal &str) const;
  1668. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  1669. virtual void setPluginName(const char *str);
  1670. virtual void setPluginVersion(const char *str);
  1671. };
  1672. class CLocalWULibrary : public CInterface, implements IWULibrary
  1673. {
  1674. Owned<IPropertyTree> p;
  1675. public:
  1676. IMPLEMENT_IINTERFACE;
  1677. CLocalWULibrary(IPropertyTree *p);
  1678. virtual IStringVal & getName(IStringVal & str) const;
  1679. virtual void setName(const char * str);
  1680. };
  1681. class CLocalWUException : public CInterface, implements IWUException
  1682. {
  1683. Owned<IPropertyTree> p;
  1684. public:
  1685. IMPLEMENT_IINTERFACE;
  1686. CLocalWUException(IPropertyTree *p);
  1687. virtual IStringVal& getExceptionSource(IStringVal &str) const;
  1688. virtual IStringVal& getExceptionMessage(IStringVal &str) const;
  1689. virtual unsigned getExceptionCode() const;
  1690. virtual ErrorSeverity getSeverity() const;
  1691. virtual IStringVal & getTimeStamp(IStringVal & dt) const;
  1692. virtual IStringVal & getExceptionFileName(IStringVal & str) const;
  1693. virtual unsigned getExceptionLineNo() const;
  1694. virtual unsigned getExceptionColumn() const;
  1695. virtual unsigned getSequence() const;
  1696. virtual void setExceptionSource(const char *str);
  1697. virtual void setExceptionMessage(const char *str);
  1698. virtual void setExceptionCode(unsigned code);
  1699. virtual void setSeverity(ErrorSeverity level);
  1700. virtual void setTimeStamp(const char * dt);
  1701. virtual void setExceptionFileName(const char *str);
  1702. virtual void setExceptionLineNo(unsigned r);
  1703. virtual void setExceptionColumn(unsigned c);
  1704. };
  1705. //==========================================================================================
  1706. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  1707. {
  1708. switch (sequence)
  1709. {
  1710. case ResultSequenceInternal:
  1711. case ResultSequenceOnce:
  1712. case ResultSequencePersist:
  1713. case ResultSequenceStored:
  1714. return true;
  1715. default:
  1716. assertex(sequence <= INT_MAX);
  1717. return false;
  1718. }
  1719. }
  1720. class CConstWUArrayIterator : public CInterface, implements IConstWorkUnitIterator
  1721. {
  1722. IArrayOf<IPropertyTree> trees;
  1723. Owned<IConstWorkUnitInfo> cur;
  1724. unsigned curTreeNum;
  1725. void setCurrent()
  1726. {
  1727. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  1728. }
  1729. public:
  1730. IMPLEMENT_IINTERFACE;
  1731. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  1732. {
  1733. ForEachItemIn(t, _trees)
  1734. trees.append(*LINK(&_trees.item(t)));
  1735. curTreeNum = 0;
  1736. }
  1737. bool first()
  1738. {
  1739. curTreeNum = 0;
  1740. return next();
  1741. }
  1742. bool isValid()
  1743. {
  1744. return (NULL != cur.get());
  1745. }
  1746. bool next()
  1747. {
  1748. if (curTreeNum >= trees.ordinality())
  1749. {
  1750. cur.clear();
  1751. return false;
  1752. }
  1753. setCurrent();
  1754. ++curTreeNum;
  1755. return true;
  1756. }
  1757. IConstWorkUnitInfo & query() { return *cur; }
  1758. };
  1759. //==========================================================================================
  1760. class CStringArrayIterator : public CInterface, implements IStringIterator
  1761. {
  1762. StringArray strings;
  1763. unsigned idx;
  1764. public:
  1765. IMPLEMENT_IINTERFACE;
  1766. CStringArrayIterator() { idx = 0; };
  1767. void append(const char *str) { strings.append(str); }
  1768. virtual bool first() { idx = 0; return strings.isItem(idx); }
  1769. virtual bool next() { idx ++; return strings.isItem(idx); }
  1770. virtual bool isValid() { return strings.isItem(idx); }
  1771. virtual IStringVal & str(IStringVal &s) { s.set(strings.item(idx)); return s; }
  1772. };
  1773. class CCachedJobNameIterator : public CInterface, implements IStringIterator
  1774. {
  1775. Owned<IPropertyTreeIterator> it;
  1776. public:
  1777. IMPLEMENT_IINTERFACE;
  1778. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  1779. virtual bool first() { return it->first(); }
  1780. virtual bool next() { return it->next(); }
  1781. virtual bool isValid() { return it->isValid(); }
  1782. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  1783. };
  1784. class CEmptyStringIterator : public CInterface, implements IStringIterator
  1785. {
  1786. public:
  1787. IMPLEMENT_IINTERFACE;
  1788. virtual bool first() { return false; }
  1789. virtual bool next() { return false; }
  1790. virtual bool isValid() { return false; }
  1791. virtual IStringVal & str(IStringVal &s) { s.clear(); return s; }
  1792. };
  1793. mapEnums workunitSortFields[] =
  1794. {
  1795. { WUSFuser, "@submitID" },
  1796. { WUSFcluster, "@clusterName" },
  1797. { WUSFjob, "@jobName" },
  1798. { WUSFstate, "@state" },
  1799. { WUSFpriority, "@priorityClass" },
  1800. { WUSFprotected, "@protected" },
  1801. { WUSFwuid, "@" },
  1802. { WUSFecl, "Query/Text" },
  1803. { WUSFfileread, "FilesRead/File/@name" },
  1804. { WUSFtotalthortime, "@totalThorTime|"
  1805. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  1806. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  1807. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  1808. "Statistics/Statistic[@desc='Total thor time']/@value|"
  1809. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  1810. },
  1811. { WUSFwuidhigh, "@" },
  1812. { WUSFwildwuid, "@" },
  1813. { WUSFappvalue, "Application" },
  1814. { WUSFfilewritten, "Files/File/@name" },
  1815. { WUSFterm, NULL }
  1816. };
  1817. extern const char *queryFilterXPath(WUSortField field)
  1818. {
  1819. return getEnumText(field, workunitSortFields);
  1820. }
  1821. mapEnums querySortFields[] =
  1822. {
  1823. { WUQSFId, "@id" },
  1824. { WUQSFwuid, "@wuid" },
  1825. { WUQSFname, "@name" },
  1826. { WUQSFdll, "@dll" },
  1827. { WUQSFmemoryLimit, "@memoryLimit" },
  1828. { WUQSFmemoryLimitHi, "@memoryLimit" },
  1829. { WUQSFtimeLimit, "@timeLimit" },
  1830. { WUQSFtimeLimitHi, "@timeLimit" },
  1831. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  1832. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  1833. { WUQSFpriority, "@priority" },
  1834. { WUQSFpriorityHi, "@priority" },
  1835. { WUQSFQuerySet, "@querySetId" },
  1836. { WUQSFActivited, "@activated" },
  1837. { WUQSFSuspendedByUser, "@suspended" },
  1838. { WUQSFLibrary, "Library"},
  1839. { WUQSFPublishedBy, "@publishedBy" },
  1840. { WUQSFterm, NULL }
  1841. };
  1842. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  1843. {
  1844. StringAttr name;
  1845. public:
  1846. IMPLEMENT_IINTERFACE;
  1847. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  1848. {
  1849. }
  1850. void execute()
  1851. {
  1852. PROGLOG("WU removeDll %s", name.get());
  1853. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  1854. }
  1855. };
  1856. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  1857. {
  1858. RemoteFilename name;
  1859. public:
  1860. IMPLEMENT_IINTERFACE;
  1861. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  1862. {
  1863. SocketEndpoint ep(_ip);
  1864. name.setPath(ep, _name);
  1865. }
  1866. void execute()
  1867. {
  1868. Owned<IFile> file = createIFile(name);
  1869. PROGLOG("WU removeDll %s",file->queryFilename());
  1870. file->remove();
  1871. }
  1872. };
  1873. //==========================================================================================
  1874. class CConstQuerySetQueryIterator : public CInterface, implements IConstQuerySetQueryIterator
  1875. {
  1876. IArrayOf<IPropertyTree> trees;
  1877. unsigned index;
  1878. public:
  1879. IMPLEMENT_IINTERFACE;
  1880. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  1881. {
  1882. ForEachItemIn(t, _trees)
  1883. trees.append(*LINK(&_trees.item(t)));
  1884. index = 0;
  1885. }
  1886. ~CConstQuerySetQueryIterator()
  1887. {
  1888. trees.kill();
  1889. }
  1890. bool first()
  1891. {
  1892. index = 0;
  1893. return (trees.ordinality()!=0);
  1894. }
  1895. bool next()
  1896. {
  1897. index++;
  1898. return (index<trees.ordinality());
  1899. }
  1900. bool isValid()
  1901. {
  1902. return (index<trees.ordinality());
  1903. }
  1904. IPropertyTree &query()
  1905. {
  1906. return trees.item(index);
  1907. }
  1908. };
  1909. class CSecurityCache
  1910. {
  1911. };
  1912. class CConstWUIterator : public CInterface, implements IConstWorkUnitIterator
  1913. {
  1914. public:
  1915. IMPLEMENT_IINTERFACE;
  1916. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  1917. : ptreeIter(_ptreeIter)
  1918. {
  1919. }
  1920. bool first()
  1921. {
  1922. if (!ptreeIter->first())
  1923. {
  1924. cur.clear();
  1925. return false;
  1926. }
  1927. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  1928. return true;
  1929. }
  1930. bool isValid()
  1931. {
  1932. return (NULL != cur.get());
  1933. }
  1934. bool next()
  1935. {
  1936. if (!ptreeIter->next())
  1937. {
  1938. cur.clear();
  1939. return false;
  1940. }
  1941. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  1942. return true;
  1943. }
  1944. IConstWorkUnitInfo & query() { return *cur; }
  1945. private:
  1946. Owned<IConstWorkUnitInfo> cur;
  1947. Owned<IPropertyTreeIterator> ptreeIter;
  1948. };
  1949. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  1950. {
  1951. public:
  1952. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  1953. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  1954. {
  1955. assertex(_secuser && _secmgr);
  1956. }
  1957. bool first()
  1958. {
  1959. if (!parent->first())
  1960. return false;
  1961. return getNext();
  1962. }
  1963. bool next()
  1964. {
  1965. if (!parent->next())
  1966. return false;
  1967. return getNext();
  1968. }
  1969. virtual bool isValid()
  1970. {
  1971. return parent->isValid();
  1972. }
  1973. virtual IConstWorkUnitInfo &query()
  1974. {
  1975. return parent->query();
  1976. }
  1977. private:
  1978. Owned<IConstWorkUnitIterator> parent;
  1979. MapStringTo<int> scopePermissions;
  1980. Linked<ISecManager> secmgr;
  1981. Linked<ISecUser> secuser;
  1982. bool getNext() // scan for a workunit with permissions
  1983. {
  1984. do
  1985. {
  1986. const char *scopeName = parent->query().queryWuScope();
  1987. if (!scopeName || !*scopeName || checkScope(scopeName))
  1988. return true;
  1989. } while (parent->next());
  1990. return false;
  1991. }
  1992. bool checkScope(const char *scopeName)
  1993. {
  1994. int *perms = scopePermissions.getValue(scopeName);
  1995. int perm;
  1996. if (!perms)
  1997. {
  1998. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName):-1;
  1999. scopePermissions.setValue(scopeName, perm);
  2000. }
  2001. else
  2002. perm = *perms;
  2003. return perm >= SecAccess_Read;
  2004. }
  2005. };
  2006. CWorkUnitFactory::CWorkUnitFactory()
  2007. {
  2008. }
  2009. CWorkUnitFactory::~CWorkUnitFactory()
  2010. {
  2011. }
  2012. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  2013. {
  2014. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  2015. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  2016. if (scope)
  2017. 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...
  2018. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  2019. ret->setDebugValue("CREATED_BY", app, true);
  2020. ret->setDebugValue("CREATED_FOR", scope, true);
  2021. return ret;
  2022. }
  2023. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  2024. {
  2025. StringBuffer wuid("W");
  2026. char result[32];
  2027. time_t ltime;
  2028. time( &ltime );
  2029. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  2030. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  2031. wuid.append(result);
  2032. if (workUnitTraceLevel > 1)
  2033. PrintLog("createWorkUnit created %s", wuid.str());
  2034. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  2035. if (workUnitTraceLevel > 1)
  2036. PrintLog("createWorkUnit created %s", ret->queryWuid());
  2037. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  2038. return ret;
  2039. }
  2040. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  2041. {
  2042. if (workUnitTraceLevel > 1)
  2043. PrintLog("deleteWorkUnit %s", wuid);
  2044. StringBuffer wuRoot;
  2045. getXPath(wuRoot, wuid);
  2046. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  2047. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  2048. return false;
  2049. try
  2050. {
  2051. cw->cleanupAndDelete(true, true);
  2052. }
  2053. catch (IException *E)
  2054. {
  2055. StringBuffer s;
  2056. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  2057. E->Release();
  2058. return false;
  2059. }
  2060. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  2061. return true;
  2062. }
  2063. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2064. {
  2065. StringBuffer wuidStr(wuid);
  2066. wuidStr.trim();
  2067. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  2068. wuidStr.setCharAt(0, 'W');
  2069. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  2070. {
  2071. if (workUnitTraceLevel > 1)
  2072. PrintLog("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  2073. return NULL;
  2074. }
  2075. if (workUnitTraceLevel > 1)
  2076. PrintLog("openWorkUnit %s", wuidStr.str());
  2077. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  2078. if (wu)
  2079. {
  2080. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  2081. return NULL; // Actually throws exception on failure, so won't reach here
  2082. return wu.getClear();
  2083. }
  2084. else
  2085. {
  2086. if (workUnitTraceLevel > 0)
  2087. PrintLog("openWorkUnit %s not found", wuidStr.str());
  2088. return NULL;
  2089. }
  2090. }
  2091. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2092. {
  2093. if (workUnitTraceLevel > 1)
  2094. PrintLog("updateWorkUnit %s", wuid);
  2095. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  2096. if (wu)
  2097. {
  2098. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  2099. return NULL;
  2100. return &wu->lockRemote(false);
  2101. }
  2102. else
  2103. {
  2104. if (workUnitTraceLevel > 0)
  2105. PrintLog("updateWorkUnit %s not found", wuid);
  2106. return NULL;
  2107. }
  2108. }
  2109. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  2110. {
  2111. Owned<IPropertyTree> ret;
  2112. IPropertyTree * branch = from->queryPropTree(xpath);
  2113. if(branch)
  2114. {
  2115. ret.setown(createPTreeFromIPT(branch));
  2116. from->removeTree(branch);
  2117. }
  2118. return ret.getClear();
  2119. }
  2120. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid)
  2121. {
  2122. StringBuffer path(base);
  2123. addPathSepChar(path).append(wuid).append(".xml");
  2124. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  2125. if (!pt)
  2126. return false;
  2127. CDateTime dt;
  2128. dt.setNow();
  2129. StringBuffer dts;
  2130. dt.getString(dts);
  2131. pt->setProp("@restoredDate", dts.str());
  2132. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  2133. Owned<IPropertyTree> associatedFiles;
  2134. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  2135. if (srcAssociated)
  2136. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  2137. // The updating of the repo is implementation specific...
  2138. if (!_restoreWorkUnit(pt.getClear(), wuid))
  2139. return false;
  2140. // now kludge back GeneratedDlls
  2141. if (generatedDlls)
  2142. {
  2143. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  2144. for(dlls->first(); dlls->isValid(); dlls->next())
  2145. {
  2146. IPropertyTree & dll = dlls->query();
  2147. char const * name = dll.queryProp("@name");
  2148. char const * kind = dll.queryProp("@kind");
  2149. char const * location = dll.queryProp("@location");
  2150. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  2151. if (!got)
  2152. {
  2153. RemoteFilename dstRfn;
  2154. dstRfn.setRemotePath(location);
  2155. StringBuffer srcPath(base);
  2156. addPathSepChar(srcPath);
  2157. dstRfn.getTail(srcPath);
  2158. OwnedIFile srcFile = createIFile(srcPath);
  2159. OwnedIFile dstFile = createIFile(dstRfn);
  2160. copyFile(dstFile, srcFile);
  2161. queryDllServer().registerDll(name, kind, location);
  2162. }
  2163. }
  2164. }
  2165. if (associatedFiles)
  2166. {
  2167. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  2168. ForEach(*associated)
  2169. {
  2170. IPropertyTree &file = associated->query();
  2171. const char *filename = file.queryProp("@filename");
  2172. SocketEndpoint ep(file.queryProp("@ip"));
  2173. RemoteFilename rfn;
  2174. rfn.setPath(ep, filename);
  2175. OwnedIFile dstFile = createIFile(rfn);
  2176. StringBuffer srcPath(base), name;
  2177. addPathSepChar(srcPath);
  2178. rfn.getTail(name);
  2179. srcPath.append(name);
  2180. if (generatedDlls)
  2181. {
  2182. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  2183. if (generatedDlls->hasProp(gDllPath))
  2184. continue; // generated dlls handled separately - see above
  2185. }
  2186. OwnedIFile srcFile = createIFile(srcPath);
  2187. if (srcFile->exists())
  2188. {
  2189. try
  2190. {
  2191. copyFile(dstFile, srcFile);
  2192. }
  2193. catch (IException *e)
  2194. {
  2195. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  2196. EXCLOG(e, msg.str());
  2197. e->Release();
  2198. }
  2199. }
  2200. }
  2201. }
  2202. return true;
  2203. }
  2204. int CWorkUnitFactory::setTracingLevel(int newLevel)
  2205. {
  2206. if (newLevel)
  2207. PrintLog("Setting workunit trace level to %d", newLevel);
  2208. int level = workUnitTraceLevel;
  2209. workUnitTraceLevel = newLevel;
  2210. return level;
  2211. }
  2212. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  2213. {
  2214. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  2215. if(!conn) return;
  2216. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  2217. KeptAtomTable entries;
  2218. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  2219. StringBuffer wuid;
  2220. for(iter->first(); iter->isValid(); iter->next())
  2221. {
  2222. char const * entry = iter->query().queryName();
  2223. if(!entries.find(entry))
  2224. {
  2225. entries.addAtom(entry);
  2226. ncnameUnescape(entry, wuid.clear());
  2227. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  2228. if(wu && (wu->getState() == WUStateWait))
  2229. wu->setState(WUStateCompleted);
  2230. }
  2231. }
  2232. bool more;
  2233. do more = root->removeProp("*"); while(more);
  2234. }
  2235. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  2236. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  2237. const void *filterbuf, // (appended) string values for filters
  2238. unsigned startoffset,
  2239. unsigned maxnum,
  2240. __int64 *cachehint,
  2241. unsigned *total,
  2242. const MapStringTo<bool> *_subset)
  2243. {
  2244. struct PostFilters
  2245. {
  2246. WUQueryFilterBoolean activatedFilter;
  2247. WUQueryFilterBoolean suspendedByUserFilter;
  2248. PostFilters()
  2249. {
  2250. activatedFilter = WUQFSAll;
  2251. suspendedByUserFilter = WUQFSAll;
  2252. };
  2253. } postFilters;
  2254. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  2255. {
  2256. StringAttr querySet;
  2257. StringAttr xPath;
  2258. StringAttr sortOrder;
  2259. PostFilters postFilters;
  2260. StringArray unknownAttributes;
  2261. const MapStringTo<bool> *subset;
  2262. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  2263. {
  2264. const char* querySetId = querySetTree->queryProp("@id");
  2265. VStringBuffer path("Query%s", xPath.get());
  2266. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  2267. ForEach(*iter)
  2268. {
  2269. IPropertyTree &query = iter->query();
  2270. bool activated = false;
  2271. const char* queryId = query.queryProp("@id");
  2272. if (queryId && *queryId)
  2273. {
  2274. if (subset)
  2275. {
  2276. VStringBuffer match("%s/%s", querySetId, queryId);
  2277. if (!subset->getValue(match))
  2278. continue;
  2279. }
  2280. VStringBuffer aliasXPath("Alias[@id='%s']", queryId);
  2281. IPropertyTree *alias = querySetTree->queryPropTree(aliasXPath.str());
  2282. if (alias)
  2283. activated = true;
  2284. }
  2285. if (activated && (postFilters.activatedFilter == WUQFSNo))
  2286. continue;
  2287. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  2288. continue;
  2289. if ((postFilters.suspendedByUserFilter == WUQFSNo) && query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  2290. continue;
  2291. if ((postFilters.suspendedByUserFilter == WUQFSYes) && !query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  2292. continue;
  2293. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  2294. queryWithSetId->setProp("@querySetId", querySetId);
  2295. queryWithSetId->setPropBool("@activated", activated);
  2296. }
  2297. }
  2298. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  2299. {
  2300. StringBuffer querySetXPath("QuerySets");
  2301. if (!querySet.isEmpty())
  2302. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  2303. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2304. if (!conn)
  2305. return NULL;
  2306. if (querySet.isEmpty())
  2307. {
  2308. Owned<IPropertyTreeIterator> querySetIter = conn->queryRoot()->getElements("*");
  2309. ForEach(*querySetIter)
  2310. populateQueryTree(&querySetIter->query(), queryTree);
  2311. }
  2312. else
  2313. populateQueryTree(conn->queryRoot(), queryTree);
  2314. return conn.getClear();
  2315. }
  2316. public:
  2317. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2318. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters, StringArray& _unknownAttributes, const MapStringTo<bool> *_subset)
  2319. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset)
  2320. {
  2321. postFilters.activatedFilter = _postFilters.activatedFilter;
  2322. postFilters.suspendedByUserFilter = _postFilters.suspendedByUserFilter;
  2323. ForEachItemIn(x, _unknownAttributes)
  2324. unknownAttributes.append(_unknownAttributes.item(x));
  2325. }
  2326. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  2327. {
  2328. Owned<IPropertyTree> elementTree = createPTree("Queries");
  2329. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  2330. if (!conn)
  2331. return NULL;
  2332. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  2333. if (!iter)
  2334. return NULL;
  2335. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  2336. return conn.getClear();
  2337. }
  2338. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  2339. };
  2340. StringAttr querySet;
  2341. StringBuffer xPath;
  2342. StringBuffer so;
  2343. StringArray unknownAttributes;
  2344. if (filters)
  2345. {
  2346. const char *fv = (const char *)filterbuf;
  2347. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  2348. int fmt = filters[i];
  2349. int subfmt = (fmt&0xff);
  2350. if (subfmt==WUQSFQuerySet)
  2351. querySet.set(fv);
  2352. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  2353. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  2354. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  2355. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  2356. else if (subfmt==WUQSFActivited)
  2357. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  2358. else if (subfmt==WUQSFSuspendedByUser)
  2359. postFilters.suspendedByUserFilter = (WUQueryFilterBoolean) atoi(fv);
  2360. else if (!fv || !*fv)
  2361. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  2362. else {
  2363. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  2364. if (fmt&WUQSFnocase)
  2365. xPath.append('?');
  2366. if (fmt&WUQSFnumeric)
  2367. xPath.append('#');
  2368. if (fmt&WUQSFwild)
  2369. xPath.append('~');
  2370. xPath.append('"').append(fv).append("\"]");
  2371. }
  2372. fv = fv + strlen(fv)+1;
  2373. }
  2374. }
  2375. if (sortorder) {
  2376. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  2377. if (so.length())
  2378. so.append(',');
  2379. int fmt = sortorder[i];
  2380. if (fmt&WUQSFreverse)
  2381. so.append('-');
  2382. if (fmt&WUQSFnocase)
  2383. so.append('?');
  2384. if (fmt&WUQSFnumeric)
  2385. so.append('#');
  2386. so.append(getEnumText(fmt&0xff,querySortFields));
  2387. }
  2388. }
  2389. IArrayOf<IPropertyTree> results;
  2390. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL, postFilters, unknownAttributes, _subset);
  2391. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  2392. return new CConstQuerySetQueryIterator(results);
  2393. }
  2394. bool CWorkUnitFactory::isAborting(const char *wuid) const
  2395. {
  2396. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  2397. try
  2398. {
  2399. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2400. if (acon)
  2401. return acon->queryRoot()->getPropInt(NULL) != 0;
  2402. }
  2403. catch (IException *E)
  2404. {
  2405. EXCLOG(E);
  2406. E->Release();
  2407. }
  2408. return false;
  2409. }
  2410. void CWorkUnitFactory::clearAborting(const char *wuid)
  2411. {
  2412. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  2413. try
  2414. {
  2415. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  2416. if (acon)
  2417. acon->close(true);
  2418. }
  2419. catch (IException *E)
  2420. {
  2421. EXCLOG(E);
  2422. E->Release();
  2423. }
  2424. }
  2425. bool CWorkUnitFactory::checkAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  2426. {
  2427. if (queryDaliServerVersion().compare("2.1")>=0)
  2428. {
  2429. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  2430. {
  2431. bool isEcl = false;
  2432. switch (state)
  2433. {
  2434. case WUStateCompiling:
  2435. isEcl = true;
  2436. // drop into
  2437. case WUStateRunning:
  2438. case WUStateBlocked:
  2439. state = WUStateFailed;
  2440. break;
  2441. case WUStateAborting:
  2442. state = WUStateAborted;
  2443. break;
  2444. default:
  2445. return false;
  2446. }
  2447. WARNLOG("checkAbnormalTermination: workunit terminated: %" I64F "d state = %d",(__int64) agent, (int) state);
  2448. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  2449. wu->setState(state);
  2450. Owned<IWUException> e = wu->createException();
  2451. e->setExceptionCode(isEcl ? 1001 : 1000);
  2452. e->setExceptionMessage(isEcl ? "EclServer terminated unexpectedly" : "Workunit terminated unexpectedly");
  2453. return true;
  2454. }
  2455. }
  2456. return false;
  2457. }
  2458. static CriticalSection deleteDllLock;
  2459. static Owned<IWorkQueueThread> deleteDllWorkQ;
  2460. static void asyncRemoveDll(const char * name)
  2461. {
  2462. CriticalBlock b(deleteDllLock);
  2463. if (!deleteDllWorkQ)
  2464. deleteDllWorkQ.setown(createWorkQueueThread());
  2465. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  2466. }
  2467. static void asyncRemoveFile(const char * ip, const char * name)
  2468. {
  2469. CriticalBlock b(deleteDllLock);
  2470. if (!deleteDllWorkQ)
  2471. deleteDllWorkQ.setown(createWorkQueueThread());
  2472. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  2473. }
  2474. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  2475. {
  2476. public:
  2477. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  2478. CDaliWorkUnitFactory()
  2479. {
  2480. // Assumes dali client configuration has already been done
  2481. sdsManager = &querySDS();
  2482. session = myProcessSession();
  2483. addShutdownHook(*this);
  2484. }
  2485. ~CDaliWorkUnitFactory()
  2486. {
  2487. removeShutdownHook(*this);
  2488. }
  2489. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  2490. {
  2491. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  2492. }
  2493. virtual unsigned validateRepository(bool fixErrors)
  2494. {
  2495. return 0;
  2496. }
  2497. virtual void deleteRepository(bool recreate)
  2498. {
  2499. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  2500. if (conn)
  2501. conn->close(true);
  2502. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  2503. if (conn)
  2504. conn->close(true);
  2505. }
  2506. virtual void createRepository()
  2507. {
  2508. // Nothing to do
  2509. }
  2510. virtual const char *queryStoreType() const
  2511. {
  2512. return "Dali";
  2513. }
  2514. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2515. {
  2516. StringBuffer wuRoot;
  2517. getXPath(wuRoot, wuid);
  2518. IRemoteConnection *conn;
  2519. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  2520. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  2521. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  2522. return new CDaliWorkUnit(conn, secmgr, secuser);
  2523. }
  2524. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2525. {
  2526. StringBuffer wuRoot;
  2527. getXPath(wuRoot, wuid);
  2528. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  2529. if (conn)
  2530. return new CDaliWorkUnit(conn, secmgr, secuser);
  2531. else
  2532. return NULL;
  2533. }
  2534. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  2535. {
  2536. Owned<IPTree> pt(_pt);
  2537. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  2538. StringBuffer wuRoot;
  2539. getXPath(wuRoot, wuid);
  2540. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  2541. if (!conn)
  2542. {
  2543. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  2544. return false;
  2545. }
  2546. IPropertyTree *root = conn->queryRoot();
  2547. if (root->hasChildren())
  2548. {
  2549. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  2550. return false;
  2551. }
  2552. root->setPropTree(NULL, pt.getClear());
  2553. conn.clear();
  2554. // now kludge back GraphProgress
  2555. if (gprogress)
  2556. {
  2557. VStringBuffer xpath("/GraphProgress/%s", wuid);
  2558. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  2559. if (conn)
  2560. {
  2561. IPropertyTree *groot = conn->queryRoot();
  2562. if (groot->hasChildren())
  2563. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  2564. groot->setPropTree(NULL, gprogress.getClear());
  2565. }
  2566. }
  2567. return true;
  2568. }
  2569. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2570. {
  2571. StringBuffer wuRoot;
  2572. getXPath(wuRoot, wuid);
  2573. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  2574. if (conn)
  2575. return new CDaliWorkUnit(conn, secmgr, secuser);
  2576. else
  2577. return NULL;
  2578. }
  2579. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  2580. {
  2581. // MORE - should it check security?
  2582. StringBuffer wuRoot;
  2583. getXPath(wuRoot, GLOBAL_WORKUNIT);
  2584. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  2585. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  2586. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  2587. return &cw->lockRemote(false);
  2588. }
  2589. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  2590. {
  2591. StringBuffer path("*");
  2592. if (owner && *owner)
  2593. path.append("[@submitID=?~\"").append(owner).append("\"]");
  2594. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  2595. }
  2596. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  2597. {
  2598. StringBuffer path("*");
  2599. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  2600. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  2601. }
  2602. virtual void clientShutdown();
  2603. virtual unsigned numWorkUnits()
  2604. {
  2605. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  2606. if (!conn)
  2607. return 0;
  2608. IPropertyTree *root = conn->queryRoot();
  2609. return root->numChildren();
  2610. }
  2611. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  2612. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  2613. const void *filterbuf, // (appended) string values for filters
  2614. unsigned startoffset,
  2615. unsigned maxnum,
  2616. __int64 *cachehint,
  2617. unsigned *total,
  2618. ISecManager *secmgr,
  2619. ISecUser *secuser)
  2620. {
  2621. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  2622. {
  2623. StringAttr xPath;
  2624. StringAttr sortOrder;
  2625. StringAttr nameFilterLo;
  2626. StringAttr nameFilterHi;
  2627. StringArray unknownAttributes;
  2628. public:
  2629. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2630. CWorkUnitsPager(const char* _xPath, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  2631. : xPath(_xPath), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  2632. {
  2633. ForEachItemIn(x, _unknownAttributes)
  2634. unknownAttributes.append(_unknownAttributes.item(x));
  2635. }
  2636. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  2637. {
  2638. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2639. if (!conn)
  2640. return NULL;
  2641. Owned<IPropertyTreeIterator> iter = conn->getElements(xPath);
  2642. if (!iter)
  2643. return NULL;
  2644. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  2645. return conn.getClear();
  2646. }
  2647. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  2648. };
  2649. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  2650. {
  2651. UniqueScopes done;
  2652. ISecManager *secmgr;
  2653. ISecUser *secuser;
  2654. CriticalSection crit;
  2655. public:
  2656. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2657. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  2658. {
  2659. secmgr = _secmgr;
  2660. secuser = _secuser;
  2661. }
  2662. bool isOK(IPropertyTree &tree)
  2663. {
  2664. const char *scopename = tree.queryProp("@scope");
  2665. if (!scopename||!*scopename)
  2666. return true;
  2667. {
  2668. CriticalBlock block(crit);
  2669. const bool *b = done.getValue(scopename);
  2670. if (b)
  2671. return *b;
  2672. }
  2673. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  2674. {
  2675. // conceivably could have already been checked and added, but ok.
  2676. CriticalBlock block(crit);
  2677. done.setValue(scopename,ret);
  2678. }
  2679. return ret;
  2680. }
  2681. };
  2682. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  2683. StringBuffer query;
  2684. StringBuffer so;
  2685. StringAttr namefilter("*");
  2686. StringAttr namefilterlo;
  2687. StringAttr namefilterhi;
  2688. StringArray unknownAttributes;
  2689. if (filters) {
  2690. const char *fv = (const char *)filterbuf;
  2691. for (unsigned i=0;filters[i]!=WUSFterm;i++) {
  2692. int fmt = filters[i];
  2693. int subfmt = (fmt&0xff);
  2694. if (subfmt==WUSFwuid)
  2695. namefilterlo.set(fv);
  2696. else if (subfmt==WUSFwuidhigh)
  2697. namefilterhi.set(fv);
  2698. else if (subfmt==WUSFwildwuid)
  2699. namefilter.set(fv);
  2700. else if (subfmt==WUSFappvalue)
  2701. {
  2702. query.append("[Application/").append(fv).append("=?~\"");
  2703. fv = fv + strlen(fv)+1;
  2704. query.append(fv).append("\"]");
  2705. }
  2706. else if (!fv || !*fv)
  2707. {
  2708. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  2709. if (subfmt==WUSFtotalthortime)
  2710. sortorder = (WUSortField) (sortorder | WUSFnumeric);
  2711. }
  2712. else {
  2713. query.append('[').append(getEnumText(subfmt,workunitSortFields)).append('=');
  2714. if (fmt&WUSFnocase)
  2715. query.append('?');
  2716. if (fmt&WUSFwild)
  2717. query.append('~');
  2718. query.append('"').append(fv).append("\"]");
  2719. }
  2720. fv = fv + strlen(fv)+1;
  2721. }
  2722. }
  2723. query.insert(0, namefilter.get());
  2724. if (sortorder)
  2725. {
  2726. if (so.length())
  2727. so.append(',');
  2728. if (sortorder & WUSFreverse)
  2729. so.append('-');
  2730. if (sortorder & WUSFnocase)
  2731. so.append('?');
  2732. if (sortorder & WUSFnumeric)
  2733. so.append('#');
  2734. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  2735. }
  2736. IArrayOf<IPropertyTree> results;
  2737. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  2738. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  2739. return new CConstWUArrayIterator(results);
  2740. }
  2741. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  2742. {
  2743. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  2744. LocalIAbortHandler abortHandler(*waiter);
  2745. WUState ret = WUStateUnknown;
  2746. StringBuffer wuRoot;
  2747. getXPath(wuRoot, wuid);
  2748. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  2749. if (conn)
  2750. {
  2751. unsigned start = msTick();
  2752. loop
  2753. {
  2754. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  2755. switch (ret)
  2756. {
  2757. case WUStateCompiled:
  2758. case WUStateUploadingFiles:
  2759. if (!compiled)
  2760. break;
  2761. // fall into
  2762. case WUStateCompleted:
  2763. case WUStateFailed:
  2764. case WUStateAborted:
  2765. return ret;
  2766. case WUStateWait:
  2767. if(returnOnWaitState)
  2768. {
  2769. return ret;
  2770. }
  2771. break;
  2772. case WUStateCompiling:
  2773. case WUStateRunning:
  2774. case WUStateDebugPaused:
  2775. case WUStateDebugRunning:
  2776. case WUStateBlocked:
  2777. case WUStateAborting:
  2778. SessionId agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  2779. if (checkAbnormalTermination(wuid, ret, agent))
  2780. {
  2781. return ret;
  2782. }
  2783. break;
  2784. }
  2785. unsigned waited = msTick() - start;
  2786. if (timeout==-1)
  2787. {
  2788. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  2789. if (waiter->aborted)
  2790. {
  2791. ret = WUStateUnknown; // MORE - throw an exception?
  2792. break;
  2793. }
  2794. }
  2795. else if (waited > timeout || !waiter->wait(timeout-waited))
  2796. {
  2797. ret = WUStateUnknown; // MORE - throw an exception?
  2798. break;
  2799. }
  2800. conn->reload();
  2801. }
  2802. }
  2803. return ret;
  2804. }
  2805. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  2806. {
  2807. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  2808. LocalIAbortHandler abortHandler(*waiter);
  2809. WUAction ret = WUActionUnknown;
  2810. StringBuffer wuRoot;
  2811. getXPath(wuRoot, wuid);
  2812. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  2813. if (conn)
  2814. {
  2815. unsigned start = msTick();
  2816. loop
  2817. {
  2818. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  2819. if (ret != original)
  2820. break;
  2821. unsigned waited = msTick() - start;
  2822. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  2823. if (waiter->aborted)
  2824. {
  2825. ret = WUActionUnknown; // MORE - throw an exception?
  2826. break;
  2827. }
  2828. conn->reload();
  2829. }
  2830. }
  2831. waiter->unsubscribe();
  2832. return ret;
  2833. }
  2834. protected:
  2835. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  2836. {
  2837. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  2838. if (conn)
  2839. {
  2840. CDaliVersion serverVersionNeeded("3.2");
  2841. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  2842. conn->queryRoot()->getElements(xpath) :
  2843. conn->getElements(xpath));
  2844. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  2845. }
  2846. else
  2847. return NULL;
  2848. }
  2849. ISDSManager *sdsManager;
  2850. SessionId session;
  2851. };
  2852. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  2853. {
  2854. if (secmgr)
  2855. return new CSecureConstWUIterator(iter, secmgr, secuser);
  2856. else
  2857. return iter;
  2858. }
  2859. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  2860. {
  2861. if (secmgr)
  2862. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  2863. else
  2864. return new CConstWUIterator(iter);
  2865. }
  2866. static CriticalSection factoryCrit;
  2867. static Owned<ILoadedDllEntry> workunitServerPlugin; // NOTE - unload AFTER the factory is released!
  2868. static Owned<IWorkUnitFactory> factory;
  2869. void CDaliWorkUnitFactory::clientShutdown()
  2870. {
  2871. CriticalBlock b(factoryCrit);
  2872. factory.clear();
  2873. }
  2874. void clientShutdownWorkUnit()
  2875. {
  2876. CriticalBlock b(factoryCrit);
  2877. factory.clear();
  2878. }
  2879. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  2880. {
  2881. CriticalBlock b(factoryCrit);
  2882. factory.setown(_factory);
  2883. }
  2884. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  2885. {
  2886. if (!factory)
  2887. {
  2888. CriticalBlock b(factoryCrit);
  2889. 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.
  2890. {
  2891. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  2892. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  2893. Owned<IRemoteConnection> conn = querySDS().connect("/Environment/Software/WorkUnitsServer", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2894. // MORE - arguably should be looking in the config section that corresponds to the dali we connected to. If you want to allow some dalis to be configured to use a WU server and others not.
  2895. if (conn && !forceDali)
  2896. {
  2897. const IPropertyTree *ptree = conn->queryRoot();
  2898. const char *pluginName = ptree->queryProp("@plugin");
  2899. if (!pluginName)
  2900. throw makeStringException(WUERR_WorkunitPluginError, "WorkUnitsServer information missing plugin name");
  2901. workunitServerPlugin.setown(createDllEntry(pluginName, false, NULL));
  2902. if (!workunitServerPlugin)
  2903. throw makeStringExceptionV(WUERR_WorkunitPluginError, "WorkUnitsServer: failed to load plugin %s", pluginName);
  2904. WorkUnitFactoryFactory pf = (WorkUnitFactoryFactory) workunitServerPlugin->getEntry("createWorkUnitFactory");
  2905. if (!pf)
  2906. throw makeStringExceptionV(WUERR_WorkunitPluginError, "WorkUnitsServer: function createWorkUnitFactory not found in plugin %s", pluginName);
  2907. factory.setown(pf(ptree));
  2908. if (!factory)
  2909. throw makeStringExceptionV(WUERR_WorkunitPluginError, "WorkUnitsServer: createWorkUnitFactory returned NULL in plugin %s", pluginName);
  2910. }
  2911. else
  2912. factory.setown(new CDaliWorkUnitFactory());
  2913. }
  2914. }
  2915. return factory.getLink();
  2916. }
  2917. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  2918. // They can still be supplied if you want...
  2919. class CSecureWorkUnitFactory : public CInterface, implements IWorkUnitFactory
  2920. {
  2921. public:
  2922. IMPLEMENT_IINTERFACE;
  2923. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  2924. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  2925. {
  2926. }
  2927. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  2928. {
  2929. return baseFactory->getWatcher(subscriber, options, wuid);
  2930. }
  2931. virtual unsigned validateRepository(bool fix)
  2932. {
  2933. return baseFactory->validateRepository(fix);
  2934. }
  2935. virtual void deleteRepository(bool recreate)
  2936. {
  2937. return baseFactory->deleteRepository(recreate);
  2938. }
  2939. virtual void createRepository()
  2940. {
  2941. return baseFactory->createRepository();
  2942. }
  2943. virtual const char *queryStoreType() const
  2944. {
  2945. return baseFactory->queryStoreType();
  2946. }
  2947. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  2948. {
  2949. return baseFactory->getUniqueValues(field, prefix, result);
  2950. }
  2951. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  2952. {
  2953. if (!secMgr) secMgr = defaultSecMgr.get();
  2954. if (!secUser) secUser = defaultSecUser.get();
  2955. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  2956. }
  2957. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  2958. {
  2959. if (!secMgr) secMgr = defaultSecMgr.get();
  2960. if (!secUser) secUser = defaultSecUser.get();
  2961. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  2962. }
  2963. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  2964. {
  2965. if (!secMgr) secMgr = defaultSecMgr.get();
  2966. if (!secUser) secUser = defaultSecUser.get();
  2967. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  2968. }
  2969. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  2970. {
  2971. if (!secMgr) secMgr = defaultSecMgr.get();
  2972. if (!secUser) secUser = defaultSecUser.get();
  2973. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  2974. }
  2975. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  2976. {
  2977. if (!secMgr) secMgr = defaultSecMgr.get();
  2978. if (!secUser) secUser = defaultSecUser.get();
  2979. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  2980. }
  2981. virtual bool restoreWorkUnit(const char *base, const char *wuid)
  2982. {
  2983. return baseFactory->restoreWorkUnit(base, wuid);
  2984. }
  2985. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  2986. {
  2987. if (!secMgr) secMgr = defaultSecMgr.get();
  2988. if (!secUser) secUser = defaultSecUser.get();
  2989. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  2990. }
  2991. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  2992. {
  2993. if (!secMgr) secMgr = defaultSecMgr.get();
  2994. if (!secUser) secUser = defaultSecUser.get();
  2995. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  2996. }
  2997. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  2998. {
  2999. if (!secMgr) secMgr = defaultSecMgr.get();
  3000. if (!secUser) secUser = defaultSecUser.get();
  3001. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  3002. }
  3003. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  3004. {
  3005. if (!secMgr) secMgr = defaultSecMgr.get();
  3006. if (!secUser) secUser = defaultSecUser.get();
  3007. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  3008. }
  3009. virtual int setTracingLevel(int newLevel)
  3010. {
  3011. return baseFactory->setTracingLevel(newLevel);
  3012. }
  3013. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  3014. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  3015. const void *filterbuf, // (appended) string values for filters
  3016. unsigned startoffset,
  3017. unsigned maxnum,
  3018. __int64 *cachehint,
  3019. unsigned *total,
  3020. ISecManager *secMgr, ISecUser *secUser)
  3021. {
  3022. if (!secMgr) secMgr = defaultSecMgr.get();
  3023. if (!secUser) secUser = defaultSecUser.get();
  3024. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  3025. }
  3026. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  3027. WUQuerySortField *filters,
  3028. const void *filterbuf,
  3029. unsigned startoffset,
  3030. unsigned maxnum,
  3031. __int64 *cachehint,
  3032. unsigned *total,
  3033. const MapStringTo<bool> *subset)
  3034. {
  3035. // MORE - why no security?
  3036. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset);
  3037. }
  3038. virtual unsigned numWorkUnits()
  3039. {
  3040. return baseFactory->numWorkUnits();
  3041. }
  3042. virtual bool isAborting(const char *wuid) const
  3043. {
  3044. return baseFactory->isAborting(wuid);
  3045. }
  3046. virtual void clearAborting(const char *wuid)
  3047. {
  3048. baseFactory->clearAborting(wuid);
  3049. }
  3050. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  3051. {
  3052. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, returnOnWaitState);
  3053. }
  3054. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  3055. {
  3056. return baseFactory->waitForWorkUnitAction(wuid, original);
  3057. }
  3058. private:
  3059. Owned<IWorkUnitFactory> baseFactory;
  3060. Linked<ISecManager> defaultSecMgr;
  3061. Linked<ISecUser> defaultSecUser;
  3062. };
  3063. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  3064. {
  3065. if (secmgr && secuser)
  3066. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  3067. else
  3068. return getWorkUnitFactory();
  3069. }
  3070. //==========================================================================================
  3071. class CStringPTreeIterator : public CInterface, implements IStringIterator
  3072. {
  3073. Owned<IPropertyTreeIterator> it;
  3074. public:
  3075. IMPLEMENT_IINTERFACE;
  3076. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  3077. virtual bool first() { return it->first(); }
  3078. virtual bool next() { return it->next(); }
  3079. virtual bool isValid() { return it->isValid(); }
  3080. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  3081. };
  3082. class CStringPTreeTagIterator : public CInterface, implements IStringIterator
  3083. {
  3084. Owned<IPropertyTreeIterator> it;
  3085. public:
  3086. IMPLEMENT_IINTERFACE;
  3087. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  3088. virtual bool first() { return it->first(); }
  3089. virtual bool next() { return it->next(); }
  3090. virtual bool isValid() { return it->isValid(); }
  3091. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  3092. };
  3093. class CStringPTreeAttrIterator : public CInterface, implements IStringIterator
  3094. {
  3095. Owned<IPropertyTreeIterator> it;
  3096. StringAttr name;
  3097. public:
  3098. IMPLEMENT_IINTERFACE;
  3099. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  3100. virtual bool first() { return it->first(); }
  3101. virtual bool next() { return it->next(); }
  3102. virtual bool isValid() { return it->isValid(); }
  3103. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  3104. };
  3105. //==========================================================================================
  3106. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  3107. {
  3108. clearCached(false);
  3109. secMgr.set(secmgr);
  3110. secUser.set(secuser);
  3111. workflowIteratorCached = false;
  3112. resultsCached = false;
  3113. graphsCached = false;
  3114. temporariesCached = false;
  3115. variablesCached = false;
  3116. exceptionsCached = false;
  3117. pluginsCached = false;
  3118. librariesCached = false;
  3119. activitiesCached = false;
  3120. webServicesInfoCached = false;
  3121. roxieQueryInfoCached = false;
  3122. }
  3123. void CLocalWorkUnit::clearCached(bool clearTree)
  3124. {
  3125. query.clear();
  3126. webServicesInfo.clear();
  3127. workflowIterator.clear();
  3128. graphs.kill();
  3129. results.kill();
  3130. variables.kill();
  3131. plugins.kill();
  3132. libraries.kill();
  3133. exceptions.kill();
  3134. temporaries.kill();
  3135. statistics.kill();
  3136. appvalues.kill();
  3137. if (clearTree)
  3138. p.clear();
  3139. workflowIteratorCached = false;
  3140. resultsCached = false;
  3141. graphsCached = false;
  3142. temporariesCached = false;
  3143. variablesCached = false;
  3144. exceptionsCached = false;
  3145. pluginsCached = false;
  3146. librariesCached = false;
  3147. activitiesCached = false;
  3148. webServicesInfoCached = false;
  3149. roxieQueryInfoCached = false;
  3150. }
  3151. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  3152. {
  3153. clearCached(false);
  3154. p.setown(ptree);
  3155. }
  3156. void CLocalWorkUnit::beforeDispose()
  3157. {
  3158. try
  3159. {
  3160. unsubscribe();
  3161. clearCached(true);
  3162. userDesc.clear();
  3163. secMgr.clear();
  3164. secUser.clear();
  3165. }
  3166. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  3167. }
  3168. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3169. {
  3170. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  3171. // Delete any related things in SDS etc that might otherwise be forgotten
  3172. if (p->getPropBool("@protected", false))
  3173. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  3174. switch (getState())
  3175. {
  3176. case WUStateAborted:
  3177. case WUStateCompleted:
  3178. case WUStateFailed:
  3179. case WUStateArchived:
  3180. break;
  3181. case WUStateCompiled:
  3182. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  3183. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  3184. break;
  3185. case WUStateWait:
  3186. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  3187. default:
  3188. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  3189. break;
  3190. }
  3191. if (getIsQueryService())
  3192. {
  3193. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  3194. if (registry)
  3195. {
  3196. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  3197. if (registry->hasProp(xpath.str()))
  3198. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  3199. }
  3200. }
  3201. try
  3202. {
  3203. if (deldll && !p->getPropBool("@isClone", false))
  3204. {
  3205. Owned<IConstWUQuery> q = getQuery();
  3206. if (q)
  3207. {
  3208. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  3209. SCMStringBuffer name;
  3210. ForEach(*iter)
  3211. {
  3212. IConstWUAssociatedFile & cur = iter->query();
  3213. cur.getNameTail(name);
  3214. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  3215. {
  3216. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  3217. if (entry.get())
  3218. asyncRemoveDll(name.str());
  3219. else
  3220. {
  3221. SCMStringBuffer ip, localPath;
  3222. cur.getName(localPath);
  3223. cur.getIp(ip);
  3224. asyncRemoveFile(ip.str(), localPath.str());
  3225. }
  3226. }
  3227. }
  3228. }
  3229. }
  3230. factory->clearAborting(queryWuid());
  3231. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  3232. }
  3233. catch(IException *E)
  3234. {
  3235. StringBuffer s;
  3236. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  3237. E->Release();
  3238. }
  3239. catch (...)
  3240. {
  3241. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  3242. }
  3243. }
  3244. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  3245. {
  3246. SCMStringBuffer strval;
  3247. val.getGmtString(strval);
  3248. p->setProp("@timescheduled",strval.str());
  3249. }
  3250. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  3251. {
  3252. StringBuffer str;
  3253. p->getProp("@timescheduled",str);
  3254. if(str.length())
  3255. val.setGmtString(str.str());
  3256. return val;
  3257. }
  3258. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  3259. {
  3260. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  3261. if(extra.length())
  3262. {
  3263. size32_t l = (size32_t)strlen(wuid);
  3264. size32_t p = buf.length()-l-4; // bit of a kludge
  3265. assertex(memcmp(buf.str()+p+2,wuid,l)==0);
  3266. StringAttr tail(buf.str()+p);
  3267. buf.setLength(p);
  3268. buf.append(extra);
  3269. buf.append(tail);
  3270. }
  3271. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  3272. }
  3273. bool CLocalWorkUnit::archiveWorkUnit(const char *base,bool del,bool ignoredllerrors,bool deleteOwned)
  3274. {
  3275. CriticalBlock block(crit);
  3276. StringBuffer path(base);
  3277. if (!p)
  3278. return false;
  3279. const char *wuid = p->queryName();
  3280. if (!wuid||!*wuid)
  3281. return false;
  3282. addPathSepChar(path).append(wuid).append(".xml");
  3283. Owned<IFile> file = createIFile(path.str());
  3284. if (!file)
  3285. return false;
  3286. Owned<IFileIO> fileio = file->open(IFOcreate);
  3287. if (!fileio)
  3288. return false;
  3289. StringBuffer buf;
  3290. exportWorkUnitToXML(this, buf, false, false, true);
  3291. StringBuffer extraWorkUnitXML;
  3292. Owned<IPTree> graphProgress = getGraphProgressTree();
  3293. if (graphProgress)
  3294. {
  3295. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  3296. graphProgress.clear();
  3297. }
  3298. Owned<IConstWUQuery> q = getQuery();
  3299. if (!q)
  3300. {
  3301. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  3302. return false;
  3303. if (del)
  3304. {
  3305. if (getState()==WUStateUnknown)
  3306. setState(WUStateArchived); // to allow delete
  3307. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  3308. }
  3309. return false;
  3310. }
  3311. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  3312. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  3313. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  3314. ForEach(*iter)
  3315. {
  3316. IConstWUAssociatedFile & cur = iter->query();
  3317. SCMStringBuffer name;
  3318. cur.getNameTail(name);
  3319. if (name.length())
  3320. {
  3321. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  3322. SCMStringBuffer curPath, curIp;
  3323. cur.getName(curPath);
  3324. cur.getIp(curIp);
  3325. SocketEndpoint curEp(curIp.str());
  3326. RemoteFilename curRfn;
  3327. curRfn.setPath(curEp, curPath.str());
  3328. StringBuffer dst(base);
  3329. addPathSepChar(dst);
  3330. curRfn.getTail(dst);
  3331. Owned<IFile> dstFile = createIFile(dst.str());
  3332. if (entry.get())
  3333. {
  3334. Owned<IException> exception;
  3335. Owned<IDllLocation> loc;
  3336. Owned<IPropertyTree> generatedDllBranch = createPTree();
  3337. generatedDllBranch->setProp("@name", entry->queryName());
  3338. generatedDllBranch->setProp("@kind", entry->queryKind());
  3339. try
  3340. {
  3341. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  3342. }
  3343. catch(IException * e)
  3344. {
  3345. exception.setown(e);
  3346. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  3347. }
  3348. RemoteFilename filename;
  3349. loc->getDllFilename(filename);
  3350. if (!exception)
  3351. {
  3352. Owned<IFile> srcfile = createIFile(filename);
  3353. try
  3354. {
  3355. if (dstFile->exists())
  3356. {
  3357. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  3358. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  3359. // still want to delete if already archived but there are source file copies
  3360. }
  3361. else
  3362. copyFile(dstFile, srcfile);
  3363. }
  3364. catch(IException * e)
  3365. {
  3366. exception.setown(e);
  3367. }
  3368. }
  3369. if (exception)
  3370. {
  3371. if (ignoredllerrors)
  3372. {
  3373. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  3374. //copy failed, so don't delete the registred dll files
  3375. deleteExclusions.append(name.str());
  3376. }
  3377. else
  3378. throw exception.getClear();
  3379. }
  3380. // Record Associated path to restore back to
  3381. StringBuffer restorePath;
  3382. curRfn.getRemotePath(restorePath);
  3383. generatedDllBranch->setProp("@location", restorePath.str());
  3384. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  3385. }
  3386. else // no generated dll entry
  3387. {
  3388. Owned<IFile> srcFile = createIFile(curRfn);
  3389. try
  3390. {
  3391. copyFile(dstFile, srcFile);
  3392. }
  3393. catch (IException *e)
  3394. {
  3395. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  3396. EXCLOG(e, msg.str());
  3397. e->Release();
  3398. deleteExclusions.append(name.str());
  3399. }
  3400. }
  3401. }
  3402. }
  3403. iter.clear();
  3404. if (generatedDlls->numChildren())
  3405. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  3406. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  3407. return false;
  3408. if (del)
  3409. {
  3410. //setState(WUStateArchived); // this isn't useful as about to delete it!
  3411. q.clear();
  3412. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  3413. }
  3414. return true;
  3415. }
  3416. void CLocalWorkUnit::loadXML(const char *xml)
  3417. {
  3418. CriticalBlock block(crit);
  3419. clearCached(true);
  3420. assertex(xml);
  3421. p.setown(createPTreeFromXMLString(xml));
  3422. }
  3423. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  3424. {
  3425. CriticalBlock block(crit);
  3426. StringBuffer x;
  3427. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  3428. }
  3429. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  3430. {
  3431. CriticalBlock block(crit);
  3432. StringAttr value;
  3433. src.read(value);
  3434. loadXML(value);
  3435. }
  3436. void CLocalWorkUnit::requestAbort()
  3437. {
  3438. CriticalBlock block(crit);
  3439. abortWorkUnit(p->queryName());
  3440. }
  3441. void CLocalWorkUnit::unlockRemote()
  3442. {
  3443. CriticalBlock block(crit);
  3444. locked.unlock();
  3445. _unlockRemote();
  3446. }
  3447. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  3448. {
  3449. if (secMgr)
  3450. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  3451. locked.lock();
  3452. CriticalBlock block(crit);
  3453. if (commit)
  3454. {
  3455. try
  3456. {
  3457. _lockRemote();
  3458. }
  3459. catch (IException *E)
  3460. {
  3461. StringBuffer s;
  3462. PrintLog("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  3463. locked.unlock();
  3464. throw;
  3465. }
  3466. }
  3467. return *new CLockedWorkUnit(LINK(this));
  3468. }
  3469. void CLocalWorkUnit::commit()
  3470. {
  3471. // Nothing to do if not backed by a persistent store
  3472. }
  3473. IWorkUnit& CLocalWorkUnit::lock()
  3474. {
  3475. return lockRemote(true);
  3476. }
  3477. const char *CLocalWorkUnit::queryWuid() const
  3478. {
  3479. CriticalBlock block(crit);
  3480. return p->queryName();
  3481. }
  3482. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  3483. {
  3484. CriticalBlock block(crit);
  3485. return p->getPropInt("@DebugListenerPort", 0);
  3486. }
  3487. unsigned CLocalWorkUnit::getTotalThorTime() const
  3488. {
  3489. CriticalBlock block(crit);
  3490. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  3491. }
  3492. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  3493. {
  3494. CriticalBlock block(crit);
  3495. p->setPropInt("@DebugListenerPort", port);
  3496. }
  3497. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  3498. {
  3499. CriticalBlock block(crit);
  3500. ip.set(p->queryProp("@DebugListenerIP"));
  3501. return ip;
  3502. }
  3503. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  3504. {
  3505. CriticalBlock block(crit);
  3506. p->setProp("@DebugListenerIP", ip);
  3507. }
  3508. IStringVal& CLocalWorkUnit::getSecurityToken(IStringVal &str) const
  3509. {
  3510. CriticalBlock block(crit);
  3511. str.set(p->queryProp("@token"));
  3512. return str;
  3513. }
  3514. void CLocalWorkUnit::setSecurityToken(const char *value)
  3515. {
  3516. CriticalBlock block(crit);
  3517. p->setProp("@token", value);
  3518. }
  3519. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3520. {
  3521. // Only implemented in derived classes
  3522. return false;
  3523. }
  3524. void CLocalWorkUnit::setJobName(const char *value)
  3525. {
  3526. CriticalBlock block(crit);
  3527. p->setProp("@jobName", value);
  3528. }
  3529. const char *CLocalWorkUnit::queryJobName() const
  3530. {
  3531. CriticalBlock block(crit);
  3532. const char *ret = p->queryProp("@jobName");
  3533. if (!ret)
  3534. ret = "";
  3535. return ret;
  3536. }
  3537. void CLocalWorkUnit::setClusterName(const char *value)
  3538. {
  3539. CriticalBlock block(crit);
  3540. p->setProp("@clusterName", value);
  3541. }
  3542. const char *CLocalWorkUnit::queryClusterName() const
  3543. {
  3544. CriticalBlock block(crit);
  3545. const char *ret = p->queryProp("@clusterName");
  3546. if (!ret)
  3547. ret = "";
  3548. return ret;
  3549. }
  3550. void CLocalWorkUnit::setAllowedClusters(const char *value)
  3551. {
  3552. setDebugValue("allowedclusters",value, true);
  3553. }
  3554. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  3555. {
  3556. CriticalBlock block(crit);
  3557. getDebugValue("allowedclusters",str);
  3558. if (str.length()!=0)
  3559. return str;
  3560. str.set(p->queryProp("@clusterName"));
  3561. return str;
  3562. }
  3563. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  3564. {
  3565. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  3566. }
  3567. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  3568. {
  3569. CriticalBlock block(crit);
  3570. return getDebugValueBool("allowautoqueueswitch",false);
  3571. }
  3572. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3573. {
  3574. StringBuffer suffix;
  3575. if (name && *name)
  3576. setApplicationValue("LibraryModule", "name", name, true);
  3577. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  3578. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  3579. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  3580. }
  3581. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3582. {
  3583. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  3584. if (writeaccess)
  3585. auditflags |= DALI_LDAP_WRITE_WANTED;
  3586. int perm = 255;
  3587. const char *scopename = p->queryProp("@scope");
  3588. if (scopename&&*scopename) {
  3589. if (!user)
  3590. user = queryUserDescriptor();
  3591. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  3592. if (perm<0) {
  3593. if (perm==-1)
  3594. perm = 255;
  3595. else
  3596. perm = 0;
  3597. }
  3598. }
  3599. if (!HASREADPERMISSION(perm))
  3600. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  3601. if (writeaccess && !HASWRITEPERMISSION(perm))
  3602. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  3603. }
  3604. void CLocalWorkUnit::setUser(const char * value)
  3605. {
  3606. CriticalBlock block(crit);
  3607. p->setProp("@submitID", value);
  3608. }
  3609. const char *CLocalWorkUnit::queryUser() const
  3610. {
  3611. CriticalBlock block(crit);
  3612. const char *ret = p->queryProp("@submitID");
  3613. if (!ret)
  3614. ret = "";
  3615. return ret;
  3616. }
  3617. void CLocalWorkUnit::setWuScope(const char * value)
  3618. {
  3619. if (value && *value)
  3620. {
  3621. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  3622. {
  3623. CriticalBlock block(crit);
  3624. p->setProp("@scope", value);
  3625. }
  3626. }
  3627. }
  3628. const char *CLocalWorkUnit::queryWuScope() const
  3629. {
  3630. CriticalBlock block(crit);
  3631. const char *ret = p->queryProp("@scope");
  3632. if (!ret)
  3633. ret = "";
  3634. return ret;
  3635. }
  3636. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  3637. {
  3638. CriticalBlock block(crit);
  3639. setEnum(p, "@priorityClass", cls, priorityClasses);
  3640. }
  3641. WUPriorityClass CLocalWorkUnit::getPriority() const
  3642. {
  3643. CriticalBlock block(crit);
  3644. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  3645. }
  3646. const char *CLocalWorkUnit::queryPriorityDesc() const
  3647. {
  3648. return getEnumText(getPriority(), priorityClasses);
  3649. }
  3650. void CLocalWorkUnit::setState(WUState value)
  3651. {
  3652. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  3653. {
  3654. if (factory)
  3655. factory->clearAborting(queryWuid());
  3656. }
  3657. CriticalBlock block(crit);
  3658. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  3659. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  3660. if (getDebugValueBool("monitorWorkunit", false))
  3661. {
  3662. switch(value)
  3663. {
  3664. case WUStateAborted:
  3665. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  3666. break;
  3667. case WUStateCompleted:
  3668. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  3669. break;
  3670. case WUStateFailed:
  3671. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  3672. break;
  3673. }
  3674. }
  3675. p->removeProp("@stateEx");
  3676. }
  3677. void CLocalWorkUnit::setStateEx(const char * text)
  3678. {
  3679. CriticalBlock block(crit);
  3680. p->setProp("@stateEx", text);
  3681. }
  3682. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  3683. {
  3684. CriticalBlock block(crit);
  3685. p->setPropInt64("@agentSession", sessionId);
  3686. }
  3687. bool CLocalWorkUnit::getIsQueryService() const
  3688. {
  3689. CriticalBlock block(crit);
  3690. return p->getPropBool("@isQueryService", false);
  3691. }
  3692. void CLocalWorkUnit::setIsQueryService(bool value)
  3693. {
  3694. CriticalBlock block(crit);
  3695. p->setPropBool("@isQueryService", value);
  3696. }
  3697. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  3698. {
  3699. if (queryDaliServerVersion().compare("2.1")<0)
  3700. return;
  3701. switch(state)
  3702. {
  3703. case WUStateRunning:
  3704. case WUStateDebugPaused:
  3705. case WUStateDebugRunning:
  3706. case WUStateBlocked:
  3707. case WUStateAborting:
  3708. case WUStateCompiling:
  3709. case WUStatePaused:
  3710. {
  3711. SessionId agent = getAgentSession();
  3712. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  3713. {
  3714. forceReload();
  3715. state = (WUState) getEnum(p, "@state", states);
  3716. bool isecl=state==WUStateCompiling;
  3717. if (aborting())
  3718. state = WUStateAborted;
  3719. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  3720. state = WUStateFailed;
  3721. else
  3722. return;
  3723. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  3724. Owned<IWorkUnit> w = &lock();
  3725. w->setState(state);
  3726. Owned<IWUException> e = w->createException();
  3727. WUAction action = w->getAction();
  3728. switch (action)
  3729. {
  3730. case WUActionPause:
  3731. case WUActionPauseNow:
  3732. case WUActionResume:
  3733. w->setAction(WUActionUnknown);
  3734. }
  3735. if(isecl)
  3736. {
  3737. e->setExceptionCode(1001);
  3738. e->setExceptionMessage("EclServer terminated unexpectedly");
  3739. }
  3740. else
  3741. {
  3742. e->setExceptionCode(1000);
  3743. e->setExceptionMessage("Workunit terminated unexpectedly");
  3744. }
  3745. }
  3746. }
  3747. }
  3748. }
  3749. WUState CLocalWorkUnit::getState() const
  3750. {
  3751. CriticalBlock block(crit);
  3752. WUState state = (WUState) getEnum(p, "@state", states);
  3753. switch (state)
  3754. {
  3755. case WUStateRunning:
  3756. case WUStateDebugPaused:
  3757. case WUStateDebugRunning:
  3758. case WUStateBlocked:
  3759. case WUStateCompiling:
  3760. if (aborting())
  3761. state = WUStateAborting;
  3762. break;
  3763. case WUStateSubmitted:
  3764. if (aborting())
  3765. state = WUStateAborted;
  3766. break;
  3767. }
  3768. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  3769. return state;
  3770. }
  3771. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  3772. {
  3773. CriticalBlock block(crit);
  3774. str.set(p->queryProp("@stateEx"));
  3775. return str;
  3776. }
  3777. __int64 CLocalWorkUnit::getAgentSession() const
  3778. {
  3779. CriticalBlock block(crit);
  3780. return p->getPropInt64("@agentSession", -1);
  3781. }
  3782. unsigned CLocalWorkUnit::getAgentPID() const
  3783. {
  3784. CriticalBlock block(crit);
  3785. return p->getPropInt("@agentPID", -1);
  3786. }
  3787. const char * CLocalWorkUnit::queryStateDesc() const
  3788. {
  3789. // MORE - not sure about this - may prefer a separate interface
  3790. CriticalBlock block(crit);
  3791. try
  3792. {
  3793. return getEnumText(getState(), states);
  3794. }
  3795. catch (...)
  3796. {
  3797. return "???";
  3798. }
  3799. }
  3800. void CLocalWorkUnit::setAction(WUAction value)
  3801. {
  3802. CriticalBlock block(crit);
  3803. setEnum(p, "Action", value, actions);
  3804. }
  3805. WUAction CLocalWorkUnit::getAction() const
  3806. {
  3807. CriticalBlock block(crit);
  3808. return (WUAction) getEnum(p, "Action", actions);
  3809. }
  3810. const char *CLocalWorkUnit::queryActionDesc() const
  3811. {
  3812. CriticalBlock block(crit);
  3813. return p->queryProp("Action");
  3814. }
  3815. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  3816. {
  3817. CriticalBlock block(crit);
  3818. StringBuffer prop("Application/");
  3819. prop.append(app).append('/').append(propname);
  3820. str.set(p->queryProp(prop.str()));
  3821. return str;
  3822. }
  3823. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  3824. {
  3825. CriticalBlock block(crit);
  3826. StringBuffer prop("Application/");
  3827. prop.append(app).append('/').append(propname);
  3828. return p->getPropInt(prop.str(), defVal);
  3829. }
  3830. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  3831. {
  3832. CriticalBlock block(crit);
  3833. appvalues.load(p,"Application/*");
  3834. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  3835. }
  3836. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  3837. {
  3838. CriticalBlock block(crit);
  3839. StringBuffer prop("Application/");
  3840. prop.append(app).append('/').append(propname);
  3841. if (overwrite || !p->hasProp(prop.str()))
  3842. {
  3843. StringBuffer sp;
  3844. p->setProp(sp.append("Application").str(), "");
  3845. p->setProp(sp.append('/').append(app).str(), "");
  3846. p->setProp(prop.str(), value);
  3847. }
  3848. }
  3849. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  3850. {
  3851. VStringBuffer s("%d", value);
  3852. setApplicationValue(app, propname, s, overwrite);
  3853. }
  3854. void CLocalWorkUnit::setPriorityLevel(int level)
  3855. {
  3856. CriticalBlock block(crit);
  3857. p->setPropInt("PriorityFlag", level);
  3858. }
  3859. int CLocalWorkUnit::getPriorityLevel() const
  3860. {
  3861. CriticalBlock block(crit);
  3862. return p->getPropInt("PriorityFlag");
  3863. }
  3864. int calcPriorityValue(const IPropertyTree * p)
  3865. {
  3866. int priority = p->getPropInt("PriorityFlag");
  3867. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  3868. {
  3869. case PriorityClassLow:
  3870. priority -= 100;
  3871. break;
  3872. case PriorityClassHigh:
  3873. priority += 100;
  3874. break;
  3875. }
  3876. return priority;
  3877. }
  3878. int CLocalWorkUnit::getPriorityValue() const
  3879. {
  3880. CriticalBlock block(crit);
  3881. return calcPriorityValue(p);
  3882. }
  3883. void CLocalWorkUnit::setRescheduleFlag(bool value)
  3884. {
  3885. CriticalBlock block(crit);
  3886. p->setPropInt("RescheduleFlag", (int) value);
  3887. }
  3888. bool CLocalWorkUnit::getRescheduleFlag() const
  3889. {
  3890. CriticalBlock block(crit);
  3891. return p->getPropInt("RescheduleFlag") != 0;
  3892. }
  3893. class NullIStringIterator : public CInterface, extends IStringIterator
  3894. {
  3895. public:
  3896. IMPLEMENT_IINTERFACE;
  3897. bool first() { return false; }
  3898. bool next() { return false; }
  3899. bool isValid() { return false; }
  3900. IStringVal & str(IStringVal & str) { return str; }
  3901. };
  3902. ClusterType getClusterType(const char * platform, ClusterType dft)
  3903. {
  3904. if (stricmp(platform, "thor") == 0)
  3905. return ThorLCRCluster;
  3906. if (stricmp(platform, "thorlcr") == 0)
  3907. return ThorLCRCluster;
  3908. if (stricmp(platform, "hthor") == 0)
  3909. return HThorCluster;
  3910. if (stricmp(platform, "roxie") == 0)
  3911. return RoxieCluster;
  3912. return dft;
  3913. }
  3914. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  3915. {
  3916. switch (clusterType)
  3917. {
  3918. case ThorLCRCluster:
  3919. if (lcrSensitive)
  3920. return "thorlcr";
  3921. return "thor";
  3922. case RoxieCluster:
  3923. return "roxie";
  3924. case HThorCluster:
  3925. return "hthor";
  3926. }
  3927. throwUnexpected();
  3928. }
  3929. IPropertyTree *queryRoxieProcessTree(IPropertyTree *environment, const char *process)
  3930. {
  3931. if (!process || !*process)
  3932. return NULL;
  3933. VStringBuffer xpath("Software/RoxieCluster[@name=\"%s\"]", process);
  3934. return environment->queryPropTree(xpath.str());
  3935. }
  3936. void getRoxieProcessServers(IPropertyTree *roxie, SocketEndpointArray &endpoints)
  3937. {
  3938. if (!roxie)
  3939. return;
  3940. Owned<IPropertyTreeIterator> servers = roxie->getElements("RoxieServerProcess");
  3941. ForEach(*servers)
  3942. {
  3943. IPropertyTree &server = servers->query();
  3944. const char *netAddress = server.queryProp("@netAddress");
  3945. if (netAddress && *netAddress)
  3946. {
  3947. SocketEndpoint ep(netAddress, server.getPropInt("@port", 9876));
  3948. endpoints.append(ep);
  3949. }
  3950. }
  3951. }
  3952. void getRoxieProcessServers(const char *process, SocketEndpointArray &servers)
  3953. {
  3954. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  3955. Owned<IConstEnvironment> env = factory->openEnvironment();
  3956. if (!env)
  3957. return;
  3958. Owned<IPropertyTree> root = &env->getPTree();
  3959. getRoxieProcessServers(queryRoxieProcessTree(root, process), servers);
  3960. }
  3961. class CEnvironmentClusterInfo: public CInterface, implements IConstWUClusterInfo
  3962. {
  3963. StringAttr name;
  3964. StringAttr serverQueue;
  3965. StringAttr agentQueue;
  3966. StringAttr roxieProcess;
  3967. SocketEndpointArray roxieServers;
  3968. StringAttr thorQueue;
  3969. StringArray thorProcesses;
  3970. StringArray primaryThorProcesses;
  3971. StringAttr prefix;
  3972. StringAttr ldapUser;
  3973. StringBuffer ldapPassword;
  3974. ClusterType platform;
  3975. unsigned clusterWidth;
  3976. unsigned roxieRedundancy;
  3977. unsigned channelsPerNode;
  3978. int roxieReplicateOffset;
  3979. public:
  3980. IMPLEMENT_IINTERFACE;
  3981. CEnvironmentClusterInfo(const char *_name, const char *_prefix, IPropertyTree *agent, IArrayOf<IPropertyTree> &thors, IPropertyTree *roxie)
  3982. : name(_name), prefix(_prefix), roxieRedundancy(0), channelsPerNode(0), roxieReplicateOffset(1)
  3983. {
  3984. StringBuffer queue;
  3985. if (thors.ordinality())
  3986. {
  3987. thorQueue.set(getClusterThorQueueName(queue.clear(), name));
  3988. clusterWidth = 0;
  3989. bool isMultiThor = (thors.length() > 1);
  3990. ForEachItemIn(i,thors)
  3991. {
  3992. IPropertyTree &thor = thors.item(i);
  3993. const char* thorName = thor.queryProp("@name");
  3994. thorProcesses.append(thorName);
  3995. if (!isMultiThor)
  3996. primaryThorProcesses.append(thorName);
  3997. else
  3998. {
  3999. const char *nodeGroup = thor.queryProp("@nodeGroup");
  4000. if (!nodeGroup || strieq(nodeGroup, thorName))
  4001. primaryThorProcesses.append(thorName);
  4002. }
  4003. unsigned nodes = thor.getCount("ThorSlaveProcess");
  4004. if (!nodes)
  4005. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: Thor cluster can not have 0 slave processes");
  4006. unsigned ts = nodes * thor.getPropInt("@slavesPerNode", 1);
  4007. if (clusterWidth && (ts!=clusterWidth))
  4008. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: mismatched thor sizes in cluster");
  4009. clusterWidth = ts;
  4010. bool islcr = !thor.getPropBool("@Legacy");
  4011. if (!islcr)
  4012. throw MakeStringException(WUERR_MismatchThorType,"CEnvironmentClusterInfo: Legacy Thor no longer supported");
  4013. }
  4014. platform = ThorLCRCluster;
  4015. }
  4016. else if (roxie)
  4017. {
  4018. roxieProcess.set(roxie->queryProp("@name"));
  4019. platform = RoxieCluster;
  4020. getRoxieProcessServers(roxie, roxieServers);
  4021. clusterWidth = roxieServers.length();
  4022. ldapUser.set(roxie->queryProp("@ldapUser"));
  4023. StringBuffer encPassword = roxie->queryProp("@ldapPassword");
  4024. if (encPassword.length())
  4025. decrypt(ldapPassword, encPassword);
  4026. const char *redundancyMode = roxie->queryProp("@slaveConfig");
  4027. if (redundancyMode && *redundancyMode)
  4028. {
  4029. unsigned dataCopies = roxie->getPropInt("@numDataCopies", 1);
  4030. if (strieq(redundancyMode, "overloaded"))
  4031. channelsPerNode = roxie->getPropInt("@channelsPernode", 1);
  4032. else if (strieq(redundancyMode, "full redundancy"))
  4033. {
  4034. roxieRedundancy = dataCopies-1;
  4035. roxieReplicateOffset = 0;
  4036. }
  4037. else if (strieq(redundancyMode, "cyclic redundancy"))
  4038. {
  4039. roxieRedundancy = dataCopies-1;
  4040. channelsPerNode = dataCopies;
  4041. roxieReplicateOffset = roxie->getPropInt("@cyclicOffset", 1);
  4042. }
  4043. }
  4044. }
  4045. else
  4046. {
  4047. clusterWidth = 1;
  4048. platform = HThorCluster;
  4049. }
  4050. if (agent)
  4051. {
  4052. assertex(!roxie);
  4053. agentQueue.set(getClusterEclAgentQueueName(queue.clear(), name));
  4054. }
  4055. else if (roxie)
  4056. agentQueue.set(getClusterRoxieQueueName(queue.clear(), name));
  4057. // MORE - does this need to be conditional?
  4058. serverQueue.set(getClusterEclCCServerQueueName(queue.clear(), name));
  4059. }
  4060. IStringVal & getName(IStringVal & str) const
  4061. {
  4062. str.set(name.get());
  4063. return str;
  4064. }
  4065. IStringVal & getScope(IStringVal & str) const
  4066. {
  4067. str.set(prefix.get());
  4068. return str;
  4069. }
  4070. IStringVal & getAgentQueue(IStringVal & str) const
  4071. {
  4072. str.set(agentQueue);
  4073. return str;
  4074. }
  4075. virtual IStringVal & getServerQueue(IStringVal & str) const
  4076. {
  4077. str.set(serverQueue);
  4078. return str;
  4079. }
  4080. IStringVal & getThorQueue(IStringVal & str) const
  4081. {
  4082. str.set(thorQueue);
  4083. return str;
  4084. }
  4085. unsigned getSize() const
  4086. {
  4087. return clusterWidth;
  4088. }
  4089. virtual ClusterType getPlatform() const
  4090. {
  4091. return platform;
  4092. }
  4093. IStringVal & getRoxieProcess(IStringVal & str) const
  4094. {
  4095. str.set(roxieProcess.get());
  4096. return str;
  4097. }
  4098. const StringArray & getThorProcesses() const
  4099. {
  4100. return thorProcesses;
  4101. }
  4102. const StringArray & getPrimaryThorProcesses() const
  4103. {
  4104. return primaryThorProcesses;
  4105. }
  4106. const SocketEndpointArray & getRoxieServers() const
  4107. {
  4108. return roxieServers;
  4109. }
  4110. unsigned getRoxieRedundancy() const
  4111. {
  4112. return roxieRedundancy;
  4113. }
  4114. unsigned getChannelsPerNode() const
  4115. {
  4116. return channelsPerNode;
  4117. }
  4118. int getRoxieReplicateOffset() const
  4119. {
  4120. return roxieReplicateOffset;
  4121. }
  4122. const char *getLdapUser() const
  4123. {
  4124. return ldapUser.get();
  4125. }
  4126. virtual const char *getLdapPassword() const
  4127. {
  4128. return ldapPassword.str();
  4129. }
  4130. };
  4131. IStringVal &getProcessQueueNames(IStringVal &ret, const char *process, const char *type, const char *suffix)
  4132. {
  4133. if (process)
  4134. {
  4135. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4136. Owned<IConstEnvironment> env = factory->openEnvironment();
  4137. if (env)
  4138. {
  4139. Owned<IPropertyTree> root = &env->getPTree();
  4140. StringBuffer queueNames;
  4141. StringBuffer xpath;
  4142. xpath.appendf("%s[@process=\"%s\"]", type, process);
  4143. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  4144. ForEach(*targets)
  4145. {
  4146. IPropertyTree &target = targets->query();
  4147. if (target.hasProp(xpath))
  4148. {
  4149. if (queueNames.length())
  4150. queueNames.append(',');
  4151. queueNames.append(target.queryProp("@name")).append(suffix);
  4152. }
  4153. }
  4154. ret.set(queueNames);
  4155. }
  4156. }
  4157. return ret;
  4158. }
  4159. #define ROXIE_QUEUE_EXT ".roxie"
  4160. #define THOR_QUEUE_EXT ".thor"
  4161. #define ECLCCSERVER_QUEUE_EXT ".eclserver"
  4162. #define ECLSERVER_QUEUE_EXT ECLCCSERVER_QUEUE_EXT
  4163. #define ECLSCHEDULER_QUEUE_EXT ".eclscheduler"
  4164. #define ECLAGENT_QUEUE_EXT ".agent"
  4165. extern WORKUNIT_API IStringVal &getEclCCServerQueueNames(IStringVal &ret, const char *process)
  4166. {
  4167. return getProcessQueueNames(ret, process, "EclCCServerProcess", ECLCCSERVER_QUEUE_EXT);
  4168. }
  4169. extern WORKUNIT_API IStringVal &getEclServerQueueNames(IStringVal &ret, const char *process)
  4170. {
  4171. return getProcessQueueNames(ret, process, "EclServerProcess", ECLSERVER_QUEUE_EXT); // shares queue name with EclCCServer
  4172. }
  4173. extern WORKUNIT_API IStringVal &getEclSchedulerQueueNames(IStringVal &ret, const char *process)
  4174. {
  4175. return getProcessQueueNames(ret, process, "EclSchedulerProcess", ECLSCHEDULER_QUEUE_EXT); // Shares deployment/config with EclCCServer
  4176. }
  4177. extern WORKUNIT_API IStringVal &getAgentQueueNames(IStringVal &ret, const char *process)
  4178. {
  4179. return getProcessQueueNames(ret, process, "EclAgentProcess", ECLAGENT_QUEUE_EXT);
  4180. }
  4181. extern WORKUNIT_API IStringVal &getRoxieQueueNames(IStringVal &ret, const char *process)
  4182. {
  4183. return getProcessQueueNames(ret, process, "RoxieCluster", ROXIE_QUEUE_EXT);
  4184. }
  4185. extern WORKUNIT_API IStringVal &getThorQueueNames(IStringVal &ret, const char *process)
  4186. {
  4187. return getProcessQueueNames(ret, process, "ThorCluster", THOR_QUEUE_EXT);
  4188. }
  4189. extern WORKUNIT_API StringBuffer &getClusterThorQueueName(StringBuffer &ret, const char *cluster)
  4190. {
  4191. return ret.append(cluster).append(THOR_QUEUE_EXT);
  4192. }
  4193. extern WORKUNIT_API StringBuffer &getClusterThorGroupName(StringBuffer &ret, const char *cluster)
  4194. {
  4195. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4196. Owned<IConstEnvironment> env = factory->openEnvironment();
  4197. if (env)
  4198. {
  4199. Owned<IPropertyTree> root = &env->getPTree();
  4200. StringBuffer path;
  4201. path.append("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  4202. IPropertyTree * child = root->queryPropTree(path);
  4203. if (child)
  4204. getClusterGroupName(*child, ret);
  4205. }
  4206. return ret;
  4207. }
  4208. extern WORKUNIT_API StringBuffer &getClusterRoxieQueueName(StringBuffer &ret, const char *cluster)
  4209. {
  4210. return ret.append(cluster).append(ROXIE_QUEUE_EXT);
  4211. }
  4212. extern WORKUNIT_API StringBuffer &getClusterEclCCServerQueueName(StringBuffer &ret, const char *cluster)
  4213. {
  4214. return ret.append(cluster).append(ECLCCSERVER_QUEUE_EXT);
  4215. }
  4216. extern WORKUNIT_API StringBuffer &getClusterEclServerQueueName(StringBuffer &ret, const char *cluster)
  4217. {
  4218. return ret.append(cluster).append(ECLSERVER_QUEUE_EXT);
  4219. }
  4220. extern WORKUNIT_API StringBuffer &getClusterEclAgentQueueName(StringBuffer &ret, const char *cluster)
  4221. {
  4222. return ret.append(cluster).append(ECLAGENT_QUEUE_EXT);
  4223. }
  4224. extern WORKUNIT_API IStringIterator *getTargetClusters(const char *processType, const char *processName)
  4225. {
  4226. Owned<CStringArrayIterator> ret = new CStringArrayIterator;
  4227. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4228. Owned<IConstEnvironment> env = factory->openEnvironment();
  4229. if (env)
  4230. {
  4231. Owned<IPropertyTree> root = &env->getPTree();
  4232. StringBuffer xpath;
  4233. xpath.appendf("%s", processType ? processType : "*");
  4234. if (processName && *processName)
  4235. xpath.appendf("[@process=\"%s\"]", processName);
  4236. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  4237. ForEach(*targets)
  4238. {
  4239. IPropertyTree &target = targets->query();
  4240. if (target.hasProp(xpath))
  4241. {
  4242. ret->append(target.queryProp("@name"));
  4243. }
  4244. }
  4245. }
  4246. return ret.getClear();
  4247. }
  4248. extern WORKUNIT_API bool isProcessCluster(const char *process)
  4249. {
  4250. if (!process || !*process)
  4251. return false;
  4252. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4253. Owned<IConstEnvironment> env = factory->openEnvironment();
  4254. if (!env)
  4255. return false;
  4256. Owned<IPropertyTree> root = &env->getPTree();
  4257. VStringBuffer xpath("Software/*Cluster[@name=\"%s\"]", process);
  4258. return root->hasProp(xpath.str());
  4259. }
  4260. extern WORKUNIT_API bool isProcessCluster(const char *remoteDali, const char *process)
  4261. {
  4262. if (!remoteDali || !*remoteDali)
  4263. return isProcessCluster(process);
  4264. if (!process || !*process)
  4265. return false;
  4266. Owned<INode> remote = createINode(remoteDali, 7070);
  4267. if (!remote)
  4268. return false;
  4269. //Cannot use getEnvironmentFactory() since it is using a remotedali
  4270. VStringBuffer xpath("Environment/Software/*Cluster[@name=\"%s\"]/@name", process);
  4271. try
  4272. {
  4273. Owned<IPropertyTreeIterator> clusters = querySDS().getElementsRaw(xpath, remote, 1000*60*1);
  4274. return clusters->first();
  4275. }
  4276. catch (IException *E)
  4277. {
  4278. StringBuffer msg;
  4279. E->errorMessage(msg);
  4280. DBGLOG("Exception validating cluster %s/%s: %s", remoteDali, xpath.str(), msg.str());
  4281. E->Release();
  4282. }
  4283. return true;
  4284. }
  4285. IConstWUClusterInfo* getTargetClusterInfo(IPropertyTree *environment, IPropertyTree *cluster)
  4286. {
  4287. const char *clustname = cluster->queryProp("@name");
  4288. // MORE - at the moment configenf specifies eclagent and thor queues by (in effect) placing an 'example' thor or eclagent in the topology
  4289. // that uses the queue that will be used.
  4290. // We should and I hope will change that, at which point the code below gets simpler
  4291. StringBuffer prefix(cluster->queryProp("@prefix"));
  4292. prefix.toLowerCase();
  4293. StringBuffer xpath;
  4294. StringBuffer querySetName;
  4295. IPropertyTree *agent = NULL;
  4296. const char *agentName = cluster->queryProp("EclAgentProcess/@process");
  4297. if (agentName)
  4298. {
  4299. xpath.clear().appendf("Software/EclAgentProcess[@name=\"%s\"]", agentName);
  4300. agent = environment->queryPropTree(xpath.str());
  4301. }
  4302. Owned<IPropertyTreeIterator> ti = cluster->getElements("ThorCluster");
  4303. IArrayOf<IPropertyTree> thors;
  4304. ForEach(*ti)
  4305. {
  4306. const char *thorName = ti->query().queryProp("@process");
  4307. if (thorName)
  4308. {
  4309. xpath.clear().appendf("Software/ThorCluster[@name=\"%s\"]", thorName);
  4310. thors.append(*environment->getPropTree(xpath.str()));
  4311. }
  4312. }
  4313. const char *roxieName = cluster->queryProp("RoxieCluster/@process");
  4314. return new CEnvironmentClusterInfo(clustname, prefix, agent, thors, queryRoxieProcessTree(environment, roxieName));
  4315. }
  4316. IPropertyTree* getTopologyCluster(Owned<IPropertyTree> &envRoot, const char *clustname)
  4317. {
  4318. if (!clustname || !*clustname)
  4319. return NULL;
  4320. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4321. Owned<IConstEnvironment> env = factory->openEnvironment();
  4322. if (!env)
  4323. return NULL;
  4324. envRoot.setown(&env->getPTree());
  4325. StringBuffer xpath;
  4326. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  4327. return envRoot->getPropTree(xpath.str());
  4328. }
  4329. bool validateTargetClusterName(const char *clustname)
  4330. {
  4331. Owned<IPropertyTree> envRoot;
  4332. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  4333. return (cluster.get()!=NULL);
  4334. }
  4335. IConstWUClusterInfo* getTargetClusterInfo(const char *clustname)
  4336. {
  4337. Owned<IPropertyTree> envRoot;
  4338. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  4339. if (!cluster)
  4340. return NULL;
  4341. return getTargetClusterInfo(envRoot, cluster);
  4342. }
  4343. unsigned getEnvironmentClusterInfo(CConstWUClusterInfoArray &clusters)
  4344. {
  4345. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4346. Owned<IConstEnvironment> env = factory->openEnvironment();
  4347. if (!env)
  4348. return 0;
  4349. Owned<IPropertyTree> root = &env->getPTree();
  4350. return getEnvironmentClusterInfo(root, clusters);
  4351. }
  4352. unsigned getEnvironmentClusterInfo(IPropertyTree* environmentRoot, CConstWUClusterInfoArray &clusters)
  4353. {
  4354. if (!environmentRoot)
  4355. return 0;
  4356. Owned<IPropertyTreeIterator> clusterIter = environmentRoot->getElements("Software/Topology/Cluster");
  4357. ForEach(*clusterIter)
  4358. {
  4359. IPropertyTree &node = clusterIter->query();
  4360. Owned<IConstWUClusterInfo> cluster = getTargetClusterInfo(environmentRoot, &node);
  4361. clusters.append(*cluster.getClear());
  4362. }
  4363. return clusters.ordinality();
  4364. }
  4365. const char *getTargetClusterComponentName(const char *clustname, const char *processType, StringBuffer &name)
  4366. {
  4367. if (!clustname)
  4368. return NULL;
  4369. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4370. Owned<IConstEnvironment> env = factory->openEnvironment();
  4371. if (!env)
  4372. return NULL;
  4373. Owned<IPropertyTree> root = &env->getPTree();
  4374. StringBuffer xpath;
  4375. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  4376. Owned<IPropertyTree> cluster = root->getPropTree(xpath.str());
  4377. if (!cluster)
  4378. return NULL;
  4379. StringBuffer xpath1;
  4380. xpath1.appendf("%s/@process", processType);
  4381. name.append(cluster->queryProp(xpath1.str()));
  4382. return name.str();
  4383. }
  4384. unsigned getEnvironmentThorClusterNames(StringArray &thorNames, StringArray &groupNames, StringArray &targetNames, StringArray &queueNames)
  4385. {
  4386. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4387. Owned<IConstEnvironment> env = factory->openEnvironment();
  4388. if (!env)
  4389. return 0;
  4390. Owned<IPropertyTree> root = &env->getPTree();
  4391. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  4392. ForEach(*allTargets)
  4393. {
  4394. IPropertyTree &target = allTargets->query();
  4395. const char *targetName = target.queryProp("@name");
  4396. if (targetName && *targetName)
  4397. {
  4398. Owned<IPropertyTreeIterator> thorClusters = target.getElements("ThorCluster");
  4399. ForEach(*thorClusters)
  4400. {
  4401. const char *thorName = thorClusters->query().queryProp("@process");
  4402. VStringBuffer query("Software/ThorCluster[@name=\"%s\"]",thorName);
  4403. IPropertyTree *thorCluster = root->queryPropTree(query.str());
  4404. if (thorCluster)
  4405. {
  4406. const char *groupName = thorCluster->queryProp("@nodeGroup");
  4407. if (!groupName||!*groupName)
  4408. groupName = thorName;
  4409. thorNames.append(thorName);
  4410. groupNames.append(groupName);
  4411. targetNames.append(targetName);
  4412. StringBuffer queueName(targetName);
  4413. queueNames.append(queueName.append(THOR_QUEUE_EXT));
  4414. }
  4415. }
  4416. }
  4417. }
  4418. return thorNames.ordinality();
  4419. }
  4420. unsigned getEnvironmentHThorClusterNames(StringArray &eclAgentNames, StringArray &groupNames, StringArray &targetNames)
  4421. {
  4422. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4423. Owned<IConstEnvironment> env = factory->openEnvironment();
  4424. if (!env)
  4425. return 0;
  4426. Owned<IPropertyTree> root = &env->getPTree();
  4427. Owned<IPropertyTreeIterator> allEclAgents = root->getElements("Software/EclAgentProcess");
  4428. ForEach(*allEclAgents)
  4429. {
  4430. IPropertyTree &eclAgent = allEclAgents->query();
  4431. const char *eclAgentName = eclAgent.queryProp("@name");
  4432. if (eclAgentName && *eclAgentName)
  4433. {
  4434. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  4435. ForEach(*allTargets)
  4436. {
  4437. IPropertyTree &target = allTargets->query();
  4438. const char *targetName = target.queryProp("@name");
  4439. if (targetName && *targetName)
  4440. {
  4441. StringBuffer xpath;
  4442. xpath.appendf("EclAgentProcess[@process=\"%s\"]", eclAgentName);
  4443. if (target.hasProp(xpath) && !target.hasProp("ThorCluster"))
  4444. {
  4445. StringBuffer groupName("hthor__");
  4446. groupName.append(eclAgentName);
  4447. groupNames.append(groupName);
  4448. eclAgentNames.append(eclAgentName);
  4449. targetNames.append(targetName);
  4450. }
  4451. }
  4452. }
  4453. }
  4454. }
  4455. return eclAgentNames.ordinality();
  4456. }
  4457. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  4458. {
  4459. CriticalBlock block(crit);
  4460. if (p->hasProp("Debug/ForceScope"))
  4461. {
  4462. StringBuffer prefix(p->queryProp("Debug/ForceScope"));
  4463. str.set(prefix.toLowerCase().str());
  4464. }
  4465. else
  4466. {
  4467. Owned <IConstWUClusterInfo> ci = getTargetClusterInfo(p->queryProp("@clusterName"));
  4468. if (ci)
  4469. ci->getScope(str);
  4470. else
  4471. str.clear();
  4472. }
  4473. return str;
  4474. }
  4475. //Queries
  4476. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  4477. {
  4478. CriticalBlock block(crit);
  4479. p->setPropInt("@codeVersion", codeVersion);
  4480. p->setProp("@buildVersion", buildVersion);
  4481. p->setProp("@eclVersion", eclVersion);
  4482. }
  4483. unsigned CLocalWorkUnit::getCodeVersion() const
  4484. {
  4485. CriticalBlock block(crit);
  4486. return p->getPropInt("@codeVersion");
  4487. }
  4488. unsigned CLocalWorkUnit::getWuidVersion() const
  4489. {
  4490. CriticalBlock block(crit);
  4491. return p->getPropInt("@wuidVersion");
  4492. }
  4493. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  4494. {
  4495. CriticalBlock block(crit);
  4496. buildVersion.set(p->queryProp("@buildVersion"));
  4497. eclVersion.set(p->queryProp("@eclVersion"));
  4498. }
  4499. void CLocalWorkUnit::setCloneable(bool value)
  4500. {
  4501. CriticalBlock block(crit);
  4502. p->setPropInt("@cloneable", value);
  4503. }
  4504. void CLocalWorkUnit::setIsClone(bool value)
  4505. {
  4506. CriticalBlock block(crit);
  4507. p->setPropInt("@isClone", value);
  4508. }
  4509. bool CLocalWorkUnit::getCloneable() const
  4510. {
  4511. CriticalBlock block(crit);
  4512. return p->getPropBool("@cloneable", false);
  4513. }
  4514. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  4515. {
  4516. CriticalBlock block(crit);
  4517. if (!userDesc)
  4518. {
  4519. SCMStringBuffer token, user, password;
  4520. getSecurityToken(token);
  4521. extractToken(token.str(), queryWuid(), user, password);
  4522. userDesc.setown(createUserDescriptor());
  4523. userDesc->set(user.str(), password.str());
  4524. }
  4525. return userDesc;
  4526. }
  4527. bool CLocalWorkUnit::isProtected() const
  4528. {
  4529. CriticalBlock block(crit);
  4530. return p->getPropBool("@protected", false);
  4531. }
  4532. bool CLocalWorkUnit::isPausing() const
  4533. {
  4534. CriticalBlock block(crit);
  4535. if (WUActionPause == getAction())
  4536. {
  4537. switch (getState())
  4538. {
  4539. case WUStateRunning:
  4540. case WUStateAborting:
  4541. return true;
  4542. }
  4543. }
  4544. return false;
  4545. }
  4546. void CLocalWorkUnit::protect(bool protectMode)
  4547. {
  4548. CriticalBlock block(crit);
  4549. p->setPropBool("@protected", protectMode);
  4550. }
  4551. void CLocalWorkUnit::setResultLimit(unsigned value)
  4552. {
  4553. CriticalBlock block(crit);
  4554. p->setPropInt("resultLimit", value);
  4555. }
  4556. unsigned CLocalWorkUnit::getResultLimit() const
  4557. {
  4558. CriticalBlock block(crit);
  4559. return p->getPropInt("resultLimit");
  4560. }
  4561. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  4562. {
  4563. CriticalBlock block(crit);
  4564. str.set(p->queryProp("SNAPSHOT"));
  4565. return str;
  4566. }
  4567. void CLocalWorkUnit::setSnapshot(const char * val)
  4568. {
  4569. CriticalBlock block(crit);
  4570. p->setProp("SNAPSHOT", val);
  4571. }
  4572. const static mapEnums warningSeverityMap[] =
  4573. {
  4574. { SeverityInformation, "info" },
  4575. { SeverityWarning, "warning" },
  4576. { SeverityError, "error" },
  4577. { SeverityAlert, "alert" },
  4578. { SeverityIgnore, "ignore" },
  4579. { SeverityFatal, "fatal" },
  4580. { SeverityUnknown, NULL }
  4581. };
  4582. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  4583. {
  4584. StringBuffer xpath;
  4585. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  4586. CriticalBlock block(crit);
  4587. IPropertyTree * mapping = p->queryPropTree(xpath);
  4588. if (mapping)
  4589. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  4590. return defaultSeverity;
  4591. }
  4592. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  4593. {
  4594. StringBuffer xpath;
  4595. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  4596. CriticalBlock block(crit);
  4597. IPropertyTree * mapping = p->queryPropTree(xpath);
  4598. if (!mapping)
  4599. {
  4600. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  4601. mapping = onWarnings->addPropTree("OnWarning", createPTree());
  4602. mapping->setPropInt("@code", code);
  4603. }
  4604. setEnum(mapping, "@severity", severity, warningSeverityMap);
  4605. }
  4606. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  4607. {
  4608. IPropertyTree *l = (IPropertyTree *) *ll;
  4609. IPropertyTree *r = (IPropertyTree *) *rr;
  4610. return stricmp(l->queryName(), r->queryName());
  4611. };
  4612. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  4613. {
  4614. // Any other values in the WU that could affect generated code should be crc'ed here
  4615. IPropertyTree *tree = p->queryBranch("Debug");
  4616. if (tree)
  4617. {
  4618. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  4619. ICopyArrayOf<IPropertyTree> subs;
  4620. for(sub->first(); sub->isValid(); sub->next())
  4621. subs.append(sub->query());
  4622. subs.sort(comparePropTrees);
  4623. ForEachItemIn(idx, subs)
  4624. {
  4625. const char *name = subs.item(idx).queryName();
  4626. const char *val = subs.item(idx).queryProp(NULL);
  4627. crc = crc32(name, (size32_t)strlen(name), crc);
  4628. if (val)
  4629. crc = crc32(val, (size32_t)strlen(val), crc);
  4630. }
  4631. }
  4632. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  4633. for (plugins->first();plugins->isValid();plugins->next())
  4634. {
  4635. IConstWUPlugin &thisplugin = plugins->query();
  4636. SCMStringBuffer version;
  4637. thisplugin.getPluginVersion(version);
  4638. crc = crc32(version.str(), version.length(), crc);
  4639. }
  4640. return crc;
  4641. }
  4642. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  4643. {
  4644. if (!to->hasProp(xpath) && from->hasProp(xpath))
  4645. to->setProp(xpath, from->queryProp(xpath));
  4646. }
  4647. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  4648. {
  4649. if (from->hasProp(xpath))
  4650. to->setProp(xpath, from->queryProp(xpath));
  4651. }
  4652. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  4653. {
  4654. IPropertyTree * match = from->getBranch(xpath);
  4655. if (match)
  4656. to->setPropTree(xpath, match);
  4657. }
  4658. IPropertyTree *CLocalWorkUnit::queryPTree() const
  4659. {
  4660. return p;
  4661. }
  4662. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool all)
  4663. {
  4664. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  4665. if (!from)
  4666. {
  4667. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  4668. if (!fl)
  4669. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  4670. from = fl->c;
  4671. }
  4672. // Need to copy the query, the results, and the graphs from the cached query.
  4673. // The cache is made before the query is executed so there is no need to clear them.
  4674. if (!cached->getCloneable())
  4675. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  4676. const IPropertyTree * fromP = from->p;
  4677. IPropertyTree *pt;
  4678. CriticalBlock block(crit);
  4679. clearCached(false);
  4680. query.clear();
  4681. updateProp(p, fromP, "@jobName");
  4682. copyTree(p, fromP, "Query");
  4683. pt = fromP->getBranch("Application/LibraryModule");
  4684. if (pt)
  4685. {
  4686. ensurePTree(p, "Application");
  4687. p->setPropTree("Application/LibraryModule", pt);
  4688. }
  4689. pt = fromP->queryBranch("Debug");
  4690. if (pt)
  4691. {
  4692. IPropertyTree *curDebug = p->queryPropTree("Debug");
  4693. if (curDebug)
  4694. {
  4695. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  4696. ForEach(*elems)
  4697. {
  4698. IPropertyTree *elem = &elems->query();
  4699. if (!curDebug->hasProp(elem->queryName()))
  4700. curDebug->setPropTree(elem->queryName(),LINK(elem));
  4701. }
  4702. }
  4703. else
  4704. p->setPropTree("Debug", LINK(pt));
  4705. }
  4706. copyTree(p, fromP, "OnWarnings");
  4707. copyTree(p, fromP, "Plugins");
  4708. copyTree(p, fromP, "Libraries");
  4709. copyTree(p, fromP, "Results");
  4710. copyTree(p, fromP, "Graphs");
  4711. copyTree(p, fromP, "Workflow");
  4712. copyTree(p, fromP, "WebServicesInfo");
  4713. if (all)
  4714. {
  4715. // 'all' mode is used when setting up a dali WU from the embedded wu in a workunit dll
  4716. // Merge timing info from both branches
  4717. pt = fromP->getBranch("Timings");
  4718. if (pt)
  4719. {
  4720. IPropertyTree *tgtTimings = ensurePTree(p, "Timings");
  4721. mergePTree(tgtTimings, pt);
  4722. pt->Release();
  4723. }
  4724. pt = fromP->getBranch("Statistics");
  4725. if (pt)
  4726. {
  4727. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  4728. mergePTree(tgtStatistics, pt);
  4729. pt->Release();
  4730. }
  4731. }
  4732. updateProp(p, fromP, "@clusterName");
  4733. updateProp(p, fromP, "allowedclusters");
  4734. updateProp(p, fromP, "@submitID");
  4735. updateProp(p, fromP, "SNAPSHOT");
  4736. setProp(p, fromP, "@eventScheduledCount");
  4737. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  4738. if (all)
  4739. {
  4740. setProp(p, fromP, "PriorityFlag");
  4741. setProp(p, fromP, "@priorityClass");
  4742. setProp(p, fromP, "@protected");
  4743. setProp(p, fromP, "@clusterName");
  4744. updateProp(p, fromP, "@scope");
  4745. }
  4746. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  4747. pt = fromP->getBranch("Variables");
  4748. if (pt)
  4749. {
  4750. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  4751. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  4752. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  4753. {
  4754. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  4755. const char *name = ptSrcVariable->queryProp("@name");
  4756. assertex(name);
  4757. StringBuffer xpath;
  4758. xpath.append("Variable[@name='").append(name).append("']");
  4759. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  4760. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  4761. merged->removeProp("Value"); // except value and status
  4762. merged->setProp("@status", "undefined");
  4763. if (!merged->getPropBool("@isScalar"))
  4764. merged->removeProp("totalRowCount");
  4765. merged->removeProp("rowCount");
  4766. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  4767. if (ptTgtVariable)
  4768. {
  4769. // copy status and Value from what is already set in target
  4770. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  4771. MemoryBuffer value;
  4772. if (ptTgtVariable->getPropBin("Value", value))
  4773. merged->setPropBin("Value", value.length(), value.toByteArray());
  4774. ptTgtVariable->removeProp(xpath.str());
  4775. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  4776. }
  4777. ptTgtVariables->addPropTree("Variable", merged);
  4778. }
  4779. pt->Release();
  4780. }
  4781. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  4782. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  4783. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  4784. p->setProp("@hash", fromP->queryProp("@hash"));
  4785. p->setPropBool("@cloneable", true);
  4786. p->setPropBool("@isClone", true);
  4787. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  4788. // resetResults(); // probably should be resetting the results as well... rather than waiting for the rerun to overwrite them
  4789. }
  4790. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  4791. {
  4792. StringBuffer lower;
  4793. lower.append(propname).toLowerCase();
  4794. CriticalBlock block(crit);
  4795. StringBuffer prop("Debug/");
  4796. return p->hasProp(prop.append(lower));
  4797. }
  4798. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  4799. {
  4800. StringBuffer lower;
  4801. lower.append(propname).toLowerCase();
  4802. CriticalBlock block(crit);
  4803. StringBuffer prop("Debug/");
  4804. str.set(p->queryProp(prop.append(lower).str()));
  4805. return str;
  4806. }
  4807. IStringIterator& CLocalWorkUnit::getDebugValues() const
  4808. {
  4809. return getDebugValues(NULL);
  4810. }
  4811. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  4812. {
  4813. CriticalBlock block(crit);
  4814. StringBuffer path("Debug/");
  4815. if (prop)
  4816. {
  4817. StringBuffer lower;
  4818. lower.append(prop).toLowerCase();
  4819. path.append(lower);
  4820. }
  4821. else
  4822. path.append("*");
  4823. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  4824. }
  4825. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  4826. {
  4827. StringBuffer lower;
  4828. lower.append(propname).toLowerCase();
  4829. CriticalBlock block(crit);
  4830. StringBuffer prop("Debug/");
  4831. prop.append(lower);
  4832. return p->getPropInt(prop.str(), defVal);
  4833. }
  4834. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  4835. {
  4836. StringBuffer lower;
  4837. lower.append(propname).toLowerCase();
  4838. CriticalBlock block(crit);
  4839. StringBuffer prop("Debug/");
  4840. prop.append(lower);
  4841. return p->getPropInt64(prop.str(), defVal);
  4842. }
  4843. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  4844. {
  4845. StringBuffer lower;
  4846. lower.append(propname).toLowerCase();
  4847. CriticalBlock block(crit);
  4848. StringBuffer prop("Debug/");
  4849. prop.append(lower);
  4850. return p->getPropBool(prop.str(), defVal);
  4851. }
  4852. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  4853. {
  4854. VStringBuffer xpath("Process/%s/", type);
  4855. if (instance)
  4856. xpath.append(instance);
  4857. else
  4858. xpath.append("*");
  4859. CriticalBlock block(crit);
  4860. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  4861. {
  4862. // NB: instance unused
  4863. if (streq("EclAgent", type))
  4864. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  4865. else if (streq("Thor", type))
  4866. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  4867. VStringBuffer xpath("Debug/%s", type);
  4868. return new CStringPTreeIterator(p->getElements(xpath.str()));
  4869. }
  4870. else
  4871. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  4872. }
  4873. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  4874. {
  4875. VStringBuffer xpath("Process/%s/", type);
  4876. if (instance)
  4877. xpath.append(instance);
  4878. else
  4879. xpath.append("*");
  4880. CriticalBlock block(crit);
  4881. return p->getElements(xpath.str());
  4882. }
  4883. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  4884. {
  4885. VStringBuffer xpath("Process/%s/*", type);
  4886. CriticalBlock block(crit);
  4887. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  4888. }
  4889. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  4890. {
  4891. VStringBuffer processType("Process/%s", type);
  4892. VStringBuffer xpath("%s/%s", processType.str(), instance);
  4893. if (log)
  4894. xpath.appendf("[@log=\"%s\"]", log);
  4895. CriticalBlock block(crit);
  4896. if (!p->hasProp(xpath))
  4897. {
  4898. IPropertyTree *node = ensurePTree(p, processType.str());
  4899. node = node->addPropTree(instance, createPTree());
  4900. node->setProp("@log", log);
  4901. node->setPropInt("@pid", pid);
  4902. }
  4903. }
  4904. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  4905. {
  4906. StringBuffer lower;
  4907. lower.append(propname).toLowerCase();
  4908. CriticalBlock block(crit);
  4909. StringBuffer prop("Debug/");
  4910. prop.append(lower);
  4911. if (overwrite || !p->hasProp(prop.str()))
  4912. {
  4913. // MORE - not sure this line should be needed....
  4914. p->setProp("Debug", "");
  4915. p->setProp(prop.str(), value);
  4916. }
  4917. }
  4918. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  4919. {
  4920. StringBuffer lower;
  4921. lower.append(propname).toLowerCase();
  4922. CriticalBlock block(crit);
  4923. StringBuffer prop("Debug/");
  4924. prop.append(lower);
  4925. if (overwrite || !p->hasProp(prop.str()))
  4926. {
  4927. // MORE - not sure this line should be needed....
  4928. p->setProp("Debug", "");
  4929. p->setPropInt(prop.str(), value);
  4930. }
  4931. }
  4932. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  4933. {
  4934. CriticalBlock block(crit);
  4935. // MORE - not sure this line should be needed....
  4936. p->setProp("Tracing", "");
  4937. StringBuffer prop("Tracing/");
  4938. p->setProp(prop.append(propname).str(), value);
  4939. }
  4940. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  4941. {
  4942. CriticalBlock block(crit);
  4943. StringBuffer prop("Tracing/");
  4944. p->setPropInt(prop.append(propname).str(), value);
  4945. }
  4946. IConstWUQuery* CLocalWorkUnit::getQuery() const
  4947. {
  4948. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  4949. CriticalBlock block(crit);
  4950. if (!query)
  4951. {
  4952. IPropertyTree *s = p->getPropTree("Query");
  4953. if (s)
  4954. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  4955. }
  4956. return query.getLink();
  4957. }
  4958. IWUQuery* CLocalWorkUnit::updateQuery()
  4959. {
  4960. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  4961. CriticalBlock block(crit);
  4962. if (!query)
  4963. {
  4964. IPropertyTree *s = p->queryPropTree("Query");
  4965. if (!s)
  4966. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  4967. s->Link();
  4968. query.setown(new CLocalWUQuery(s));
  4969. }
  4970. return query.getLink();
  4971. }
  4972. void CLocalWorkUnit::loadPlugins() const
  4973. {
  4974. CriticalBlock block(crit);
  4975. if (!pluginsCached)
  4976. {
  4977. assertex(plugins.length() == 0);
  4978. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  4979. for (r->first(); r->isValid(); r->next())
  4980. {
  4981. IPropertyTree *rp = &r->query();
  4982. rp->Link();
  4983. plugins.append(*new CLocalWUPlugin(rp));
  4984. }
  4985. pluginsCached = true;
  4986. }
  4987. }
  4988. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  4989. {
  4990. CriticalBlock block(crit);
  4991. loadPlugins();
  4992. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  4993. }
  4994. void CLocalWorkUnit::loadLibraries() const
  4995. {
  4996. CriticalBlock block(crit);
  4997. if (!librariesCached)
  4998. {
  4999. assertex(libraries.length() == 0);
  5000. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  5001. ForEach(*r)
  5002. {
  5003. IPropertyTree *rp = &r->query();
  5004. rp->Link();
  5005. libraries.append(*new CLocalWULibrary(rp));
  5006. }
  5007. librariesCached = true;
  5008. }
  5009. }
  5010. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  5011. {
  5012. CriticalBlock block(crit);
  5013. loadLibraries();
  5014. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  5015. }
  5016. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  5017. {
  5018. CriticalBlock block(crit);
  5019. loadLibraries();
  5020. ForEachItemIn(idx, libraries)
  5021. {
  5022. SCMStringBuffer name;
  5023. IConstWULibrary &cur = libraries.item(idx);
  5024. cur.getName(name);
  5025. if (stricmp(name.str(), search)==0)
  5026. return &OLINK(cur);
  5027. }
  5028. return NULL;
  5029. }
  5030. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  5031. {
  5032. str.append("Graph ").append(graphName);
  5033. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  5034. else if (subId) str.append(" - id(").append(subId).append(")");
  5035. return str;
  5036. }
  5037. StringBuffer &formatGraphTimerScope(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  5038. {
  5039. str.append(graphName);
  5040. if (subId) str.append(":sg").append(subId);
  5041. return str;
  5042. }
  5043. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  5044. {
  5045. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  5046. unsigned len = (size32_t)strlen(label);
  5047. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  5048. return false;
  5049. graphNum = 0;
  5050. subGraphNum = 0;
  5051. subId = 0;
  5052. const char *finger = label+6;
  5053. const char *finger2 = strchr(finger, '-');
  5054. if (NULL == finger2) // just graphName
  5055. graphName.set(finger);
  5056. else
  5057. {
  5058. graphName.set(finger, (size32_t)((finger2-1)-finger));
  5059. finger = finger2+2; // skip '-' and space
  5060. finger2 = strchr(finger, ' ');
  5061. if (finger2)
  5062. {
  5063. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  5064. finger = finger2+2; // skip space and '('
  5065. finger2 = strchr(finger, ')');
  5066. if (finger2)
  5067. subId = atoi_l(finger, (size32_t)(finger2-finger));
  5068. }
  5069. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  5070. {
  5071. finger += 3;
  5072. finger2 = strchr(finger, ')');
  5073. if (finger2)
  5074. subId = atoi_l(finger, (size32_t)(finger2-finger));
  5075. }
  5076. }
  5077. if (graphName && !memicmp(graphName, "graph", 5))
  5078. graphNum = atoi(graphName + 5);
  5079. return true;
  5080. }
  5081. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  5082. {
  5083. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  5084. return false;
  5085. graphNum = atoi(scope + CONST_STRLEN(GraphScopePrefix));
  5086. subGraphId = 0;
  5087. const char * colon = strchr(scope, ':');
  5088. if (!colon)
  5089. {
  5090. graphName.set(scope);
  5091. return true;
  5092. }
  5093. const char * subgraph = colon+1;
  5094. graphName.set(scope, (size32_t)(colon - scope));
  5095. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  5096. subGraphId = atoi(subgraph+CONST_STRLEN(SubGraphScopePrefix));
  5097. return true;
  5098. }
  5099. class WorkUnitStatisticsIterator : public CArrayIteratorOf<IConstWUStatistic,IConstWUStatisticIterator>
  5100. {
  5101. typedef CArrayIteratorOf<IConstWUStatistic,IConstWUStatisticIterator> PARENT;
  5102. public:
  5103. WorkUnitStatisticsIterator(const IArray &a, aindex_t start, IInterface *owner, const IStatisticsFilter * _filter)
  5104. : PARENT(a,start, owner), filter(_filter)
  5105. {
  5106. }
  5107. virtual bool first()
  5108. {
  5109. if (!PARENT::first())
  5110. return false;
  5111. if (matchesFilter())
  5112. return true;
  5113. return next();
  5114. }
  5115. virtual bool next()
  5116. {
  5117. loop
  5118. {
  5119. if (!PARENT::next())
  5120. return false;
  5121. if (matchesFilter())
  5122. return true;
  5123. }
  5124. }
  5125. protected:
  5126. bool matchesFilter()
  5127. {
  5128. if (!filter)
  5129. return true;
  5130. return query().matches(filter);
  5131. }
  5132. protected:
  5133. Linked<const IStatisticsFilter> filter;
  5134. };
  5135. 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)
  5136. {
  5137. if (!scope || !*scope) scope = GLOBAL_SCOPE;
  5138. const char * kindName = queryStatisticName(kind);
  5139. StatisticMeasure measure = queryMeasure(kind);
  5140. //creator. scope and name must all be present, and must not contain semi colons.
  5141. assertex(creator && scope);
  5142. CriticalBlock block(crit);
  5143. IPropertyTree * stats = p->queryPropTree("Statistics");
  5144. if (!stats)
  5145. stats = p->addPropTree("Statistics", createPTree("Statistics"));
  5146. IPropertyTree * statTree = NULL;
  5147. if (mergeAction != StatsMergeAppend)
  5148. {
  5149. StringBuffer xpath;
  5150. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  5151. statTree = stats->queryPropTree(xpath.str());
  5152. }
  5153. if (!statTree)
  5154. {
  5155. statTree = stats->addPropTree("Statistic", createPTree("Statistic"));
  5156. statTree->setProp("@creator", creator);
  5157. statTree->setProp("@scope", scope);
  5158. statTree->setProp("@kind", kindName);
  5159. //These items are primarily here to facilitate filtering.
  5160. statTree->setProp("@unit", queryMeasureName(measure));
  5161. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  5162. statTree->setProp("@s", queryScopeTypeName(scopeType));
  5163. statTree->setPropInt64("@ts", getTimeStampNowValue());
  5164. if (optDescription)
  5165. statTree->setProp("@desc", optDescription);
  5166. if (statistics.cached)
  5167. statistics.append(LINK(statTree));
  5168. mergeAction = StatsMergeAppend;
  5169. }
  5170. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  5171. {
  5172. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  5173. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  5174. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  5175. if (oldMax < oldValue)
  5176. oldMax = oldValue;
  5177. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  5178. statTree->setPropInt64("@count", count + oldCount);
  5179. if (maxValue > oldMax)
  5180. statTree->setPropInt64("@max", maxValue);
  5181. }
  5182. else
  5183. {
  5184. statTree->setPropInt64("@value", value);
  5185. statTree->setPropInt64("@count", count);
  5186. if (maxValue)
  5187. statTree->setPropInt64("@max", maxValue);
  5188. else
  5189. statTree->removeProp("@max");
  5190. }
  5191. if (creatorType==SCTsummary && kind==StTimeElapsed && strsame(scope, GLOBAL_SCOPE))
  5192. {
  5193. StringBuffer t;
  5194. formatTimeCollatable(t, value, false);
  5195. p->setProp("@totalThorTime", t);
  5196. }
  5197. }
  5198. void CLocalWorkUnit::_loadStatistics() const
  5199. {
  5200. statistics.load(p,"Statistics/*");
  5201. }
  5202. IConstWUStatisticIterator& CLocalWorkUnit::getStatistics(const IStatisticsFilter * filter) const
  5203. {
  5204. CriticalBlock block(crit);
  5205. //This should be deleted in version 6.0 when support for 4.x is no longer required
  5206. legacyTimings.load(p,"Timings/*");
  5207. if (legacyTimings.ordinality())
  5208. return *new WorkUnitStatisticsIterator(legacyTimings, 0, (IConstWorkUnit *) this, filter);
  5209. statistics.load(p,"Statistics/*");
  5210. Owned<IConstWUStatisticIterator> localStats = new WorkUnitStatisticsIterator(statistics, 0, (IConstWorkUnit *) this, filter);
  5211. const char * wuid = p->queryName();
  5212. Owned<IConstWUStatisticIterator> graphStats = new CConstGraphProgressStatisticsIterator(wuid, filter);
  5213. return * new CCompoundIteratorOf<IConstWUStatisticIterator, IConstWUStatistic>(localStats, graphStats);
  5214. }
  5215. IConstWUStatistic * CLocalWorkUnit::getStatistic(const char * creator, const char * scope, StatisticKind kind) const
  5216. {
  5217. //MORE: Optimize this....
  5218. StatisticsFilter filter;
  5219. filter.setCreator(creator);
  5220. filter.setScope(scope);
  5221. filter.setKind(kind);
  5222. Owned<IConstWUStatisticIterator> stats = &getStatistics(&filter);
  5223. if (stats->first())
  5224. return LINK(&stats->query());
  5225. return NULL;
  5226. }
  5227. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  5228. {
  5229. CriticalBlock block(crit);
  5230. IConstWUPlugin *existing = getPluginByName(qname);
  5231. if (existing)
  5232. return (IWUPlugin *) existing;
  5233. if (!plugins.length())
  5234. p->addPropTree("Plugins", createPTree("Plugins"));
  5235. IPropertyTree *pl = p->queryPropTree("Plugins");
  5236. IPropertyTree *s = pl->addPropTree("Plugin", createPTree("Plugin"));
  5237. s->Link();
  5238. IWUPlugin* q = new CLocalWUPlugin(s);
  5239. q->Link();
  5240. plugins.append(*q);
  5241. q->setPluginName(qname);
  5242. return q;
  5243. }
  5244. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  5245. {
  5246. CriticalBlock block(crit);
  5247. loadPlugins();
  5248. ForEachItemIn(idx, plugins)
  5249. {
  5250. SCMStringBuffer name;
  5251. IConstWUPlugin &cur = plugins.item(idx);
  5252. cur.getPluginName(name);
  5253. if (stricmp(name.str(), qname)==0)
  5254. {
  5255. cur.Link();
  5256. return &cur;
  5257. }
  5258. }
  5259. return NULL;
  5260. }
  5261. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  5262. {
  5263. CriticalBlock block(crit);
  5264. IConstWULibrary *existing = getLibraryByName(qname);
  5265. if (existing)
  5266. return (IWULibrary *) existing;
  5267. if (!libraries.length())
  5268. p->addPropTree("Libraries", createPTree("Libraries"));
  5269. IPropertyTree *pl = p->queryPropTree("Libraries");
  5270. IPropertyTree *s = pl->addPropTree("Library", createPTree("Library"));
  5271. s->Link();
  5272. IWULibrary* q = new CLocalWULibrary(s);
  5273. q->Link();
  5274. libraries.append(*q);
  5275. q->setName(qname);
  5276. return q;
  5277. }
  5278. void CLocalWorkUnit::_loadExceptions() const
  5279. {
  5280. assertex(exceptions.length() == 0);
  5281. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  5282. for (r->first(); r->isValid(); r->next())
  5283. {
  5284. IPropertyTree *rp = &r->query();
  5285. rp->Link();
  5286. exceptions.append(*new CLocalWUException(rp));
  5287. }
  5288. }
  5289. void CLocalWorkUnit::loadExceptions() const
  5290. {
  5291. CriticalBlock block(crit);
  5292. if (!exceptionsCached)
  5293. {
  5294. _loadExceptions();
  5295. exceptionsCached = true;
  5296. }
  5297. }
  5298. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  5299. {
  5300. CriticalBlock block(crit);
  5301. loadExceptions();
  5302. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  5303. }
  5304. unsigned CLocalWorkUnit::getExceptionCount() const
  5305. {
  5306. CriticalBlock block(crit);
  5307. loadExceptions();
  5308. return exceptions.length();
  5309. }
  5310. void CLocalWorkUnit::clearExceptions()
  5311. {
  5312. CriticalBlock block(crit);
  5313. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5314. exceptions.kill();
  5315. exceptionsCached = true;
  5316. p->removeProp("Exceptions");
  5317. }
  5318. IWUException* CLocalWorkUnit::createException()
  5319. {
  5320. CriticalBlock block(crit);
  5321. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5322. loadExceptions();
  5323. if (!exceptions.length())
  5324. p->addPropTree("Exceptions", createPTree("Exceptions"));
  5325. IPropertyTree *r = p->queryPropTree("Exceptions");
  5326. IPropertyTree *s = r->addPropTree("Exception", createPTree("Exception"));
  5327. s->setPropInt("@sequence", exceptions.ordinality());
  5328. IWUException* q = new CLocalWUException(LINK(s));
  5329. exceptions.append(*LINK(q));
  5330. Owned<IJlibDateTime> now = createDateTimeNow();
  5331. SCMStringBuffer temp;
  5332. now->getString(temp);
  5333. q->setTimeStamp(temp.str());
  5334. return q;
  5335. }
  5336. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  5337. {
  5338. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  5339. CriticalBlock block(crit);
  5340. if (!webServicesInfoCached)
  5341. {
  5342. assertex(!webServicesInfo);
  5343. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  5344. if (s)
  5345. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  5346. webServicesInfoCached = true;
  5347. }
  5348. return webServicesInfo.getLink();
  5349. }
  5350. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  5351. {
  5352. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5353. CriticalBlock block(crit);
  5354. if (!webServicesInfoCached)
  5355. {
  5356. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  5357. if (!s)
  5358. {
  5359. if (create)
  5360. s = p->addPropTree("WebServicesInfo", createPTreeFromXMLString("<WebServicesInfo />"));
  5361. else
  5362. return NULL;
  5363. }
  5364. s->Link();
  5365. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  5366. webServicesInfoCached = true;
  5367. }
  5368. return webServicesInfo.getLink();
  5369. }
  5370. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  5371. {
  5372. CLocalWUResult *l = (CLocalWUResult *) *ll;
  5373. CLocalWUResult *r = (CLocalWUResult *) *rr;
  5374. return l->getResultSequence() - r->getResultSequence();
  5375. }
  5376. void CLocalWorkUnit::_loadResults() const
  5377. {
  5378. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  5379. for (r->first(); r->isValid(); r->next())
  5380. {
  5381. IPropertyTree *rp = &r->query();
  5382. rp->Link();
  5383. results.append(*new CLocalWUResult(rp));
  5384. }
  5385. }
  5386. void CLocalWorkUnit::loadResults() const
  5387. {
  5388. if (!resultsCached)
  5389. {
  5390. assertex(results.length() == 0);
  5391. _loadResults();
  5392. results.sort(compareResults);
  5393. resultsCached = true;
  5394. }
  5395. }
  5396. void CLocalWorkUnit::_loadVariables() const
  5397. {
  5398. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  5399. for (r->first(); r->isValid(); r->next())
  5400. {
  5401. IPropertyTree *rp = &r->query();
  5402. rp->Link();
  5403. variables.append(*new CLocalWUResult(rp));
  5404. }
  5405. }
  5406. void CLocalWorkUnit::loadVariables() const
  5407. {
  5408. if (!variablesCached)
  5409. {
  5410. assertex(variables.length() == 0);
  5411. _loadVariables();
  5412. variablesCached = true;
  5413. }
  5414. }
  5415. void CLocalWorkUnit::_loadTemporaries() const
  5416. {
  5417. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  5418. for (r->first(); r->isValid(); r->next())
  5419. {
  5420. IPropertyTree *rp = &r->query();
  5421. rp->Link();
  5422. temporaries.append(*new CLocalWUResult(rp));
  5423. }
  5424. }
  5425. void CLocalWorkUnit::loadTemporaries() const
  5426. {
  5427. if (!temporariesCached)
  5428. {
  5429. assertex(temporaries.length() == 0);
  5430. _loadTemporaries();
  5431. temporariesCached = true;
  5432. }
  5433. }
  5434. void CLocalWorkUnit::deleteTemporaries()
  5435. {
  5436. CriticalBlock block(crit);
  5437. if (temporariesCached)
  5438. {
  5439. temporaries.kill();
  5440. temporariesCached = false;
  5441. }
  5442. p->removeProp("Temporaries");
  5443. }
  5444. IWUResult* CLocalWorkUnit::createResult()
  5445. {
  5446. CriticalBlock block(crit);
  5447. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5448. loadResults();
  5449. if (!results.length())
  5450. p->addPropTree("Results", createPTree("Results"));
  5451. IPropertyTree *r = p->queryPropTree("Results");
  5452. IPropertyTree *s = r->addPropTree("Result", createPTree());
  5453. s->Link();
  5454. IWUResult* q = new CLocalWUResult(s);
  5455. q->Link();
  5456. results.append(*q);
  5457. return q;
  5458. }
  5459. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  5460. {
  5461. CriticalBlock block(crit);
  5462. IConstWUResult *existing = getResultByName(qname);
  5463. if (existing)
  5464. return (IWUResult *) existing;
  5465. IWUResult* q = createResult();
  5466. q->setResultName(qname);
  5467. return q;
  5468. }
  5469. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  5470. {
  5471. CriticalBlock block(crit);
  5472. IConstWUResult *existing = getResultBySequence(seq);
  5473. if (existing)
  5474. return (IWUResult *) existing;
  5475. IWUResult* q = createResult();
  5476. q->setResultSequence(seq);
  5477. return q;
  5478. }
  5479. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  5480. {
  5481. CriticalBlock block(crit);
  5482. loadResults();
  5483. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  5484. }
  5485. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  5486. {
  5487. CriticalBlock block(crit);
  5488. loadResults();
  5489. ForEachItemIn(idx, results)
  5490. {
  5491. SCMStringBuffer name;
  5492. IConstWUResult &cur = results.item(idx);
  5493. cur.getResultName(name);
  5494. if (stricmp(name.str(), qname)==0)
  5495. {
  5496. cur.Link();
  5497. return &cur;
  5498. }
  5499. }
  5500. return NULL;
  5501. }
  5502. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  5503. {
  5504. CriticalBlock block(crit);
  5505. loadResults();
  5506. ForEachItemIn(idx, results)
  5507. {
  5508. IConstWUResult &cur = results.item(idx);
  5509. if (cur.getResultSequence() == seq)
  5510. {
  5511. cur.Link();
  5512. return &cur;
  5513. }
  5514. }
  5515. return NULL;
  5516. }
  5517. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  5518. {
  5519. CriticalBlock block(crit);
  5520. loadVariables();
  5521. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  5522. }
  5523. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  5524. {
  5525. CriticalBlock block(crit);
  5526. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  5527. return getVariableByName(qname);
  5528. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  5529. return global->getVariableByName(qname);
  5530. }
  5531. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  5532. {
  5533. CriticalBlock block(crit);
  5534. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  5535. return updateVariableByName(qname);
  5536. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  5537. return global->updateVariableByName(qname);
  5538. }
  5539. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  5540. {
  5541. CriticalBlock block(crit);
  5542. loadVariables();
  5543. ForEachItemIn(idx, variables)
  5544. {
  5545. SCMStringBuffer name;
  5546. IConstWUResult &cur = variables.item(idx);
  5547. cur.getResultName(name);
  5548. if (stricmp(name.str(), qname)==0)
  5549. {
  5550. cur.Link();
  5551. return &cur;
  5552. }
  5553. }
  5554. return NULL;
  5555. }
  5556. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  5557. {
  5558. CriticalBlock block(crit);
  5559. loadTemporaries();
  5560. ForEachItemIn(idx, temporaries)
  5561. {
  5562. SCMStringBuffer name;
  5563. IConstWUResult &cur = temporaries.item(idx);
  5564. cur.getResultName(name);
  5565. if (stricmp(name.str(), qname)==0)
  5566. {
  5567. cur.Link();
  5568. return &cur;
  5569. }
  5570. }
  5571. return NULL;
  5572. }
  5573. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  5574. {
  5575. CriticalBlock block(crit);
  5576. loadTemporaries();
  5577. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  5578. }
  5579. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  5580. {
  5581. CriticalBlock block(crit);
  5582. IConstWUResult *existing = getTemporaryByName(qname);
  5583. if (existing)
  5584. return (IWUResult *) existing;
  5585. if (!temporaries.length())
  5586. p->addPropTree("Temporaries", createPTree("Temporaries"));
  5587. IPropertyTree *vars = p->queryPropTree("Temporaries");
  5588. IPropertyTree *s = vars->addPropTree("Variable", createPTree("Variable"));
  5589. s->Link();
  5590. IWUResult* q = new CLocalWUResult(s);
  5591. q->Link();
  5592. temporaries.append(*q);
  5593. q->setResultName(qname);
  5594. q->setResultSequence(ResultSequenceInternal);
  5595. return q;
  5596. }
  5597. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  5598. {
  5599. CriticalBlock block(crit);
  5600. IConstWUResult *existing = getVariableByName(qname);
  5601. if (existing)
  5602. return (IWUResult *) existing;
  5603. if (!variables.length())
  5604. p->addPropTree("Variables", createPTree("Variables"));
  5605. IPropertyTree *vars = p->queryPropTree("Variables");
  5606. IPropertyTree *s = vars->addPropTree("Variable", createPTree("Variable"));
  5607. s->Link();
  5608. IWUResult* q = new CLocalWUResult(s);
  5609. q->Link();
  5610. variables.append(*q);
  5611. q->setResultName(qname);
  5612. q->setResultSequence(ResultSequenceStored);
  5613. return q;
  5614. }
  5615. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  5616. {
  5617. CriticalBlock block(crit);
  5618. IPropertyTree *files = p->queryPropTree("Files");
  5619. if (!files) return;
  5620. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  5621. ICopyArrayOf<IPropertyTree> toRemove;
  5622. ForEach (*iter)
  5623. {
  5624. IPropertyTree &file = iter->query();
  5625. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  5626. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  5627. bool needDelete;
  5628. switch(fileKind)
  5629. {
  5630. case WUFileTemporary:
  5631. if(graph==NULL)
  5632. needDelete = true;
  5633. else
  5634. {
  5635. const char *graphOwner = file.queryProp("@graph");
  5636. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  5637. }
  5638. break;
  5639. case WUFileJobOwned:
  5640. needDelete = ((graph==NULL) && deleteJobOwned);
  5641. break;
  5642. case WUFileOwned:
  5643. needDelete = ((graph==NULL) && deleteOwned);
  5644. break;
  5645. default:
  5646. needDelete = false;
  5647. }
  5648. if(needDelete)
  5649. {
  5650. const char *name = file.queryProp("@name");
  5651. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  5652. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  5653. toRemove.append(file);
  5654. }
  5655. }
  5656. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  5657. }
  5658. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  5659. {
  5660. IDistributedSuperFile *super = file->querySuperFile();
  5661. StringBuffer fname;
  5662. file->getLogicalName(fname);
  5663. if (fname.length())
  5664. {
  5665. StringBuffer path("File[@name=\"");
  5666. path.append(fname).append("\"]");
  5667. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  5668. if (fileTree)
  5669. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  5670. else
  5671. {
  5672. StringBuffer cluster;
  5673. file->getClusterName(0,cluster);
  5674. fileTree = createPTree();
  5675. fileTree->setProp("@name", fname.str());
  5676. fileTree->setProp("@cluster", cluster.str());
  5677. fileTree->setPropInt("@useCount", 1);
  5678. fileTree = filesRead->addPropTree("File", fileTree);
  5679. }
  5680. if (super)
  5681. {
  5682. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  5683. ForEach (*iter)
  5684. {
  5685. IDistributedFile &file = iter->query();
  5686. StringBuffer fname;
  5687. file.getLogicalName(fname);
  5688. Owned<IPropertyTree> subfile = createPTree();
  5689. subfile->setProp("@name", fname.str());
  5690. fileTree->addPropTree("Subfile", subfile.getClear());
  5691. _noteFileRead(&file, filesRead);
  5692. }
  5693. }
  5694. }
  5695. }
  5696. void CLocalWorkUnit::_loadFilesRead() const
  5697. {
  5698. // Nothing to do
  5699. }
  5700. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  5701. {
  5702. if (file)
  5703. {
  5704. CriticalBlock block(crit);
  5705. IPropertyTree *files = p->queryPropTree("FilesRead");
  5706. if (!files)
  5707. files = p->addPropTree("FilesRead", createPTree());
  5708. _noteFileRead(file, files);
  5709. }
  5710. }
  5711. void CLocalWorkUnit::_loadFilesWritten() const
  5712. {
  5713. // Nothing to do
  5714. }
  5715. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  5716. {
  5717. StringBuffer path("File[@name=\"");
  5718. path.append(fileName).append("\"]");
  5719. if (cluster)
  5720. path.append("[@cluster=\"").append(cluster).append("\"]");
  5721. IPropertyTree *file = files->queryPropTree(path.str());
  5722. if (file) files->removeTree(file);
  5723. file = createPTree();
  5724. file->setProp("@name", fileName);
  5725. if (cluster)
  5726. file->setProp("@cluster", cluster);
  5727. if (graphOwner)
  5728. file->setProp("@graph", graphOwner);
  5729. file->setPropInt("@kind", (unsigned)fileKind);
  5730. if (WUFileTemporary == fileKind)
  5731. file->setPropInt("@usageCount", usageCount);
  5732. files->addPropTree("File", file);
  5733. }
  5734. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  5735. {
  5736. CriticalBlock block(crit);
  5737. IPropertyTree *files = p->queryPropTree("Files");
  5738. if (!files)
  5739. files = p->addPropTree("Files", createPTree());
  5740. if (!clusters)
  5741. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  5742. else
  5743. {
  5744. ForEachItemIn(c, *clusters)
  5745. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  5746. }
  5747. }
  5748. void CLocalWorkUnit::releaseFile(const char *fileName)
  5749. {
  5750. StringBuffer path("File[@name=\"");
  5751. path.append(fileName).append("\"]");
  5752. CriticalBlock block(crit);
  5753. IPropertyTree *files = p->queryPropTree("Files");
  5754. if (!files) return;
  5755. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  5756. ForEach (*fiter)
  5757. {
  5758. IPropertyTree *file = &fiter->query();
  5759. unsigned usageCount = file->getPropInt("@usageCount");
  5760. if (usageCount > 1)
  5761. file->setPropInt("@usageCount", usageCount-1);
  5762. else
  5763. {
  5764. StringAttr name(file->queryProp("@name"));
  5765. files->removeTree(file);
  5766. if (!name.isEmpty()&&(1 == usageCount))
  5767. {
  5768. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  5769. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  5770. }
  5771. }
  5772. }
  5773. }
  5774. void CLocalWorkUnit::clearGraphProgress() const
  5775. {
  5776. }
  5777. void CLocalWorkUnit::resetBeforeGeneration()
  5778. {
  5779. CriticalBlock block(crit);
  5780. //Remove all associated files
  5781. Owned<IWUQuery> q = updateQuery();
  5782. q->removeAssociatedFiles();
  5783. //Remove any pre-existing workflow information
  5784. workflowIterator.clear();
  5785. p->removeProp("Workflow");
  5786. }
  5787. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  5788. {
  5789. StringBuffer path("Files/File[@name=\"");
  5790. path.append(fileName).append("\"]/@usageCount");
  5791. CriticalBlock block(crit);
  5792. return p->getPropInt(path.str());
  5793. }
  5794. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  5795. {
  5796. return p->getPropTree("DiskUsageStats");
  5797. }
  5798. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  5799. {
  5800. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  5801. offset_t maxNodeUsage;
  5802. if (stats)
  5803. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  5804. else
  5805. {
  5806. stats = p->addPropTree("DiskUsageStats", createPTree());
  5807. maxNodeUsage = 0;
  5808. }
  5809. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  5810. {
  5811. // record all details at time of max node usage.
  5812. stats->setPropInt("@minNode", _minNode);
  5813. stats->setPropInt("@maxNode", _maxNode);
  5814. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  5815. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  5816. stats->setPropInt64("@graphId", _graphId);
  5817. if (_avgNodeUsage)
  5818. {
  5819. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  5820. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  5821. stats->setPropInt("@skewHi", _skewHi);
  5822. stats->setPropInt("@skewLo", _skewLo);
  5823. }
  5824. }
  5825. }
  5826. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  5827. {
  5828. CriticalBlock block(crit);
  5829. _loadFilesWritten();
  5830. return * p->getElements("Files/File");
  5831. }
  5832. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  5833. {
  5834. CriticalBlock block(crit);
  5835. _loadFilesRead();
  5836. return * p->getElements("FilesRead/File");
  5837. }
  5838. //=================================================================================================
  5839. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  5840. {
  5841. CriticalBlock block(crit);
  5842. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  5843. return false;
  5844. Owned<IConstWUClusterInfo> newci = getTargetClusterInfo(cluster);
  5845. if (!newci)
  5846. return false;
  5847. StringBuffer currentcluster;
  5848. if (!p->getProp("@clusterName",currentcluster))
  5849. return false;
  5850. Owned<IConstWUClusterInfo> curci = getTargetClusterInfo(currentcluster.str());
  5851. if (!curci)
  5852. return false;
  5853. SCMStringBuffer curqname;
  5854. curci->getThorQueue(curqname);
  5855. const char *wuid = p->queryName();
  5856. void *qi = qs->getQ(curqname.str(),wuid);
  5857. if (!qi)
  5858. return false;
  5859. setClusterName(cluster);
  5860. SCMStringBuffer newqname;
  5861. newci->getThorQueue(newqname);
  5862. qs->putQ(newqname.str(),wuid,qi);
  5863. return true;
  5864. }
  5865. //=================================================================================================
  5866. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  5867. {
  5868. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  5869. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  5870. ForEach(*graphIter)
  5871. {
  5872. IConstWUGraph &graph = graphIter->query();
  5873. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  5874. SCMStringBuffer gName;
  5875. graph.getName(gName);
  5876. StringBuffer xpath("Graphs/Graph[@name=\"");
  5877. xpath.append(gName.s).append("\"]/xgmml");
  5878. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  5879. if (xgmml) // don't know of any reason it shouldn't exist
  5880. {
  5881. xgmml->removeProp("graphBin");
  5882. xgmml->setPropTree("graph", graphTree.getClear());
  5883. }
  5884. }
  5885. return ret.getClear();
  5886. }
  5887. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  5888. {
  5889. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  5890. ForEach(*iter)
  5891. {
  5892. IPropertyTree &graph = iter->query();
  5893. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  5894. }
  5895. }
  5896. void CLocalWorkUnit::loadGraphs(bool heavy) const
  5897. {
  5898. if (graphsCached < (heavy ? 2 : 1))
  5899. {
  5900. graphs.kill();
  5901. _loadGraphs(heavy);
  5902. graphsCached = (heavy ? 2 : 1);
  5903. }
  5904. }
  5905. mapEnums graphTypes[] = {
  5906. { GraphTypeAny, "unknown" },
  5907. { GraphTypeProgress, "progress" },
  5908. { GraphTypeEcl, "ECL" },
  5909. { GraphTypeActivities, "activities" },
  5910. { GraphTypeSubProgress, "subgraph" },
  5911. { GraphTypeSize, NULL },
  5912. };
  5913. WUGraphType getGraphTypeFromString(const char* type)
  5914. {
  5915. return (WUGraphType) getEnum(type, graphTypes);
  5916. }
  5917. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  5918. {
  5919. wuidVersion = owner.getWuidVersion();
  5920. }
  5921. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  5922. {
  5923. str.set(p->queryProp("@name"));
  5924. return str;
  5925. }
  5926. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  5927. {
  5928. if (wuidVersion >= 2)
  5929. {
  5930. str.set(p->queryProp("@label"));
  5931. return str;
  5932. }
  5933. else
  5934. {
  5935. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  5936. str.set(xgmml->queryProp("@label"));
  5937. return str;
  5938. }
  5939. }
  5940. WUGraphState CLocalWUGraph::getState() const
  5941. {
  5942. return owner.queryGraphState(p->queryProp("@name"));
  5943. }
  5944. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  5945. {
  5946. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  5947. if (xgmml)
  5948. {
  5949. StringBuffer x;
  5950. toXML(xgmml, x);
  5951. str.set(x.str());
  5952. }
  5953. return str;
  5954. }
  5955. unsigned CLocalWorkUnit::getGraphCount() const
  5956. {
  5957. CriticalBlock block(crit);
  5958. if (p->hasProp("Graphs"))
  5959. {
  5960. return p->queryPropTree("Graphs")->numChildren();
  5961. }
  5962. return 0;
  5963. }
  5964. unsigned CLocalWorkUnit::getSourceFileCount() const
  5965. {
  5966. CriticalBlock block(crit);
  5967. _loadFilesRead();
  5968. if (p->hasProp("FilesRead"))
  5969. {
  5970. return p->queryPropTree("FilesRead")->numChildren();
  5971. }
  5972. return 0;
  5973. }
  5974. unsigned CLocalWorkUnit::getResultCount() const
  5975. {
  5976. CriticalBlock block(crit);
  5977. if (p->hasProp("Results"))
  5978. {
  5979. return p->queryPropTree("Results")->numChildren();
  5980. }
  5981. return 0;
  5982. }
  5983. unsigned CLocalWorkUnit::getVariableCount() const
  5984. {
  5985. CriticalBlock block(crit);
  5986. if (p->hasProp("Variables"))
  5987. {
  5988. return p->queryPropTree("Variables")->numChildren();
  5989. }
  5990. return 0;
  5991. }
  5992. unsigned CLocalWorkUnit::getApplicationValueCount() const
  5993. {
  5994. CriticalBlock block(crit);
  5995. if (p->hasProp("Application"))
  5996. {
  5997. return p->queryPropTree("Application")->numChildren();
  5998. }
  5999. return 0;
  6000. }
  6001. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent)
  6002. {
  6003. appendXMLOpenTag(s, name, NULL, false);
  6004. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  6005. if (attrs->first())
  6006. {
  6007. unsigned attributeindent = indent + (size32_t) strlen(name);
  6008. unsigned count = attrs->count();
  6009. bool doindent = false;
  6010. ForEach(*attrs)
  6011. {
  6012. if (doindent)
  6013. s.append('\n').appendN(attributeindent, ' ');
  6014. else if (count > 3)
  6015. doindent = true;
  6016. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  6017. }
  6018. }
  6019. s.append('>');
  6020. return s;
  6021. }
  6022. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  6023. {
  6024. CriticalBlock block(crit);
  6025. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  6026. if (!paramTree)
  6027. return str;
  6028. StringBuffer xml;
  6029. if (!hidePasswords)
  6030. toXML(paramTree, xml);
  6031. else
  6032. {
  6033. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0).append('\n');
  6034. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  6035. ForEach(*elems)
  6036. {
  6037. const char *paramname = elems->query().queryName();
  6038. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  6039. if (p->getPropBool(xpath))
  6040. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  6041. else
  6042. toXML(&elems->query(), xml, 2);
  6043. }
  6044. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  6045. }
  6046. str.set(xml);
  6047. return str;
  6048. }
  6049. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  6050. {
  6051. CriticalBlock block(crit);
  6052. return p->getPropTree("Parameters");
  6053. }
  6054. void CLocalWorkUnit::setXmlParams(const char *params)
  6055. {
  6056. CriticalBlock block(crit);
  6057. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  6058. }
  6059. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  6060. {
  6061. CriticalBlock block(crit);
  6062. p->setPropTree("Parameters", tree);
  6063. }
  6064. unsigned __int64 CLocalWorkUnit::getHash() const
  6065. {
  6066. CriticalBlock block(crit);
  6067. return p->getPropInt64("@hash");
  6068. }
  6069. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  6070. {
  6071. CriticalBlock block(crit);
  6072. p->setPropInt64("@hash", hash);
  6073. }
  6074. // getGraphs / getGraphsMeta
  6075. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  6076. // If a type other than any is requested, a postfilter is needed.
  6077. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  6078. {
  6079. WUGraphType type;
  6080. Owned<T> base;
  6081. bool match()
  6082. {
  6083. return base->query().getType()==type;
  6084. }
  6085. public:
  6086. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  6087. : base(_base), type(_type)
  6088. {
  6089. }
  6090. bool first()
  6091. {
  6092. if (!base->first())
  6093. return false;
  6094. if (match())
  6095. return true;
  6096. return next();
  6097. }
  6098. bool next()
  6099. {
  6100. while (base->next())
  6101. if (match())
  6102. return true;
  6103. return false;
  6104. }
  6105. virtual bool isValid()
  6106. {
  6107. return base->isValid();
  6108. }
  6109. U & query()
  6110. {
  6111. return base->query();
  6112. }
  6113. };
  6114. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  6115. {
  6116. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  6117. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  6118. */
  6119. CriticalBlock block(crit);
  6120. loadGraphs(false);
  6121. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  6122. if (type!=GraphTypeAny)
  6123. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  6124. return *giter;
  6125. }
  6126. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  6127. {
  6128. CriticalBlock block(crit);
  6129. loadGraphs(true);
  6130. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  6131. if (type!=GraphTypeAny)
  6132. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  6133. return *giter;
  6134. }
  6135. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  6136. {
  6137. CriticalBlock block(crit);
  6138. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  6139. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  6140. IPTree *graph = p->queryPropTree(xpath);
  6141. if (graph)
  6142. return new CLocalWUGraph(*this, LINK(graph));
  6143. return NULL;
  6144. }
  6145. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml)
  6146. {
  6147. CriticalBlock block(crit);
  6148. if (!graphs.length())
  6149. p->addPropTree("Graphs", createPTree("Graphs"));
  6150. IPropertyTree *r = p->queryPropTree("Graphs");
  6151. IPropertyTree *s = r->addPropTree("Graph", createPTree());
  6152. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  6153. q->setName(name);
  6154. q->setLabel(label);
  6155. q->setType(type);
  6156. q->setXGMMLTree(xgmml);
  6157. graphs.append(*q);
  6158. }
  6159. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  6160. {
  6161. throwUnexpected(); // Should only be used for persisted workunits
  6162. }
  6163. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  6164. {
  6165. throwUnexpected(); // Should only be used for persisted workunits
  6166. }
  6167. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  6168. {
  6169. throwUnexpected(); // Should only be used for persisted workunits
  6170. }
  6171. void CLocalWorkUnit::setGraphState(const char *graphName, WUGraphState state) const
  6172. {
  6173. throwUnexpected(); // Should only be used for persisted workunits
  6174. }
  6175. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  6176. {
  6177. throwUnexpected(); // Should only be used for persisted workunits
  6178. }
  6179. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned subgraph) const
  6180. {
  6181. throwUnexpected(); // Should only be used for persisted workunits
  6182. }
  6183. void CLocalWUGraph::setName(const char *str)
  6184. {
  6185. p->setProp("@name", str);
  6186. }
  6187. void CLocalWUGraph::setLabel(const char *str)
  6188. {
  6189. p->setProp("@label", str);
  6190. }
  6191. void CLocalWUGraph::setXGMML(const char *str)
  6192. {
  6193. setXGMMLTree(createPTreeFromXMLString(str));
  6194. }
  6195. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  6196. {
  6197. assertex(strcmp(_graph->queryName(), "graph")==0);
  6198. IPropertyTree *xgmml = p->setPropTree("xgmml", createPTree());
  6199. MemoryBuffer mb;
  6200. _graph->serialize(mb);
  6201. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  6202. // Cassandra workunit code actually lzw compresses the parent anyway
  6203. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  6204. graph.setown(_graph);
  6205. }
  6206. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  6207. {
  6208. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  6209. ForEach (*aIter)
  6210. {
  6211. const char *aName = aIter->queryName()+1;
  6212. if (0 != stricmp("id", aName)) // "id" reserved.
  6213. {
  6214. IPropertyTree *att = targetNode.addPropTree("att", createPTree());
  6215. att->setProp("@name", aName);
  6216. att->setProp("@value", aIter->queryValue());
  6217. }
  6218. }
  6219. }
  6220. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  6221. {
  6222. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  6223. if (!graphNode) return;
  6224. unsigned nodeId = rootNode.getPropInt("@id");
  6225. StringBuffer progressNodePath("node[@id=\"");
  6226. progressNodePath.append(nodeId).append("\"]");
  6227. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  6228. if (progressNode)
  6229. {
  6230. expandAttributes(*graphNode, *progressNode);
  6231. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  6232. ForEach (*edges)
  6233. {
  6234. IPropertyTree &edge = edges->query();
  6235. StringBuffer edgePath("edge[@id=\"");
  6236. edgePath.append(edge.queryProp("@id")).append("\"]");
  6237. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  6238. if (graphEdge)
  6239. {
  6240. if (progressV < 1)
  6241. mergePTree(graphEdge, &edge);
  6242. else
  6243. { // must translate to XGMML format
  6244. expandAttributes(*graphEdge, edge);
  6245. // 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)
  6246. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  6247. ForEach (*iter)
  6248. {
  6249. IPropertyTree &t = iter->query();
  6250. IPropertyTree *att = graphEdge->addPropTree("att", createPTree());
  6251. att->setProp("@name", t.queryName());
  6252. att->setProp("@value", t.queryProp(NULL));
  6253. }
  6254. }
  6255. }
  6256. }
  6257. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  6258. ForEach (*nodes)
  6259. {
  6260. IPropertyTree &node = nodes->query();
  6261. StringBuffer nodePath("node[@id=\"");
  6262. nodePath.append(node.queryProp("@id")).append("\"]");
  6263. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  6264. if (_node)
  6265. {
  6266. if (progressV < 1)
  6267. mergePTree(_node, &node);
  6268. else
  6269. { // must translate to XGMML format
  6270. expandAttributes(*_node, node);
  6271. }
  6272. }
  6273. }
  6274. }
  6275. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  6276. ForEach (*iter)
  6277. mergeProgress(iter->query(), progressTree, progressV);
  6278. }
  6279. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  6280. {
  6281. return p->getPropTree("xgmml");
  6282. }
  6283. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  6284. {
  6285. if (!graph)
  6286. {
  6287. // NB: although graphBin introduced in wuidVersion==2,
  6288. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  6289. MemoryBuffer mb;
  6290. if (p->getPropBin("xgmml/graphBin", mb))
  6291. graph.setown(createPTree(mb));
  6292. else
  6293. graph.setown(p->getBranch("xgmml/graph"));
  6294. if (!graph)
  6295. return NULL;
  6296. }
  6297. if (!doMergeProgress)
  6298. return graph.getLink();
  6299. else
  6300. {
  6301. Owned<IPropertyTree> copy = createPTreeFromIPT(graph);
  6302. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  6303. if (progress)
  6304. {
  6305. //MORE: Eventually this should directly access the new stats structure
  6306. unsigned progressV = progress->queryFormatVersion();
  6307. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  6308. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  6309. ForEach (*nodeIterator)
  6310. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  6311. }
  6312. return copy.getClear();
  6313. }
  6314. }
  6315. WUGraphType CLocalWUGraph::getType() const
  6316. {
  6317. return (WUGraphType) getEnum(p, "@type", graphTypes);
  6318. }
  6319. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  6320. {
  6321. str.set(p->queryProp("@type"));
  6322. if (!str.length())
  6323. str.set("unknown");
  6324. return str;
  6325. }
  6326. void CLocalWUGraph::setType(WUGraphType _type)
  6327. {
  6328. setEnum(p, "@type", _type, graphTypes);
  6329. }
  6330. //=================================================================================================
  6331. mapEnums queryFileTypes[] = {
  6332. { FileTypeCpp, "cpp" },
  6333. { FileTypeDll, "dll" },
  6334. { FileTypeResText, "res" },
  6335. { FileTypeHintXml, "hint" },
  6336. { FileTypeXml, "xml" },
  6337. { FileTypeSize, NULL },
  6338. };
  6339. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  6340. {
  6341. }
  6342. WUFileType CLocalWUAssociated::getType() const
  6343. {
  6344. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  6345. }
  6346. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  6347. {
  6348. str.set(p->queryProp("@desc"));
  6349. return str;
  6350. }
  6351. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  6352. {
  6353. str.set(p->queryProp("@ip"));
  6354. return str;
  6355. }
  6356. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  6357. {
  6358. str.set(p->queryProp("@filename"));
  6359. return str;
  6360. }
  6361. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  6362. {
  6363. str.set(pathTail(p->queryProp("@filename")));
  6364. return str;
  6365. }
  6366. unsigned CLocalWUAssociated::getCrc() const
  6367. {
  6368. return p->getPropInt("@crc", 0);
  6369. }
  6370. //=================================================================================================
  6371. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  6372. {
  6373. associatedCached = false;
  6374. }
  6375. mapEnums queryTypes[] = {
  6376. { QueryTypeUnknown, "unknown" },
  6377. { QueryTypeEcl, "ECL" },
  6378. { QueryTypeSql, "SQL" },
  6379. { QueryTypeXml, "XML" },
  6380. { QueryTypeAttribute, "Attribute" },
  6381. { QueryTypeSize, NULL },
  6382. };
  6383. WUQueryType CLocalWUQuery::getQueryType() const
  6384. {
  6385. return (WUQueryType) getEnum(p, "@type", queryTypes);
  6386. }
  6387. void CLocalWUQuery::setQueryType(WUQueryType qt)
  6388. {
  6389. setEnum(p, "@type", qt, queryTypes);
  6390. }
  6391. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  6392. {
  6393. str.set(p->queryProp("Text"));
  6394. return str;
  6395. }
  6396. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  6397. {
  6398. const char * text = p->queryProp("ShortText");
  6399. if (text)
  6400. str.set(text);
  6401. else
  6402. {
  6403. text = p->queryProp("Text");
  6404. if (isArchiveQuery(text))
  6405. {
  6406. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive);
  6407. const char * path = xml->queryProp("Query/@attributePath");
  6408. if (path)
  6409. {
  6410. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  6411. if (resolved)
  6412. str.set(resolved->queryProp(NULL));
  6413. }
  6414. else
  6415. str.set(xml->queryProp("Query"));
  6416. }
  6417. else
  6418. str.set(text);
  6419. }
  6420. return str;
  6421. }
  6422. bool CLocalWUQuery::isArchive() const
  6423. {
  6424. if (p->hasProp("@isArchive"))
  6425. return p->getPropBool("@isArchive");
  6426. const char *text = p->queryProp("Text");
  6427. return isArchiveQuery(text);
  6428. }
  6429. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  6430. {
  6431. str.set(p->queryProp("@name"));
  6432. return str;
  6433. }
  6434. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  6435. {
  6436. str.set(p->queryProp("@main"));
  6437. return str;
  6438. }
  6439. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  6440. {
  6441. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  6442. if (entry)
  6443. entry->getNameTail(str);
  6444. return str;
  6445. }
  6446. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  6447. {
  6448. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  6449. if (entry)
  6450. entry->getName(str);
  6451. return str;
  6452. }
  6453. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  6454. {
  6455. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  6456. if (entry)
  6457. entry->getName(str);
  6458. return str;
  6459. }
  6460. unsigned CLocalWUQuery::getQueryDllCrc() const
  6461. {
  6462. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  6463. if (entry)
  6464. return entry->getCrc();
  6465. return 0;
  6466. }
  6467. void CLocalWUQuery::setQueryText(const char *text)
  6468. {
  6469. p->setProp("Text", text);
  6470. bool isArchive = isArchiveQuery(text);
  6471. if (isArchive)
  6472. {
  6473. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive);
  6474. const char * path = xml->queryProp("Query/@attributePath");
  6475. if (path)
  6476. {
  6477. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  6478. if (resolved)
  6479. p->setProp("ShortText", resolved->queryProp(NULL));
  6480. }
  6481. else
  6482. p->setProp("ShortText", xml->queryProp("Query"));
  6483. }
  6484. p->setPropBool("@isArchive", isArchive);
  6485. }
  6486. void CLocalWUQuery::setQueryName(const char *qname)
  6487. {
  6488. p->setProp("@name", qname);
  6489. }
  6490. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  6491. {
  6492. p->setProp("@main", str);
  6493. }
  6494. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc)
  6495. {
  6496. CriticalBlock block(crit);
  6497. loadAssociated();
  6498. if (!associated.length())
  6499. p->addPropTree("Associated", createPTree("Associated"));
  6500. IPropertyTree *pl = p->queryPropTree("Associated");
  6501. IPropertyTree *s = pl->addPropTree("File", createPTree("File"));
  6502. setEnum(s, "@type", type, queryFileTypes);
  6503. s->setProp("@filename", name);
  6504. s->setProp("@ip", ip);
  6505. s->setProp("@desc", desc);
  6506. if (crc)
  6507. s->setPropInt("@crc", crc);
  6508. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  6509. associated.append(*q);
  6510. }
  6511. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  6512. {
  6513. CriticalBlock block(crit);
  6514. associatedCached = false;
  6515. associated.kill();
  6516. StringBuffer xpath;
  6517. xpath.append("Associated/File");
  6518. if (type)
  6519. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  6520. if (name)
  6521. xpath.append("[@filename=\"").append(name).append("\"]");
  6522. if (desc)
  6523. xpath.append("[@desc=\"").append(desc).append("\"]");
  6524. p->removeProp(xpath.str());
  6525. }
  6526. void CLocalWUQuery::removeAssociatedFiles()
  6527. {
  6528. associatedCached = false;
  6529. associated.kill();
  6530. p->removeProp("Associated");
  6531. }
  6532. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  6533. {
  6534. CriticalBlock block(crit);
  6535. loadAssociated();
  6536. ForEachItemIn(idx, associated)
  6537. {
  6538. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  6539. if (cur.getType() == type)
  6540. {
  6541. if (index-- == 0)
  6542. return &OLINK(cur);
  6543. }
  6544. }
  6545. return NULL;
  6546. }
  6547. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  6548. {
  6549. const char * name = p->queryProp(propname);
  6550. if (name)
  6551. {
  6552. IPropertyTree *s = createPTree("File");
  6553. setEnum(s, "@type", type, queryFileTypes);
  6554. s->setProp("@filename", name);
  6555. if (crc)
  6556. s->setPropInt("@crc", crc);
  6557. associated.append(*new CLocalWUAssociated(s));
  6558. }
  6559. }
  6560. void CLocalWUQuery::loadAssociated() const
  6561. {
  6562. CriticalBlock block(crit);
  6563. if (!associatedCached)
  6564. {
  6565. assertex(associated.length() == 0);
  6566. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  6567. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  6568. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  6569. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  6570. for (r->first(); r->isValid(); r->next())
  6571. {
  6572. IPropertyTree *rp = &r->query();
  6573. rp->Link();
  6574. associated.append(*new CLocalWUAssociated(rp));
  6575. }
  6576. associatedCached = true;
  6577. }
  6578. }
  6579. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  6580. {
  6581. CriticalBlock block(crit);
  6582. loadAssociated();
  6583. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  6584. }
  6585. //========================================================================================
  6586. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  6587. {
  6588. }
  6589. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  6590. {
  6591. str.set(p->queryProp("@module"));
  6592. return str;
  6593. }
  6594. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  6595. {
  6596. str.set(p->queryProp("@attribute"));
  6597. return str;
  6598. }
  6599. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  6600. {
  6601. str.set(p->queryProp("@defaultName"));
  6602. return str;
  6603. }
  6604. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  6605. {
  6606. return (unsigned) p->getPropInt("@crc");
  6607. }
  6608. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  6609. {
  6610. if (!name)
  6611. {
  6612. StringBuffer ws_info;
  6613. ws_info.appendf("<%s ", p->queryName());
  6614. Owned<IAttributeIterator> attrs = p->getAttributes();
  6615. for(attrs->first(); attrs->isValid(); attrs->next())
  6616. {
  6617. const char *name = attrs->queryName()+1;
  6618. const char *value = attrs->queryValue();
  6619. ws_info.appendf("%s='%s' ", name, value);
  6620. }
  6621. ws_info.append("> \n");
  6622. Owned<IPropertyTreeIterator> info = p->getElements("*");
  6623. ForEach(*info)
  6624. {
  6625. IPropertyTree &item = info->query();
  6626. const char *name = item.queryName();
  6627. if (name)
  6628. {
  6629. MemoryBuffer mb;
  6630. bool isbin = p->isBinary(name);
  6631. if (isbin)
  6632. {
  6633. p->getPropBin(name,mb);
  6634. if (mb.length())
  6635. {
  6636. unsigned len = 0;
  6637. mb.read(len);
  6638. StringBuffer encodedString;
  6639. StringBuffer val(len, (const char *) mb.readDirect(len));
  6640. encodeXML(val, encodedString);
  6641. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  6642. }
  6643. }
  6644. else
  6645. {
  6646. StringBuffer tmp;
  6647. toXML(&item, tmp);
  6648. ws_info.append(tmp.str());
  6649. }
  6650. }
  6651. }
  6652. ws_info.appendf("</%s>", p->queryName());
  6653. str.setLen(ws_info.str(), ws_info.length());
  6654. }
  6655. else
  6656. {
  6657. MemoryBuffer mb;
  6658. p->getPropBin(name,mb);
  6659. if (mb.length())
  6660. {
  6661. unsigned len;
  6662. mb.read(len);
  6663. str.setLen((const char *) mb.readDirect(len), len);
  6664. }
  6665. }
  6666. return str;
  6667. }
  6668. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  6669. {
  6670. str.set(p->queryProp(name));
  6671. return str;
  6672. }
  6673. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  6674. {
  6675. p->setProp("@module", mname);
  6676. }
  6677. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  6678. {
  6679. p->setProp("@attribute", aname);
  6680. }
  6681. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  6682. {
  6683. p->setProp("@defaultName", dname);
  6684. }
  6685. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  6686. {
  6687. p->setPropInt("@crc", crc);
  6688. }
  6689. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  6690. {
  6691. MemoryBuffer m;
  6692. unsigned len = (size32_t)strlen(info);
  6693. serializeLPString(len, info, m);
  6694. p->setPropBin(name, m.length(), m.toByteArray());
  6695. }
  6696. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  6697. {
  6698. p->setProp(name, info);
  6699. }
  6700. //========================================================================================
  6701. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  6702. {
  6703. }
  6704. mapEnums resultStatuses[] = {
  6705. { ResultStatusUndefined, "undefined" },
  6706. { ResultStatusCalculated, "calculated" },
  6707. { ResultStatusSupplied, "supplied" },
  6708. { ResultStatusFailed, "failed" },
  6709. { ResultStatusPartial, "partial" },
  6710. { ResultStatusSize, NULL }
  6711. };
  6712. WUResultStatus CLocalWUResult::getResultStatus() const
  6713. {
  6714. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  6715. }
  6716. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  6717. {
  6718. str.set(p->queryProp("@name"));
  6719. return str;
  6720. }
  6721. int CLocalWUResult::getResultSequence() const
  6722. {
  6723. return p->getPropInt("@sequence", -1);
  6724. }
  6725. bool CLocalWUResult::isResultScalar() const
  6726. {
  6727. return p->getPropInt("@isScalar", 1) != 0;
  6728. }
  6729. bool findSize(int size, IntArray &sizes)
  6730. {
  6731. ForEachItemIn(idx, sizes)
  6732. {
  6733. if (sizes.item(idx)==size)
  6734. return true;
  6735. }
  6736. return false;
  6737. }
  6738. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  6739. {
  6740. MemoryBuffer schema;
  6741. p->getPropBin("SchemaRaw", schema);
  6742. if (schema.length())
  6743. {
  6744. for (;;)
  6745. {
  6746. StringAttr name;
  6747. schema.read(name);
  6748. if (*schema.readDirect(0)==type_void)
  6749. break;
  6750. names.append(*new StringAttrItem(name));
  6751. types.append(*deserializeType(schema)); // MORE - nested records!
  6752. }
  6753. schema.skip(1);
  6754. if (schema.length() != schema.getPos())
  6755. {
  6756. unsigned eclLen;
  6757. schema.read(eclLen);
  6758. const char * schemaData = (const char *)schema.readDirect(eclLen);
  6759. if (eclText)
  6760. {
  6761. eclText->setLen(schemaData, eclLen);
  6762. if ((eclLen == 0) && names.ordinality())
  6763. {
  6764. const char * firstName = names.item(0).text;
  6765. StringBuffer temp;
  6766. temp.append("RECORD ");
  6767. types.item(0).getECLType(temp);
  6768. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  6769. eclText->set(temp.str());
  6770. }
  6771. }
  6772. }
  6773. }
  6774. }
  6775. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  6776. {
  6777. ForEachItemIn(idx, types)
  6778. {
  6779. StringAttrItem &name = names.item(idx);
  6780. ITypeInfo &type = types.item(idx);
  6781. unsigned size = type.getSize();
  6782. switch(type.getTypeCode())
  6783. {
  6784. case type_data:
  6785. if (size==UNKNOWN_LENGTH)
  6786. {
  6787. if (in.remaining() < sizeof(int))
  6788. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  6789. in.read(size);
  6790. }
  6791. outputXmlData(size, in.readDirect(size), name.text, out);
  6792. break;
  6793. case type_string:
  6794. if (size==UNKNOWN_LENGTH)
  6795. {
  6796. if (in.remaining() < sizeof(int))
  6797. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  6798. in.read(size);
  6799. }
  6800. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  6801. break;
  6802. case type_varstring:
  6803. {
  6804. if (size == UNKNOWN_LENGTH)
  6805. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  6806. const char * text = (const char *) in.readDirect(size);
  6807. outputXmlString((size32_t)strlen(text), text, name.text, out);
  6808. break;
  6809. }
  6810. case type_unicode:
  6811. {
  6812. unsigned len = type.getStringLen();
  6813. if (size==UNKNOWN_LENGTH)
  6814. in.read(len);
  6815. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  6816. }
  6817. break;
  6818. case type_utf8:
  6819. {
  6820. unsigned len = type.getStringLen();
  6821. if (size==UNKNOWN_LENGTH)
  6822. {
  6823. in.read(len);
  6824. size = rtlUtf8Size(len, in.readDirect(0));
  6825. }
  6826. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  6827. }
  6828. break;
  6829. case type_qstring:
  6830. {
  6831. unsigned len = type.getStringLen();
  6832. if (size==UNKNOWN_LENGTH)
  6833. in.read(len);
  6834. unsigned outlen;
  6835. char *outstr;
  6836. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  6837. outputXmlString(outlen, outstr, name.text, out);
  6838. free(outstr);
  6839. break;
  6840. }
  6841. case type_int:
  6842. case type_swapint:
  6843. if (type.isSigned())
  6844. {
  6845. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  6846. unsigned __int64 cval8 = 0;
  6847. //MORE: I think this is wrong - swapped doesn't mean little/big/
  6848. if (type.isSwappedEndian())
  6849. {
  6850. unsigned idx = 0;
  6851. if (raw[idx] & 0x80)
  6852. cval8 = (__int64)-1;
  6853. while (size--)
  6854. cval8 = (cval8 << 8) | raw[idx++];
  6855. }
  6856. else
  6857. {
  6858. if (raw[size-1] & 0x80)
  6859. cval8 = (__int64)-1;
  6860. while (size--)
  6861. cval8 = (cval8 << 8) | raw[size];
  6862. }
  6863. outputXmlInt((__int64) cval8, name.text, out);
  6864. }
  6865. else
  6866. {
  6867. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  6868. unsigned __int64 cval8 = 0;
  6869. if (type.isSwappedEndian())
  6870. {
  6871. unsigned idx = 0;
  6872. while (size--)
  6873. cval8 = (cval8 << 8) | raw[idx++];
  6874. }
  6875. else
  6876. {
  6877. while (size--)
  6878. cval8 = (cval8 << 8) | raw[size];
  6879. }
  6880. outputXmlUInt(cval8, name.text, out);
  6881. }
  6882. break;
  6883. case type_boolean:
  6884. bool cvalb;
  6885. in.read(cvalb);
  6886. outputXmlBool(cvalb, name.text, out);
  6887. break;
  6888. case type_decimal:
  6889. if (type.isSigned())
  6890. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  6891. else
  6892. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  6893. break;
  6894. case type_real:
  6895. double cvald;
  6896. switch(size)
  6897. {
  6898. case 4:
  6899. float cvalf;
  6900. in.read(cvalf);
  6901. cvald = cvalf;
  6902. break;
  6903. case 8:
  6904. in.read(cvald);
  6905. break;
  6906. }
  6907. outputXmlReal(cvald, name.text, out);
  6908. break;
  6909. default:
  6910. assertex(!"unexpected type in raw record");
  6911. break;
  6912. }
  6913. }
  6914. }
  6915. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  6916. {
  6917. TypeInfoArray types;
  6918. StringAttrArray names;
  6919. getSchema(types, names);
  6920. StringBuffer xml;
  6921. const char * name = p->queryProp("@name");
  6922. if (name)
  6923. xml.appendf("<Dataset name=\'%s\'>\n", name);
  6924. else
  6925. xml.append("<Dataset>\n");
  6926. if (hidePassword && p->getPropBool("Format/@password"))
  6927. {
  6928. xml.append(" <Row>");
  6929. appendXMLTag(xml, name, "****");
  6930. xml.append("</Row>\n");
  6931. }
  6932. else if (p->hasProp("Value"))
  6933. {
  6934. MemoryBuffer raw;
  6935. p->getPropBin("Value", raw);
  6936. unsigned __int64 numrows = getResultRowCount();
  6937. while (numrows--)
  6938. {
  6939. xml.append(" <Row>");
  6940. readRow(xml, raw, types, names);
  6941. xml.append("</Row>\n");
  6942. }
  6943. }
  6944. else if (p->hasProp("xmlValue"))
  6945. {
  6946. xml.append(" <Row>");
  6947. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  6948. xml.append("</Row>\n");
  6949. }
  6950. xml.append("</Dataset>\n");
  6951. str.set(xml.str());
  6952. return str;
  6953. }
  6954. IProperties *CLocalWUResult::queryResultXmlns()
  6955. {
  6956. CriticalBlock block(crit);
  6957. if (xmlns)
  6958. return xmlns;
  6959. xmlns.setown(createProperties());
  6960. Owned<IAttributeIterator> it = p->getAttributes();
  6961. unsigned prefixLen = strlen("@xmlns");
  6962. ForEach(*it)
  6963. {
  6964. const char *name = it->queryName();
  6965. if (!strncmp("@xmlns", name, prefixLen))
  6966. {
  6967. if (name[prefixLen]==':') //normal case
  6968. xmlns->setProp(name+prefixLen+1, it->queryValue());
  6969. else if (!name[prefixLen]) //special case, unprefixed namespace
  6970. xmlns->setProp("xmlns", it->queryValue());
  6971. }
  6972. }
  6973. return xmlns;
  6974. }
  6975. unsigned CLocalWUResult::getResultFetchSize() const
  6976. {
  6977. return p->getPropInt("fetchSize", 100);
  6978. }
  6979. __int64 CLocalWUResult::getResultTotalRowCount() const
  6980. {
  6981. return p->getPropInt64("totalRowCount", -1);
  6982. }
  6983. __int64 CLocalWUResult::getResultRowCount() const
  6984. {
  6985. return p->getPropInt64("rowCount", 0);
  6986. }
  6987. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  6988. {
  6989. ecl.set(p->queryProp("datasetEcl"));
  6990. defs.set(p->queryProp("datasetEclDefs"));
  6991. }
  6992. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  6993. {
  6994. val.set(p->queryProp("logicalName"));
  6995. return val;
  6996. }
  6997. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  6998. {
  6999. ecl.set(p->queryProp("keyField"));
  7000. return ecl;
  7001. }
  7002. unsigned CLocalWUResult::getResultRequestedRows() const
  7003. {
  7004. return p->getPropInt("requestedRows", 1);
  7005. }
  7006. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  7007. {
  7008. TypeInfoArray types;
  7009. StringAttrArray names;
  7010. getSchema(types, names, &str);
  7011. return str;
  7012. }
  7013. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  7014. {
  7015. str.set(p->queryProp("@recordSizeEntry"));
  7016. return str;
  7017. }
  7018. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  7019. {
  7020. str.set(p->queryProp("@transformerEntry"));
  7021. return str;
  7022. }
  7023. __int64 CLocalWUResult::getResultRowLimit() const
  7024. {
  7025. return p->getPropInt64("@rowLimit");
  7026. }
  7027. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  7028. {
  7029. str.set(p->queryProp("@tempFilename"));
  7030. return str;
  7031. }
  7032. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  7033. {
  7034. str.clear();
  7035. if (!name || !*name)
  7036. return str;
  7037. IPropertyTree *format = p->queryPropTree("Format");
  7038. if (!format)
  7039. return str;
  7040. VStringBuffer xpath("@%s", name);
  7041. str.set(format->queryProp(xpath));
  7042. return str;
  7043. }
  7044. void CLocalWUResult::setResultStatus(WUResultStatus status)
  7045. {
  7046. setEnum(p, "@status", status, resultStatuses);
  7047. if (status==ResultStatusUndefined)
  7048. p->removeProp("Value");
  7049. }
  7050. void CLocalWUResult::setResultName(const char *s)
  7051. {
  7052. p->setProp("@name", s);
  7053. }
  7054. void CLocalWUResult::setResultSequence(unsigned seq)
  7055. {
  7056. p->setPropInt("@sequence", seq);
  7057. }
  7058. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  7059. {
  7060. p->setPropBin("SchemaRaw", size, schema);
  7061. }
  7062. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  7063. {
  7064. StringBuffer xpath("@xmlns");
  7065. if (prefix && *prefix)
  7066. xpath.append(':').append(prefix);
  7067. p->setProp(xpath, uri);
  7068. }
  7069. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  7070. {
  7071. if (!name || !*name)
  7072. return;
  7073. IPropertyTree *format = ensurePTree(p, "Format");
  7074. VStringBuffer xpath("@%s", name);
  7075. format->setProp(xpath, value);
  7076. }
  7077. void CLocalWUResult::setResultScalar(bool isScalar)
  7078. {
  7079. p->setPropInt("@isScalar", (int) isScalar);
  7080. if (isScalar)
  7081. setResultTotalRowCount(1);
  7082. }
  7083. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  7084. {
  7085. p->setPropBin("Value", len, data);
  7086. setResultStatus(ResultStatusSupplied);
  7087. setResultFormat(format);
  7088. }
  7089. void CLocalWUResult::setResultFormat(WUResultFormat format)
  7090. {
  7091. switch (format)
  7092. {
  7093. case ResultFormatXml:
  7094. p->setProp("@format","xml");
  7095. break;
  7096. case ResultFormatXmlSet:
  7097. p->setProp("@format","xmlSet");
  7098. break;
  7099. case ResultFormatCsv:
  7100. p->setProp("@format","csv");
  7101. break;
  7102. default:
  7103. p->removeProp("@format");
  7104. break;
  7105. }
  7106. }
  7107. void CLocalWUResult::setResultXML(const char *val)
  7108. {
  7109. p->setProp("xmlValue", val);
  7110. }
  7111. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  7112. {
  7113. p->appendPropBin("Value", len, data);
  7114. setResultStatus(ResultStatusPartial);
  7115. const char *existingFormat = p->queryProp("@format");
  7116. const char *formatStr = NULL;
  7117. switch (format)
  7118. {
  7119. case ResultFormatXml:
  7120. formatStr = "xml";
  7121. break;
  7122. case ResultFormatXmlSet:
  7123. formatStr = "xmlSet";
  7124. break;
  7125. case ResultFormatCsv:
  7126. formatStr = "csv";
  7127. break;
  7128. default:
  7129. p->removeProp("@format");
  7130. break;
  7131. }
  7132. if (format)
  7133. {
  7134. if (existingFormat)
  7135. {
  7136. if (0 != stricmp(formatStr, existingFormat))
  7137. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  7138. }
  7139. else
  7140. p->setProp("@format", formatStr);
  7141. }
  7142. }
  7143. void CLocalWUResult::setResultFetchSize(unsigned rows)
  7144. {
  7145. p->setPropInt("fetchSize", rows);
  7146. }
  7147. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  7148. {
  7149. p->setPropInt64("totalRowCount", rows);
  7150. }
  7151. void CLocalWUResult::setResultRowCount(__int64 rows)
  7152. {
  7153. p->setPropInt64("rowCount", rows);
  7154. }
  7155. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  7156. {
  7157. p->setProp("datasetEcl", ecl);
  7158. p->setProp("datasetEclDefs", defs);
  7159. }
  7160. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  7161. {
  7162. p->setProp("logicalName", logicalName);
  7163. }
  7164. void CLocalWUResult::setResultKeyField(const char *ecl)
  7165. {
  7166. p->setProp("keyField", ecl);
  7167. }
  7168. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  7169. {
  7170. p->setPropInt("requestedRows", rows);
  7171. }
  7172. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  7173. {
  7174. p->setProp("@recordSizeEntry", entry);
  7175. }
  7176. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  7177. {
  7178. p->setProp("@transformerEntry", entry);
  7179. }
  7180. void CLocalWUResult::setResultRowLimit(__int64 value)
  7181. {
  7182. p->setPropInt64("@rowLimit", value);
  7183. }
  7184. void CLocalWUResult::setResultFilename(const char * name)
  7185. {
  7186. p->setProp("@tempFilename", name);
  7187. }
  7188. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  7189. __int64 CLocalWUResult::getResultInt() const
  7190. {
  7191. __int64 result = 0;
  7192. MemoryBuffer s;
  7193. p->getPropBin("Value", s);
  7194. if (s.length())
  7195. s.read(result);
  7196. else
  7197. result = p->getPropInt64("xmlValue");
  7198. return result;
  7199. }
  7200. bool CLocalWUResult::getResultBool() const
  7201. {
  7202. bool result = false;
  7203. MemoryBuffer s;
  7204. p->getPropBin("Value", s);
  7205. if (s.length())
  7206. s.read(result);
  7207. else
  7208. result = p->getPropBool("xmlValue");
  7209. return result;
  7210. }
  7211. double CLocalWUResult::getResultReal() const
  7212. {
  7213. double result = 0;
  7214. MemoryBuffer s;
  7215. p->getPropBin("Value", s);
  7216. if (s.length())
  7217. s.read(result);
  7218. else
  7219. {
  7220. const char *xmlVal = p->queryProp("xmlValue");
  7221. if (xmlVal)
  7222. result = atof(xmlVal);
  7223. }
  7224. return result;
  7225. }
  7226. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  7227. {
  7228. MemoryBuffer s;
  7229. p->getPropBin("Value", s);
  7230. if (s.length())
  7231. {
  7232. assertex(s.length() == len);
  7233. s.read(len, val);
  7234. }
  7235. else
  7236. {
  7237. const char *xmlVal = p->queryProp("xmlValue");
  7238. if (xmlVal)
  7239. {
  7240. Decimal d;
  7241. d.setString(strlen(xmlVal), xmlVal);
  7242. if (isSigned)
  7243. d.getDecimal(len, precision, val);
  7244. else
  7245. d.getUDecimal(len, precision, val);
  7246. }
  7247. else
  7248. memset(val, 0, len);
  7249. }
  7250. }
  7251. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  7252. {
  7253. if (hidePassword && p->getPropBool("@password"))
  7254. {
  7255. str.set("****");
  7256. return str;
  7257. }
  7258. MemoryBuffer s;
  7259. p->getPropBin("Value", s);
  7260. if (s.length())
  7261. {
  7262. unsigned len;
  7263. s.read(len);
  7264. str.setLen((const char *) s.readDirect(len), len);
  7265. }
  7266. else
  7267. {
  7268. p->getPropBin("xmlValue", s);
  7269. if (p->isBinary("xmlValue"))
  7270. str.setLen(s.toByteArray(), s.length());
  7271. else
  7272. {
  7273. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  7274. str.set(ascii);
  7275. rtlFree(ascii);
  7276. }
  7277. }
  7278. return str;
  7279. }
  7280. WUResultFormat CLocalWUResult::getResultFormat() const
  7281. {
  7282. const char * format = p->queryProp("@format");
  7283. if (!format)
  7284. return ResultFormatRaw;
  7285. else if (strcmp(format, "xml") == 0)
  7286. return ResultFormatXml;
  7287. else if (strcmp(format, "xmlSet") == 0)
  7288. return ResultFormatXmlSet;
  7289. else if (strcmp(format, "csv") == 0)
  7290. return ResultFormatCsv;
  7291. else
  7292. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  7293. }
  7294. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  7295. {
  7296. MemoryBuffer s;
  7297. p->getPropBin("Value", s);
  7298. unsigned len = s.length();
  7299. if (len)
  7300. {
  7301. WUResultFormat format = getResultFormat();
  7302. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  7303. {
  7304. if (!xmlTransformer)
  7305. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  7306. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  7307. }
  7308. else if (format == ResultFormatCsv)
  7309. {
  7310. if (!csvTransformer)
  7311. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  7312. csvTransformer->transform(data, len, s.readDirect(len), true);
  7313. }
  7314. else
  7315. data.setLen(s.readDirect(len), len);
  7316. }
  7317. else
  7318. data.clear();
  7319. return data;
  7320. }
  7321. unsigned CLocalWUResult::getResultHash() const
  7322. {
  7323. MemoryBuffer s;
  7324. p->getPropBin("Value", s);
  7325. unsigned len = s.length();
  7326. const byte * data = (const byte *)s.toByteArray();
  7327. return ~hashc(data, len, ~0);
  7328. }
  7329. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  7330. {
  7331. MemoryBuffer s;
  7332. p->getPropBin("Value", s);
  7333. if (s.length())
  7334. {
  7335. unsigned len;
  7336. s.read(len);
  7337. data.setLen(s.readDirect(len*2), len*2);
  7338. }
  7339. else
  7340. {
  7341. StringBuffer utf8;
  7342. if (p->getProp("xmlValue", utf8))
  7343. {
  7344. unsigned outlen;
  7345. UChar *out;
  7346. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  7347. data.setLen(out, outlen*2);
  7348. rtlFree(out);
  7349. }
  7350. else
  7351. data.clear();
  7352. }
  7353. return data;
  7354. }
  7355. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  7356. {
  7357. WUResultFormat format = getResultFormat();
  7358. if (format == ResultFormatRaw)
  7359. {
  7360. //MORE: This should not load the whole property...
  7361. MemoryBuffer s;
  7362. p->getPropBin("Value", s);
  7363. return s.length();
  7364. }
  7365. else
  7366. {
  7367. MemoryBuffer temp;
  7368. MemoryBuffer2IDataVal adaptor(temp);
  7369. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  7370. return temp.length();
  7371. }
  7372. }
  7373. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  7374. {
  7375. WUResultFormat format = getResultFormat();
  7376. if (format != ResultFormatRaw)
  7377. {
  7378. MemoryBuffer temp;
  7379. MemoryBuffer2IDataVal adaptor(temp);
  7380. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  7381. unsigned len = temp.length();
  7382. if (from > len) from = len;
  7383. if (from + length > len) length = len - from;
  7384. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  7385. return data;
  7386. }
  7387. else
  7388. {
  7389. //MORE: This should not load the whole property, and should be different from the code above...
  7390. MemoryBuffer s;
  7391. p->getPropBin("Value", s);
  7392. unsigned len = s.length();
  7393. if (from > len) from = len;
  7394. if (from + length > len) length = len - from;
  7395. data.setLen(s.readDirect(len) + from, (size32_t)length);
  7396. return data;
  7397. }
  7398. }
  7399. bool CLocalWUResult::getResultIsAll() const
  7400. {
  7401. return p->getPropBool("@isAll", false);
  7402. }
  7403. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  7404. void CLocalWUResult::setResultInt(__int64 val)
  7405. {
  7406. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  7407. MemoryBuffer m;
  7408. serializeInt8(val, m);
  7409. p->setPropBin("Value", m.length(), m.toByteArray());
  7410. setResultRowCount(1);
  7411. setResultTotalRowCount(1);
  7412. }
  7413. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  7414. {
  7415. setResultInt((__int64) val);
  7416. }
  7417. void CLocalWUResult::setResultReal(double val)
  7418. {
  7419. // Note: we always serialize scalar real results as real8, and schema must reflect this
  7420. MemoryBuffer m;
  7421. serializeReal8(val, m);
  7422. p->setPropBin("Value", m.length(), m.toByteArray());
  7423. setResultRowCount(1);
  7424. setResultTotalRowCount(1);
  7425. }
  7426. void CLocalWUResult::setResultBool(bool val)
  7427. {
  7428. MemoryBuffer m;
  7429. serializeBool(val, m);
  7430. p->setPropBin("Value", m.length(), m.toByteArray());
  7431. setResultRowCount(1);
  7432. setResultTotalRowCount(1);
  7433. }
  7434. void CLocalWUResult::setResultString(const char *val, unsigned len)
  7435. {
  7436. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  7437. MemoryBuffer m;
  7438. serializeLPString(len, val, m);
  7439. p->setPropBin("Value", m.length(), m.toByteArray());
  7440. setResultRowCount(1);
  7441. setResultTotalRowCount(1);
  7442. }
  7443. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  7444. {
  7445. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  7446. MemoryBuffer m;
  7447. m.append(len).append(len*2, val);
  7448. p->setPropBin("Value", m.length(), m.toByteArray());
  7449. setResultRowCount(1);
  7450. setResultTotalRowCount(1);
  7451. }
  7452. void CLocalWUResult::setResultData(const void *val, unsigned len)
  7453. {
  7454. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  7455. MemoryBuffer m;
  7456. serializeLPString(len, (const char *)val, m);
  7457. p->setPropBin("Value", m.length(), m.toByteArray());
  7458. setResultRowCount(1);
  7459. setResultTotalRowCount(1);
  7460. }
  7461. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  7462. {
  7463. // Note: serialized as data but with length known from schema
  7464. MemoryBuffer m;
  7465. serializeFixedData(len, val, m);
  7466. p->setPropBin("Value", m.length(), m.toByteArray());
  7467. setResultRowCount(1);
  7468. setResultTotalRowCount(1);
  7469. }
  7470. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  7471. {
  7472. p->setPropBin("Value", len, data);
  7473. setResultRowCount(1);
  7474. setResultTotalRowCount(1);
  7475. setResultFormat(ResultFormatRaw);
  7476. }
  7477. void CLocalWUResult::setResultIsAll(bool value)
  7478. {
  7479. p->setPropBool("@isAll", value);
  7480. }
  7481. //==========================================================================================
  7482. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  7483. {
  7484. }
  7485. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  7486. {
  7487. str.set(p->queryProp("@dllname"));
  7488. return str;
  7489. }
  7490. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  7491. {
  7492. str.set(p->queryProp("@version"));
  7493. return str;
  7494. }
  7495. void CLocalWUPlugin::setPluginName(const char *str)
  7496. {
  7497. p->setProp("@dllname", str);
  7498. }
  7499. void CLocalWUPlugin::setPluginVersion(const char *str)
  7500. {
  7501. p->setProp("@version", str);
  7502. }
  7503. //==========================================================================================
  7504. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  7505. {
  7506. }
  7507. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  7508. {
  7509. str.set(p->queryProp("@name"));
  7510. return str;
  7511. }
  7512. void CLocalWULibrary::setName(const char *str)
  7513. {
  7514. p->setProp("@name", str);
  7515. }
  7516. //==========================================================================================
  7517. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  7518. {
  7519. }
  7520. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  7521. {
  7522. str.set(p->queryProp("@source"));
  7523. return str;
  7524. }
  7525. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  7526. {
  7527. str.set(p->queryProp(NULL));
  7528. return str;
  7529. }
  7530. unsigned CLocalWUException::getExceptionCode() const
  7531. {
  7532. return p->getPropInt("@code", 0);
  7533. }
  7534. ErrorSeverity CLocalWUException::getSeverity() const
  7535. {
  7536. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  7537. }
  7538. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  7539. {
  7540. dt.set(p->queryProp("@time"));
  7541. return dt;
  7542. }
  7543. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  7544. {
  7545. str.set(p->queryProp("@filename"));
  7546. return str;
  7547. }
  7548. unsigned CLocalWUException::getExceptionLineNo() const
  7549. {
  7550. return p->getPropInt("@row", 0);
  7551. }
  7552. unsigned CLocalWUException::getExceptionColumn() const
  7553. {
  7554. return p->getPropInt("@col", 0);
  7555. }
  7556. unsigned CLocalWUException::getSequence() const
  7557. {
  7558. return p->getPropInt("@sequence", 0);
  7559. }
  7560. void CLocalWUException::setExceptionSource(const char *str)
  7561. {
  7562. p->setProp("@source", str);
  7563. }
  7564. void CLocalWUException::setExceptionMessage(const char *str)
  7565. {
  7566. p->setProp(NULL, str);
  7567. }
  7568. void CLocalWUException::setExceptionCode(unsigned code)
  7569. {
  7570. p->setPropInt("@code", code);
  7571. }
  7572. void CLocalWUException::setSeverity(ErrorSeverity level)
  7573. {
  7574. p->setPropInt("@severity", level);
  7575. }
  7576. void CLocalWUException::setTimeStamp(const char *str)
  7577. {
  7578. p->setProp("@time", str);
  7579. }
  7580. void CLocalWUException::setExceptionFileName(const char *str)
  7581. {
  7582. p->setProp("@filename", str);
  7583. }
  7584. void CLocalWUException::setExceptionLineNo(unsigned r)
  7585. {
  7586. p->setPropInt("@row", r);
  7587. }
  7588. void CLocalWUException::setExceptionColumn(unsigned c)
  7589. {
  7590. p->setPropInt("@col", c);
  7591. }
  7592. //==========================================================================================
  7593. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  7594. {
  7595. StringAttrBuilder propPath(prop);
  7596. propPath.append("*[").append(child).append("]");
  7597. }
  7598. const char * CLocalWUAppValue::queryApplication() const
  7599. {
  7600. return p->queryName();
  7601. }
  7602. const char * CLocalWUAppValue::queryName() const
  7603. {
  7604. IPropertyTree* val=p->queryPropTree(prop.str());
  7605. if(val)
  7606. return val->queryName();
  7607. return ""; // Should not happen in normal usage
  7608. }
  7609. const char * CLocalWUAppValue::queryValue() const
  7610. {
  7611. return p->queryProp(prop.str());
  7612. }
  7613. //==========================================================================================
  7614. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  7615. {
  7616. }
  7617. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  7618. {
  7619. const char * creator = p->queryProp("@creator");
  7620. str.set(creator);
  7621. return str;
  7622. }
  7623. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  7624. {
  7625. const char * desc = p->queryProp("@desc");
  7626. if (desc)
  7627. {
  7628. str.set(desc); // legacy and in case it is overridden
  7629. }
  7630. else if (createDefault)
  7631. {
  7632. StatisticKind kind = getKind();
  7633. assertex(kind != StKindNone);
  7634. const char * scope = p->queryProp("@scope");
  7635. assertex(scope);
  7636. //Clean up the format of the scope when converting it to a description
  7637. StringBuffer descriptionText;
  7638. if (streq(scope, GLOBAL_SCOPE))
  7639. {
  7640. const char * creator = p->queryProp("@creator");
  7641. descriptionText.append(creator).append(":");
  7642. queryLongStatisticName(descriptionText, kind);
  7643. }
  7644. else
  7645. {
  7646. loop
  7647. {
  7648. char c = *scope++;
  7649. if (!c)
  7650. break;
  7651. if (c == ':')
  7652. descriptionText.append(": ");
  7653. else
  7654. descriptionText.append(c);
  7655. }
  7656. if (kind != StTimeElapsed)
  7657. queryLongStatisticName(descriptionText.append(": "), kind);
  7658. }
  7659. str.set(descriptionText);
  7660. }
  7661. else
  7662. str.clear();
  7663. return str;
  7664. }
  7665. IStringVal & CLocalWUStatistic::getType(IStringVal & str) const
  7666. {
  7667. StatisticKind kind = getKind();
  7668. if (kind != StKindNone)
  7669. str.set(queryStatisticName(kind));
  7670. return str;
  7671. }
  7672. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  7673. {
  7674. StringBuffer formatted;
  7675. formatStatistic(formatted, getValue(), getMeasure());
  7676. str.set(formatted);
  7677. return str;
  7678. }
  7679. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  7680. {
  7681. return queryCreatorType(p->queryProp("@c"));
  7682. }
  7683. StatisticScopeType CLocalWUStatistic::getScopeType() const
  7684. {
  7685. return queryScopeType(p->queryProp("@s"));
  7686. }
  7687. StatisticKind CLocalWUStatistic::getKind() const
  7688. {
  7689. return queryStatisticKind(p->queryProp("@kind"));
  7690. }
  7691. IStringVal & CLocalWUStatistic::getScope(IStringVal & str) const
  7692. {
  7693. const char * scope = p->queryProp("@scope");
  7694. str.set(scope);
  7695. return str;
  7696. }
  7697. StatisticMeasure CLocalWUStatistic::getMeasure() const
  7698. {
  7699. return queryMeasure(p->queryProp("@unit"));
  7700. }
  7701. unsigned __int64 CLocalWUStatistic::getValue() const
  7702. {
  7703. return p->getPropInt64("@value", 0);
  7704. }
  7705. unsigned __int64 CLocalWUStatistic::getCount() const
  7706. {
  7707. return p->getPropInt64("@count", 0);
  7708. }
  7709. unsigned __int64 CLocalWUStatistic::getMax() const
  7710. {
  7711. return p->getPropInt64("@max", 0);
  7712. }
  7713. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  7714. {
  7715. return p->getPropInt64("@ts", 0);
  7716. }
  7717. bool CLocalWUStatistic::matches(const IStatisticsFilter * filter) const
  7718. {
  7719. if (!filter)
  7720. return true;
  7721. const char * creator = p->queryProp("@creator");
  7722. const char * scope = p->queryProp("@scope");
  7723. return filter->matches(getCreatorType(), creator, getScopeType(), scope, getMeasure(), getKind());
  7724. }
  7725. //==========================================================================================
  7726. CLocalWULegacyTiming::CLocalWULegacyTiming(IPropertyTree *props) : p(props)
  7727. {
  7728. }
  7729. IStringVal & CLocalWULegacyTiming::getCreator(IStringVal & str) const
  7730. {
  7731. str.clear();
  7732. return str;
  7733. }
  7734. IStringVal & CLocalWULegacyTiming::getDescription(IStringVal & str, bool createDefault) const
  7735. {
  7736. str.set(p->queryProp("@name"));
  7737. return str;
  7738. }
  7739. IStringVal & CLocalWULegacyTiming::getType(IStringVal & str) const
  7740. {
  7741. str.set(queryStatisticName(StTimeElapsed));
  7742. return str;
  7743. }
  7744. IStringVal & CLocalWULegacyTiming::getFormattedValue(IStringVal & str) const
  7745. {
  7746. StringBuffer formatted;
  7747. formatStatistic(formatted, getValue(), getMeasure());
  7748. str.set(formatted);
  7749. return str;
  7750. }
  7751. StatisticCreatorType CLocalWULegacyTiming::getCreatorType() const
  7752. {
  7753. return SCTunknown;
  7754. }
  7755. StatisticScopeType CLocalWULegacyTiming::getScopeType() const
  7756. {
  7757. return SSTnone;
  7758. }
  7759. StatisticKind CLocalWULegacyTiming::getKind() const
  7760. {
  7761. return StTimeElapsed;
  7762. }
  7763. IStringVal & CLocalWULegacyTiming::getScope(IStringVal & str) const
  7764. {
  7765. str.clear();
  7766. return str;
  7767. }
  7768. StatisticMeasure CLocalWULegacyTiming::getMeasure() const
  7769. {
  7770. return SMeasureTimeNs;
  7771. }
  7772. unsigned __int64 CLocalWULegacyTiming::getValue() const
  7773. {
  7774. return p->getPropInt64("@duration", 0) * 1000000;
  7775. }
  7776. unsigned __int64 CLocalWULegacyTiming::getCount() const
  7777. {
  7778. return p->getPropInt64("@count", 0);
  7779. }
  7780. unsigned __int64 CLocalWULegacyTiming::getMax() const
  7781. {
  7782. return p->getPropInt64("@max", 0);
  7783. }
  7784. unsigned __int64 CLocalWULegacyTiming::getTimestamp() const
  7785. {
  7786. return 0;
  7787. }
  7788. bool CLocalWULegacyTiming::matches(const IStatisticsFilter * filter) const
  7789. {
  7790. if (!filter)
  7791. return true;
  7792. const char * creator = p->queryProp("@creator");
  7793. const char * scope = p->queryProp("@scope");
  7794. return filter->matches(SCTall, NULL, SSTall, NULL, getMeasure(), getKind());
  7795. }
  7796. //==========================================================================================
  7797. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  7798. {
  7799. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  7800. if (xml)
  7801. cw->loadPTree(createPTreeFromXMLString(xml));
  7802. else
  7803. {
  7804. Owned<IPropertyTree> p = createPTree("W_LOCAL");
  7805. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  7806. cw->loadPTree(p.getClear());
  7807. }
  7808. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  7809. return ret;
  7810. }
  7811. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  7812. {
  7813. const char *name = p->queryName();
  7814. if (!name)
  7815. name = "__unnamed__";
  7816. StringBuffer temp;
  7817. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1));
  7818. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  7819. ForEach(*elems)
  7820. {
  7821. IPropertyTree &elem = elems->query();
  7822. if (streq(elem.queryName(), "Parameters"))
  7823. {
  7824. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2).append('\n'));
  7825. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  7826. ForEach(*params)
  7827. {
  7828. IPropertyTree &param = params->query();
  7829. const char *paramname = param.queryName();
  7830. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  7831. if (p->getPropBool(xpath))
  7832. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  7833. else
  7834. {
  7835. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  7836. }
  7837. }
  7838. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  7839. }
  7840. else if (streq(elem.queryName(), "Variables"))
  7841. {
  7842. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2).append('\n'));
  7843. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  7844. ForEach(*vars)
  7845. {
  7846. Owned<IPropertyTree> var = LINK(&vars->query());
  7847. if (var->getPropBool("Format/@password"))
  7848. {
  7849. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  7850. var->removeProp("Value");
  7851. var->removeProp("xmlValue");
  7852. }
  7853. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  7854. }
  7855. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  7856. }
  7857. else
  7858. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  7859. }
  7860. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  7861. }
  7862. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  7863. {
  7864. class CAdapter : public CInterface, implements IIOStream
  7865. {
  7866. StringBuffer &out;
  7867. public:
  7868. IMPLEMENT_IINTERFACE;
  7869. CAdapter(StringBuffer &_out) : out(_out) { }
  7870. virtual void flush() { }
  7871. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  7872. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  7873. } adapter(str);
  7874. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  7875. return str;
  7876. }
  7877. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  7878. {
  7879. OwnedIFile ifile = createIFile(filename);
  7880. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  7881. Owned<IIOStream> stream = createIOStream(ifileio);
  7882. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  7883. }
  7884. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  7885. {
  7886. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  7887. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  7888. if (ewu)
  7889. {
  7890. Linked<IPropertyTree> p;
  7891. if (unpack||includeProgress)
  7892. p.setown(ewu->getUnpackedTree(includeProgress));
  7893. else
  7894. p.set(ewu->queryPTree());
  7895. if (hidePasswords && p->hasProp("Variables/Variable[Format/@password]"))
  7896. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  7897. toXML(p, str, 0, XML_Format|XML_SortTags);
  7898. }
  7899. else
  7900. str.append("Unrecognized workunit format");
  7901. return str;
  7902. }
  7903. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords)
  7904. {
  7905. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  7906. if (ewu)
  7907. {
  7908. Linked<IPropertyTree> p;
  7909. if (unpack||includeProgress)
  7910. p.setown(ewu->getUnpackedTree(includeProgress));
  7911. else
  7912. p.set(ewu->queryPTree());
  7913. if (hidePasswords && p->hasProp("Variables/Variable[Format/@password]"))
  7914. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  7915. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  7916. }
  7917. else
  7918. throw makeStringException(0, "Unrecognized workunit format");
  7919. }
  7920. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  7921. {
  7922. MemoryBuffer buffer;
  7923. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  7924. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  7925. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  7926. assertex(workunit);
  7927. SCMStringBuffer token;
  7928. createToken(wuid, username, password, token);
  7929. workunit->setSecurityToken(token.str());
  7930. StringAttr clusterName(workunit->queryClusterName());
  7931. if (!clusterName.length())
  7932. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  7933. workunit->commit();
  7934. workunit.clear();
  7935. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  7936. if (!clusterInfo)
  7937. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName.str());
  7938. SCMStringBuffer serverQueue;
  7939. clusterInfo->getServerQueue(serverQueue);
  7940. assertex(serverQueue.length());
  7941. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  7942. if (!queue.get())
  7943. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  7944. IJobQueueItem *item = createJobQueueItem(wuid);
  7945. queue->enqueue(item);
  7946. }
  7947. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  7948. {
  7949. StringBuffer xpath("/WorkUnitAborts/");
  7950. xpath.append(wuid);
  7951. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  7952. acon->queryRoot()->setPropInt(NULL, 1);
  7953. }
  7954. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  7955. {
  7956. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  7957. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  7958. }
  7959. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  7960. {
  7961. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  7962. abortWorkUnit(wuid);
  7963. }
  7964. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  7965. {
  7966. if (secmgr && secuser)
  7967. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  7968. if (secuser)
  7969. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  7970. submitWorkUnit(wuid, "", "");
  7971. }
  7972. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  7973. {
  7974. if (secmgr && secuser)
  7975. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  7976. abortWorkUnit(wuid);
  7977. }
  7978. bool CLocalWorkUnit::hasWorkflow() const
  7979. {
  7980. return p->hasProp("Workflow");
  7981. }
  7982. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  7983. {
  7984. CriticalBlock block(crit);
  7985. if (p->hasProp("@eventScheduledCount"))
  7986. return p->getPropInt("@eventScheduledCount", 0);
  7987. else
  7988. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  7989. }
  7990. void CLocalWorkUnit::incEventScheduledCount()
  7991. {
  7992. CriticalBlock block(crit);
  7993. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  7994. }
  7995. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  7996. {
  7997. CriticalBlock block(crit);
  7998. return p->queryPropTree("Workflow");
  7999. }
  8000. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  8001. {
  8002. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  8003. CriticalBlock block(crit);
  8004. if(!workflowIteratorCached)
  8005. {
  8006. assertex(!workflowIterator);
  8007. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  8008. if(s)
  8009. workflowIterator.setown(createWorkflowItemIterator(s));
  8010. workflowIteratorCached = true;
  8011. }
  8012. return workflowIterator.getLink();
  8013. }
  8014. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  8015. {
  8016. unsigned count = 0;
  8017. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  8018. for(iter->first(); iter->isValid(); iter->next())
  8019. count++;
  8020. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  8021. for(iter->first(); iter->isValid(); iter->next())
  8022. array->addClone(iter->query());
  8023. return array.getLink();
  8024. }
  8025. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  8026. {
  8027. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8028. CriticalBlock block(crit);
  8029. workflowIterator.clear();
  8030. workflowIteratorCached = false;
  8031. IPropertyTree * s = p->queryPropTree("Workflow");
  8032. if(!s)
  8033. s = p->addPropTree("Workflow", createPTree("Workflow"));
  8034. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  8035. }
  8036. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  8037. {
  8038. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8039. CriticalBlock block(crit);
  8040. if(!workflowIterator)
  8041. {
  8042. IPropertyTree * s = p->queryPropTree("Workflow");
  8043. if(!s)
  8044. s = p->addPropTree("Workflow", createPTree("Workflow"));
  8045. workflowIterator.setown(createWorkflowItemIterator(s));
  8046. workflowIteratorCached = true;
  8047. }
  8048. return workflowIterator.getLink();
  8049. }
  8050. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  8051. {
  8052. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  8053. Owned<IWorkflowItem> item;
  8054. for(iter->first(); iter->isValid(); iter->next())
  8055. {
  8056. item.setown(iter->get());
  8057. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  8058. }
  8059. workflowIterator.clear();
  8060. workflowIteratorCached = false;
  8061. }
  8062. void CLocalWorkUnit::resetWorkflow()
  8063. {
  8064. if (hasWorkflow())
  8065. {
  8066. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  8067. Owned<IWorkflowItem> wf;
  8068. for(iter->first(); iter->isValid(); iter->next())
  8069. {
  8070. wf.setown(iter->get());
  8071. wf->reset();
  8072. }
  8073. workflowIterator.clear();
  8074. workflowIteratorCached = false;
  8075. }
  8076. }
  8077. void CLocalWorkUnit::schedule()
  8078. {
  8079. CriticalBlock block(crit);
  8080. if(queryEventScheduledCount() == 0) return;
  8081. switch(getState())
  8082. {
  8083. case WUStateCompleted:
  8084. setState(WUStateWait);
  8085. break;
  8086. case WUStateFailed:
  8087. case WUStateArchived:
  8088. case WUStateAborting:
  8089. case WUStateAborted:
  8090. case WUStateScheduled:
  8091. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  8092. }
  8093. StringBuffer rootPath;
  8094. rootPath.append("/Schedule/").append(queryClusterName());
  8095. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  8096. Owned<IPropertyTree> root = conn->getRoot();
  8097. if(!root->hasChildren())
  8098. {
  8099. StringBuffer addPath;
  8100. addPath.append("/Schedulers/").append(queryClusterName());
  8101. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  8102. }
  8103. char const * wuid = p->queryName();
  8104. StringBuffer xpath("*/*/");
  8105. ncnameEscape(wuid, xpath);
  8106. bool more;
  8107. do more = root->removeProp(xpath.str()); while(more);
  8108. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  8109. Owned<IWorkflowEvent> event;
  8110. Owned<IPropertyTree> branch1, branch2;
  8111. for(iter->first(); iter->isValid(); iter->next())
  8112. {
  8113. event.setown(iter->query()->getScheduleEvent());
  8114. if(!event) continue;
  8115. ncnameEscape(event->queryName(), xpath.clear());
  8116. ensurePTree(root, xpath.str());
  8117. branch1.setown(root->getPropTree(xpath.str()));
  8118. ncnameEscape(event->queryText(), xpath.clear());
  8119. ensurePTree(branch1, xpath.str());
  8120. branch2.setown(branch1->getPropTree(xpath.str()));
  8121. ncnameEscape(wuid, xpath.clear());
  8122. ensurePTree(branch2, xpath.str());
  8123. }
  8124. }
  8125. void CLocalWorkUnit::deschedule()
  8126. {
  8127. if(queryEventScheduledCount() == 0) return;
  8128. if(getState() == WUStateWait)
  8129. setState(WUStateCompleted);
  8130. doDescheduleWorkkunit(p->queryName());
  8131. }
  8132. mapEnums localFileUploadTypes[] = {
  8133. { UploadTypeFileSpray, "FileSpray" },
  8134. { UploadTypeWUResult, "WUResult" },
  8135. { UploadTypeWUResultCsv, "WUResultCsv" },
  8136. { UploadTypeWUResultXml, "WUResultXml" },
  8137. { UploadTypeSize, NULL }
  8138. };
  8139. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  8140. {
  8141. public:
  8142. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  8143. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  8144. {
  8145. tree.setown(createPTree());
  8146. tree->setPropInt("@id", id);
  8147. setEnum(tree, "@type", type, localFileUploadTypes);
  8148. tree->setProp("@source", source);
  8149. tree->setProp("@destination", destination);
  8150. if (eventTag)
  8151. tree->setProp("@eventTag", eventTag);
  8152. }
  8153. IMPLEMENT_IINTERFACE;
  8154. IPropertyTree * getTree() { return tree.getLink(); }
  8155. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  8156. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  8157. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  8158. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  8159. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  8160. private:
  8161. Owned<IPropertyTree> tree;
  8162. };
  8163. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  8164. {
  8165. public:
  8166. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  8167. IMPLEMENT_IINTERFACE;
  8168. bool first() { return iter->first(); }
  8169. bool isValid() { return iter->isValid(); }
  8170. bool next() { return iter->next(); }
  8171. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  8172. private:
  8173. Owned<IPropertyTree> tree;
  8174. Owned<IPropertyTreeIterator> iter;
  8175. };
  8176. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  8177. {
  8178. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  8179. CriticalBlock block(crit);
  8180. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  8181. if(s)
  8182. return new CLocalFileUploadIterator(s.getClear());
  8183. else
  8184. return NULL;
  8185. }
  8186. bool CLocalWorkUnit::requiresLocalFileUpload() const
  8187. {
  8188. SCMStringBuffer dest;
  8189. Owned<IConstWUResult> result;
  8190. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  8191. if(!iter)
  8192. return false;
  8193. for(iter->first(); iter->isValid(); iter->next())
  8194. {
  8195. Owned<IConstLocalFileUpload> upload(iter->get());
  8196. switch(upload->queryType())
  8197. {
  8198. case UploadTypeWUResult:
  8199. case UploadTypeWUResultCsv:
  8200. case UploadTypeWUResultXml:
  8201. upload->getDestination(dest);
  8202. result.setown(getResultByName(dest.str()));
  8203. if(!result)
  8204. return true;
  8205. break;
  8206. default:
  8207. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  8208. }
  8209. }
  8210. return false;
  8211. }
  8212. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  8213. {
  8214. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8215. CriticalBlock block(crit);
  8216. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  8217. if(!s)
  8218. s = p->addPropTree("LocalFileUploads", createPTree());
  8219. unsigned id = s->numChildren();
  8220. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  8221. s->addPropTree("LocalFileUpload", upload->getTree());
  8222. return id;
  8223. }
  8224. #if 0
  8225. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  8226. {
  8227. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  8228. unsigned deps = 0;
  8229. Owned<IWorkflowDependencyIterator> diter;
  8230. switch(cwf->queryWfid())
  8231. {
  8232. case 1:
  8233. assertex(!cwf->isScheduled());
  8234. assertex(cwf->queryType() == WFTypeNormal);
  8235. assertex(cwf->queryState() == WFStateNull);
  8236. diter.setown(cwf->getDependencies());
  8237. for(diter->first(); diter->isValid(); diter->next())
  8238. deps++;
  8239. assertex(deps==0);
  8240. okay[0] = true;
  8241. break;
  8242. case 2:
  8243. assertex(!cwf->isScheduled());
  8244. assertex(cwf->queryType() == WFTypeRecovery);
  8245. assertex(cwf->queryState() == WFStateSkip);
  8246. okay[1] = true;
  8247. break;
  8248. case 3:
  8249. assertex(cwf->queryContingencyFor() == 4);
  8250. okay[2] = true;
  8251. break;
  8252. case 4:
  8253. assertex(cwf->isScheduled());
  8254. assertex(cwf->queryType() == WFTypeNormal);
  8255. assertex(cwf->queryState() == WFStateReqd);
  8256. assertex(cwf->querySuccess() == 0);
  8257. assertex(cwf->queryFailure() == 3);
  8258. assertex(cwf->queryRecovery() == 2);
  8259. assertex(cwf->queryRetriesAllowed() == 10);
  8260. assertex(cwf->queryRetriesRemaining() == 10);
  8261. diter.setown(cwf->getDependencies());
  8262. for(diter->first(); diter->isValid(); diter->next())
  8263. {
  8264. dep[diter->query()-1] = true;
  8265. deps++;
  8266. }
  8267. assertex(deps==2);
  8268. assertex(dep[0]);
  8269. assertex(dep[1]);
  8270. okay[3] = true;
  8271. break;
  8272. case 5:
  8273. assertex(cwf->isScheduled());
  8274. assertex(!cwf->isScheduledNow());
  8275. assertex(cwf->querySchedulePriority() == 75);
  8276. assertex(cwf->queryScheduleCount() == 5);
  8277. assertex(cwf->queryScheduleCountRemaining() == 5);
  8278. okay[4] = true;
  8279. break;
  8280. case 6:
  8281. assertex(cwf->isScheduled());
  8282. assertex(!cwf->isScheduledNow());
  8283. assertex(cwf->querySchedulePriority() == 25);
  8284. assertex(!cwf->hasScheduleCount());
  8285. okay[5] = true;
  8286. break;
  8287. default:
  8288. assertex(!"unknown wfid in test");
  8289. }
  8290. }
  8291. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  8292. {
  8293. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  8294. switch(rwf->queryWfid())
  8295. {
  8296. case 1:
  8297. case 2:
  8298. case 3:
  8299. okay[rwf->queryWfid()-1] = true;
  8300. break;
  8301. case 4:
  8302. {
  8303. unsigned tries = 0;
  8304. while(rwf->testAndDecRetries())
  8305. tries++;
  8306. assertex(tries == 10);
  8307. assertex(rwf->queryRetriesRemaining() == 0);
  8308. rwf->setState(WFStateFail);
  8309. assertex(rwf->queryState() == WFStateFail);
  8310. rwf->reset();
  8311. assertex(rwf->queryRetriesRemaining() == 10);
  8312. assertex(rwf->queryState() == WFStateReqd);
  8313. }
  8314. okay[3] = true;
  8315. break;
  8316. case 5:
  8317. {
  8318. assertex(rwf->queryScheduleCountRemaining() == 5);
  8319. unsigned count = 0;
  8320. do count++; while(rwf->decAndTestScheduleCountRemaining());
  8321. assertex(count == 5);
  8322. assertex(rwf->queryScheduleCountRemaining() == 0);
  8323. rwf->reset();
  8324. assertex(rwf->queryScheduleCountRemaining() == 5);
  8325. }
  8326. okay[4] = true;
  8327. break;
  8328. case 6:
  8329. {
  8330. assertex(!rwf->hasScheduleCount());
  8331. unsigned count;
  8332. for(count=0; count<20; count++)
  8333. assertex(rwf->decAndTestScheduleCountRemaining());
  8334. }
  8335. okay[5] = true;
  8336. break;
  8337. default:
  8338. assertex(!"unknown wfid in test");
  8339. }
  8340. }
  8341. void testWorkflow()
  8342. {
  8343. DBGLOG("workunit.cpp : testWorkflow");
  8344. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  8345. Owned<IWorkflowItem> wf;
  8346. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  8347. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  8348. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  8349. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  8350. wf->setScheduledNow();
  8351. wf->addDependency(1);
  8352. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  8353. wf->setScheduledOn("test", "foo*");
  8354. wf->setSchedulePriority(75);
  8355. wf->setScheduleCount(5);
  8356. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  8357. wf->setScheduledOn("test", "bar*");
  8358. wf->setSchedulePriority(25);
  8359. unsigned const n = 6;
  8360. bool okay[n];
  8361. bool dep[n];
  8362. unsigned i;
  8363. for(i=0; i<n; i++)
  8364. okay[i] = dep[i] = 0;
  8365. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  8366. for(citer->first(); citer->isValid(); citer->next())
  8367. testConstWorkflow(citer->query(), okay, dep);
  8368. for(i=0; i<n; i++)
  8369. {
  8370. assertex(okay[i]);
  8371. okay[i] = false;
  8372. }
  8373. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  8374. for(miter->first(); miter->isValid(); miter->next())
  8375. {
  8376. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  8377. testRuntimeWorkflow(rwf, okay);
  8378. }
  8379. for(i=0; i<n; i++)
  8380. {
  8381. assertex(okay[i]);
  8382. okay[i] = dep[i] = false;
  8383. }
  8384. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  8385. unsigned wfid;
  8386. for(wfid = 1; array->isValid(wfid); wfid++)
  8387. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  8388. for(i=0; i<n; i++)
  8389. {
  8390. assertex(okay[i]);
  8391. okay[i] = false;
  8392. }
  8393. for(wfid = 1; array->isValid(wfid); wfid++)
  8394. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  8395. for(i=0; i<n; i++)
  8396. {
  8397. assertex(okay[i]);
  8398. okay[i] = false;
  8399. }
  8400. }
  8401. #endif
  8402. //------------------------------------------------------------------------------------------
  8403. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, bool returnOnWaitState)
  8404. {
  8405. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, returnOnWaitState);
  8406. }
  8407. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, bool returnOnWaitState)
  8408. {
  8409. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  8410. return waitForWorkUnitToComplete(wuid, timeout, returnOnWaitState);
  8411. return WUStateUnknown;
  8412. }
  8413. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  8414. {
  8415. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, true))
  8416. {
  8417. case WUStateCompiled:
  8418. case WUStateCompleted:
  8419. case WUStateWait:
  8420. case WUStateUploadingFiles:
  8421. return true;
  8422. default:
  8423. return false;
  8424. }
  8425. }
  8426. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  8427. {
  8428. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  8429. return waitForWorkUnitToCompile(wuid, timeout);
  8430. return false;
  8431. }
  8432. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  8433. {
  8434. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  8435. {
  8436. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  8437. SCMStringBuffer ip;
  8438. unsigned port;
  8439. port = wu->getDebugAgentListenerPort();
  8440. wu->getDebugAgentListenerIP(ip);
  8441. SocketEndpoint debugEP(ip.str(), port);
  8442. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  8443. unsigned len = (size32_t)strlen(command);
  8444. unsigned revlen = len;
  8445. _WINREV(revlen);
  8446. socket->write(&revlen, sizeof(revlen));
  8447. socket->write(command, len);
  8448. for (;;)
  8449. {
  8450. socket->read(&len, sizeof(len));
  8451. _WINREV(len);
  8452. if (len == 0)
  8453. break;
  8454. if (len & 0x80000000)
  8455. {
  8456. throwUnexpected();
  8457. }
  8458. char * mem = (char*) response.reserve(len);
  8459. socket->read(mem, len);
  8460. }
  8461. return true;
  8462. }
  8463. return false;
  8464. }
  8465. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  8466. {
  8467. TypeInfoArray types;
  8468. StringAttrArray names;
  8469. r->getSchema(types, names, NULL);
  8470. if (types.ordinality()==1)
  8471. type.set(&types.item(0));
  8472. }
  8473. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  8474. {
  8475. if (!r->isResultScalar())
  8476. return false;
  8477. if (!curVal.hasChildren())
  8478. return true;
  8479. getSimpleResultType(r, type);
  8480. return type && type->isScalar();
  8481. }
  8482. void updateSuppliedXmlParams(IWorkUnit * w)
  8483. {
  8484. Owned<const IPropertyTree> params = w->getXmlParams();
  8485. if (!params)
  8486. return;
  8487. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  8488. ForEach(*elems)
  8489. {
  8490. IPropertyTree & curVal = elems->query();
  8491. const char *name = curVal.queryName();
  8492. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  8493. if (r)
  8494. {
  8495. Owned<ITypeInfo> type;
  8496. StringBuffer s;
  8497. if (isSuppliedParamScalar(r, curVal, type))
  8498. {
  8499. curVal.getProp(".", s);
  8500. r->setResultXML(s);
  8501. r->setResultStatus(ResultStatusSupplied);
  8502. }
  8503. else
  8504. {
  8505. toXML(&curVal, s);
  8506. if (!type)
  8507. getSimpleResultType(r, type);
  8508. bool isSet = (type && type->getTypeCode()==type_set);
  8509. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  8510. }
  8511. }
  8512. else
  8513. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  8514. }
  8515. }
  8516. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  8517. {
  8518. switch ((int)sequence)
  8519. {
  8520. case ResultSequenceStored:
  8521. return w->updateVariableByName(name);
  8522. case ResultSequencePersist:
  8523. return w->updateGlobalByName(name);
  8524. case ResultSequenceInternal:
  8525. case ResultSequenceOnce:
  8526. return w->updateTemporaryByName(name);
  8527. default:
  8528. return w->updateResultBySequence(sequence);
  8529. }
  8530. }
  8531. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  8532. {
  8533. switch ((int)sequence)
  8534. {
  8535. case ResultSequenceStored:
  8536. return w->getVariableByName(name);
  8537. case ResultSequencePersist:
  8538. return w->getGlobalByName(name);
  8539. case ResultSequenceInternal:
  8540. case ResultSequenceOnce:
  8541. return w->getTemporaryByName(name);
  8542. default:
  8543. if (name && name[0])
  8544. return w->getResultByName(name);//name takes precedence over sequence
  8545. else
  8546. return w->getResultBySequence(sequence);
  8547. }
  8548. }
  8549. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  8550. {
  8551. if (wuid) {
  8552. char prefchar;
  8553. unsigned year,month,day,hour,min,sec;
  8554. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  8555. time.set(year, month, day, hour, min, sec, 0, true);
  8556. // time.setDate(year, month, day);
  8557. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  8558. return true;
  8559. }
  8560. }
  8561. return false;
  8562. }
  8563. extern WORKUNIT_API IStringVal& createToken(const char *wuid, const char *user, const char *password, IStringVal &str)
  8564. {
  8565. StringBuffer wu, token("X");
  8566. wu.append(wuid).append(';').append(user).append(';').append(password);
  8567. encrypt(token,wu.str());
  8568. str.set(token.str());
  8569. return str;
  8570. }
  8571. // This will be replaced by something more secure!
  8572. extern WORKUNIT_API void extractToken(const char *token, const char *wuid, IStringVal &user, IStringVal &password)
  8573. {
  8574. if (token && *token)
  8575. {
  8576. StringBuffer wu;
  8577. decrypt(wu, token+1);
  8578. const char *finger = strchr(wu.str(),';');
  8579. if (finger && strnicmp(wuid, wu.str(), finger-wu.str())==0)
  8580. {
  8581. const char *finger1 = strchr(++finger,';');
  8582. if(finger1)
  8583. {
  8584. user.setLen(finger, (size32_t)(finger1-finger));
  8585. finger1++;
  8586. password.setLen(finger1, (size32_t)(wu.str() + wu.length() - finger1));
  8587. return;
  8588. }
  8589. }
  8590. throw MakeStringException(WUERR_InvalidSecurityToken, "Invalid call to extractToken");
  8591. }
  8592. }
  8593. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  8594. {
  8595. return (WUState) getEnum(state, states);
  8596. }
  8597. const LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  8598. class CWorkflowScheduleConnection : public CInterface, implements IWorkflowScheduleConnection
  8599. {
  8600. public:
  8601. CWorkflowScheduleConnection(char const * wuid)
  8602. {
  8603. basexpath.append("/WorkflowSchedule/").append(wuid);
  8604. flagxpath.append(basexpath.str()).append("/Active");
  8605. }
  8606. IMPLEMENT_IINTERFACE;
  8607. virtual void lock()
  8608. {
  8609. LOG(MCschedconn, "Locking base schedule connection");
  8610. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  8611. if(!baseconn)
  8612. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  8613. }
  8614. virtual void unlock()
  8615. {
  8616. LOG(MCschedconn, "Unlocking base schedule connection");
  8617. baseconn.clear();
  8618. }
  8619. virtual void setActive()
  8620. {
  8621. LOG(MCschedconn, "Setting active flag in schedule connection");
  8622. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  8623. if(!flagconn)
  8624. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  8625. }
  8626. virtual void resetActive()
  8627. {
  8628. LOG(MCschedconn, "Resetting active flag in schedule connection");
  8629. flagconn.clear();
  8630. }
  8631. virtual bool queryActive()
  8632. {
  8633. return baseconn->queryRoot()->hasProp("Active");
  8634. }
  8635. virtual bool pull(IWorkflowItemArray * workflow)
  8636. {
  8637. assertex(baseconn);
  8638. Owned<IPropertyTree> root = baseconn->getRoot();
  8639. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  8640. if(!eventQueue) return false;
  8641. if(!eventQueue->hasProp("Item")) return false;
  8642. {
  8643. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  8644. Owned<IPropertyTree> eventItem;
  8645. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  8646. Owned<IRuntimeWorkflowItem> wfItem;
  8647. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  8648. {
  8649. eventItem.setown(&eventItems->get());
  8650. const char * eventName = eventItem->queryProp("@name");
  8651. const char * eventText = eventItem->queryProp("@text");
  8652. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  8653. {
  8654. wfItem.setown(wfItems->get());
  8655. if(wfItem->queryState() != WFStateWait)
  8656. continue;
  8657. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  8658. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  8659. continue;
  8660. wfItem->setEvent(eventName, eventText);
  8661. wfItem->setState(WFStateReqd);
  8662. resetDependentsState(workflow, *wfItem);
  8663. }
  8664. }
  8665. }
  8666. bool more;
  8667. do
  8668. more = eventQueue->removeProp("Item");
  8669. while(more);
  8670. return true;
  8671. }
  8672. virtual void push(char const * name, char const * text)
  8673. {
  8674. assertex(baseconn);
  8675. Owned<IPropertyTree> root = baseconn->getRoot();
  8676. ensurePTree(root, "EventQueue");
  8677. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  8678. Owned<IPropertyTree> eventItem = createPTree();
  8679. eventItem->setProp("@name", name);
  8680. eventItem->setProp("@text", text);
  8681. eventQueue->addPropTree("Item", eventItem.getLink());
  8682. }
  8683. virtual void remove()
  8684. {
  8685. if (baseconn)
  8686. {
  8687. baseconn->close(true);
  8688. baseconn.clear();
  8689. }
  8690. }
  8691. private:
  8692. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  8693. {
  8694. if (wfid)
  8695. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  8696. }
  8697. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  8698. {
  8699. switch(item.queryState())
  8700. {
  8701. case WFStateDone:
  8702. case WFStateFail:
  8703. {
  8704. item.setState(WFStateNull);
  8705. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  8706. resetDependentsState(workflow, item);
  8707. break;
  8708. }
  8709. }
  8710. }
  8711. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  8712. {
  8713. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  8714. for(iter->first(); iter->isValid(); iter->next())
  8715. {
  8716. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  8717. resetItemStateAndDependents(workflow, dep);
  8718. }
  8719. }
  8720. private:
  8721. StringBuffer basexpath;
  8722. StringBuffer flagxpath;
  8723. Owned<IRemoteConnection> baseconn;
  8724. Owned<IRemoteConnection> flagconn;
  8725. };
  8726. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  8727. {
  8728. return new CWorkflowScheduleConnection(wuid);
  8729. }
  8730. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  8731. {
  8732. return QUERYINTERFACE(wu, IExtendedWUInterface);
  8733. }
  8734. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  8735. {
  8736. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  8737. }
  8738. extern WORKUNIT_API void addExceptionToWorkunit(IWorkUnit * wu, ErrorSeverity severity, const char * source, unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column)
  8739. {
  8740. Owned<IWUException> we = wu->createException();
  8741. we->setSeverity(severity);
  8742. we->setExceptionMessage(text);
  8743. if (source)
  8744. we->setExceptionSource(source);
  8745. if (code)
  8746. we->setExceptionCode(code);
  8747. if (filename)
  8748. we->setExceptionFileName(filename);
  8749. if (lineno)
  8750. {
  8751. we->setExceptionLineNo(lineno);
  8752. if (column)
  8753. we->setExceptionColumn(lineno);
  8754. }
  8755. }
  8756. const char * skipLeadingXml(const char * text)
  8757. {
  8758. if (!text)
  8759. return NULL;
  8760. //skip utf8 BOM, probably excessive
  8761. if (memcmp(text, UTF8_BOM, 3) == 0)
  8762. text += 3;
  8763. loop
  8764. {
  8765. if (isspace(*text))
  8766. text++;
  8767. else if (text[0] == '<' && text[1] == '?')
  8768. {
  8769. text += 2;
  8770. loop
  8771. {
  8772. if (!*text) break;
  8773. if (text[0] == '?' && text[1] == '>')
  8774. {
  8775. text += 2;
  8776. break;
  8777. }
  8778. text++;
  8779. }
  8780. }
  8781. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  8782. {
  8783. text += 4;
  8784. loop
  8785. {
  8786. if (!*text) break;
  8787. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  8788. {
  8789. text += 3;
  8790. break;
  8791. }
  8792. text++;
  8793. }
  8794. }
  8795. else
  8796. break;
  8797. }
  8798. return text;
  8799. }
  8800. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  8801. {
  8802. text = skipLeadingXml(text);
  8803. if (!text)
  8804. return false;
  8805. const char * archivePrefix = "<Archive";
  8806. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  8807. }
  8808. extern WORKUNIT_API bool isQueryManifest(const char * text)
  8809. {
  8810. text = skipLeadingXml(text);
  8811. if (!text)
  8812. return false;
  8813. const char * manifestPrefix = "<Manifest";
  8814. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  8815. }
  8816. //------------------------------------------------------------------------------
  8817. // Named Alias helper function
  8818. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  8819. {
  8820. StringBuffer xpath;
  8821. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  8822. return queryRegistry->getPropTree(xpath);
  8823. }
  8824. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  8825. {
  8826. StringBuffer xpath;
  8827. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  8828. return queryRegistry->getPropTree(xpath);
  8829. }
  8830. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  8831. {
  8832. StringBuffer lcId(id);
  8833. lcId.toLowerCase();
  8834. StringBuffer xpath;
  8835. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  8836. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  8837. ForEach(*iter)
  8838. {
  8839. queryRegistry->removeProp(xpath.str());
  8840. }
  8841. }
  8842. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  8843. {
  8844. StringBuffer lcName(name);
  8845. lcName.toLowerCase();
  8846. StringBuffer xpath;
  8847. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  8848. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  8849. unsigned seq = 1;
  8850. ForEach(*iter)
  8851. {
  8852. IPropertyTree &item = iter->query();
  8853. const char *thisWuid = item.queryProp("@wuid");
  8854. if (strieq(wuid, thisWuid))
  8855. return &item;
  8856. unsigned thisSeq = item.getPropInt("@seq");
  8857. if (thisSeq >= seq)
  8858. seq = thisSeq + 1;
  8859. }
  8860. StringBuffer id;
  8861. id.append(lcName).append(".").append(seq);
  8862. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive);
  8863. newEntry->setProp("@name", lcName);
  8864. newEntry->setProp("@wuid", wuid);
  8865. newEntry->setProp("@dll", dll);
  8866. newEntry->setProp("@id", id);
  8867. newEntry->setPropInt("@seq", seq);
  8868. if (library)
  8869. newEntry->setPropBool("@isLibrary", true);
  8870. if (userid && *userid)
  8871. newEntry->setProp("@publishedBy", userid);
  8872. if (snapshot && *snapshot)
  8873. newEntry->setProp("@snapshot", snapshot);
  8874. return queryRegistry->addPropTree("Query", newEntry);
  8875. }
  8876. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  8877. {
  8878. StringBuffer lcId(id);
  8879. lcId.toLowerCase();
  8880. clearAliases(queryRegistry, lcId);
  8881. StringBuffer xpath;
  8882. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  8883. queryRegistry->removeProp(xpath);
  8884. }
  8885. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  8886. {
  8887. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  8888. if (!match)
  8889. return;
  8890. clearAliases(queryRegistry, match->queryProp("@id"));
  8891. queryRegistry->removeTree(match);
  8892. }
  8893. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  8894. {
  8895. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  8896. if (!match)
  8897. return;
  8898. clearAliases(queryRegistry, match->queryProp("@id"));
  8899. queryRegistry->removeTree(match);
  8900. }
  8901. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  8902. {
  8903. clearAliases(queryRegistry, id);
  8904. }
  8905. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  8906. {
  8907. StringBuffer lcName(name);
  8908. lcName.toLowerCase();
  8909. StringBuffer xpath;
  8910. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  8911. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  8912. if (!match)
  8913. {
  8914. IPropertyTree * newEntry = createPTree("Alias");
  8915. newEntry->setProp("@name", lcName);
  8916. match = queryRegistry->addPropTree("Alias", newEntry);
  8917. }
  8918. match->setProp("@id", value);
  8919. }
  8920. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  8921. {
  8922. if (!queryRegistry || !queryid)
  8923. return NULL;
  8924. StringBuffer xpath;
  8925. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  8926. return queryRegistry->getPropTree(xpath);
  8927. }
  8928. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  8929. {
  8930. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  8931. return getQueryById(queryRegistry, queryid);
  8932. }
  8933. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  8934. {
  8935. if (!queryRegistry || !alias)
  8936. return NULL;
  8937. StringBuffer xpath;
  8938. unsigned cnt = 0;
  8939. StringBuffer lc(alias);
  8940. const char * search = lc.toLowerCase().str();
  8941. loop
  8942. {
  8943. xpath.set("Alias[@name='").append(search).append("']/@id");
  8944. const char * queryId = queryRegistry->queryProp(xpath);
  8945. if (!queryId)
  8946. break;
  8947. //Check for too many alias indirections.
  8948. if (cnt++ > 10)
  8949. return NULL;
  8950. search = lc.set(queryId).toLowerCase().str();
  8951. }
  8952. return getQueryById(queryRegistry, search);
  8953. }
  8954. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  8955. {
  8956. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  8957. return resolveQueryAlias(queryRegistry, alias);
  8958. }
  8959. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  8960. {
  8961. StringBuffer lcId(id);
  8962. lcId.toLowerCase();
  8963. StringBuffer xpath;
  8964. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  8965. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  8966. if (tree)
  8967. {
  8968. if (tree->getPropBool("@suspended", false) == suspend)
  8969. return;
  8970. if (suspend)
  8971. {
  8972. tree->addPropBool("@suspended", true);
  8973. if (userid && *userid)
  8974. tree->addProp("@suspendedBy", userid);
  8975. }
  8976. else
  8977. {
  8978. tree->removeProp("@suspended");
  8979. tree->removeProp("@suspendedBy");
  8980. }
  8981. }
  8982. else
  8983. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  8984. }
  8985. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  8986. {
  8987. if (queryComment)
  8988. {
  8989. StringBuffer lcId(id);
  8990. lcId.toLowerCase();
  8991. StringBuffer xpath;
  8992. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  8993. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  8994. if (tree)
  8995. tree->setProp("@queryComment", queryComment);
  8996. else
  8997. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  8998. }
  8999. }
  9000. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  9001. {
  9002. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  9003. if (conn)
  9004. return conn->getRoot();
  9005. else
  9006. return NULL;
  9007. }
  9008. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  9009. {
  9010. if (!queryTree || !libraries)
  9011. return;
  9012. if (queryTree->hasProp("@libCount")) //already added
  9013. return;
  9014. unsigned libCount=0;
  9015. ForEach(*libraries)
  9016. {
  9017. IConstWULibrary &library = libraries->query();
  9018. SCMStringBuffer libname;
  9019. if (!library.getName(libname).length())
  9020. continue;
  9021. queryTree->addProp("Library", libname.str());
  9022. libCount++;
  9023. }
  9024. queryTree->setPropInt("@libCount", libCount);
  9025. }
  9026. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  9027. {
  9028. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  9029. checkAddLibrariesToQueryEntry(queryTree, libraries);
  9030. }
  9031. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  9032. {
  9033. //Only lock the branch for the target we're interested in.
  9034. StringBuffer xpath;
  9035. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  9036. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  9037. if (conn)
  9038. return conn->getRoot();
  9039. if (readonly)
  9040. return NULL;
  9041. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  9042. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  9043. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  9044. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  9045. if (conn)
  9046. return conn->getRoot();
  9047. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  9048. if (!conn)
  9049. throwUnexpected();
  9050. IPropertyTree * root = conn->queryRoot();
  9051. root->setProp("@id",wsEclId);
  9052. conn->commit();
  9053. return LINK(root);
  9054. }
  9055. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  9056. {
  9057. StringBuffer xpath;
  9058. StringBuffer lcName(name);
  9059. lcName.toLowerCase();
  9060. // see if "name" already exists
  9061. xpath.append("Package[@id='").append(name).append("']");
  9062. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  9063. if (pkgTree)
  9064. {
  9065. if (overWrite)
  9066. packageRegistry->removeTree(pkgTree);
  9067. else
  9068. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  9069. }
  9070. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  9071. tree->setProp("@id", lcName);
  9072. return tree;
  9073. }
  9074. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  9075. {
  9076. StringBuffer lcId(id);
  9077. lcId.toLowerCase();
  9078. StringBuffer xpath;
  9079. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  9080. packageRegistry->removeProp(xpath);
  9081. }
  9082. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  9083. {
  9084. //Only lock the branch for the target we're interested in.
  9085. StringBuffer xpath;
  9086. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  9087. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  9088. if (conn)
  9089. return conn->getRoot();
  9090. if (readonly)
  9091. return NULL;
  9092. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  9093. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  9094. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  9095. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  9096. if (conn)
  9097. return conn->getRoot();
  9098. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  9099. if (!conn)
  9100. throwUnexpected();
  9101. IPropertyTree* root = conn->queryRoot();
  9102. root->setProp("@id",wsEclId);
  9103. conn->commit();
  9104. return LINK(root);
  9105. }
  9106. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  9107. {
  9108. StringBuffer cleanQueryName;
  9109. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  9110. SCMStringBuffer dllName;
  9111. Owned<IConstWUQuery> q = workunit->getQuery();
  9112. q->getQueryDllName(dllName);
  9113. if (!dllName.length())
  9114. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  9115. StringBuffer currentTargetClusterType;
  9116. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  9117. SCMStringBuffer targetClusterType;
  9118. workunit->getDebugValue("targetclustertype", targetClusterType);
  9119. SCMStringBuffer snapshot;
  9120. workunit->getSnapshot(snapshot);
  9121. if (currentTargetClusterType.length() < 1)
  9122. {
  9123. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  9124. }
  9125. else
  9126. {
  9127. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  9128. {
  9129. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  9130. }
  9131. }
  9132. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  9133. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  9134. checkAddLibrariesToQueryEntry(newEntry, libraries);
  9135. newQueryId.append(newEntry->queryProp("@id"));
  9136. workunit->setIsQueryService(true); //will check querysets before delete
  9137. workunit->commit();
  9138. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  9139. }
  9140. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  9141. {
  9142. StringBuffer cleanQueryName;
  9143. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  9144. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  9145. {
  9146. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  9147. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  9148. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  9149. {
  9150. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  9151. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  9152. else
  9153. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  9154. }
  9155. }
  9156. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  9157. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  9158. }
  9159. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  9160. {
  9161. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  9162. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  9163. }
  9164. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  9165. {
  9166. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9167. StringBuffer xpath;
  9168. xpath.appendf("Alias[@name='%s']", alias);
  9169. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  9170. return queryRegistry->removeTree(t);
  9171. }
  9172. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  9173. {
  9174. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  9175. setQueryAlias(queryRegistry, alias, id);
  9176. }
  9177. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  9178. {
  9179. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9180. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  9181. }
  9182. void deleteQuerySetQuery(const char *querySetName, const char *id)
  9183. {
  9184. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9185. removeNamedQuery(queryRegistry, id);
  9186. }
  9187. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  9188. {
  9189. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9190. clearAliases(queryRegistry, id);
  9191. }
  9192. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  9193. {
  9194. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9195. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  9196. }
  9197. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  9198. {
  9199. if (!queryRegistry)
  9200. return NULL;
  9201. StringBuffer xpath;
  9202. xpath.appendf("Query[@wuid='%s']", wuid);
  9203. if (queryName && *queryName)
  9204. xpath.appendf("[@name='%s']", queryName);
  9205. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  9206. if (q)
  9207. {
  9208. id.set(q->queryProp("@id"));
  9209. }
  9210. return id.str();
  9211. }
  9212. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  9213. {
  9214. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9215. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  9216. }
  9217. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  9218. {
  9219. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  9220. ForEach(*wulibraries)
  9221. {
  9222. SCMStringBuffer libname;
  9223. IConstWULibrary &wulibrary = wulibraries->query();
  9224. wulibrary.getName(libname);
  9225. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  9226. continue;
  9227. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  9228. if (query && query->getPropBool("@isLibrary"))
  9229. {
  9230. const char *wuid = query->queryProp("@wuid");
  9231. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  9232. if (libcw)
  9233. {
  9234. names.appendUniq(libname.str());
  9235. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  9236. continue;
  9237. }
  9238. }
  9239. unresolved.appendUniq(libname.str());
  9240. }
  9241. }
  9242. bool looksLikeAWuid(const char * wuid, const char firstChar)
  9243. {
  9244. if (!wuid)
  9245. return false;
  9246. if (wuid[0] != firstChar)
  9247. return false;
  9248. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  9249. return false;
  9250. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  9251. return false;
  9252. return (wuid[9]=='-');
  9253. }
  9254. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  9255. {
  9256. IPropertyTree * module = archive;
  9257. const char * dot = strrchr(path, '.');
  9258. StringBuffer xpath;
  9259. if (dot)
  9260. {
  9261. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  9262. module = archive->queryPropTree(xpath);
  9263. path = dot+1;
  9264. }
  9265. else
  9266. module = archive->queryPropTree("Module[@key='']");
  9267. if (!module)
  9268. return NULL;
  9269. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  9270. return module->queryPropTree(xpath);
  9271. }
  9272. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc)
  9273. {
  9274. StringBuffer hostname;
  9275. queryHostIP().getIpText(hostname);
  9276. StringBuffer fullPathname;
  9277. makeAbsolutePath(name, fullPathname);
  9278. query->addAssociatedFile(type, fullPathname, hostname, description, crc);
  9279. }
  9280. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  9281. {
  9282. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  9283. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  9284. if(workunit)
  9285. workunit->deschedule();
  9286. else
  9287. doDescheduleWorkkunit(wuid);
  9288. }
  9289. extern WORKUNIT_API void updateWorkunitTimeStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value)
  9290. {
  9291. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, description, value, 1, 0, StatsMergeReplace);
  9292. }
  9293. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  9294. {
  9295. StringBuffer scope;
  9296. for (unsigned i = 0; i < timer->numSections(); i++)
  9297. {
  9298. StatisticScopeType scopeType= timer->getScopeType(i);
  9299. timer->getScope(i, scope.clear());
  9300. StatisticKind kind = timer->getTimerType(i);
  9301. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, timer->getTime(i), timer->getCount(i), timer->getMaxTime(i), StatsMergeReplace);
  9302. }
  9303. }
  9304. extern WORKUNIT_API void getWorkunitTotalTime(IConstWorkUnit* workunit, const char* creator, unsigned __int64 & totalTimeNs, unsigned __int64 & totalThisTimeNs)
  9305. {
  9306. StatisticsFilter summaryTimeFilter(SCTsummary, creator, SSTglobal, GLOBAL_SCOPE, SMeasureTimeNs, StTimeElapsed);
  9307. Owned<IConstWUStatistic> totalThorTime = getStatistic(workunit, summaryTimeFilter);
  9308. Owned<IConstWUStatistic> totalThisThorTime = workunit->getStatistic(queryStatisticsComponentName(), GLOBAL_SCOPE, StTimeElapsed);
  9309. if (totalThorTime)
  9310. totalTimeNs = totalThorTime->getValue();
  9311. else
  9312. totalTimeNs = 0;
  9313. if (totalThisThorTime)
  9314. totalThisTimeNs = totalThisThorTime->getValue();
  9315. else
  9316. totalThisTimeNs = 0;
  9317. }
  9318. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind)
  9319. {
  9320. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  9321. }
  9322. IConstWUStatistic * getStatistic(IConstWorkUnit * wu, const IStatisticsFilter & filter)
  9323. {
  9324. Owned<IConstWUStatisticIterator> iter = &wu->getStatistics(&filter);
  9325. if (iter->first())
  9326. return &OLINK(iter->query());
  9327. return NULL;
  9328. }
  9329. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  9330. {
  9331. public:
  9332. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  9333. virtual void beginScope(const StatsScopeId & id)
  9334. {
  9335. prevLenStack.append(scope.length());
  9336. if (scope.length())
  9337. scope.append(":");
  9338. id.getScopeText(scope);
  9339. scopeTypeStack.append(id.queryScopeType());
  9340. }
  9341. virtual void beginSubGraphScope(unsigned id)
  9342. {
  9343. StatsScopeId scopeId(SSTsubgraph, id);
  9344. beginScope(scopeId);
  9345. }
  9346. virtual void beginActivityScope(unsigned id)
  9347. {
  9348. StatsScopeId scopeId(SSTactivity, id);
  9349. beginScope(scopeId);
  9350. }
  9351. virtual void beginEdgeScope(unsigned id, unsigned oid)
  9352. {
  9353. StatsScopeId scopeId(SSTedge, id, oid);
  9354. beginScope(scopeId);
  9355. }
  9356. virtual void endScope()
  9357. {
  9358. scope.setLength(prevLenStack.popGet());
  9359. scopeTypeStack.pop();
  9360. }
  9361. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  9362. {
  9363. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  9364. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  9365. }
  9366. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  9367. {
  9368. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  9369. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  9370. }
  9371. virtual IStatisticCollection * getResult()
  9372. {
  9373. return NULL;
  9374. }
  9375. protected:
  9376. Linked<IWorkUnit> wu;
  9377. StringBuffer scope;
  9378. UnsignedArray prevLenStack;
  9379. UnsignedArray scopeTypeStack;
  9380. };
  9381. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  9382. {
  9383. return new GlobalStatisticGatherer(wu);
  9384. }