workunit.cpp 301 KB

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