workunit.cpp 307 KB

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