workunit.cpp 289 KB

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