workunit.cpp 338 KB

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