workunit.cpp 301 KB

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