workunit.cpp 348 KB

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