ws_dfuService.cpp 233 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457
  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. #pragma warning (disable : 4786)
  14. #include <math.h>
  15. #include "daclient.hpp"
  16. #include "daft.hpp"
  17. #include "daftcfg.hpp"
  18. #include "fterror.hpp"
  19. #include "fverror.hpp"
  20. #include "daftprogress.hpp"
  21. #include "mpbase.hpp"
  22. #include "daclient.hpp"
  23. #include "dadfs.hpp"
  24. #include "dafdesc.hpp"
  25. #include "dasds.hpp"
  26. #include "danqs.hpp"
  27. #include "dalienv.hpp"
  28. #include "dautils.hpp"
  29. #include "jfile.hpp"
  30. #include "wshelpers.hpp"
  31. #include "LogicFileWrapper.hpp"
  32. #include "rmtfile.hpp"
  33. #include "dfuutil.hpp"
  34. #include "TpWrapper.hpp"
  35. #include "WUWrapper.hpp"
  36. #include "portlist.h"
  37. #include "roxiecommlib.hpp"
  38. #include "dfuwu.hpp"
  39. #include "fverror.hpp"
  40. #include "nbcd.hpp"
  41. #include "jstring.hpp"
  42. #include "exception_util.hpp"
  43. #include "ws_dfuService.hpp"
  44. #include "hqlerror.hpp"
  45. #include "hqlexpr.hpp"
  46. #include "hqlutil.hpp"
  47. #include "eclrtl.hpp"
  48. #include "package.h"
  49. #include "daaudit.hpp"
  50. #include "jflz.hpp"
  51. #include "digisign.hpp"
  52. using namespace cryptohelper;
  53. #define Action_Delete "Delete"
  54. #define Action_AddtoSuperfile "Add To Superfile"
  55. static const char* FEATURE_URL="DfuAccess";
  56. #define FILE_NEWEST 1
  57. #define FILE_OLDEST 2
  58. #define FILE_LARGEST 3
  59. #define FILE_SMALLEST 4
  60. #define COUNTBY_SCOPE "Scope"
  61. #define COUNTBY_OWNER "Owner"
  62. #define COUNTBY_DATE "Date"
  63. #define COUNTBY_YEAR "Year"
  64. #define COUNTBY_QUARTER "Quarter"
  65. #define COUNTBY_MONTH "Month"
  66. #define COUNTBY_DAY "Day"
  67. #define REMOVE_FILE_SDS_CONNECT_TIMEOUT (1000*15) // 15 seconds
  68. static const char *DFUFileIdSeparator = "|";
  69. static const char *DFUFileCreate_FileNamePostfix = ".wsdfucreate.tmp";
  70. static const char *DFUFileCreate_GroupNamePrefix = "wsdfucreate";
  71. static const char *ConfigurationDirectoryForDataCategory = "data";
  72. const unsigned NODE_GROUP_CACHE_DEFAULT_TIMEOUT = 30*60*1000; //30 minutes
  73. const unsigned MAX_VIEWKEYFILE_ROWS = 1000;
  74. const unsigned MAX_KEY_ROWS = 20;
  75. short days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  76. CThorNodeGroup* CThorNodeGroupCache::readNodeGroup(const char* _groupName)
  77. {
  78. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  79. Owned<IConstEnvironment> env = factory->openEnvironment();
  80. Owned<IPropertyTree> root = &env->getPTree();
  81. Owned<IPropertyTreeIterator> it= root->getElements("Software/ThorCluster");
  82. ForEach(*it)
  83. {
  84. IPropertyTree& cluster = it->query();
  85. StringBuffer groupName;
  86. getClusterGroupName(cluster, groupName);
  87. if (groupName.length() && strieq(groupName.str(), _groupName))
  88. return new CThorNodeGroup(_groupName, cluster.getCount("ThorSlaveProcess"), cluster.getPropBool("@replicateOutputs", false));
  89. }
  90. return NULL;
  91. }
  92. CThorNodeGroup* CThorNodeGroupCache::lookup(const char* groupName, unsigned timeout)
  93. {
  94. CriticalBlock block(sect);
  95. CThorNodeGroup* item=SuperHashTableOf<CThorNodeGroup, const char>::find(groupName);
  96. if (item && !item->checkTimeout(timeout))
  97. return LINK(item);
  98. Owned<CThorNodeGroup> e = readNodeGroup(groupName);
  99. if (e)
  100. replace(*e.getLink()); //if not exists, will be added.
  101. return e.getClear();
  102. }
  103. void CWsDfuEx::init(IPropertyTree *cfg, const char *process, const char *service)
  104. {
  105. DBGLOG("Initializing %s service [process = %s]", service, process);
  106. espProcess.set(process);
  107. VStringBuffer xpath("Software/EspProcess[@name=\"%s\"]", process);
  108. IPropertyTree *processTree = cfg->queryPropTree(xpath);
  109. if (!processTree)
  110. throw MakeStringException(-1, "config not found for process %s", process);
  111. xpath.clear().appendf("EspService[@name=\"%s\"]", service);
  112. IPropertyTree *serviceTree = processTree->queryPropTree(xpath);
  113. if (!serviceTree)
  114. throw MakeStringException(-1, "config not found for service %s", service);
  115. serviceTree->getProp("DefaultScope", defaultScope_);
  116. serviceTree->getProp("User", user_);
  117. serviceTree->getProp("Password", password_);
  118. StringBuffer disableUppercaseTranslation;
  119. serviceTree->getProp("DisableUppercaseTranslation", disableUppercaseTranslation);
  120. m_clusterName.clear();
  121. serviceTree->getProp("ClusterName", m_clusterName);
  122. const char * plugins = serviceTree->queryProp("Plugins/@path");
  123. if (plugins)
  124. queryTransformerRegistry().addPlugins(plugins);
  125. m_disableUppercaseTranslation = false;
  126. if (streq(disableUppercaseTranslation.str(), "true"))
  127. m_disableUppercaseTranslation = true;
  128. if (processTree->hasProp("@PageCacheTimeoutSeconds"))
  129. setPageCacheTimeoutMilliSeconds(processTree->getPropInt("@PageCacheTimeoutSeconds"));
  130. if (processTree->hasProp("@MaxPageCacheItems"))
  131. setMaxPageCacheItems(processTree->getPropInt("@MaxPageCacheItems"));
  132. int timeout = serviceTree->getPropInt("NodeGroupCacheMinutes", -1);
  133. if (timeout > -1)
  134. nodeGroupCacheTimeout = (unsigned) timeout*60*1000;
  135. else
  136. nodeGroupCacheTimeout = NODE_GROUP_CACHE_DEFAULT_TIMEOUT;
  137. thorNodeGroupCache.setown(new CThorNodeGroupCache());
  138. if (!daliClientActive())
  139. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  140. setDaliServixSocketCaching(true);
  141. factory.setown(getEnvironmentFactory(true));
  142. env.setown(factory->openEnvironment());
  143. maxFileAccessExpirySeconds = serviceTree->getPropInt("@maxFileAccessExpirySeconds", defaultMaxFileAccessExpirySeconds);
  144. }
  145. bool CWsDfuEx::onDFUSearch(IEspContext &context, IEspDFUSearchRequest & req, IEspDFUSearchResponse & resp)
  146. {
  147. try
  148. {
  149. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUSearch: Permission denied.");
  150. StringBuffer username;
  151. context.getUserID(username);
  152. Owned<IUserDescriptor> userdesc;
  153. if(username.length() > 0)
  154. {
  155. userdesc.setown(createUserDescriptor());
  156. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  157. }
  158. CTpWrapper dummy;
  159. IArrayOf<IEspTpCluster> clusters;
  160. dummy.getClusterProcessList(eqThorCluster, clusters);
  161. dummy.getHthorClusterList(clusters);
  162. StringArray dfuclusters;
  163. ForEachItemIn(k, clusters)
  164. {
  165. IEspTpCluster& cluster = clusters.item(k);
  166. dfuclusters.append(cluster.getName());
  167. }
  168. IArrayOf<IEspTpCluster> clusters1;
  169. dummy.getClusterProcessList(eqRoxieCluster, clusters1);
  170. ForEachItemIn(k1, clusters1)
  171. {
  172. IEspTpCluster& cluster = clusters1.item(k1);
  173. StringBuffer slaveName = cluster.getName();
  174. dfuclusters.append(slaveName.str());
  175. }
  176. StringArray ftarray;
  177. ftarray.append("Logical Files and Superfiles");
  178. ftarray.append("Logical Files Only");
  179. ftarray.append("Superfiles Only");
  180. ftarray.append("Not in Superfiles");
  181. if (req.getShowExample() && *req.getShowExample())
  182. resp.setShowExample(req.getShowExample());
  183. resp.setClusterNames(dfuclusters);
  184. resp.setFileTypes(ftarray);
  185. }
  186. catch(IException* e)
  187. {
  188. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  189. }
  190. return true;
  191. }
  192. void addToQueryString(StringBuffer &queryString, const char *name, const char *value)
  193. {
  194. if (queryString.length() > 0)
  195. {
  196. queryString.append("&");
  197. }
  198. queryString.append(name);
  199. queryString.append("=");
  200. queryString.append(value);
  201. }
  202. void addToQueryStringFromInt(StringBuffer &queryString, const char *name, __int64 value)
  203. {
  204. if (queryString.length() > 0)
  205. {
  206. queryString.append("&");
  207. }
  208. queryString.append(name);
  209. queryString.append("=");
  210. queryString.append(value);
  211. }
  212. void parseTwoStringArrays(const char *input, StringArray& strarray1, StringArray& strarray2)
  213. {
  214. if (!input || strlen(input) <= 2)
  215. return;
  216. char c0[2], c1[2];
  217. c0[0] = input[0], c0[1] = 0;
  218. c1[0] = input[1], c1[1] = 0;
  219. //the first string usually is a name; the second is a value
  220. unsigned int name_len = atoi(c0);
  221. unsigned int value_len = atoi(c1);
  222. if (name_len > 0 && value_len > 0)
  223. {
  224. char * inputText = (char *) input;
  225. inputText += 2; //skip 2 chars
  226. for (;;)
  227. {
  228. if (!inputText || strlen(inputText) < name_len + value_len)
  229. break;
  230. StringBuffer columnNameLenStr, columnValueLenStr;
  231. for (unsigned i_name = 0; i_name < name_len; i_name++)
  232. {
  233. columnNameLenStr.append(inputText[0]);
  234. inputText++;
  235. }
  236. for (unsigned i_value = 0; i_value < value_len; i_value++)
  237. {
  238. columnValueLenStr.append(inputText[0]);
  239. inputText++;
  240. }
  241. unsigned columnNameLen = atoi(columnNameLenStr.str());
  242. unsigned columnValueLen = atoi(columnValueLenStr.str());
  243. if (!inputText || strlen(inputText) < columnNameLen + columnValueLen)
  244. break;
  245. char * colon = inputText + columnNameLen;
  246. if (!colon)
  247. break;
  248. StringAttr tmp;
  249. tmp.set(inputText, columnNameLen);
  250. strarray1.append(tmp.get());
  251. tmp.set(colon, columnValueLen);
  252. //tmp.toUpperCase();
  253. strarray2.append(tmp.get());
  254. inputText = colon + columnValueLen;
  255. }
  256. }
  257. return;
  258. }
  259. bool CWsDfuEx::onDFUQuery(IEspContext &context, IEspDFUQueryRequest & req, IEspDFUQueryResponse & resp)
  260. {
  261. try
  262. {
  263. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUQuery: Permission denied.");
  264. StringBuffer username;
  265. context.getUserID(username);
  266. Owned<IUserDescriptor> userdesc;
  267. if(username.length() > 0)
  268. {
  269. userdesc.setown(createUserDescriptor());
  270. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  271. }
  272. doLogicalFileSearch(context, userdesc.get(), req, resp);
  273. }
  274. catch(IException* e)
  275. {
  276. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  277. }
  278. return true;
  279. }
  280. bool CWsDfuEx::onDFUInfo(IEspContext &context, IEspDFUInfoRequest &req, IEspDFUInfoResponse &resp)
  281. {
  282. try
  283. {
  284. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUInfo: Permission denied.");
  285. StringBuffer username;
  286. context.getUserID(username);
  287. Owned<IUserDescriptor> userdesc;
  288. if(username.length() > 0)
  289. {
  290. userdesc.setown(createUserDescriptor());
  291. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  292. }
  293. if (req.getUpdateDescription())
  294. {
  295. double version = context.getClientVersion();
  296. if (version < 1.38)
  297. doGetFileDetails(context, userdesc.get(), req.getFileName(), req.getCluster(), req.getQuerySet(), req.getQuery(), req.getFileDesc(),
  298. req.getIncludeJsonTypeInfo(), req.getIncludeBinTypeInfo(), req.getProtect(), resp.updateFileDetail());
  299. else
  300. doGetFileDetails(context, userdesc.get(), req.getName(), req.getCluster(), req.getQuerySet(), req.getQuery(), req.getFileDesc(),
  301. req.getIncludeJsonTypeInfo(), req.getIncludeBinTypeInfo(), req.getProtect(), resp.updateFileDetail());
  302. }
  303. else
  304. {
  305. doGetFileDetails(context, userdesc.get(), req.getName(), req.getCluster(), req.getQuerySet(), req.getQuery(), NULL,
  306. req.getIncludeJsonTypeInfo(), req.getIncludeBinTypeInfo(), req.getProtect(), resp.updateFileDetail());
  307. }
  308. }
  309. catch(IException* e)
  310. {
  311. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  312. }
  313. return true;
  314. }
  315. bool CWsDfuEx::onDFUSpace(IEspContext &context, IEspDFUSpaceRequest & req, IEspDFUSpaceResponse & resp)
  316. {
  317. try
  318. {
  319. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUSpace: Permission denied.");
  320. StringBuffer username;
  321. context.getUserID(username);
  322. Owned<IUserDescriptor> userdesc;
  323. if(username.length() > 0)
  324. {
  325. userdesc.setown(createUserDescriptor());
  326. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  327. }
  328. const char *countby = req.getCountBy();
  329. if (!countby || strlen(countby) < 1)
  330. return true;
  331. char *scopeName = NULL;
  332. StringBuffer filter;
  333. if(req.getScopeUnder() && *req.getScopeUnder())
  334. {
  335. scopeName = (char *) req.getScopeUnder();
  336. filter.appendf("%s::*", scopeName);
  337. resp.setScopeUnder(req.getScopeUnder());
  338. }
  339. else
  340. {
  341. filter.append("*");
  342. }
  343. PROGLOG("DFUSpace: filter %s ", filter.str());
  344. Owned<IDFAttributesIterator> fi = queryDistributedFileDirectory().getDFAttributesIterator(filter, userdesc.get(), true, false, NULL);
  345. if(!fi)
  346. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get information from file system.");
  347. const char *ownerUnder = NULL;
  348. if(req.getOwnerUnder() && *req.getOwnerUnder())
  349. {
  350. ownerUnder = req.getOwnerUnder();
  351. resp.setOwnerUnder(ownerUnder);
  352. }
  353. StringBuffer wuFrom, wuTo, interval;
  354. unsigned yearFrom = 0, monthFrom, dayFrom, yearTo = 0, monthTo, dayTo, hour, minute, second, nano;
  355. if(req.getStartDate() && *req.getStartDate())
  356. {
  357. CDateTime wuTime;
  358. wuTime.setString(req.getStartDate(),NULL,true);
  359. wuTime.getDate(yearFrom, monthFrom, dayFrom, true);
  360. wuTime.getTime(hour, minute, second, nano, true);
  361. wuFrom.appendf("%4d-%02d-%02d %02d:%02d:%02d",yearFrom,monthFrom,dayFrom,hour,minute,second);
  362. StringBuffer startDate;
  363. startDate.appendf("%02d/%02d/%04d", monthFrom, dayFrom, yearFrom);
  364. resp.setStartDate(startDate.str());
  365. }
  366. if(req.getEndDate() && *req.getEndDate())
  367. {
  368. CDateTime wuTime;
  369. wuTime.setString(req.getEndDate(),NULL,true);
  370. wuTime.getDate(yearTo, monthTo, dayTo, true);
  371. wuTime.getTime(hour, minute, second, nano, true);
  372. wuTo.appendf("%4d-%02d-%02d %02d:%02d:%02d",yearTo,monthTo,dayTo,hour,minute,second);
  373. StringBuffer endDate;
  374. endDate.appendf("%02d/%02d/%04d", monthTo, dayTo, yearTo);
  375. resp.setEndDate(endDate.str());
  376. }
  377. unsigned i = 0;
  378. IArrayOf<IEspSpaceItem> SpaceItems64;
  379. if (!stricmp(countby, COUNTBY_DATE))
  380. {
  381. if (yearFrom < 1 || yearTo < 1)
  382. {
  383. StringBuffer wuFrom, wuTo;
  384. bool bFirst = true;
  385. ForEach(*fi)
  386. {
  387. IPropertyTree &attr=fi->query();
  388. StringBuffer modf(attr.queryProp("@modified"));
  389. //char* t=strchr(modf.str(),'T');
  390. //if(t) *t=' ';
  391. if (bFirst)
  392. {
  393. bFirst = false;
  394. wuFrom = modf.str();
  395. wuTo = modf.str();
  396. continue;
  397. }
  398. if (strcmp(modf.str(),wuFrom.str())<0)
  399. wuFrom = modf.str();
  400. if (strcmp(modf.str(),wuTo.str())>0)
  401. wuTo = modf.str();
  402. }
  403. if (yearFrom < 1)
  404. {
  405. CDateTime wuTime;
  406. wuTime.setString(wuFrom.str(),NULL,true);
  407. wuTime.getDate(yearFrom, monthFrom, dayFrom, true);
  408. }
  409. if (yearTo < 1)
  410. {
  411. CDateTime wuTime;
  412. wuTime.setString(wuTo.str(),NULL,true);
  413. wuTime.getDate(yearTo, monthTo, dayTo, true);
  414. }
  415. }
  416. interval = req.getInterval();
  417. resp.setInterval(interval);
  418. createSpaceItemsByDate(SpaceItems64, interval, yearFrom, monthFrom, dayFrom, yearTo, monthTo, dayTo);
  419. }
  420. else
  421. {
  422. Owned<IEspSpaceItem> item64 = createSpaceItem();
  423. if (stricmp(countby, COUNTBY_OWNER))
  424. {
  425. if (scopeName)
  426. item64->setName(scopeName);
  427. else
  428. item64->setName("(root)");
  429. }
  430. else
  431. {
  432. item64->setName("(empty)");
  433. }
  434. item64->setNumOfFilesInt(0);
  435. item64->setNumOfFilesIntUnknown(0);
  436. item64->setTotalSizeInt(0);
  437. item64->setLargestSizeInt(0);
  438. item64->setSmallestSizeInt(0);
  439. item64->setLargestFile("");
  440. item64->setSmallestFile("");
  441. SpaceItems64.append(*item64.getClear());
  442. }
  443. ForEach(*fi)
  444. {
  445. IPropertyTree &attr=fi->query();
  446. if (attr.hasProp("@numsubfiles"))
  447. continue; //exclude superfiles
  448. if (ownerUnder)
  449. {
  450. const char* owner=attr.queryProp("@owner");
  451. if (owner && stricmp(owner, ownerUnder))
  452. continue;
  453. }
  454. StringBuffer modf(attr.queryProp("@modified"));
  455. char* t= (char *) strchr(modf.str(),'T');
  456. if(t) *t=' ';
  457. if (wuFrom.length() && strcmp(modf.str(),wuFrom.str())<0)
  458. continue;
  459. if (wuTo.length() && strcmp(modf.str(),wuTo.str())>0)
  460. continue;
  461. if (!stricmp(countby, COUNTBY_DATE))
  462. {
  463. setSpaceItemByDate(SpaceItems64, interval, attr.queryProp("@modified"), attr.queryProp("@name"), attr.getPropInt64("@size",-1));
  464. }
  465. else if (!stricmp(countby, COUNTBY_OWNER))
  466. {
  467. setSpaceItemByOwner(SpaceItems64, attr.queryProp("@owner"), attr.queryProp("@name"), attr.getPropInt64("@size",-1));
  468. }
  469. else
  470. {
  471. setSpaceItemByScope(SpaceItems64, scopeName, attr.queryProp("@name"), attr.getPropInt64("@size",-1));
  472. }
  473. }
  474. i = 0;
  475. IEspSpaceItem& item0 = SpaceItems64.item(0);
  476. if (item0.getNumOfFilesInt() < 1)
  477. {
  478. i++;
  479. }
  480. double version = context.getClientVersion();
  481. IArrayOf<IEspDFUSpaceItem> SpaceItems;
  482. for(; i < SpaceItems64.length();i++)
  483. {
  484. IEspSpaceItem& item64 = SpaceItems64.item(i);
  485. if (item64.getNumOfFilesInt() < 1)
  486. continue;
  487. StringBuffer buf;
  488. Owned<IEspDFUSpaceItem> item1 = createDFUSpaceItem("","");
  489. __int64 numOfFiles = item64.getNumOfFilesInt();
  490. __int64 numOfFilesIntUnknown = item64.getNumOfFilesIntUnknown();
  491. __int64 totalSize = item64.getTotalSizeInt();
  492. __int64 largestSize = item64.getLargestSizeInt();
  493. __int64 smallestSize = item64.getSmallestSizeInt();
  494. if (version >= 1.38)
  495. {
  496. item1->setNumOfFilesInt64(numOfFiles);
  497. item1->setNumOfFilesUnknownInt64(numOfFilesIntUnknown);
  498. item1->setTotalSizeInt64(totalSize);
  499. item1->setLargestSizeInt64(largestSize);
  500. item1->setSmallestSizeInt64(smallestSize);
  501. }
  502. item1->setName(item64.getName());
  503. buf << comma(numOfFiles);
  504. item1->setNumOfFiles(buf.str());
  505. buf.clear();
  506. buf << comma(numOfFilesIntUnknown);
  507. item1->setNumOfFilesUnknown(buf.str());
  508. buf.clear();
  509. buf << comma(totalSize);
  510. item1->setTotalSize(buf.str());
  511. buf.clear();
  512. buf << comma(largestSize);
  513. item1->setLargestSize(buf.str());
  514. buf.clear();
  515. buf << comma(smallestSize);
  516. item1->setSmallestSize(buf.str());
  517. item1->setLargestFile(item64.getLargestFile());
  518. item1->setSmallestFile(item64.getSmallestFile());
  519. SpaceItems.append(*item1.getClear());
  520. }
  521. resp.setDFUSpaceItems(SpaceItems);
  522. resp.setCountBy(req.getCountBy());
  523. }
  524. catch(IException* e)
  525. {
  526. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  527. }
  528. return true;
  529. }
  530. bool CWsDfuEx::setSpaceItemByScope(IArrayOf<IEspSpaceItem>& SpaceItems64, const char*scopeName, const char*logicalName, __int64 size)
  531. {
  532. char scope[1024];
  533. scope[0] = 0;
  534. const char* pName = NULL;
  535. if (!scopeName)
  536. {
  537. pName = strstr(logicalName, "::");
  538. if (!pName)
  539. return false;
  540. strncpy(scope, logicalName, pName - logicalName);
  541. scope[pName - logicalName] = 0;
  542. }
  543. else
  544. {
  545. if (strlen(logicalName) <= strlen(scopeName)+2)
  546. return false;
  547. char* ppName = (char*) logicalName + strlen(scopeName) + 2;
  548. pName = strstr(ppName, "::");
  549. if (pName)
  550. {
  551. strncpy(scope, logicalName, pName - logicalName);
  552. scope[pName - logicalName] = 0;
  553. }
  554. }
  555. if (strlen(scope) > 0)
  556. {
  557. IEspSpaceItem *item0 = NULL;
  558. for(unsigned i = 0; i < SpaceItems64.length();i++)
  559. {
  560. IEspSpaceItem& item1 = SpaceItems64.item(i);
  561. if (!stricmp(item1.getName(), scope))
  562. {
  563. item0 = &item1;
  564. break;
  565. }
  566. }
  567. if (!item0)
  568. {
  569. Owned<IEspSpaceItem> item1 = createSpaceItem();
  570. item1->setName(scope);
  571. item1->setNumOfFilesInt(1);
  572. if (size < 0)
  573. {
  574. item1->setNumOfFilesIntUnknown(1);
  575. item1->setTotalSizeInt(0);
  576. item1->setLargestSizeInt(0);
  577. item1->setSmallestSizeInt(0);
  578. item1->setLargestFile("");
  579. item1->setSmallestFile("");
  580. }
  581. else
  582. {
  583. item1->setNumOfFilesIntUnknown(0);
  584. item1->setTotalSizeInt(size);
  585. item1->setLargestSizeInt(size);
  586. item1->setSmallestSizeInt(size);
  587. item1->setLargestFile(logicalName);
  588. item1->setSmallestFile(logicalName);
  589. }
  590. SpaceItems64.append(*item1.getClear());
  591. }
  592. else if (size < 0)
  593. {
  594. item0->setNumOfFilesIntUnknown(item0->getNumOfFilesIntUnknown() + 1);
  595. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  596. }
  597. else
  598. {
  599. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size > item0->getLargestSizeInt())
  600. {
  601. item0->setLargestSizeInt(size);
  602. item0->setLargestFile(logicalName);
  603. }
  604. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size < item0->getSmallestSizeInt())
  605. {
  606. item0->setSmallestSizeInt(size);
  607. item0->setSmallestFile(logicalName);
  608. }
  609. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  610. item0->setTotalSizeInt(item0->getTotalSizeInt() + size);
  611. }
  612. }
  613. else
  614. {
  615. IEspSpaceItem& item0 = SpaceItems64.item(0);
  616. if (size < 0)
  617. {
  618. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  619. item0.setNumOfFilesIntUnknown(item0.getNumOfFilesIntUnknown() + 1);
  620. }
  621. else
  622. {
  623. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size > item0.getLargestSizeInt()))
  624. {
  625. item0.setLargestSizeInt(size);
  626. item0.setLargestFile(logicalName);
  627. }
  628. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size < item0.getSmallestSizeInt()))
  629. {
  630. item0.setSmallestSizeInt(size);
  631. item0.setSmallestFile(logicalName);
  632. }
  633. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  634. item0.setTotalSizeInt(item0.getTotalSizeInt() + size);
  635. }
  636. }
  637. return true;
  638. }
  639. bool CWsDfuEx::setSpaceItemByOwner(IArrayOf<IEspSpaceItem>& SpaceItems64, const char *owner, const char *logicalName, __int64 size)
  640. {
  641. if (owner && *owner)
  642. {
  643. IEspSpaceItem *item0 = NULL;
  644. for(unsigned i = 0; i < SpaceItems64.length();i++)
  645. {
  646. IEspSpaceItem& item1 = SpaceItems64.item(i);
  647. if (!stricmp(item1.getName(), owner))
  648. {
  649. item0 = &item1;
  650. break;
  651. }
  652. }
  653. if (!item0)
  654. {
  655. Owned<IEspSpaceItem> item1 = createSpaceItem();
  656. item1->setName(owner);
  657. item1->setNumOfFilesInt(1);
  658. if (size < 0)
  659. {
  660. item1->setNumOfFilesIntUnknown(1);
  661. item1->setTotalSizeInt(0);
  662. item1->setLargestSizeInt(0);
  663. item1->setSmallestSizeInt(0);
  664. item1->setLargestFile("");
  665. item1->setSmallestFile("");
  666. }
  667. else
  668. {
  669. item1->setNumOfFilesIntUnknown(0);
  670. item1->setTotalSizeInt(size);
  671. item1->setLargestSizeInt(size);
  672. item1->setSmallestSizeInt(size);
  673. item1->setLargestFile(logicalName);
  674. item1->setSmallestFile(logicalName);
  675. }
  676. SpaceItems64.append(*item1.getClear());
  677. }
  678. else if (size < 0)
  679. {
  680. item0->setNumOfFilesIntUnknown(item0->getNumOfFilesIntUnknown() + 1);
  681. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  682. }
  683. else
  684. {
  685. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size > item0->getLargestSizeInt())
  686. {
  687. item0->setLargestSizeInt(size);
  688. item0->setLargestFile(logicalName);
  689. }
  690. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size < item0->getSmallestSizeInt())
  691. {
  692. item0->setSmallestSizeInt(size);
  693. item0->setSmallestFile(logicalName);
  694. }
  695. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  696. item0->setTotalSizeInt(item0->getTotalSizeInt() + size);
  697. }
  698. }
  699. else
  700. {
  701. IEspSpaceItem& item0 = SpaceItems64.item(0);
  702. if (size < 0)
  703. {
  704. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  705. item0.setNumOfFilesIntUnknown(item0.getNumOfFilesIntUnknown() + 1);
  706. }
  707. else
  708. {
  709. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size > item0.getLargestSizeInt()))
  710. {
  711. item0.setLargestSizeInt(size);
  712. item0.setLargestFile(logicalName);
  713. }
  714. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size < item0.getSmallestSizeInt()))
  715. {
  716. item0.setSmallestSizeInt(size);
  717. item0.setSmallestFile(logicalName);
  718. }
  719. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  720. item0.setTotalSizeInt(item0.getTotalSizeInt() + size);
  721. }
  722. }
  723. return true;
  724. }
  725. bool CWsDfuEx::createSpaceItemsByDate(IArrayOf<IEspSpaceItem>& SpaceItems, StringBuffer interval, unsigned& yearFrom,
  726. unsigned& monthFrom, unsigned& dayFrom, unsigned& yearTo, unsigned& monthTo, unsigned& dayTo)
  727. {
  728. if (!stricmp(interval, COUNTBY_YEAR))
  729. {
  730. for (unsigned i = yearFrom; i <= yearTo; i++)
  731. {
  732. Owned<IEspSpaceItem> item64 = createSpaceItem();
  733. StringBuffer name;
  734. name.appendf("%04d", i);
  735. item64->setName(name.str());
  736. item64->setNumOfFilesInt(0);
  737. item64->setNumOfFilesIntUnknown(0);
  738. item64->setTotalSizeInt(0);
  739. item64->setLargestSizeInt(0);
  740. item64->setSmallestSizeInt(0);
  741. item64->setLargestFile("");
  742. item64->setSmallestFile("");
  743. SpaceItems.append(*item64.getClear());
  744. }
  745. }
  746. else if (!stricmp(interval, COUNTBY_QUARTER))
  747. {
  748. for (unsigned i = yearFrom; i <= yearTo; i++)
  749. {
  750. int quartStart = 1;
  751. int quartEnd = 4;
  752. if (i == yearFrom)
  753. {
  754. if (monthFrom > 9)
  755. {
  756. quartStart = 4;
  757. }
  758. else if (monthFrom > 6)
  759. {
  760. quartStart = 3;
  761. }
  762. else if (monthFrom > 3)
  763. {
  764. quartStart = 2;
  765. }
  766. }
  767. if (i == yearTo)
  768. {
  769. if (monthTo > 9)
  770. {
  771. quartEnd = 4;
  772. }
  773. else if (monthTo > 6)
  774. {
  775. quartEnd = 3;
  776. }
  777. else if (monthTo > 3)
  778. {
  779. quartEnd = 2;
  780. }
  781. }
  782. for (int j = quartStart; j <= quartEnd; j++)
  783. {
  784. Owned<IEspSpaceItem> item64 = createSpaceItem();
  785. StringBuffer name;
  786. name.appendf("%04d quarter: %d", i, j);
  787. item64->setName(name.str());
  788. item64->setNumOfFilesInt(0);
  789. item64->setNumOfFilesIntUnknown(0);
  790. item64->setTotalSizeInt(0);
  791. item64->setLargestSizeInt(0);
  792. item64->setSmallestSizeInt(0);
  793. item64->setLargestFile("");
  794. item64->setSmallestFile("");
  795. SpaceItems.append(*item64.getClear());
  796. }
  797. }
  798. }
  799. else if (!stricmp(interval, COUNTBY_MONTH))
  800. {
  801. for (unsigned i = yearFrom; i <= yearTo; i++)
  802. {
  803. int jFrom = (i != yearFrom) ? 1 : monthFrom;
  804. int jTo = (i != yearTo) ? 12 : monthTo;
  805. for (int j = jFrom; j <= jTo; j++)
  806. {
  807. Owned<IEspSpaceItem> item64 = createSpaceItem();
  808. StringBuffer name;
  809. name.appendf("%04d-%02d", i, j);
  810. item64->setName(name.str());
  811. item64->setNumOfFilesInt(0);
  812. item64->setNumOfFilesIntUnknown(0);
  813. item64->setTotalSizeInt(0);
  814. item64->setLargestSizeInt(0);
  815. item64->setSmallestSizeInt(0);
  816. item64->setLargestFile("");
  817. item64->setSmallestFile("");
  818. SpaceItems.append(*item64.getClear());
  819. }
  820. }
  821. }
  822. else
  823. {
  824. for (unsigned i = yearFrom; i <= yearTo; i++)
  825. {
  826. int jFrom = (i != yearFrom) ? 1 : monthFrom;
  827. int jTo = (i != yearTo) ? 12 : monthTo;
  828. for (int j = jFrom; j <= jTo; j++)
  829. {
  830. int dayStart = 1;
  831. int dayEnd = days[j-1];
  832. if (i == yearFrom && j == monthFrom)
  833. {
  834. dayStart = dayFrom;
  835. }
  836. else if (i == yearTo && j == monthTo)
  837. {
  838. dayEnd = dayTo;
  839. }
  840. for (int k = dayStart; k <= dayEnd; k++)
  841. {
  842. Owned<IEspSpaceItem> item64 = createSpaceItem();
  843. StringBuffer name;
  844. name.appendf("%04d-%02d-%02d", i, j, k);
  845. item64->setName(name.str());
  846. item64->setNumOfFilesInt(0);
  847. item64->setNumOfFilesIntUnknown(0);
  848. item64->setTotalSizeInt(0);
  849. item64->setLargestSizeInt(0);
  850. item64->setSmallestSizeInt(0);
  851. item64->setLargestFile("");
  852. item64->setSmallestFile("");
  853. SpaceItems.append(*item64.getClear());
  854. }
  855. }
  856. }
  857. }
  858. return true;
  859. }
  860. bool CWsDfuEx::setSpaceItemByDate(IArrayOf<IEspSpaceItem>& SpaceItems, StringBuffer interval, StringBuffer mod, const char*logicalName, __int64 size)
  861. {
  862. unsigned year, month, day;
  863. CDateTime wuTime;
  864. wuTime.setString(mod.str(),NULL,true);
  865. wuTime.getDate(year, month, day, true);
  866. StringBuffer name;
  867. if (!stricmp(interval, COUNTBY_YEAR))
  868. {
  869. name.appendf("%04d", year);
  870. }
  871. else if (!stricmp(interval, COUNTBY_QUARTER))
  872. {
  873. int quart = 1;
  874. if (month > 9)
  875. {
  876. quart = 4;
  877. }
  878. else if (month > 6)
  879. {
  880. quart = 3;
  881. }
  882. else if (month > 3)
  883. {
  884. quart = 2;
  885. }
  886. name.appendf("%04d quarter: %d", year, quart);
  887. }
  888. else if (!stricmp(interval, COUNTBY_MONTH))
  889. {
  890. name.appendf("%04d-%02d", year, month);
  891. }
  892. else
  893. {
  894. name.appendf("%04d-%02d-%02d", year, month, day);
  895. }
  896. for (unsigned i = 0; i < SpaceItems.length(); i++)
  897. {
  898. IEspSpaceItem& item0 = SpaceItems.item(i);
  899. if (!stricmp(item0.getName(), name))
  900. {
  901. if (size < 0)
  902. {
  903. item0.setNumOfFilesIntUnknown(item0.getNumOfFilesIntUnknown() + 1);
  904. }
  905. else
  906. {
  907. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size > item0.getLargestSizeInt()))
  908. {
  909. item0.setLargestSizeInt(size);
  910. item0.setLargestFile(logicalName);
  911. }
  912. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size < item0.getSmallestSizeInt()))
  913. {
  914. item0.setSmallestSizeInt(size);
  915. item0.setSmallestFile(logicalName);
  916. }
  917. item0.setTotalSizeInt(item0.getTotalSizeInt() + size);
  918. }
  919. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  920. break;
  921. }
  922. }
  923. return true;
  924. }
  925. void CWsDfuEx::parseStringArray(const char *input, StringArray& strarray)
  926. {
  927. if (!input || !*input)
  928. return;
  929. const char *ptr = input;
  930. const char *pptr = ptr;
  931. while (pptr[0])
  932. {
  933. if (pptr[0] == ',')
  934. {
  935. StringAttr tmp;
  936. tmp.set(ptr, pptr-ptr);
  937. strarray.append(tmp.get());
  938. ptr = pptr + 1;
  939. }
  940. pptr++;
  941. }
  942. if (pptr > ptr)
  943. {
  944. StringAttr tmp;
  945. tmp.set(ptr, pptr-ptr);
  946. strarray.append(tmp.get());
  947. }
  948. }
  949. int CWsDfuEx::superfileAction(IEspContext &context, const char* action, const char* superfile, StringArray& subfiles,
  950. const char* beforeSubFile, bool existingSuperfile, bool autocreatesuper, bool deleteFile, bool removeSuperfile)
  951. {
  952. if (!action || !*action)
  953. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Superfile action not specified");
  954. if(!strieq(action, "add") && !strieq(action, "remove"))
  955. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Only Add or Remove is allowed.");
  956. if (!superfile || !*superfile)
  957. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Superfile name not specified");
  958. StringBuffer username;
  959. context.getUserID(username);
  960. Owned<IUserDescriptor> userdesc;
  961. if(username.length() > 0)
  962. {
  963. userdesc.setown(createUserDescriptor());
  964. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  965. }
  966. if (!autocreatesuper)
  967. {//a file lock created by the lookup() will be released after '}'
  968. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(superfile, userdesc.get(), true);
  969. if (existingSuperfile)
  970. {
  971. if (!df)
  972. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",superfile);
  973. if(!df->querySuperFile())
  974. throw MakeStringException(ECLWATCH_NOT_SUPERFILE,"%s is not a superfile.",superfile);
  975. }
  976. else if (df)
  977. throw MakeStringException(ECLWATCH_FILE_ALREADY_EXISTS,"The file %s already exists.",superfile);
  978. }
  979. PointerArrayOf<char> subfileArray;
  980. unsigned num = subfiles.length();
  981. if (num > 0)
  982. {
  983. StringBuffer msgHead;
  984. if(username.length() > 0)
  985. msgHead.appendf("%s: Superfile:%s, Subfile(s): ", action, superfile);
  986. else
  987. msgHead.appendf("%s: Superfile:%s, Subfile(s): ", action, superfile);
  988. unsigned filesInMsgBuf = 0;
  989. StringBuffer msgBuf = msgHead;
  990. for(unsigned i = 0; i < num; i++)
  991. {
  992. subfileArray.append((char*) subfiles.item(i));
  993. msgBuf.appendf("%s, ", subfiles.item(i));
  994. filesInMsgBuf++;
  995. if (filesInMsgBuf > 9)
  996. {
  997. PROGLOG("%s",msgBuf.str());
  998. msgBuf = msgHead;
  999. filesInMsgBuf = 0;
  1000. }
  1001. }
  1002. if (filesInMsgBuf > 0)
  1003. PROGLOG("%s", msgBuf.str());
  1004. }
  1005. else
  1006. PROGLOG("%s: %s", action, superfile);
  1007. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  1008. synchronized block(m_superfilemutex);
  1009. if(strieq(action, "add"))
  1010. dfuhelper->addSuper(superfile, userdesc.get(), num, (const char**) subfileArray.getArray(), beforeSubFile, true);
  1011. else
  1012. dfuhelper->removeSuper(superfile, userdesc.get(), num, (const char**) subfileArray.getArray(), deleteFile, removeSuperfile);
  1013. PROGLOG("%s done", action);
  1014. return num;
  1015. }
  1016. bool CWsDfuEx::onAddtoSuperfile(IEspContext &context, IEspAddtoSuperfileRequest &req, IEspAddtoSuperfileResponse &resp)
  1017. {
  1018. try
  1019. {
  1020. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Write, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::AddtoSuperfile: Permission denied.");
  1021. double version = context.getClientVersion();
  1022. if (version > 1.17)
  1023. {
  1024. const char* backTo = req.getBackToPage();
  1025. if (backTo && *backTo)
  1026. resp.setBackToPage(backTo);
  1027. }
  1028. resp.setSubfiles(req.getSubfiles());
  1029. const char* superfile = req.getSuperfile();
  1030. if (!superfile || !*superfile)
  1031. {
  1032. if (version > 1.15)
  1033. {//Display the subfiles inside a table
  1034. const char* files = req.getSubfiles();
  1035. if (files && *files)
  1036. {
  1037. StringArray subfileNames;
  1038. parseStringArray(files, subfileNames);
  1039. if (subfileNames.length() > 0)
  1040. resp.setSubfileNames(subfileNames);
  1041. }
  1042. }
  1043. return true;//Display a form for user to specify superfile
  1044. }
  1045. if (version > 1.15)
  1046. {
  1047. superfileAction(context, "add", superfile, req.getNames(), NULL, req.getExistingFile(), false, false);
  1048. }
  1049. else
  1050. {
  1051. StringArray subfileNames;
  1052. const char *subfilesStr = req.getSubfiles();
  1053. if (subfilesStr && *subfilesStr)
  1054. parseStringArray(subfilesStr, subfileNames);
  1055. superfileAction(context, "add", superfile, subfileNames, NULL, req.getExistingFile(), false, false);
  1056. }
  1057. resp.setRedirectUrl(StringBuffer("/WsDFU/DFUInfo?Name=").append(superfile));
  1058. }
  1059. catch(IException* e)
  1060. {
  1061. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1062. }
  1063. return true;
  1064. }
  1065. void setDeleteFileResults(const char* fileName, const char* nodeGroup, bool failed, const char *start, const char* text, StringBuffer& resultString,
  1066. IArrayOf<IEspDFUActionInfo>& actionResults)
  1067. {
  1068. if (!fileName || !*fileName)
  1069. return;
  1070. Owned<IEspDFUActionInfo> resultObj = createDFUActionInfo("", "");
  1071. resultObj->setFileName(fileName);
  1072. resultObj->setFailed(failed);
  1073. if (nodeGroup && *nodeGroup)
  1074. resultObj->setNodeGroup(nodeGroup);
  1075. StringBuffer message;
  1076. if (start)
  1077. message.append(start).append(' ');
  1078. message.append(fileName);
  1079. if (nodeGroup && *nodeGroup)
  1080. message.append(" on ").append(nodeGroup);
  1081. if (text && *text)
  1082. message.append(failed ? ": " : " ").append(text);
  1083. resultObj->setActionResult(message);
  1084. resultString.appendf("<Message><Value>%s</Value></Message>", message.str());
  1085. actionResults.append(*resultObj.getClear());
  1086. }
  1087. typedef enum {
  1088. DeleteActionSuccess,
  1089. DeleteActionFailure,
  1090. DeleteActionSkip
  1091. } DeleteActionResult;
  1092. DeleteActionResult doDeleteFile(const char *fn, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles,
  1093. const char *auditStr, StringBuffer& returnStr, IArrayOf<IEspDFUActionInfo>& actionResults, bool superFilesOnly, bool removeFromSuperfiles, bool deleteRecursively);
  1094. bool doRemoveFileFromSuperfiles(const char *lfn, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles, bool deleteRecursively,
  1095. const char *auditStr, StringBuffer& returnStr, IArrayOf<IEspDFUActionInfo>& actionResults)
  1096. {
  1097. StringArray emptySuperFiles;
  1098. IDistributedFileDirectory &fdir = queryDistributedFileDirectory();
  1099. {
  1100. Owned<IDistributedFile> df = fdir.lookup(lfn, userdesc, true);
  1101. if(!df)
  1102. return false;
  1103. Owned<IDistributedSuperFileIterator> supers = df->getOwningSuperFiles();
  1104. ForEach(*supers)
  1105. {
  1106. IDistributedSuperFile &super = supers->query();
  1107. try
  1108. {
  1109. super.removeSubFile(lfn, false, false, NULL);
  1110. VStringBuffer text("from superfile %s", super.queryLogicalName());
  1111. setDeleteFileResults(lfn, NULL, false, "Removed subfile", text, returnStr, actionResults);
  1112. }
  1113. catch(IException* e)
  1114. {
  1115. StringBuffer emsg;
  1116. VStringBuffer text("from superfile %s: %s", super.queryLogicalName(), e->errorMessage(emsg).str());
  1117. setDeleteFileResults(lfn, NULL, true, "Could not remove subfile ", text, returnStr, actionResults);
  1118. e->Release();
  1119. return false;
  1120. }
  1121. catch(...)
  1122. {
  1123. VStringBuffer text("from superfile %s", super.queryLogicalName());
  1124. setDeleteFileResults(lfn, NULL, true, "Could not remove subfile ", text, returnStr, actionResults);
  1125. return false;
  1126. }
  1127. if (deleteRecursively && super.numSubFiles(false)==0)
  1128. emptySuperFiles.appendUniq(super.queryLogicalName());
  1129. }
  1130. }
  1131. ForEachItemIn(i, emptySuperFiles)
  1132. doDeleteFile(emptySuperFiles.item(i), userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, false, true, deleteRecursively);
  1133. return true;
  1134. }
  1135. DeleteActionResult doDeleteFile(const char *fn, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles,
  1136. const char *auditStr, StringBuffer& returnStr, IArrayOf<IEspDFUActionInfo>& actionResults,
  1137. bool superFilesOnly, bool removeFromSuperfiles, bool deleteRecursively)
  1138. {
  1139. StringArray parsed;
  1140. parsed.appendListUniq(fn, "@");
  1141. const char *lfn = parsed.item(0);
  1142. const char *group = NULL;
  1143. if (parsed.length() > 1)
  1144. {
  1145. group = parsed.item(1);
  1146. if (group && (!*group || strieq(group, "null"))) //null is used by new ECLWatch for a superfile
  1147. group = NULL;
  1148. }
  1149. bool isSuper = false;
  1150. if (superFiles.contains(fn) || failedFiles.contains(fn))
  1151. return DeleteActionSkip;
  1152. try
  1153. {
  1154. IDistributedFileDirectory &fdir = queryDistributedFileDirectory();
  1155. {
  1156. Owned<IDistributedFile> df = fdir.lookup(lfn, userdesc, true);
  1157. if(!df)
  1158. {
  1159. PROGLOG("CWsDfuEx::DFUDeleteFiles: %s not found", lfn);
  1160. setDeleteFileResults(lfn, group, true, "File not found", NULL, returnStr, actionResults);
  1161. return DeleteActionFailure;
  1162. }
  1163. isSuper = df->querySuperFile()!=NULL;
  1164. if (superFilesOnly) // skip non-super files on 1st pass
  1165. {
  1166. if(!isSuper)
  1167. return DeleteActionSkip;
  1168. superFiles.append(fn);
  1169. }
  1170. }
  1171. fdir.removeEntry(fn, userdesc, NULL, REMOVE_FILE_SDS_CONNECT_TIMEOUT, true);
  1172. LOG(daliAuditLogCat, "%s,%s", auditStr, fn);
  1173. setDeleteFileResults(lfn, group, false, isSuper ? "Deleted Superfile" : "Deleted File", NULL, returnStr, actionResults);
  1174. }
  1175. catch(IException* e)
  1176. {
  1177. StringBuffer emsg;
  1178. e->errorMessage(emsg);
  1179. if (removeFromSuperfiles && strstr(emsg, "owned by"))
  1180. {
  1181. if (!doRemoveFileFromSuperfiles(lfn, userdesc, superFiles, failedFiles, deleteRecursively, auditStr, returnStr, actionResults))
  1182. return DeleteActionFailure;
  1183. return doDeleteFile(fn, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, superFilesOnly, false, false);
  1184. }
  1185. if (e->errorCode() == DFSERR_CreateAccessDenied)
  1186. emsg.replaceString("Create ", "Delete ");
  1187. setDeleteFileResults(lfn, group, true, "Could not delete", emsg.str(), returnStr, actionResults);
  1188. e->Release();
  1189. return DeleteActionFailure;
  1190. }
  1191. catch(...)
  1192. {
  1193. setDeleteFileResults(lfn, group, true, "Could not delete", "unknown exception", returnStr, actionResults);
  1194. return DeleteActionFailure;
  1195. }
  1196. return DeleteActionSuccess;
  1197. }
  1198. void doDeleteFiles(StringArray &files, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles,
  1199. const char *auditStr, StringBuffer &returnStr, IArrayOf<IEspDFUActionInfo> &actionResults,
  1200. bool superFilesOnly, bool removeFromSuperfiles, bool deleteRecursively)
  1201. {
  1202. ForEachItemIn(i, files)
  1203. {
  1204. const char* fn = files.item(i);
  1205. if(!fn || !*fn)
  1206. continue;
  1207. PROGLOG("Deleting %s", fn);
  1208. if (DeleteActionFailure==doDeleteFile(fn, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, superFilesOnly, removeFromSuperfiles, deleteRecursively))
  1209. {
  1210. failedFiles.appendUniq(fn);
  1211. PROGLOG("Delete %s failed", fn);
  1212. }
  1213. else
  1214. PROGLOG("Delete %s done", fn);
  1215. }
  1216. }
  1217. inline void doDeleteSuperFiles(StringArray &files, IUserDescriptor *userdesc, StringArray &superFiles,
  1218. StringArray &failedFiles, const char *auditStr, StringBuffer &returnStr, IArrayOf<IEspDFUActionInfo> &actionResults,
  1219. bool removeFromSuperfiles, bool deleteRecursively)
  1220. {
  1221. doDeleteFiles(files, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, true, removeFromSuperfiles, deleteRecursively);
  1222. }
  1223. inline void doDeleteSubFiles(StringArray &files, IUserDescriptor *userdesc, StringArray &superFiles,
  1224. StringArray &failedFiles, const char *auditStr, StringBuffer &returnStr, IArrayOf<IEspDFUActionInfo> &actionResults,
  1225. bool removeFromSuperfiles, bool deleteRecursively)
  1226. {
  1227. doDeleteFiles(files, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, false, removeFromSuperfiles, deleteRecursively);
  1228. }
  1229. bool CWsDfuEx::DFUDeleteFiles(IEspContext &context, IEspDFUArrayActionRequest &req, IEspDFUArrayActionResponse &resp)
  1230. {
  1231. if (isDetachedFromDali())
  1232. throw MakeStringException(ECLWATCH_INVALID_INPUT, "ESP server is detached from Dali. Please try later.");
  1233. double version = context.getClientVersion();
  1234. Owned<IUserDescriptor> userdesc;
  1235. const char *username = context.queryUserId();
  1236. if(username && *username)
  1237. {
  1238. userdesc.setown(createUserDescriptor());
  1239. userdesc->set(username, context.queryPassword(), context.querySignature());
  1240. }
  1241. StringBuffer returnStr, auditStr = (",FileAccess,WsDfu,DELETED,");
  1242. IArrayOf<IEspDFUActionInfo> actionResults;
  1243. StringArray superFiles, failedFiles;
  1244. auditStr.append(espProcess.get());
  1245. auditStr.append(',');
  1246. if (!isEmptyString(username))
  1247. auditStr.append(username).append('@');
  1248. context.getPeer(auditStr);
  1249. doDeleteSuperFiles(req.getLogicalFiles(), userdesc, superFiles, failedFiles, auditStr.str(),
  1250. returnStr, actionResults, req.getRemoveFromSuperfiles(), req.getRemoveRecursively());
  1251. doDeleteSubFiles(req.getLogicalFiles(), userdesc, superFiles, failedFiles, auditStr.str(),
  1252. returnStr, actionResults, req.getRemoveFromSuperfiles(), req.getRemoveRecursively());
  1253. if (version >= 1.27)
  1254. resp.setActionResults(actionResults);
  1255. if (version < 1.33)
  1256. resp.setDFUArrayActionResult(returnStr.str());
  1257. return true;
  1258. }
  1259. bool CWsDfuEx::onDFUArrayAction(IEspContext &context, IEspDFUArrayActionRequest &req, IEspDFUArrayActionResponse &resp)
  1260. {
  1261. try
  1262. {
  1263. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Write, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUArrayAction: Permission denied.");
  1264. CDFUArrayActions action = req.getType();
  1265. if (action == DFUArrayActions_Undefined)
  1266. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined.");
  1267. double version = context.getClientVersion();
  1268. if (version > 1.03)
  1269. {
  1270. StringBuffer backToPage = req.getBackToPage();
  1271. if (backToPage.length() > 0)
  1272. {
  1273. const char* oldStr = "&";
  1274. const char* newStr = "&amp;";
  1275. backToPage.replaceString(oldStr, newStr);
  1276. resp.setBackToPage(backToPage.str());
  1277. }
  1278. }
  1279. if (action == CDFUArrayActions_Delete)
  1280. return DFUDeleteFiles(context, req, resp);
  1281. //the code below is only for legacy ECLWatch. Other application should use AddtoSuperfile.
  1282. StringBuffer username;
  1283. context.getUserID(username);
  1284. Owned<IUserDescriptor> userdesc;
  1285. if(username.length() > 0)
  1286. {
  1287. userdesc.setown(createUserDescriptor());
  1288. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  1289. }
  1290. IArrayOf<IEspDFUActionInfo> actionResults;
  1291. StringBuffer errorStr, subfiles;
  1292. for(unsigned i = 0; i < req.getLogicalFiles().length();i++)
  1293. {
  1294. const char* file = req.getLogicalFiles().item(i);
  1295. if(!file || !*file)
  1296. continue;
  1297. unsigned len = strlen(file);
  1298. char* curfile = new char[len+1];
  1299. const char* cluster = NULL;
  1300. const char *pCh = strchr(file, '@');
  1301. if (pCh)
  1302. {
  1303. len = pCh - file;
  1304. if (len+1 < strlen(file))
  1305. cluster = pCh + 1;
  1306. }
  1307. strncpy(curfile, file, len);
  1308. curfile[len] = 0;
  1309. try
  1310. {
  1311. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(curfile, userdesc.get(), true);
  1312. if (df)
  1313. {
  1314. if (subfiles.length() > 0)
  1315. subfiles.append(",");
  1316. subfiles.append(curfile);
  1317. }
  1318. else
  1319. setDeleteFileResults(file, NULL, true, NULL, "not found", errorStr, actionResults);
  1320. }
  1321. catch(IException* e)
  1322. {
  1323. StringBuffer emsg;
  1324. e->errorMessage(emsg);
  1325. if (e->errorCode() == DFSERR_CreateAccessDenied)
  1326. emsg.replaceString("Create ", "AddtoSuperfile ");
  1327. setDeleteFileResults(file, NULL, true, NULL, emsg.str(), errorStr, actionResults);
  1328. e->Release();
  1329. }
  1330. catch(...)
  1331. {
  1332. setDeleteFileResults(file, NULL, true, NULL, "unknown exception", errorStr, actionResults);
  1333. }
  1334. delete [] curfile;
  1335. }
  1336. if (version >= 1.27)
  1337. resp.setActionResults(actionResults);
  1338. if (errorStr.length())
  1339. {
  1340. if (version < 1.33)
  1341. resp.setDFUArrayActionResult(errorStr.str());
  1342. return false;
  1343. }
  1344. if (version < 1.18)
  1345. resp.setRedirectUrl(StringBuffer("/WsDFU/AddtoSuperfile?Subfiles=").append(subfiles.str()));
  1346. else
  1347. resp.setRedirectTo(subfiles.str());
  1348. }
  1349. catch(IException* e)
  1350. {
  1351. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1352. }
  1353. return true;
  1354. }
  1355. bool CWsDfuEx::onDFUDefFile(IEspContext &context,IEspDFUDefFileRequest &req, IEspDFUDefFileResponse &resp)
  1356. {
  1357. try
  1358. {
  1359. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUDefFile: Permission denied.");
  1360. CDFUDefFileFormat format = req.getFormat();
  1361. if (format == DFUDefFileFormat_Undefined)
  1362. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Invalid format");
  1363. const char* fileName = req.getName();
  1364. if (!fileName || !*fileName)
  1365. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "File name required");
  1366. PROGLOG("DFUDefFile: %s", fileName);
  1367. StringBuffer username;
  1368. context.getUserID(username);
  1369. StringBuffer rawStr,returnStr;
  1370. Owned<IUserDescriptor> userdesc;
  1371. if(username.length() > 0)
  1372. {
  1373. userdesc.setown(createUserDescriptor());
  1374. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  1375. }
  1376. getDefFile(userdesc.get(), req.getName(),rawStr);
  1377. StringBuffer xsltFile;
  1378. xsltFile.append(getCFD()).append("smc_xslt/").append(req.getFormatAsString()).append("_def_file.xslt");
  1379. xsltTransformer(xsltFile.str(),rawStr,returnStr);
  1380. //set the file
  1381. MemoryBuffer buff;
  1382. buff.setBuffer(returnStr.length(), (void*)returnStr.str());
  1383. resp.setDefFile(buff);
  1384. //set the type
  1385. StringBuffer type = "text/";
  1386. if (format == CDFUDefFileFormat_xml)
  1387. type.append("xml");
  1388. else
  1389. type.append("plain");
  1390. resp.setDefFile_mimetype(type.str());
  1391. }
  1392. catch(IException* e)
  1393. {
  1394. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1395. }
  1396. return true;
  1397. }
  1398. IHqlExpression * getEclRecordDefinition(const char * ecl)
  1399. {
  1400. MultiErrorReceiver errs;
  1401. OwnedHqlExpr record = parseQuery(ecl, &errs);
  1402. if (errs.errCount())
  1403. {
  1404. StringBuffer errtext;
  1405. IError *first = errs.firstError();
  1406. first->toString(errtext);
  1407. throw MakeStringException(ECLWATCH_CANNOT_PARSE_ECL_QUERY, "Failed in parsing ECL record definition: %s @ %d:%d.", errtext.str(), first->getColumn(), first->getLine());
  1408. }
  1409. if(!record)
  1410. throw MakeStringException(ECLWATCH_CANNOT_PARSE_ECL_QUERY, "Failed in parsing ECL record definition.");
  1411. return record.getClear();
  1412. }
  1413. IHqlExpression * getEclRecordDefinition(IUserDescriptor* udesc, const char* FileName)
  1414. {
  1415. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(FileName, udesc);
  1416. if(!df)
  1417. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",FileName);
  1418. if(!df->queryAttributes().hasProp("ECL"))
  1419. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"No record definition for file %s.",FileName);
  1420. return getEclRecordDefinition(df->queryAttributes().queryProp("ECL"));
  1421. }
  1422. bool getRecordFormatFromRtlType(MemoryBuffer &binLayout, StringBuffer &jsonLayout, const IPropertyTree &attr, bool includeBin, bool includeJson)
  1423. {
  1424. if (!attr.hasProp("_rtlType"))
  1425. return false;
  1426. try
  1427. {
  1428. MemoryBuffer mb;
  1429. attr.getPropBin("_rtlType", mb);
  1430. if (includeJson)
  1431. {
  1432. Owned<IRtlFieldTypeDeserializer> deserializer(createRtlFieldTypeDeserializer());
  1433. const RtlTypeInfo *typeInfo = deserializer->deserialize(mb);
  1434. dumpTypeInfo(jsonLayout, typeInfo);
  1435. }
  1436. if (includeBin)
  1437. mb.swapWith(binLayout);
  1438. return true;
  1439. }
  1440. catch (IException *e)
  1441. {
  1442. EXCLOG(e, "Failed to process _rtlType");
  1443. e->Release();
  1444. }
  1445. return false;
  1446. }
  1447. bool getRecordFormatFromECL(MemoryBuffer &binLayout, StringBuffer &jsonLayout, const IPropertyTree &attr, bool includeBin, bool includeJson)
  1448. {
  1449. if (!attr.hasProp("ECL"))
  1450. return false;
  1451. try
  1452. {
  1453. const char * kind = attr.queryProp("@kind");
  1454. bool isIndex = (kind && streq(kind, "key"));
  1455. OwnedHqlExpr record = getEclRecordDefinition(attr.queryProp("ECL"));
  1456. MemoryBuffer mb;
  1457. if (attr.hasProp("_record_layout"))
  1458. {
  1459. attr.getPropBin("_record_layout", mb);
  1460. record.setown(patchEclRecordDefinitionFromRecordLayout(record, mb));
  1461. }
  1462. if (includeJson)
  1463. exportJsonType(jsonLayout, record, isIndex);
  1464. if (includeBin)
  1465. exportBinaryType(binLayout, record, isIndex);
  1466. return true;
  1467. }
  1468. catch (IException *e)
  1469. {
  1470. EXCLOG(e, "Failed to process ECL record");
  1471. e->Release();
  1472. }
  1473. return false;
  1474. }
  1475. bool CWsDfuEx::onDFURecordTypeInfo(IEspContext &context, IEspDFURecordTypeInfoRequest &req, IEspDFURecordTypeInfoResponse &resp)
  1476. {
  1477. try
  1478. {
  1479. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFURecordTypeInfo: Permission denied.");
  1480. const char* fileName = req.getName();
  1481. if (!fileName || !*fileName)
  1482. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "File name required");
  1483. PROGLOG("DFURecordTypeInfo file: %s", fileName);
  1484. const char* userId = context.queryUserId();
  1485. Owned<IUserDescriptor> userdesc;
  1486. if (userId && *userId)
  1487. {
  1488. userdesc.setown(createUserDescriptor());
  1489. userdesc->set(userId, context.queryPassword(), context.querySignature());
  1490. }
  1491. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(fileName, userdesc);
  1492. if (!df)
  1493. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",fileName);
  1494. MemoryBuffer binLayout;
  1495. StringBuffer jsonLayout;
  1496. if (getRecordFormatFromRtlType(binLayout, jsonLayout, df->queryAttributes(), req.getIncludeBinTypeInfo(), req.getIncludeJsonTypeInfo()) ||
  1497. getRecordFormatFromECL(binLayout.clear(), jsonLayout.clear(), df->queryAttributes(), req.getIncludeBinTypeInfo(), req.getIncludeJsonTypeInfo()))
  1498. {
  1499. if (req.getIncludeBinTypeInfo())
  1500. resp.setBinInfo(binLayout);
  1501. if (req.getIncludeJsonTypeInfo())
  1502. resp.setJsonInfo(jsonLayout);
  1503. }
  1504. }
  1505. catch (IException* e)
  1506. {
  1507. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1508. }
  1509. return true;
  1510. }
  1511. bool CWsDfuEx::onEclRecordTypeInfo(IEspContext &context, IEspEclRecordTypeInfoRequest &req, IEspEclRecordTypeInfoResponse &resp)
  1512. {
  1513. try
  1514. {
  1515. OwnedHqlExpr record = getEclRecordDefinition(req.getEcl());
  1516. if (req.getIncludeJsonTypeInfo())
  1517. {
  1518. StringBuffer jsonFormat;
  1519. exportJsonType(jsonFormat, record, false); // MORE - could allow isIndex to be passed in?
  1520. resp.setJsonInfo(jsonFormat);
  1521. }
  1522. if (req.getIncludeBinTypeInfo())
  1523. {
  1524. MemoryBuffer binFormat;
  1525. exportBinaryType(binFormat, record, false);
  1526. resp.setBinInfo(binFormat);
  1527. }
  1528. }
  1529. catch(IException* e)
  1530. {
  1531. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1532. }
  1533. return true;
  1534. }
  1535. void CWsDfuEx::xsltTransformer(const char* xsltPath,StringBuffer& source,StringBuffer& returnStr)
  1536. {
  1537. if (m_xsl.get() == 0)
  1538. {
  1539. m_xsl.setown(getXslProcessor());
  1540. }
  1541. Owned<IXslTransform> xform = m_xsl->createXslTransform();
  1542. xform->loadXslFromFile(xsltPath);
  1543. xform->setXmlSource(source.str(), source.length()+1);
  1544. xform->transform(returnStr.clear());
  1545. }
  1546. void CWsDfuEx::getDefFile(IUserDescriptor* udesc, const char* FileName,StringBuffer& returnStr)
  1547. {
  1548. OwnedHqlExpr record = getEclRecordDefinition(udesc, FileName);
  1549. Owned<IPropertyTree> data = createPTree("Table", ipt_caseInsensitive);
  1550. exportData(data, record);
  1551. const char* fname=strrchr(FileName,':');
  1552. data->setProp("filename",fname ? fname+1 : FileName);
  1553. toXML(data, returnStr, 0, 0);
  1554. }
  1555. bool CWsDfuEx::checkFileContent(IEspContext &context, IUserDescriptor* udesc, const char * logicalName, const char * cluster)
  1556. {
  1557. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(logicalName, udesc);
  1558. if (!df)
  1559. return false;
  1560. if (!cluster || !stricmp(cluster, ""))
  1561. {
  1562. StringAttr eclCluster;
  1563. const char* wuid = df->queryAttributes().queryProp("@workunit");
  1564. if (wuid && *wuid)
  1565. {
  1566. try
  1567. {
  1568. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  1569. if (factory)
  1570. {
  1571. IConstWorkUnit* wu = factory->openWorkUnit(wuid, context.querySecManager(), context.queryUser());
  1572. if (wu)
  1573. eclCluster.set(wu->queryClusterName());
  1574. }
  1575. }
  1576. catch(...)
  1577. {
  1578. return false;
  1579. }
  1580. }
  1581. if (!eclCluster.length())
  1582. return false;
  1583. }
  1584. bool blocked;
  1585. if (df->isCompressed(&blocked) && !blocked)
  1586. return false;
  1587. IPropertyTree & properties = df->queryAttributes();
  1588. const char * format = properties.queryProp("@format");
  1589. if (format && (stricmp(format,"csv")==0 || memicmp(format, "utf", 3) == 0))
  1590. {
  1591. return true;
  1592. }
  1593. const char * recordEcl = properties.queryProp("ECL");
  1594. if (!recordEcl)
  1595. return false;
  1596. MultiErrorReceiver errs;
  1597. Owned< IHqlExpression> ret = ::parseQuery(recordEcl, &errs);
  1598. return errs.errCount() == 0;
  1599. }
  1600. bool FindInStringArray(StringArray& clusters, const char *cluster)
  1601. {
  1602. bool bFound = false;
  1603. if(cluster && *cluster)
  1604. {
  1605. if (clusters.ordinality())
  1606. {
  1607. ForEachItemIn(i, clusters)
  1608. {
  1609. const char* cluster0 = clusters.item(i);
  1610. if(cluster0 && *cluster0 && !stricmp(cluster, cluster0))
  1611. return true;
  1612. }
  1613. }
  1614. }
  1615. else
  1616. {
  1617. #if 0 //Comment out since clusters are not set for some old files
  1618. if (!clusters.ordinality())
  1619. return true;
  1620. ForEachItemIn(i, clusters)
  1621. {
  1622. const char* cluster0 = clusters.item(i);
  1623. if(cluster0 && !*cluster0)
  1624. {
  1625. return true;
  1626. }
  1627. }
  1628. #else
  1629. return true;
  1630. #endif
  1631. }
  1632. return bFound;
  1633. }
  1634. static void getFilePermission(CDfsLogicalFileName &dlfn, ISecUser & user, IUserDescriptor* udesc, ISecManager* secmgr, SecAccessFlags& permission)
  1635. {
  1636. if (dlfn.isMulti())
  1637. {
  1638. if (!dlfn.isExpanded())
  1639. dlfn.expand(udesc);
  1640. unsigned i = dlfn.multiOrdinality();
  1641. while (i--)
  1642. {
  1643. getFilePermission((CDfsLogicalFileName &)dlfn.multiItem(i), user, udesc, secmgr, permission);
  1644. }
  1645. }
  1646. else
  1647. {
  1648. SecAccessFlags permissionTemp;
  1649. if (dlfn.isForeign())
  1650. {
  1651. permissionTemp = queryDistributedFileDirectory().getFilePermissions(dlfn.get(), udesc);
  1652. }
  1653. else
  1654. {
  1655. StringBuffer scopes;
  1656. dlfn.getScopes(scopes);
  1657. permissionTemp = secmgr->authorizeFileScope(user, scopes.str());
  1658. }
  1659. //Descrease the permission whenever a component has a lower permission.
  1660. if (permissionTemp < permission)
  1661. permission = permissionTemp;
  1662. }
  1663. return;
  1664. }
  1665. bool CWsDfuEx::getUserFilePermission(IEspContext &context, IUserDescriptor* udesc, const char* logicalName, SecAccessFlags& permission)
  1666. {
  1667. ISecManager* secmgr = context.querySecManager();
  1668. if (!secmgr)
  1669. {
  1670. return false;
  1671. }
  1672. CDfsLogicalFileName dlfn;
  1673. dlfn.set(logicalName);
  1674. //Start from the SecAccess_Full. Decrease the permission whenever a component has a lower permission.
  1675. permission = SecAccess_Full;
  1676. getFilePermission(dlfn, *context.queryUser(), udesc, secmgr, permission);
  1677. return true;
  1678. }
  1679. void CWsDfuEx::getFilePartsOnClusters(IEspContext &context, const char* clusterReq, StringArray& clusters, IDistributedFile* df, IEspDFUFileDetail& FileDetails,
  1680. offset_t& mn, offset_t& mx, offset_t& sum, offset_t& count)
  1681. {
  1682. double version = context.getClientVersion();
  1683. IArrayOf<IConstDFUFilePartsOnCluster>& partsOnClusters = FileDetails.getDFUFilePartsOnClusters();
  1684. ForEachItemIn(i, clusters)
  1685. {
  1686. const char* clusterName = clusters.item(i);
  1687. if (!clusterName || !*clusterName || (clusterReq && *clusterReq && !strieq(clusterReq, clusterName)))
  1688. continue;
  1689. Owned<IEspDFUFilePartsOnCluster> partsOnCluster = createDFUFilePartsOnCluster("","");
  1690. partsOnCluster->setCluster(clusterName);
  1691. IArrayOf<IConstDFUPart>& filePartList = partsOnCluster->getDFUFileParts();
  1692. Owned<IFileDescriptor> fdesc = df->getFileDescriptor(clusterName);
  1693. Owned<IPartDescriptorIterator> pi = fdesc->getIterator();
  1694. ForEach(*pi)
  1695. {
  1696. IPartDescriptor& part = pi->query();
  1697. unsigned partIndex = part.queryPartIndex();
  1698. __int64 size = -1;
  1699. StringBuffer partSizeStr;
  1700. IPropertyTree* partPropertyTree = &part.queryProperties();
  1701. if (!partPropertyTree)
  1702. partSizeStr.set("<N/A>");
  1703. else
  1704. {
  1705. size = partPropertyTree->getPropInt64("@size", -1);
  1706. comma c4(size);
  1707. partSizeStr<<c4;
  1708. count++;
  1709. sum+=size;
  1710. if(size>mx) mx=size;
  1711. if(size<mn) mn=size;
  1712. }
  1713. for (unsigned int i=0; i<part.numCopies(); i++)
  1714. {
  1715. StringBuffer b;
  1716. part.queryNode(i)->endpoint().getUrlStr(b);
  1717. Owned<IEspDFUPart> FilePart = createDFUPart("","");
  1718. FilePart->setId(partIndex+1);
  1719. FilePart->setPartsize(partSizeStr.str());
  1720. if (version >= 1.38)
  1721. FilePart->setPartSizeInt64(size);
  1722. FilePart->setIp(b.str());
  1723. FilePart->setCopy(i+1);
  1724. filePartList.append(*FilePart.getClear());
  1725. }
  1726. }
  1727. if (version >= 1.31)
  1728. {
  1729. IClusterInfo* clusterInfo = fdesc->queryCluster(clusterName);
  1730. if (clusterInfo) //Should be valid. But, check it just in case.
  1731. {
  1732. partsOnCluster->setReplicate(clusterInfo->queryPartDiskMapping().isReplicated());
  1733. Owned<CThorNodeGroup> nodeGroup = thorNodeGroupCache->lookup(clusterName, nodeGroupCacheTimeout);
  1734. if (nodeGroup)
  1735. partsOnCluster->setCanReplicate(nodeGroup->queryCanReplicate());
  1736. const char* defaultDir = fdesc->queryDefaultDir();
  1737. if (defaultDir && *defaultDir)
  1738. {
  1739. DFD_OS os = SepCharBaseOs(getPathSepChar(defaultDir));
  1740. StringBuffer baseDir, repDir;
  1741. clusterInfo->getBaseDir(baseDir, os);
  1742. clusterInfo->getReplicateDir(repDir, os);
  1743. partsOnCluster->setBaseDir(baseDir.str());
  1744. partsOnCluster->setReplicateDir(baseDir.str());
  1745. }
  1746. }
  1747. }
  1748. partsOnClusters.append(*partsOnCluster.getClear());
  1749. }
  1750. }
  1751. void CWsDfuEx::parseFieldMask(unsigned __int64 fieldMask, unsigned &fieldCount, IntArray &fieldIndexArray)
  1752. {
  1753. while (fieldMask > 0)
  1754. {
  1755. if (fieldMask & 1)
  1756. fieldIndexArray.append(fieldCount); //index from 0
  1757. fieldMask >>= 1;
  1758. fieldCount++;
  1759. }
  1760. }
  1761. void CWsDfuEx::queryFieldNames(IEspContext &context, const char *fileName, const char *cluster,
  1762. unsigned __int64 fieldMask, StringArray &fieldNames)
  1763. {
  1764. if (!fileName || !*fileName)
  1765. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "File name required");
  1766. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  1767. Owned<INewResultSet> result = resultSetFactory->createNewFileResultSet(fileName, cluster);
  1768. if (!result)
  1769. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed to access FileResultSet for %s.", fileName);
  1770. unsigned fieldCount = 0;
  1771. IntArray fieldIndexArray;
  1772. parseFieldMask(fieldMask, fieldCount, fieldIndexArray);
  1773. const IResultSetMetaData& metaData = result->getMetaData();
  1774. unsigned totalColumns = (unsigned) metaData.getColumnCount();
  1775. if (fieldCount > totalColumns)
  1776. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid FieldMask %" I64F "u: total fields %u, ask for %u.",
  1777. fieldMask, totalColumns, fieldCount);
  1778. ForEachItemIn(i, fieldIndexArray)
  1779. {
  1780. int fieldIndex = fieldIndexArray.item(i);
  1781. SCMStringBuffer columnLabel;
  1782. if (metaData.hasSetTranslation(fieldIndex))
  1783. metaData.getNaturalColumnLabel(columnLabel, fieldIndex);
  1784. if (columnLabel.length() < 1)
  1785. metaData.getColumnLabel(columnLabel, fieldIndex);
  1786. fieldNames.append(columnLabel.str());
  1787. }
  1788. }
  1789. void CWsDfuEx::doGetFileDetails(IEspContext &context, IUserDescriptor *udesc, const char *name, const char *cluster,
  1790. const char *querySet, const char *query, const char *description, bool includeJsonTypeInfo, bool includeBinTypeInfo,
  1791. CDFUChangeProtection protect, IEspDFUFileDetail &FileDetails)
  1792. {
  1793. if (!name || !*name)
  1794. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "File name required");
  1795. PROGLOG("doGetFileDetails: %s", name);
  1796. double version = context.getClientVersion();
  1797. if ((version >= 1.38) && !isEmptyString(querySet) && !isEmptyString(query))
  1798. {
  1799. if (getQueryFile(name, querySet, query, FileDetails))
  1800. return;
  1801. }
  1802. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(name, udesc, false, false, true); // lock super-owners
  1803. if(!df)
  1804. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",name);
  1805. StringArray clusters;
  1806. df->getClusterNames(clusters);
  1807. if (cluster && *cluster && !FindInStringArray(clusters, cluster))
  1808. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s on %s.", name, cluster);
  1809. if (protect != CDFUChangeProtection_NoChange)
  1810. {
  1811. StringBuffer protectBy;
  1812. context.getUserID(protectBy);
  1813. if (protectBy.isEmpty())
  1814. protectBy.set("hpcc");
  1815. df->setProtect(protectBy.str(), protect == CDFUChangeProtection_Protect ? true : false);
  1816. }
  1817. offset_t size=queryDistributedFileSystem().getSize(df), recordSize=df->queryAttributes().getPropInt64("@recordSize",0);
  1818. CDateTime dt;
  1819. df->getModificationTime(dt);
  1820. const char* lname=df->queryLogicalName(), *fname=strrchr(lname,':');
  1821. FileDetails.setName(lname);
  1822. FileDetails.setFilename(fname ? fname+1 : lname);
  1823. FileDetails.setDir(df->queryDefaultDir());
  1824. FileDetails.setPathMask(df->queryPartMask());
  1825. if (version >= 1.28)
  1826. {
  1827. StringBuffer buf;
  1828. FileDetails.setPrefix(getPrefixFromLogicalName(lname, buf));
  1829. if (cluster && *cluster)
  1830. FileDetails.setNodeGroup(cluster);
  1831. else if (clusters.length() == 1)
  1832. FileDetails.setNodeGroup(clusters.item(0));
  1833. IArrayOf<IEspDFUFileProtect> protectList;
  1834. Owned<IPropertyTreeIterator> itr= df->queryAttributes().getElements("Protect");
  1835. ForEach(*itr)
  1836. {
  1837. IPropertyTree &tree = itr->query();
  1838. const char *owner = tree.queryProp("@name");
  1839. const char *modified = tree.queryProp("@modified");
  1840. int count = tree.getPropInt("@count", 0);
  1841. Owned<IEspDFUFileProtect> protect= createDFUFileProtect();
  1842. if(owner && *owner)
  1843. protect->setOwner(owner);
  1844. if(modified && *modified)
  1845. protect->setModified(modified);
  1846. protect->setCount(count);
  1847. protectList.append(*protect.getLink());
  1848. }
  1849. FileDetails.setProtectList(protectList);
  1850. }
  1851. StringBuffer strDesc = df->queryAttributes().queryProp("@description");
  1852. if (description)
  1853. {
  1854. DistributedFilePropertyLock lock(df);
  1855. lock.queryAttributes().setProp("@description",description);
  1856. strDesc = description;
  1857. }
  1858. FileDetails.setDescription(strDesc);
  1859. if (version >= 1.38)
  1860. FileDetails.setFileSizeInt64(size);
  1861. comma c1(size);
  1862. StringBuffer tmpstr;
  1863. tmpstr<<c1;
  1864. FileDetails.setFilesize(tmpstr.str());
  1865. bool isKeyFile = isFileKey(df);
  1866. if (isKeyFile || df->isCompressed())
  1867. {
  1868. if (version < 1.22)
  1869. FileDetails.setZipFile(true);
  1870. else
  1871. {
  1872. FileDetails.setIsCompressed(true);
  1873. if (df->queryAttributes().hasProp("@compressedSize"))
  1874. {
  1875. __int64 compressedSize = df->queryAttributes().getPropInt64("@compressedSize");
  1876. FileDetails.setCompressedFileSize(compressedSize);
  1877. if (version >= 1.34)
  1878. {
  1879. Decimal d(((double) compressedSize)/size*100);
  1880. d.round(2);
  1881. FileDetails.setPercentCompressed(d.getCString());
  1882. }
  1883. }
  1884. else if (isKeyFile)
  1885. FileDetails.setCompressedFileSize(size);
  1886. }
  1887. }
  1888. if (version >= 1.38)
  1889. FileDetails.setRecordSizeInt64(recordSize);
  1890. comma c2(recordSize);
  1891. tmpstr.clear();
  1892. tmpstr<<c2;
  1893. FileDetails.setRecordSize(tmpstr.str());
  1894. tmpstr.clear();
  1895. __int64 recordCount = -1;
  1896. if (df->queryAttributes().hasProp("@recordCount"))
  1897. {
  1898. recordCount = df->queryAttributes().getPropInt64("@recordCount");
  1899. }
  1900. else if (recordSize)
  1901. {
  1902. recordCount = size/recordSize;
  1903. }
  1904. if (version >= 1.38)
  1905. FileDetails.setRecordCountInt64(recordCount);
  1906. if (recordCount != -1)
  1907. {
  1908. comma c3(recordCount);
  1909. tmpstr<<c3;
  1910. }
  1911. FileDetails.setRecordCount(tmpstr.str());
  1912. FileDetails.setOwner(df->queryAttributes().queryProp("@owner"));
  1913. FileDetails.setJobName(df->queryAttributes().queryProp("@job"));
  1914. if (version >= 1.39)
  1915. {
  1916. if (df->queryAttributes().hasProp("@partitionFieldMask"))
  1917. {
  1918. StringArray partitionFieldNames;
  1919. unsigned __int64 partitionFieldMask = df->queryAttributes().getPropInt64("@partitionFieldMask");
  1920. queryFieldNames(context, name, cluster, partitionFieldMask, partitionFieldNames);
  1921. IEspDFUFilePartition &partition = FileDetails.updatePartition();
  1922. partition.setFieldMask(partitionFieldMask);
  1923. partition.setFieldNames(partitionFieldNames);
  1924. }
  1925. IArrayOf<IEspDFUFileBloom> bloomList;
  1926. Owned<IPropertyTreeIterator> itr= df->queryAttributes().getElements("Bloom");
  1927. ForEach(*itr)
  1928. {
  1929. IPropertyTree &bloomTree = itr->query();
  1930. StringArray bloomFieldNames;
  1931. unsigned __int64 bloomFieldMask = bloomTree.getPropInt64("@bloomFieldMask");
  1932. queryFieldNames(context, name, cluster, bloomFieldMask, bloomFieldNames);
  1933. Owned<IEspDFUFileBloom> bloom= createDFUFileBloom();
  1934. bloom->setFieldMask(bloomFieldMask);
  1935. bloom->setFieldNames(bloomFieldNames);
  1936. bloom->setLimit(bloomTree.getPropInt64("@bloomLimit"));
  1937. bloom->setProbability(bloomTree.queryProp("@bloomProbability"));
  1938. bloomList.append(*bloom.getLink());
  1939. }
  1940. if (bloomList.ordinality())
  1941. FileDetails.setBlooms(bloomList);
  1942. }
  1943. if ((version >= 1.40) && df->queryAttributes().hasProp("@expireDays"))
  1944. FileDetails.setExpireDays(df->queryAttributes().getPropInt("@expireDays"));
  1945. //#14280
  1946. IDistributedSuperFile *sf = df->querySuperFile();
  1947. if(sf)
  1948. {
  1949. StringArray farray;
  1950. Owned<IDistributedFileIterator> iter=sf->getSubFileIterator();
  1951. ForEach(*iter)
  1952. {
  1953. StringBuffer subfileName;
  1954. iter->getName(subfileName);
  1955. farray.append(subfileName.str());
  1956. }
  1957. unsigned numSubFiles = farray.length();
  1958. if(numSubFiles > 0)
  1959. {
  1960. FileDetails.setSubfiles(farray);
  1961. }
  1962. if ((version >= 1.28) && (numSubFiles > 1))
  1963. FileDetails.setBrowseData(false); //ViewKeyFile Cannot handle superfile with multiple subfiles
  1964. FileDetails.setIsSuperfile(true);
  1965. return;
  1966. }
  1967. //#14280
  1968. FileDetails.setWuid(df->queryAttributes().queryProp("@workunit"));
  1969. if (version >= 1.28)
  1970. FileDetails.setNumParts(df->numParts());
  1971. //#17430
  1972. {
  1973. IArrayOf<IEspDFULogicalFile> LogicalFiles;
  1974. Owned<IDistributedSuperFileIterator> iter = df->getOwningSuperFiles();
  1975. if(iter.get() != NULL)
  1976. {
  1977. ForEach(*iter)
  1978. {
  1979. //printf("%s,%s\n",iter->query().queryLogicalName(),lname);
  1980. Owned<IEspDFULogicalFile> File = createDFULogicalFile("","");
  1981. File->setName(iter->queryName());
  1982. LogicalFiles.append(*File.getClear());
  1983. }
  1984. }
  1985. if(LogicalFiles.length() > 0)
  1986. {
  1987. FileDetails.setSuperfiles(LogicalFiles);
  1988. }
  1989. }
  1990. //#17430
  1991. //new (optional) attribute on a logical file (@persistent)
  1992. //indicates the ESP page that shows the details of a file. It indicates
  1993. //whether the file was created with a PERSIST() ecl attribute.
  1994. FileDetails.setPersistent(df->queryAttributes().queryProp("@persistent"));
  1995. //@format - what format the file is (if not fixed with)
  1996. FileDetails.setFormat(df->queryAttributes().queryProp("@format"));
  1997. if ((version >= 1.21) && (df->queryAttributes().hasProp("@kind")))
  1998. FileDetails.setContentType(df->queryAttributes().queryProp("@kind"));
  1999. //@maxRecordSize - what the maximum length of records is
  2000. FileDetails.setMaxRecordSize(df->queryAttributes().queryProp("@maxRecordSize"));
  2001. //@csvSeparate - separators between fields for a CSV/utf file
  2002. FileDetails.setCsvSeparate(df->queryAttributes().queryProp("@csvSeparate"));
  2003. //@csvQuote - character used to quote fields for a csv/utf file.
  2004. FileDetails.setCsvQuote(df->queryAttributes().queryProp("@csvQuote"));
  2005. //@csvTerminate - characters used to terminate a record in a csv.utf file
  2006. FileDetails.setCsvTerminate(df->queryAttributes().queryProp("@csvTerminate"));
  2007. //@csvEscape - character used to define escape for a csv/utf file.
  2008. if (version >= 1.20)
  2009. FileDetails.setCsvEscape(df->queryAttributes().queryProp("@csvEscape"));
  2010. //Time and date of the file
  2011. tmpstr.clear();
  2012. dt.getDateString(tmpstr);
  2013. tmpstr.append(" ");
  2014. dt.getTimeString(tmpstr);
  2015. FileDetails.setModified(tmpstr.str());
  2016. if(df->queryAttributes().hasProp("ECL"))
  2017. FileDetails.setEcl(df->queryAttributes().queryProp("ECL"));
  2018. StringBuffer clusterStr;
  2019. ForEachItemIn(i, clusters)
  2020. {
  2021. if (!clusterStr.length())
  2022. clusterStr.append(clusters.item(i));
  2023. else
  2024. clusterStr.append(",").append(clusters.item(i));
  2025. }
  2026. if (clusterStr.length() > 0)
  2027. {
  2028. if (!checkFileContent(context, udesc, name, clusterStr.str()))
  2029. FileDetails.setShowFileContent(false);
  2030. if (version > 1.05)
  2031. {
  2032. bool fromRoxieCluster = false;
  2033. StringArray roxieClusterNames;
  2034. IArrayOf<IEspTpCluster> roxieclusters;
  2035. CTpWrapper dummy;
  2036. dummy.getClusterProcessList(eqRoxieCluster, roxieclusters);
  2037. ForEachItemIn(k, roxieclusters)
  2038. {
  2039. IEspTpCluster& r_cluster = roxieclusters.item(k);
  2040. StringBuffer sName = r_cluster.getName();
  2041. if (FindInStringArray(clusters, sName.str()))
  2042. {
  2043. fromRoxieCluster = true;
  2044. break;
  2045. }
  2046. }
  2047. FileDetails.setFromRoxieCluster(fromRoxieCluster);
  2048. }
  2049. }
  2050. offset_t mn=LLC(0x7fffffffffffffff), mx=0, sum=0, count=0;
  2051. if (version >= 1.25)
  2052. getFilePartsOnClusters(context, cluster, clusters, df, FileDetails, mn, mx, sum, count);
  2053. else
  2054. {
  2055. FileDetails.setCluster(clusters.item(0));
  2056. IArrayOf<IConstDFUPart>& PartList = FileDetails.getDFUFileParts();
  2057. Owned<IDistributedFilePartIterator> pi = df->getIterator();
  2058. ForEach(*pi)
  2059. {
  2060. Owned<IDistributedFilePart> part = &pi->get();
  2061. for (unsigned int i=0; i<part->numCopies(); i++)
  2062. {
  2063. Owned<IEspDFUPart> FilePart = createDFUPart("","");
  2064. StringBuffer b;
  2065. part->queryNode(i)->endpoint().getUrlStr(b);
  2066. FilePart->setId(part->getPartIndex()+1);
  2067. FilePart->setCopy(i+1);
  2068. FilePart->setIp(b.str());
  2069. FilePart->setPartsize("<N/A>");
  2070. try
  2071. {
  2072. offset_t size=queryDistributedFileSystem().getSize(part);
  2073. if (version >= 1.38)
  2074. FilePart->setPartSizeInt64(size);
  2075. comma c4(size);
  2076. tmpstr.clear();
  2077. tmpstr<<c4;
  2078. FilePart->setPartsize(tmpstr.str());
  2079. if(size!=-1)
  2080. {
  2081. count+=1;
  2082. sum+=size;
  2083. if(size>mx) mx=size;
  2084. if(size<mn) mn=size;
  2085. }
  2086. }
  2087. catch(IException *e)
  2088. {
  2089. StringBuffer msg;
  2090. ERRLOG("Exception %d:%s in WS_DFU queryDistributedFileSystem().getSize()", e->errorCode(), e->errorMessage(msg).str());
  2091. e->Release();
  2092. }
  2093. catch(...)
  2094. {
  2095. ERRLOG("Unknown exception in WS_DFU queryDistributedFileSystem().getSize()");
  2096. }
  2097. PartList.append(*FilePart.getClear());
  2098. }
  2099. }
  2100. }
  2101. if(count)
  2102. {
  2103. IEspDFUFileStat& Stat = FileDetails.updateStat();
  2104. offset_t avg=sum/count;
  2105. offset_t minSkew = avg-mn;
  2106. offset_t maxSkew = mx-avg;
  2107. if (version >= 1.38)
  2108. {
  2109. Stat.setMinSkewInt64(minSkew);
  2110. Stat.setMaxSkewInt64(maxSkew);
  2111. }
  2112. comma c5(minSkew);
  2113. tmpstr.clear();
  2114. tmpstr<<c5;
  2115. Stat.setMinSkew(tmpstr.str());
  2116. comma c6(maxSkew);
  2117. tmpstr.clear();
  2118. tmpstr<<c6;
  2119. Stat.setMaxSkew(tmpstr.str());
  2120. }
  2121. if (version > 1.06)
  2122. {
  2123. const char *wuid = df->queryAttributes().queryProp("@workunit");
  2124. if (wuid && *wuid && (wuid[0]=='W'))
  2125. {
  2126. try
  2127. {
  2128. CWUWrapper wu(wuid, context);
  2129. StringArray graphs;
  2130. Owned<IPropertyTreeIterator> f=&wu->getFileIterator();
  2131. ForEach(*f)
  2132. {
  2133. IPropertyTree &query = f->query();
  2134. const char *fileName = query.queryProp("@name");
  2135. const char *graphName = query.queryProp("@graph");
  2136. if (!fileName || !graphName || !*graphName || stricmp(fileName, name))
  2137. continue;
  2138. graphs.append(graphName);
  2139. }
  2140. FileDetails.setGraphs(graphs);
  2141. }
  2142. catch(...)
  2143. {
  2144. DBGLOG("Failed in retrieving graphs from workunit %s", wuid);
  2145. }
  2146. }
  2147. }
  2148. if (version > 1.08 && udesc)
  2149. {
  2150. SecAccessFlags permission;
  2151. if (getUserFilePermission(context, udesc, name, permission))
  2152. {
  2153. switch (permission)
  2154. {
  2155. case SecAccess_Full:
  2156. FileDetails.setUserPermission("Full Access Permission");
  2157. break;
  2158. case SecAccess_Write:
  2159. FileDetails.setUserPermission("Write Access Permission");
  2160. break;
  2161. case SecAccess_Read:
  2162. FileDetails.setUserPermission("Read Access Permission");
  2163. break;
  2164. case SecAccess_Access:
  2165. FileDetails.setUserPermission("Access Permission");
  2166. break;
  2167. case SecAccess_None:
  2168. FileDetails.setUserPermission("None Access Permission");
  2169. break;
  2170. default:
  2171. FileDetails.setUserPermission("Permission Unknown");
  2172. break;
  2173. }
  2174. }
  2175. }
  2176. if (includeJsonTypeInfo||includeBinTypeInfo)
  2177. {
  2178. MemoryBuffer binLayout;
  2179. StringBuffer jsonLayout;
  2180. if (getRecordFormatFromRtlType(binLayout, jsonLayout, df->queryAttributes(), includeBinTypeInfo, includeJsonTypeInfo) ||
  2181. getRecordFormatFromECL(binLayout.clear(), jsonLayout.clear(), df->queryAttributes(), includeBinTypeInfo, includeJsonTypeInfo))
  2182. {
  2183. if (includeBinTypeInfo)
  2184. FileDetails.setBinInfo(binLayout);
  2185. if (includeJsonTypeInfo)
  2186. FileDetails.setJsonInfo(jsonLayout);
  2187. }
  2188. }
  2189. PROGLOG("doGetFileDetails: %s done", name);
  2190. }
  2191. bool CWsDfuEx::getQueryFile(const char *logicalName, const char *querySet, const char *queryID, IEspDFUFileDetail &fileDetails)
  2192. {
  2193. Owned<IConstWUClusterInfo> info = getTargetClusterInfo(querySet);
  2194. if (!info || (info->getPlatform()!=RoxieCluster))
  2195. return false;
  2196. SCMStringBuffer process;
  2197. info->getRoxieProcess(process);
  2198. if (!process.length())
  2199. return false;
  2200. Owned<IHpccPackageSet> ps = createPackageSet(process.str());
  2201. if (!ps)
  2202. return false;
  2203. const IHpccPackageMap *pm = ps->queryActiveMap(querySet);
  2204. if (!pm)
  2205. return false;
  2206. const IHpccPackage *pkg = pm->matchPackage(queryID);
  2207. if (!pkg)
  2208. return false;
  2209. const char *pkgid = pkg->locateSuperFile(logicalName);
  2210. if (!pkgid)
  2211. return false;
  2212. fileDetails.setName(logicalName);
  2213. fileDetails.setIsSuperfile(true);
  2214. fileDetails.setPackageID(pkgid);
  2215. StringArray subFiles;
  2216. Owned<ISimpleSuperFileEnquiry> ssfe = pkg->resolveSuperFile(logicalName);
  2217. if (ssfe && ssfe->numSubFiles()>0)
  2218. {
  2219. unsigned count = ssfe->numSubFiles();
  2220. while (count--)
  2221. {
  2222. StringBuffer subfile;
  2223. ssfe->getSubFileName(count, subfile);
  2224. subFiles.append(subfile.str());
  2225. }
  2226. if (!subFiles.empty())
  2227. fileDetails.setSubfiles(subFiles);
  2228. }
  2229. return true;
  2230. }
  2231. void CWsDfuEx::getLogicalFileAndDirectory(IEspContext &context, IUserDescriptor* udesc, const char *dirname,
  2232. bool includeSuperOwner, IArrayOf<IEspDFULogicalFile>& logicalFiles, int& numFiles, int& numDirs)
  2233. {
  2234. double version = context.getClientVersion();
  2235. if (dirname && *dirname)
  2236. PROGLOG("getLogicalFileAndDirectory: %s", dirname);
  2237. else
  2238. PROGLOG("getLogicalFileAndDirectory: folder not specified");
  2239. numFiles = 0;
  2240. numDirs = 0;
  2241. if (dirname && *dirname)
  2242. {
  2243. StringBuffer filterBuf;
  2244. setFileNameFilter(NULL, dirname, filterBuf);
  2245. if (includeSuperOwner)
  2246. filterBuf.append(DFUQFTincludeFileAttr).append(DFUQFilterSeparator).append(DFUQSFAOincludeSuperOwner).append(DFUQFilterSeparator);
  2247. //filters used to filter query result received from dali server.
  2248. DFUQResultField localFilters[8];
  2249. localFilters[0] = DFUQRFterm;
  2250. DFUQResultField sortOrder[] = {DFUQRFterm};
  2251. __int64 cacheHint = 0; //No page
  2252. unsigned totalFiles = 0;
  2253. bool allMatchingFilesReceived = true;
  2254. Owned<IDFAttributesIterator> it = queryDistributedFileDirectory().getLogicalFiles(udesc, sortOrder, filterBuf.str(),
  2255. localFilters, NULL, 0, (unsigned)-1, &cacheHint, &totalFiles, &allMatchingFilesReceived, false, false);
  2256. if(!it)
  2257. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get LogicalFile information from file system.");
  2258. ForEach(*it)
  2259. addToLogicalFileList(it->query(), NULL, version, logicalFiles);
  2260. numFiles = totalFiles;
  2261. }
  2262. Owned<IDFScopeIterator> iter = queryDistributedFileDirectory().getScopeIterator(udesc,dirname,false);
  2263. if(iter)
  2264. {
  2265. ForEach(*iter)
  2266. {
  2267. const char *scope = iter->query();
  2268. if (scope && *scope)
  2269. {
  2270. Owned<IEspDFULogicalFile> file = createDFULogicalFile("","");
  2271. file->setDirectory(scope);
  2272. file->setIsDirectory(true);
  2273. logicalFiles.append(*file.getClear());
  2274. numDirs++;
  2275. }
  2276. }
  2277. }
  2278. }
  2279. bool CWsDfuEx::onDFUFileView(IEspContext &context, IEspDFUFileViewRequest &req, IEspDFUFileViewResponse &resp)
  2280. {
  2281. try
  2282. {
  2283. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUFileView: Permission denied.");
  2284. Owned<IUserDescriptor> userdesc;
  2285. StringBuffer username;
  2286. context.getUserID(username);
  2287. if(username.length() > 0)
  2288. {
  2289. userdesc.setown(createUserDescriptor());
  2290. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  2291. }
  2292. int numDirs = 0;
  2293. int numFiles = 0;
  2294. IArrayOf<IEspDFULogicalFile> logicalFiles;
  2295. getLogicalFileAndDirectory(context, userdesc.get(), req.getScope(), !req.getIncludeSuperOwner_isNull() && req.getIncludeSuperOwner(), logicalFiles, numFiles, numDirs);
  2296. if (numFiles > 0)
  2297. resp.setNumFiles(numFiles);
  2298. if (req.getScope() && *req.getScope())
  2299. resp.setScope(req.getScope());
  2300. else
  2301. resp.setScope("");
  2302. resp.setDFULogicalFiles(logicalFiles);
  2303. }
  2304. catch(IException* e)
  2305. {
  2306. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2307. }
  2308. return true;
  2309. }
  2310. __int64 CWsDfuEx::findPositionBySize(const __int64 size, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2311. {
  2312. __int64 addToPos = -1;
  2313. ForEachItemIn(i, LogicalFiles)
  2314. {
  2315. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2316. const char* sSize = File.getLongSize();
  2317. __int64 nSize = atoi64_l(sSize,strlen(sSize));
  2318. if (descend && size > nSize)
  2319. {
  2320. addToPos = i;
  2321. break;
  2322. }
  2323. if (!descend && size < nSize)
  2324. {
  2325. addToPos = i;
  2326. break;
  2327. }
  2328. }
  2329. return addToPos;
  2330. }
  2331. __int64 CWsDfuEx::findPositionByParts(const __int64 parts, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2332. {
  2333. __int64 addToPos = -1;
  2334. ForEachItemIn(i, LogicalFiles)
  2335. {
  2336. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2337. const char* sParts = File.getParts();
  2338. __int64 nParts = atoi64_l(sParts,strlen(sParts));
  2339. if (descend && parts > nParts)
  2340. {
  2341. addToPos = i;
  2342. break;
  2343. }
  2344. if (!descend && parts < nParts)
  2345. {
  2346. addToPos = i;
  2347. break;
  2348. }
  2349. }
  2350. return addToPos;
  2351. }
  2352. __int64 CWsDfuEx::findPositionByRecords(const __int64 records, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2353. {
  2354. __int64 addToPos = -1;
  2355. ForEachItemIn(i, LogicalFiles)
  2356. {
  2357. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2358. const char* sRecords = File.getLongRecordCount();
  2359. __int64 nRecords = atoi64_l(sRecords,strlen(sRecords));
  2360. if (descend && records > nRecords)
  2361. {
  2362. addToPos = i;
  2363. break;
  2364. }
  2365. if (!descend && records < nRecords)
  2366. {
  2367. addToPos = i;
  2368. break;
  2369. }
  2370. }
  2371. return addToPos;
  2372. }
  2373. __int64 CWsDfuEx::findPositionByName(const char *name, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2374. {
  2375. if (!name || (strlen(name) < 1))
  2376. {
  2377. if (descend)
  2378. return -1;
  2379. else
  2380. return 0;
  2381. }
  2382. __int64 addToPos = -1;
  2383. ForEachItemIn(i, LogicalFiles)
  2384. {
  2385. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2386. const char *Name = File.getName();
  2387. if (!Name)
  2388. continue;
  2389. if (descend && strcmp(name, Name)>0)
  2390. {
  2391. addToPos = i;
  2392. break;
  2393. }
  2394. if (!descend && strcmp(name, Name)<0)
  2395. {
  2396. addToPos = i;
  2397. break;
  2398. }
  2399. }
  2400. return addToPos;
  2401. }
  2402. __int64 CWsDfuEx::findPositionByNodeGroup(double version, const char *node, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2403. {
  2404. if (!node || !*node)
  2405. {
  2406. if (descend)
  2407. return -1;
  2408. else
  2409. return 0;
  2410. }
  2411. __int64 addToPos = -1;
  2412. ForEachItemIn(i, LogicalFiles)
  2413. {
  2414. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2415. const char *nodeGroup = NULL;
  2416. if (version < 1.26)
  2417. nodeGroup = File.getClusterName();
  2418. else
  2419. nodeGroup = File.getNodeGroup();
  2420. if (!nodeGroup)
  2421. continue;
  2422. if (descend && strcmp(node, nodeGroup)>0)
  2423. {
  2424. addToPos = i;
  2425. break;
  2426. }
  2427. if (!descend && strcmp(node, nodeGroup)<0)
  2428. {
  2429. addToPos = i;
  2430. break;
  2431. }
  2432. }
  2433. return addToPos;
  2434. }
  2435. __int64 CWsDfuEx::findPositionByOwner(const char *owner, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2436. {
  2437. if (!owner || (strlen(owner) < 1))
  2438. {
  2439. if (descend)
  2440. return -1;
  2441. else
  2442. return 0;
  2443. }
  2444. __int64 addToPos = -1;
  2445. ForEachItemIn(i, LogicalFiles)
  2446. {
  2447. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2448. const char *Owner = File.getOwner();
  2449. if (!Owner)
  2450. continue;
  2451. if (descend && strcmp(owner, Owner)>0)
  2452. {
  2453. addToPos = i;
  2454. break;
  2455. }
  2456. if (!descend && strcmp(owner, Owner)<0)
  2457. {
  2458. addToPos = i;
  2459. break;
  2460. }
  2461. }
  2462. return addToPos;
  2463. }
  2464. __int64 CWsDfuEx::findPositionByDate(const char *datetime, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2465. {
  2466. if (!datetime || (strlen(datetime) < 1))
  2467. {
  2468. if (descend)
  2469. return -1;
  2470. else
  2471. return 0;
  2472. }
  2473. __int64 addToPos = -1;
  2474. ForEachItemIn(i, LogicalFiles)
  2475. {
  2476. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2477. const char *modDate = File.getModified();
  2478. if (!modDate)
  2479. continue;
  2480. if (descend && strcmp(datetime, modDate)>0)
  2481. {
  2482. addToPos = i;
  2483. break;
  2484. }
  2485. if (!descend && strcmp(datetime, modDate)<0)
  2486. {
  2487. addToPos = i;
  2488. break;
  2489. }
  2490. }
  2491. return addToPos;
  2492. }
  2493. __int64 CWsDfuEx::findPositionByDescription(const char *description, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2494. {
  2495. if (!description || (strlen(description) < 1))
  2496. {
  2497. if (descend)
  2498. return -1;
  2499. else
  2500. return 0;
  2501. }
  2502. __int64 addToPos = -1;
  2503. ForEachItemIn(i, LogicalFiles)
  2504. {
  2505. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2506. const char *Description = File.getDescription();
  2507. if (!Description)
  2508. continue;
  2509. if (descend && strcmp(description, Description)>0)
  2510. {
  2511. addToPos = i;
  2512. break;
  2513. }
  2514. if (!descend && strcmp(description, Description)<0)
  2515. {
  2516. addToPos = i;
  2517. break;
  2518. }
  2519. }
  2520. return addToPos;
  2521. }
  2522. //The code inside this method is copied from previous code for legacy (< 5.0) dali support
  2523. void CWsDfuEx::getAPageOfSortedLogicalFile(IEspContext &context, IUserDescriptor* udesc, IEspDFUQueryRequest & req, IEspDFUQueryResponse & resp)
  2524. {
  2525. double version = context.getClientVersion();
  2526. IArrayOf<IEspDFULogicalFile> LogicalFiles;
  2527. StringBuffer filter;
  2528. const char* fname = req.getLogicalName();
  2529. if(fname && *fname)
  2530. {
  2531. filter.append(fname);
  2532. }
  2533. else
  2534. {
  2535. if(req.getPrefix() && *req.getPrefix())
  2536. {
  2537. filter.append(req.getPrefix());
  2538. filter.append("::");
  2539. }
  2540. filter.append("*");
  2541. }
  2542. Owned<IDFAttributesIterator> fi;
  2543. bool bNotInSuperfile = false;
  2544. const char* sFileType = req.getFileType();
  2545. if (sFileType && !stricmp(sFileType, "Not in Superfiles"))
  2546. {
  2547. bNotInSuperfile = true;
  2548. }
  2549. if (bNotInSuperfile)
  2550. {
  2551. fi.setown(createSubFileFilter(
  2552. queryDistributedFileDirectory().getDFAttributesIterator(filter.toLowerCase().str(),udesc,true,true, NULL),udesc,false)); // NB wrapper owns wrapped iterator
  2553. }
  2554. else
  2555. {
  2556. fi.setown(queryDistributedFileDirectory().getDFAttributesIterator(filter.toLowerCase().str(), udesc,true,true, NULL));
  2557. }
  2558. if(!fi)
  2559. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get information from file system.");
  2560. StringBuffer wuFrom, wuTo;
  2561. if(req.getStartDate() && *req.getStartDate())
  2562. {
  2563. CDateTime wuTime;
  2564. wuTime.setString(req.getStartDate(),NULL,true);
  2565. unsigned year, month, day, hour, minute, second, nano;
  2566. wuTime.getDate(year, month, day, true);
  2567. wuTime.getTime(hour, minute, second, nano, true);
  2568. wuFrom.appendf("%4d-%02d-%02d %02d:%02d:%02d",year,month,day,hour,minute,second);
  2569. }
  2570. if(req.getEndDate() && *req.getEndDate())
  2571. {
  2572. CDateTime wuTime;
  2573. wuTime.setString(req.getEndDate(),NULL,true);
  2574. unsigned year, month, day, hour, minute, second, nano;
  2575. wuTime.getDate(year, month, day, true);
  2576. wuTime.getTime(hour, minute, second, nano, true);
  2577. wuTo.appendf("%4d-%02d-%02d %02d:%02d:%02d",year,month,day,hour,minute,second);
  2578. }
  2579. StringBuffer sortBy;
  2580. if(req.getSortby() && *req.getSortby())
  2581. {
  2582. sortBy.append(req.getSortby());
  2583. }
  2584. unsigned pagesize = req.getPageSize();
  2585. if (pagesize < 1)
  2586. {
  2587. pagesize = 100;
  2588. }
  2589. __int64 displayStartReq = 1;
  2590. if (req.getPageStartFrom() > 0)
  2591. displayStartReq = req.getPageStartFrom();
  2592. __int64 displayStart = displayStartReq - 1;
  2593. __int64 displayEnd = displayStart + pagesize;
  2594. bool descending = req.getDescending();
  2595. const int nFirstN = req.getFirstN();
  2596. const char* sFirstNType = req.getFirstNType();
  2597. const __int64 nFileSizeFrom = req.getFileSizeFrom();
  2598. const __int64 nFileSizeTo = req.getFileSizeTo();
  2599. if (nFirstN > 0)
  2600. {
  2601. displayStart = 0;
  2602. displayEnd = nFirstN;
  2603. if (!stricmp(sFirstNType, "newest"))
  2604. {
  2605. sortBy.set("Modified");
  2606. descending = true;
  2607. }
  2608. else if (!stricmp(sFirstNType, "oldest"))
  2609. {
  2610. sortBy.set("Modified");
  2611. descending = false;
  2612. }
  2613. else if (!stricmp(sFirstNType, "largest"))
  2614. {
  2615. sortBy.set("FileSize");
  2616. descending = true;
  2617. }
  2618. else if (!stricmp(sFirstNType, "smallest"))
  2619. {
  2620. sortBy.set("FileSize");
  2621. descending = false;
  2622. }
  2623. pagesize = nFirstN;
  2624. }
  2625. StringArray roxieClusterNames;
  2626. IArrayOf<IEspTpCluster> roxieclusters;
  2627. CTpWrapper dummy;
  2628. dummy.getClusterProcessList(eqRoxieCluster, roxieclusters);
  2629. ForEachItemIn(k, roxieclusters)
  2630. {
  2631. IEspTpCluster& cluster = roxieclusters.item(k);
  2632. StringBuffer sName = cluster.getName();
  2633. roxieClusterNames.append(sName.str());
  2634. }
  2635. StringArray nodeGroupsReq;
  2636. const char* nodeGroupsReqString = req.getNodeGroup();
  2637. if (nodeGroupsReqString && *nodeGroupsReqString)
  2638. nodeGroupsReq.appendListUniq(nodeGroupsReqString, ",");
  2639. StringBuffer size;
  2640. __int64 totalFiles = 0;
  2641. IArrayOf<IEspDFULogicalFile> LogicalFileList;
  2642. ForEach(*fi)
  2643. {
  2644. IPropertyTree &attr=fi->query();
  2645. const char* logicalName=attr.queryProp("@name");
  2646. if (!logicalName || (logicalName[0] == 0))
  2647. continue;
  2648. try
  2649. {
  2650. StringBuffer pref;
  2651. const char *c=strstr(logicalName, "::");
  2652. if (c)
  2653. pref.append(c-logicalName, logicalName);
  2654. else
  2655. pref.append(logicalName);
  2656. const char* owner=attr.queryProp("@owner");
  2657. if (req.getOwner() && *req.getOwner()!=0)
  2658. {
  2659. if (!owner || stricmp(owner, req.getOwner()))
  2660. continue;
  2661. }
  2662. StringArray nodeGroups;
  2663. StringArray fileNodeGroups;
  2664. if (getFileGroups(&attr,fileNodeGroups)==0)
  2665. {
  2666. if (!nodeGroupsReq.length())
  2667. nodeGroups.append("");
  2668. }
  2669. else if (nodeGroupsReq.length() > 0) // check specified cluster name in list
  2670. {
  2671. ForEachItemIn(ii,nodeGroupsReq)
  2672. {
  2673. const char* nodeGroupReq = nodeGroupsReq.item(ii);
  2674. ForEachItemIn(i,fileNodeGroups)
  2675. {
  2676. if (strieq(fileNodeGroups.item(i), nodeGroupReq))
  2677. {
  2678. nodeGroups.append(nodeGroupReq);
  2679. break;
  2680. }
  2681. }
  2682. }
  2683. }
  2684. else if (fileNodeGroups.length())
  2685. {
  2686. ForEachItemIn(i,fileNodeGroups)
  2687. nodeGroups.append(fileNodeGroups.item(i));
  2688. }
  2689. if (sFileType && *sFileType)
  2690. {
  2691. bool bHasSubFiles = attr.hasProp("@numsubfiles");
  2692. if (bHasSubFiles && (bNotInSuperfile || !stricmp(sFileType, "Logical Files Only")))
  2693. continue;
  2694. else if (!bHasSubFiles && !stricmp(sFileType, "Superfiles Only"))
  2695. continue;
  2696. }
  2697. __int64 recordSize=attr.getPropInt64("@recordSize",0), size=attr.getPropInt64("@size",-1);
  2698. if (nFileSizeFrom > 0 && size < nFileSizeFrom)
  2699. continue;
  2700. if (nFileSizeTo > 0 && size > nFileSizeTo)
  2701. continue;
  2702. StringBuffer modf(attr.queryProp("@modified"));
  2703. char* t=(char *) strchr(modf.str(),'T');
  2704. if(t) *t=' ';
  2705. if (wuFrom.length() && strcmp(modf.str(),wuFrom.str())<0)
  2706. continue;
  2707. if (wuTo.length() && strcmp(modf.str(),wuTo.str())>0)
  2708. continue;
  2709. __int64 parts = 0;
  2710. if(!attr.hasProp("@numsubfiles"))
  2711. parts = attr.getPropInt64("@numparts");
  2712. __int64 records = 0;
  2713. if (attr.hasProp("@recordCount"))
  2714. records = attr.getPropInt64("@recordCount");
  2715. else if(recordSize)
  2716. records = size/recordSize;
  2717. const char* desc = attr.queryProp("@description");
  2718. ForEachItemIn(i, nodeGroups)
  2719. {
  2720. const char* nodeGroup = nodeGroups.item(i);
  2721. __int64 addToPos = -1; //Add to tail
  2722. if (stricmp(sortBy, "FileSize")==0)
  2723. {
  2724. addToPos = findPositionBySize(size, descending, LogicalFileList);
  2725. }
  2726. else if (stricmp(sortBy, "Parts")==0)
  2727. {
  2728. addToPos = findPositionByParts(parts, descending, LogicalFileList);
  2729. }
  2730. else if (stricmp(sortBy, "Owner")==0)
  2731. {
  2732. addToPos = findPositionByOwner(owner, descending, LogicalFileList);
  2733. }
  2734. else if (stricmp(sortBy, "NodeGroup")==0)
  2735. {
  2736. addToPos = findPositionByNodeGroup(version, nodeGroup, descending, LogicalFileList);
  2737. }
  2738. else if (stricmp(sortBy, "Records")==0)
  2739. {
  2740. addToPos = findPositionByRecords(records, descending, LogicalFileList);
  2741. }
  2742. else if (stricmp(sortBy, "Modified")==0)
  2743. {
  2744. addToPos = findPositionByDate(modf.str(), descending, LogicalFileList);
  2745. }
  2746. else if (stricmp(sortBy, "Description")==0)
  2747. {
  2748. addToPos = findPositionByDescription(desc, descending, LogicalFileList);
  2749. }
  2750. else
  2751. {
  2752. addToPos = findPositionByName(logicalName, descending, LogicalFileList);
  2753. }
  2754. totalFiles++;
  2755. if (addToPos < 0 && (totalFiles > displayEnd))
  2756. continue;
  2757. Owned<IEspDFULogicalFile> File = createDFULogicalFile("","");
  2758. File->setPrefix(pref);
  2759. if (version < 1.26)
  2760. File->setClusterName(nodeGroup);
  2761. else
  2762. File->setNodeGroup(nodeGroup);
  2763. File->setName(logicalName);
  2764. File->setOwner(owner);
  2765. File->setDescription(desc);
  2766. File->setModified(modf.str());
  2767. File->setReplicate(true);
  2768. ForEachItemIn(j, roxieClusterNames)
  2769. {
  2770. const char* roxieClusterName = roxieClusterNames.item(j);
  2771. if (roxieClusterName && nodeGroup && strieq(roxieClusterName, nodeGroup))
  2772. {
  2773. File->setFromRoxieCluster(true);
  2774. break;
  2775. }
  2776. }
  2777. bool bSuperfile = false;
  2778. int numSubFiles = attr.hasProp("@numsubfiles");
  2779. if(!numSubFiles)
  2780. {
  2781. File->setDirectory(attr.queryProp("@directory"));
  2782. File->setParts(attr.queryProp("@numparts"));
  2783. }
  2784. else
  2785. {
  2786. bSuperfile = true;
  2787. }
  2788. File->setIsSuperfile(bSuperfile);
  2789. if (version < 1.22)
  2790. File->setIsZipfile(isCompressed(attr));
  2791. else
  2792. {
  2793. File->setIsCompressed(isCompressed(attr));
  2794. if (attr.hasProp("@compressedSize"))
  2795. File->setCompressedFileSize(attr.getPropInt64("@compressedSize"));
  2796. }
  2797. //File->setBrowseData(bKeyFile); //Bug: 39750 - All files should be viewable through ViewKeyFile function
  2798. if (numSubFiles > 1) //Bug 41379 - ViewKeyFile Cannot handle superfile with multiple subfiles
  2799. File->setBrowseData(false);
  2800. else
  2801. File->setBrowseData(true);
  2802. if (version > 1.13)
  2803. {
  2804. bool bKeyFile = false;
  2805. const char * kind = attr.queryProp("@kind");
  2806. if (kind && (stricmp(kind, "key") == 0))
  2807. {
  2808. bKeyFile = true;
  2809. }
  2810. if (version < 1.24)
  2811. File->setIsKeyFile(bKeyFile);
  2812. else if (kind && *kind)
  2813. File->setContentType(kind);
  2814. }
  2815. StringBuffer buf;
  2816. buf << comma(size);
  2817. File->setTotalsize(buf.str());
  2818. char temp[64];
  2819. numtostr(temp, size);
  2820. File->setLongSize(temp);
  2821. numtostr(temp, records);
  2822. File->setLongRecordCount(temp);
  2823. if (records > 0)
  2824. File->setRecordCount((buf.clear()<<comma(records)).str());
  2825. if (addToPos < 0)
  2826. LogicalFileList.append(*File.getClear());
  2827. else
  2828. LogicalFileList.add(*File.getClear(), (int) addToPos);
  2829. if (LogicalFileList.length() > displayEnd)
  2830. LogicalFileList.pop();
  2831. }
  2832. }
  2833. catch(IException* e)
  2834. {
  2835. VStringBuffer msg("Failed to retrieve data for logical file %s: ", logicalName);
  2836. int code = e->errorCode();
  2837. e->errorMessage(msg);
  2838. e->Release();
  2839. throw MakeStringException(code, "%s", msg.str());
  2840. }
  2841. }
  2842. if (displayEnd > LogicalFileList.length())
  2843. displayEnd = LogicalFileList.length();
  2844. for (int i = (int) displayStart; i < (int) displayEnd; i++)
  2845. {
  2846. Owned<IEspDFULogicalFile> File = createDFULogicalFile("","");
  2847. IEspDFULogicalFile& File0 = LogicalFileList.item(i);
  2848. File->copy(File0);
  2849. LogicalFiles.append(*File.getClear());
  2850. }
  2851. resp.setNumFiles(totalFiles);
  2852. resp.setPageSize(pagesize);
  2853. resp.setPageStartFrom(displayStart+1);
  2854. resp.setPageEndAt(displayEnd);
  2855. if (displayStart - pagesize > 0)
  2856. resp.setPrevPageFrom(displayStart - pagesize + 1);
  2857. else if(displayStart > 0)
  2858. resp.setPrevPageFrom(1);
  2859. if(displayEnd < totalFiles)
  2860. {
  2861. resp.setNextPageFrom(displayEnd+1);
  2862. resp.setLastPageFrom((int)(pagesize * floor((double) ((totalFiles-1) / pagesize)) + 1));
  2863. }
  2864. StringBuffer basicQuery;
  2865. if (req.getNodeGroup() && *req.getNodeGroup())
  2866. {
  2867. if (version < 1.26)
  2868. resp.setClusterName(req.getNodeGroup());
  2869. else
  2870. resp.setNodeGroup(req.getNodeGroup());
  2871. addToQueryString(basicQuery, "NodeGroup", req.getNodeGroup());
  2872. }
  2873. if (req.getOwner() && *req.getOwner())
  2874. {
  2875. resp.setOwner(req.getOwner());
  2876. addToQueryString(basicQuery, "Owner", req.getOwner());
  2877. }
  2878. if (req.getPrefix() && *req.getPrefix())
  2879. {
  2880. resp.setPrefix(req.getPrefix());
  2881. addToQueryString(basicQuery, "Prefix", req.getPrefix());
  2882. }
  2883. if (req.getLogicalName() && *req.getLogicalName())
  2884. {
  2885. resp.setLogicalName(req.getLogicalName());
  2886. addToQueryString(basicQuery, "LogicalName", req.getLogicalName());
  2887. }
  2888. if (req.getStartDate() && *req.getStartDate())
  2889. {
  2890. resp.setStartDate(req.getStartDate());
  2891. addToQueryString(basicQuery, "StartDate", req.getStartDate());
  2892. }
  2893. if (req.getEndDate() && *req.getEndDate())
  2894. {
  2895. resp.setEndDate(req.getEndDate());
  2896. addToQueryString(basicQuery, "EndDate", req.getEndDate());
  2897. }
  2898. if (req.getFileType() && *req.getFileType())
  2899. {
  2900. resp.setFileType(req.getFileType());
  2901. addToQueryString(basicQuery, "FileType", req.getFileType());
  2902. }
  2903. if (req.getFileSizeFrom())
  2904. {
  2905. resp.setFileSizeFrom(req.getFileSizeFrom());
  2906. addToQueryStringFromInt(basicQuery, "FileSizeFrom", req.getFileSizeFrom());
  2907. }
  2908. if (req.getFileSizeTo())
  2909. {
  2910. resp.setFileSizeTo(req.getFileSizeTo());
  2911. addToQueryStringFromInt(basicQuery, "FileSizeTo", req.getFileSizeTo());
  2912. }
  2913. StringBuffer ParametersForFilters = basicQuery;
  2914. StringBuffer ParametersForPaging = basicQuery;
  2915. addToQueryStringFromInt(ParametersForFilters, "PageSize",pagesize);
  2916. addToQueryStringFromInt(ParametersForPaging, "PageSize", pagesize);
  2917. if (ParametersForFilters.length() > 0)
  2918. resp.setFilters(ParametersForFilters.str());
  2919. sortBy.clear();
  2920. descending = false;
  2921. if ((req.getFirstN() > 0) && req.getFirstNType() && *req.getFirstNType())
  2922. {
  2923. const char *sFirstNType = req.getFirstNType();
  2924. if (!stricmp(sFirstNType, "newest"))
  2925. {
  2926. sortBy.set("Modified");
  2927. descending = true;
  2928. }
  2929. else if (!stricmp(sFirstNType, "oldest"))
  2930. {
  2931. sortBy.set("Modified");
  2932. descending = false;
  2933. }
  2934. else if (!stricmp(sFirstNType, "largest"))
  2935. {
  2936. sortBy.set("FileSize");
  2937. descending = true;
  2938. }
  2939. else if (!stricmp(sFirstNType, "smallest"))
  2940. {
  2941. sortBy.set("FileSize");
  2942. descending = false;
  2943. }
  2944. }
  2945. else if (req.getSortby() && *req.getSortby())
  2946. {
  2947. sortBy.set(req.getSortby());
  2948. if (req.getDescending())
  2949. descending = req.getDescending();
  2950. }
  2951. if (sortBy.length())
  2952. {
  2953. resp.setSortby(sortBy);
  2954. resp.setDescending(descending);
  2955. StringBuffer strbuf = sortBy;
  2956. strbuf.append("=");
  2957. String str1(strbuf.str());
  2958. String str(basicQuery.str());
  2959. if (str.indexOf(str1) < 0)
  2960. {
  2961. addToQueryString(ParametersForPaging, "Sortby", sortBy);
  2962. addToQueryString(basicQuery, "Sortby", sortBy);
  2963. if (descending)
  2964. {
  2965. addToQueryString(ParametersForPaging, "Descending", "1");
  2966. addToQueryString(basicQuery, "Descending", "1");
  2967. }
  2968. }
  2969. }
  2970. if (basicQuery.length() > 0)
  2971. resp.setBasicQuery(basicQuery.str());
  2972. if (ParametersForPaging.length() > 0)
  2973. resp.setParametersForPaging(ParametersForPaging.str());
  2974. resp.setDFULogicalFiles(LogicalFiles);
  2975. return;
  2976. }
  2977. bool CWsDfuEx::addDFUQueryFilter(DFUQResultField *filters, unsigned short &count, MemoryBuffer &buff, const char* value, DFUQResultField name)
  2978. {
  2979. if (!value || !*value)
  2980. return false;
  2981. filters[count++] = name;
  2982. buff.append(value);
  2983. return true;
  2984. }
  2985. void CWsDfuEx::appendDFUQueryFilter(const char *name, DFUQFilterType type, const char *value, StringBuffer& filterBuf)
  2986. {
  2987. if (!name || !*name || !value || !*value)
  2988. return;
  2989. filterBuf.append(type).append(DFUQFilterSeparator).append(name).append(DFUQFilterSeparator).append(value).append(DFUQFilterSeparator);
  2990. }
  2991. void CWsDfuEx::appendDFUQueryFilter(const char *name, DFUQFilterType type, const char *value, const char *valueHigh, StringBuffer& filterBuf)
  2992. {
  2993. if (!name || !*name || !value || !*value)
  2994. return;
  2995. filterBuf.append(type).append(DFUQFilterSeparator).append(name).append(DFUQFilterSeparator).append(value).append(DFUQFilterSeparator);
  2996. filterBuf.append(valueHigh).append(DFUQFilterSeparator);
  2997. }
  2998. void CWsDfuEx::setFileTypeFilter(const char* fileType, StringBuffer& filterBuf)
  2999. {
  3000. DFUQFileTypeFilter fileTypeFilter = DFUQFFTall;
  3001. if (!fileType || !*fileType)
  3002. {
  3003. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFFileType).append(DFUQFilterSeparator).append(fileTypeFilter).append(DFUQFilterSeparator);
  3004. return;
  3005. }
  3006. bool notInSuperfile = false;
  3007. if (strieq(fileType, "Superfiles Only"))
  3008. fileTypeFilter = DFUQFFTsuperfileonly;
  3009. else if (strieq(fileType, "Logical Files Only"))
  3010. fileTypeFilter = DFUQFFTnonsuperfileonly;
  3011. else if (strieq(fileType, "Not in Superfiles"))
  3012. notInSuperfile = true;
  3013. else
  3014. fileTypeFilter = DFUQFFTall;
  3015. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFFileType).append(DFUQFilterSeparator).append(fileTypeFilter).append(DFUQFilterSeparator);
  3016. if (notInSuperfile)
  3017. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFsuperowner), DFUQFThasProp, "0", filterBuf);
  3018. }
  3019. void CWsDfuEx::setFileNameFilter(const char* fname, const char* prefix, StringBuffer &filterBuf)
  3020. {
  3021. StringBuffer fileNameFilter;
  3022. if(fname && *fname)
  3023. fileNameFilter.append(fname);//ex. *part_of_file_name*
  3024. else
  3025. {
  3026. if(prefix && *prefix)
  3027. {
  3028. fileNameFilter.append(prefix);
  3029. fileNameFilter.append("::");
  3030. }
  3031. fileNameFilter.append("*");
  3032. }
  3033. fileNameFilter.toLowerCase();
  3034. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFFileNameWithPrefix).append(DFUQFilterSeparator).append(fileNameFilter.str()).append(DFUQFilterSeparator);
  3035. }
  3036. void CWsDfuEx::setFileIterateFilter(unsigned maxFiles, StringBuffer &filterBuf)
  3037. {
  3038. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFMaxFiles).append(DFUQFilterSeparator)
  3039. .append(maxFiles).append(DFUQFilterSeparator);
  3040. }
  3041. void CWsDfuEx::setDFUQueryFilters(IEspDFUQueryRequest& req, StringBuffer& filterBuf)
  3042. {
  3043. setFileNameFilter(req.getLogicalName(), req.getPrefix(), filterBuf);
  3044. setFileTypeFilter(req.getFileType(), filterBuf);
  3045. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFattrowner), DFUQFTwildcardMatch, req.getOwner(), filterBuf);
  3046. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFkind), DFUQFTwildcardMatch, req.getContentType(), filterBuf);
  3047. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFgroup), DFUQFTcontainString, req.getNodeGroup(), ",", filterBuf);
  3048. if (!req.getIncludeSuperOwner_isNull() && req.getIncludeSuperOwner())
  3049. filterBuf.append(DFUQFTincludeFileAttr).append(DFUQFilterSeparator).append(DFUQSFAOincludeSuperOwner).append(DFUQFilterSeparator);
  3050. __int64 sizeFrom = req.getFileSizeFrom();
  3051. __int64 sizeTo = req.getFileSizeTo();
  3052. if ((sizeFrom > 0) || (sizeTo > 0))
  3053. {
  3054. StringBuffer buf;
  3055. if (sizeFrom > 0)
  3056. buf.append(sizeFrom);
  3057. buf.append("|");
  3058. if (sizeTo > 0)
  3059. buf.append(sizeTo);
  3060. filterBuf.append(DFUQFTinteger64Range).append(DFUQFilterSeparator).append(getDFUQFilterFieldName(DFUQFFattrsize));
  3061. filterBuf.append(DFUQFilterSeparator).append(buf.str()).append(DFUQFilterSeparator);
  3062. }
  3063. const char* startDate = req.getStartDate();
  3064. const char* endDate = req.getEndDate();
  3065. if((startDate && *startDate) || (endDate && *endDate))
  3066. {
  3067. StringBuffer buf;
  3068. if(startDate && *startDate)
  3069. {
  3070. StringBuffer wuFrom;
  3071. CDateTime wuTime;
  3072. wuTime.setString(startDate,NULL);
  3073. buf.append(wuTime.getString(wuFrom).str());
  3074. }
  3075. buf.append("|");
  3076. if(endDate && *endDate)
  3077. {
  3078. StringBuffer wuTo;
  3079. CDateTime wuTime;
  3080. wuTime.setString(endDate,NULL);
  3081. buf.append(wuTime.getString(wuTo).str());
  3082. }
  3083. filterBuf.append(DFUQFTstringRange).append(DFUQFilterSeparator).append(getDFUQFilterFieldName(DFUQFFtimemodified));
  3084. filterBuf.append(DFUQFilterSeparator).append(buf.str()).append(DFUQFilterSeparator);
  3085. }
  3086. }
  3087. void CWsDfuEx::setDFUQuerySortOrder(IEspDFUQueryRequest& req, StringBuffer& sortBy, bool& descending, DFUQResultField* sortOrder)
  3088. {
  3089. const char* sortByReq = req.getSortby();
  3090. if (!sortByReq || !*sortByReq)
  3091. return;
  3092. sortBy.set(sortByReq);
  3093. if (req.getDescending())
  3094. descending = req.getDescending();
  3095. const char* sortByPtr = sortBy.str();
  3096. if (strieq(sortByPtr, "FileSize"))
  3097. sortOrder[0] = (DFUQResultField) (DFUQRFsize | DFUQRFnumeric);
  3098. else if (strieq(sortByPtr, "IsCompressed"))
  3099. sortOrder[0] = (DFUQResultField) (DFUQRFiscompressed | DFUQRFnumeric);
  3100. else if (strieq(sortByPtr, "CompressedSize"))
  3101. sortOrder[0] = (DFUQResultField) (DFUQRFcompressedsize | DFUQRFnumeric);
  3102. else if (strieq(sortByPtr, "Parts"))
  3103. sortOrder[0] = (DFUQResultField) (DFUQRFnumparts | DFUQRFnumeric);
  3104. else if (strieq(sortByPtr, "Records"))
  3105. sortOrder[0] = (DFUQResultField) (DFUQRFrecordcount | DFUQRFnumeric);
  3106. else if (strieq(sortByPtr, "Owner"))
  3107. sortOrder[0] = DFUQRFowner;
  3108. else if (strieq(sortByPtr, "NodeGroup"))
  3109. sortOrder[0] = DFUQRFnodegroup;
  3110. else if (strieq(sortByPtr, "Modified"))
  3111. sortOrder[0] = DFUQRFtimemodified;
  3112. else if (strieq(sortByPtr, "ContentType"))
  3113. sortOrder[0] = DFUQRFkind;
  3114. else
  3115. sortOrder[0] = DFUQRFname;
  3116. sortOrder[0] = (DFUQResultField) (sortOrder[0] | DFUQRFnocase);
  3117. if (descending)
  3118. sortOrder[0] = (DFUQResultField) (sortOrder[0] | DFUQRFreverse);
  3119. return;
  3120. }
  3121. const char* CWsDfuEx::getPrefixFromLogicalName(const char* logicalName, StringBuffer& prefix)
  3122. {
  3123. if (!logicalName || !*logicalName)
  3124. return NULL;
  3125. const char *c=strstr(logicalName, "::");
  3126. if (c)
  3127. prefix.append(c-logicalName, logicalName);
  3128. else
  3129. prefix.append(logicalName);
  3130. return prefix.str();
  3131. }
  3132. bool CWsDfuEx::addToLogicalFileList(IPropertyTree& file, const char* nodeGroup, double version, IArrayOf<IEspDFULogicalFile>& logicalFiles)
  3133. {
  3134. const char* logicalName = file.queryProp(getDFUQResultFieldName(DFUQRFname));
  3135. if (!logicalName || !*logicalName)
  3136. return false;
  3137. try
  3138. {
  3139. Owned<IEspDFULogicalFile> lFile = createDFULogicalFile("","");
  3140. lFile->setName(logicalName);
  3141. lFile->setOwner(file.queryProp(getDFUQResultFieldName(DFUQRFowner)));
  3142. StringBuffer buf(file.queryProp(getDFUQResultFieldName(DFUQRFtimemodified)));
  3143. lFile->setModified(buf.replace('T', ' ').str());
  3144. lFile->setPrefix(getPrefixFromLogicalName(logicalName, buf.clear()));
  3145. lFile->setDescription(file.queryProp(getDFUQResultFieldName(DFUQRFdescription)));
  3146. if (!nodeGroup || !*nodeGroup)
  3147. nodeGroup = file.queryProp(getDFUQResultFieldName(DFUQRFnodegroup));
  3148. if (nodeGroup && *nodeGroup)
  3149. {
  3150. if (version < 1.26)
  3151. lFile->setClusterName(nodeGroup);
  3152. else
  3153. lFile->setNodeGroup(nodeGroup);
  3154. }
  3155. int numSubFiles = file.hasProp(getDFUQResultFieldName(DFUQRFnumsubfiles));
  3156. if(numSubFiles)
  3157. lFile->setIsSuperfile(true);
  3158. else
  3159. {
  3160. lFile->setIsSuperfile(false);
  3161. lFile->setDirectory(file.queryProp(getDFUQResultFieldName(DFUQRFdirectory)));
  3162. lFile->setParts(file.queryProp(getDFUQResultFieldName(DFUQRFnumparts)));
  3163. }
  3164. lFile->setBrowseData(numSubFiles > 1 ? false : true); ////Bug 41379 - ViewKeyFile Cannot handle superfile with multiple subfiles
  3165. if (version >= 1.30)
  3166. {
  3167. bool persistent = file.getPropBool(getDFUQResultFieldName(DFUQRFpersistent), false);
  3168. if (persistent)
  3169. lFile->setPersistent(true);
  3170. if (file.hasProp(getDFUQResultFieldName(DFUQRFsuperowners)))
  3171. lFile->setSuperOwners(file.queryProp(getDFUQResultFieldName(DFUQRFsuperowners)));
  3172. if (file.hasProp(getDFUQResultFieldName(DFUQRFprotect)))
  3173. lFile->setIsProtected(true);
  3174. }
  3175. __int64 size = file.getPropInt64(getDFUQResultFieldName(DFUQRForigsize),0);
  3176. if (size > 0)
  3177. {
  3178. lFile->setIntSize(size);
  3179. lFile->setTotalsize((buf.clear()<<comma(size)).str());
  3180. }
  3181. __int64 records = file.getPropInt64(getDFUQResultFieldName(DFUQRFrecordcount),0);
  3182. if (!records)
  3183. records = file.getPropInt64(getDFUQResultFieldName(DFUQRForigrecordcount),0);
  3184. if (!records)
  3185. {
  3186. __int64 recordSize=file.getPropInt64(getDFUQResultFieldName(DFUQRFrecordsize),0);
  3187. if(recordSize > 0)
  3188. records = size/recordSize;
  3189. }
  3190. if (records > 0)
  3191. {
  3192. lFile->setIntRecordCount(records);
  3193. lFile->setRecordCount((buf.clear()<<comma(records)).str());
  3194. }
  3195. bool isKeyFile = false;
  3196. if (version > 1.13)
  3197. {
  3198. const char * kind = file.queryProp(getDFUQResultFieldName(DFUQRFkind));
  3199. if (kind && *kind)
  3200. {
  3201. if (strieq(kind, "key"))
  3202. isKeyFile = true;
  3203. if (version >= 1.24)
  3204. lFile->setContentType(kind);
  3205. else
  3206. lFile->setIsKeyFile(isKeyFile);
  3207. }
  3208. }
  3209. bool isFileCompressed = file.getPropBool(getDFUQResultFieldName(DFUQRFiscompressed));
  3210. if (isFileCompressed)
  3211. {
  3212. if (version >= 1.22)
  3213. {
  3214. if (file.hasProp(getDFUQResultFieldName(DFUQRFcompressedsize)))
  3215. lFile->setCompressedFileSize(file.getPropInt64(getDFUQResultFieldName(DFUQRFcompressedsize)));
  3216. else if (isKeyFile)
  3217. lFile->setCompressedFileSize(size);
  3218. }
  3219. }
  3220. if (version < 1.22)
  3221. lFile->setIsZipfile(isFileCompressed);
  3222. else
  3223. lFile->setIsCompressed(isFileCompressed);
  3224. logicalFiles.append(*lFile.getClear());
  3225. }
  3226. catch(IException* e)
  3227. {
  3228. VStringBuffer msg("Failed to retrieve data for logical file %s: ", logicalName);
  3229. int code = e->errorCode();
  3230. e->errorMessage(msg);
  3231. e->Release();
  3232. throw MakeStringException(code, "%s", msg.str());
  3233. }
  3234. return true;
  3235. }
  3236. void CWsDfuEx::setDFUQueryResponse(IEspContext &context, unsigned totalFiles, StringBuffer& sortBy, bool descending, unsigned pageStart, unsigned pageSize,
  3237. IEspDFUQueryRequest& req, IEspDFUQueryResponse& resp)
  3238. {
  3239. //for legacy
  3240. double version = context.getClientVersion();
  3241. unsigned pageEnd = pageStart + pageSize;
  3242. if (pageEnd > totalFiles)
  3243. pageEnd = totalFiles;
  3244. resp.setNumFiles(totalFiles);
  3245. resp.setPageSize(pageSize);
  3246. resp.setPageStartFrom(pageStart+1);
  3247. resp.setPageEndAt(pageEnd);
  3248. if (pageStart > pageSize)
  3249. resp.setPrevPageFrom(pageStart - pageSize + 1);
  3250. else if(pageStart > 0)
  3251. resp.setPrevPageFrom(1);
  3252. if(pageEnd < totalFiles)
  3253. {
  3254. resp.setNextPageFrom(pageEnd+1);
  3255. resp.setLastPageFrom((int)(pageSize * floor((double) ((totalFiles-1) / pageSize)) + 1));
  3256. }
  3257. StringBuffer queryReq;
  3258. if (req.getNodeGroup() && *req.getNodeGroup())
  3259. {
  3260. if (version < 1.26)
  3261. resp.setClusterName(req.getNodeGroup());
  3262. else
  3263. resp.setNodeGroup(req.getNodeGroup());
  3264. addToQueryString(queryReq, "NodeGroup", req.getNodeGroup());
  3265. }
  3266. if (req.getOwner() && *req.getOwner())
  3267. {
  3268. resp.setOwner(req.getOwner());
  3269. addToQueryString(queryReq, "Owner", req.getOwner());
  3270. }
  3271. if (req.getPrefix() && *req.getPrefix())
  3272. {
  3273. resp.setPrefix(req.getPrefix());
  3274. addToQueryString(queryReq, "Prefix", req.getPrefix());
  3275. }
  3276. if (req.getLogicalName() && *req.getLogicalName())
  3277. {
  3278. resp.setLogicalName(req.getLogicalName());
  3279. addToQueryString(queryReq, "LogicalName", req.getLogicalName());
  3280. }
  3281. if (req.getStartDate() && *req.getStartDate())
  3282. {
  3283. resp.setStartDate(req.getStartDate());
  3284. addToQueryString(queryReq, "StartDate", req.getStartDate());
  3285. }
  3286. if (req.getEndDate() && *req.getEndDate())
  3287. {
  3288. resp.setEndDate(req.getEndDate());
  3289. addToQueryString(queryReq, "EndDate", req.getEndDate());
  3290. }
  3291. if (req.getFileType() && *req.getFileType())
  3292. {
  3293. resp.setFileType(req.getFileType());
  3294. addToQueryString(queryReq, "FileType", req.getFileType());
  3295. }
  3296. if (req.getFileSizeFrom())
  3297. {
  3298. resp.setFileSizeFrom(req.getFileSizeFrom());
  3299. addToQueryStringFromInt(queryReq, "FileSizeFrom", req.getFileSizeFrom());
  3300. }
  3301. if (req.getFileSizeTo())
  3302. {
  3303. resp.setFileSizeTo(req.getFileSizeTo());
  3304. addToQueryStringFromInt(queryReq, "FileSizeTo", req.getFileSizeTo());
  3305. }
  3306. StringBuffer queryReqNoPageSize = queryReq;
  3307. addToQueryStringFromInt(queryReq, "PageSize", pageSize);
  3308. resp.setFilters(queryReq.str());
  3309. if (sortBy.length())
  3310. {
  3311. resp.setSortby(sortBy.str());
  3312. resp.setDescending(descending);
  3313. addToQueryString(queryReq, "Sortby", sortBy.str());
  3314. addToQueryString(queryReqNoPageSize, "Sortby", sortBy.str());
  3315. if (descending)
  3316. {
  3317. addToQueryString(queryReq, "Descending", "1");
  3318. addToQueryString(queryReqNoPageSize, "Descending", "1");
  3319. }
  3320. }
  3321. resp.setBasicQuery(queryReqNoPageSize.str());
  3322. resp.setParametersForPaging(queryReq.str());
  3323. return;
  3324. }
  3325. bool CWsDfuEx::doLogicalFileSearch(IEspContext &context, IUserDescriptor* udesc, IEspDFUQueryRequest & req, IEspDFUQueryResponse & resp)
  3326. {
  3327. double version = context.getClientVersion();
  3328. if (req.getOneLevelDirFileReturn())
  3329. {
  3330. int numDirs = 0;
  3331. int numFiles = 0;
  3332. IArrayOf<IEspDFULogicalFile> logicalFiles;
  3333. getLogicalFileAndDirectory(context, udesc, req.getLogicalName(), !req.getIncludeSuperOwner_isNull() && req.getIncludeSuperOwner(), logicalFiles, numFiles, numDirs);
  3334. return true;
  3335. }
  3336. if (queryDaliServerVersion().compare("3.11") < 0)
  3337. {//Dali server does not support Filtered File Query. Use legacy code.
  3338. PROGLOG("DFUQuery: getAPageOfSortedLogicalFile");
  3339. getAPageOfSortedLogicalFile(context, udesc, req, resp);
  3340. return true;
  3341. }
  3342. StringBuffer filterBuf;
  3343. setDFUQueryFilters(req, filterBuf);
  3344. //Now, set filters which are used to filter query result received from dali server.
  3345. unsigned short localFilterCount = 0;
  3346. DFUQResultField localFilters[8];
  3347. MemoryBuffer localFilterBuf;
  3348. addDFUQueryFilter(localFilters, localFilterCount, localFilterBuf, req.getNodeGroup(), DFUQRFnodegroup);
  3349. localFilters[localFilterCount] = DFUQRFterm;
  3350. StringBuffer sortBy;
  3351. bool descending = false;
  3352. DFUQResultField sortOrder[2] = {DFUQRFname, DFUQRFterm};
  3353. setDFUQuerySortOrder(req, sortBy, descending, sortOrder);
  3354. unsigned pageStart = 0;
  3355. if (req.getPageStartFrom() > 0)
  3356. pageStart = req.getPageStartFrom() - 1;
  3357. unsigned pageSize = req.getPageSize();
  3358. if (pageSize < 1)
  3359. pageSize = 100;
  3360. const int firstN = req.getFirstN();
  3361. if (firstN > 0)
  3362. {
  3363. pageStart = 0;
  3364. pageSize = firstN;
  3365. }
  3366. unsigned maxFiles = 0;
  3367. if(!req.getMaxNumberOfFiles_isNull())
  3368. maxFiles = req.getMaxNumberOfFiles();
  3369. if (maxFiles == 0)
  3370. maxFiles = ITERATE_FILTEREDFILES_LIMIT;
  3371. if (maxFiles != ITERATE_FILTEREDFILES_LIMIT)
  3372. setFileIterateFilter(maxFiles, filterBuf);
  3373. __int64 cacheHint = 0;
  3374. if (!req.getCacheHint_isNull())
  3375. cacheHint = req.getCacheHint();
  3376. bool allMatchingFilesReceived = true;
  3377. unsigned totalFiles = 0;
  3378. PROGLOG("DFUQuery: getLogicalFilesSorted");
  3379. Owned<IDFAttributesIterator> it = queryDistributedFileDirectory().getLogicalFilesSorted(udesc, sortOrder, filterBuf.str(),
  3380. localFilters, localFilterBuf.bufferBase(), pageStart, pageSize, &cacheHint, &totalFiles, &allMatchingFilesReceived);
  3381. if(!it)
  3382. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get information from file system.");
  3383. PROGLOG("DFUQuery: getLogicalFilesSorted done");
  3384. IArrayOf<IEspDFULogicalFile> logicalFiles;
  3385. ForEach(*it)
  3386. addToLogicalFileList(it->query(), NULL, version, logicalFiles);
  3387. if (!allMatchingFilesReceived)
  3388. {
  3389. VStringBuffer warning("The returned results (%d files) represent a subset of the total number of matches. Using a correct filter may reduce the number of matches.",
  3390. maxFiles);
  3391. resp.setWarning(warning.str());
  3392. resp.setIsSubsetOfFiles(!allMatchingFilesReceived);
  3393. }
  3394. resp.setCacheHint(cacheHint);
  3395. resp.setDFULogicalFiles(logicalFiles);
  3396. setDFUQueryResponse(context, totalFiles, sortBy, descending, pageStart, pageSize, req, resp); //This call may be removed after 5.0
  3397. return true;
  3398. }
  3399. bool CWsDfuEx::onSuperfileList(IEspContext &context, IEspSuperfileListRequest &req, IEspSuperfileListResponse &resp)
  3400. {
  3401. try
  3402. {
  3403. const char* superfile = req.getSuperfile();
  3404. if (!superfile || !*superfile)
  3405. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Superfile name required");
  3406. PROGLOG("SuperfileList: %s", superfile);
  3407. StringBuffer username;
  3408. context.getUserID(username);
  3409. Owned<IUserDescriptor> userdesc;
  3410. if(username.length() > 0)
  3411. {
  3412. userdesc.setown(createUserDescriptor());
  3413. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3414. }
  3415. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3416. StringArray farray;
  3417. StringAttrArray subfiles;
  3418. dfuhelper->listSubFiles(req.getSuperfile(), subfiles, userdesc.get());
  3419. for(unsigned i = 0; i < subfiles.length(); i++)
  3420. {
  3421. StringAttrItem& subfile = subfiles.item(i);
  3422. farray.append(subfile.text);
  3423. }
  3424. if(farray.length() > 0)
  3425. resp.setSubfiles(farray);
  3426. resp.setSuperfile(req.getSuperfile());
  3427. }
  3428. catch(IException* e)
  3429. {
  3430. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3431. }
  3432. return true;
  3433. }
  3434. bool CWsDfuEx::onSuperfileAction(IEspContext &context, IEspSuperfileActionRequest &req, IEspSuperfileActionResponse &resp)
  3435. {
  3436. try
  3437. {
  3438. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Write, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::SuperfileAction: Permission denied.");
  3439. const char* action = req.getAction();
  3440. const char* superfile = req.getSuperfile();
  3441. superfileAction(context, action, superfile, req.getSubfiles(), req.getBefore(), true, true, req.getDelete(), req.getRemoveSuperfile());
  3442. resp.setRetcode(0);
  3443. if (superfile && *superfile && action && strieq(action, "remove"))
  3444. {
  3445. Owned<IUserDescriptor> udesc;
  3446. udesc.setown(createUserDescriptor());
  3447. udesc->set(context.queryUserId(), context.queryPassword(), context.querySignature());
  3448. Owned<IDistributedSuperFile> fp = queryDistributedFileDirectory().lookupSuperFile(superfile,udesc);
  3449. if (!fp)
  3450. resp.setRetcode(-1); //Superfile has been removed.
  3451. }
  3452. resp.setSuperfile(req.getSuperfile());
  3453. }
  3454. catch(IException* e)
  3455. {
  3456. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3457. }
  3458. return true;
  3459. }
  3460. bool CWsDfuEx::onSavexml(IEspContext &context, IEspSavexmlRequest &req, IEspSavexmlResponse &resp)
  3461. {
  3462. try
  3463. {
  3464. StringBuffer username;
  3465. context.getUserID(username);
  3466. Owned<IUserDescriptor> userdesc;
  3467. if(username.length() > 0)
  3468. {
  3469. userdesc.setown(createUserDescriptor());
  3470. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3471. }
  3472. if (!req.getName() || !*req.getName())
  3473. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Name required");
  3474. PROGLOG("getFileXML: %s", req.getName());
  3475. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3476. StringBuffer out;
  3477. dfuhelper->getFileXML(req.getName(), out, userdesc.get());
  3478. MemoryBuffer xmlmap;
  3479. int len = out.length();
  3480. xmlmap.setBuffer(len, out.detach(), true);
  3481. resp.setXmlmap(xmlmap);
  3482. }
  3483. catch(IException* e)
  3484. {
  3485. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3486. }
  3487. return true;
  3488. }
  3489. bool CWsDfuEx::onAdd(IEspContext &context, IEspAddRequest &req, IEspAddResponse &resp)
  3490. {
  3491. try
  3492. {
  3493. StringBuffer username;
  3494. context.getUserID(username);
  3495. Owned<IUserDescriptor> userdesc;
  3496. if(username.length() > 0)
  3497. {
  3498. userdesc.setown(createUserDescriptor());
  3499. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3500. }
  3501. if (!req.getDstname() || !*req.getDstname())
  3502. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Dstname required.");
  3503. PROGLOG("addFileXML: %s", req.getDstname());
  3504. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3505. StringBuffer xmlstr(req.getXmlmap().length(),(const char*)req.getXmlmap().bufferBase());
  3506. dfuhelper->addFileXML(req.getDstname(), xmlstr, userdesc.get());
  3507. }
  3508. catch(IException* e)
  3509. {
  3510. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3511. }
  3512. return true;
  3513. }
  3514. bool CWsDfuEx::onAddRemote(IEspContext &context, IEspAddRemoteRequest &req, IEspAddRemoteResponse &resp)
  3515. {
  3516. try
  3517. {
  3518. StringBuffer username;
  3519. context.getUserID(username);
  3520. Owned<IUserDescriptor> userdesc;
  3521. if(username.length() > 0)
  3522. {
  3523. userdesc.setown(createUserDescriptor());
  3524. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3525. }
  3526. const char* srcusername = req.getSrcusername();
  3527. Owned<IUserDescriptor> srcuserdesc;
  3528. if(srcusername && *srcusername)
  3529. {
  3530. srcuserdesc.setown(createUserDescriptor());
  3531. srcuserdesc->set(srcusername, req.getSrcpassword(), context.querySignature());
  3532. }
  3533. const char* srcname = req.getSrcname();
  3534. if(srcname == NULL || *srcname == '\0')
  3535. throw MakeStringException(ECLWATCH_INVALID_INPUT, "srcname can't be empty.");
  3536. const char* srcdali = req.getSrcdali();
  3537. if(srcdali == NULL || *srcdali == '\0')
  3538. throw MakeStringException(ECLWATCH_INVALID_INPUT, "srcdali can't be empty.");
  3539. const char* dstname = req.getDstname();
  3540. if(dstname == NULL || *dstname == '\0')
  3541. throw MakeStringException(ECLWATCH_INVALID_INPUT, "dstname can't be empty.");
  3542. PROGLOG("addFileRemote: Srcdali %s, Srcname %s, Dstname %s", srcdali, srcname, dstname);
  3543. SocketEndpoint ep(srcdali);
  3544. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3545. dfuhelper->addFileRemote(dstname, ep, srcname, srcuserdesc.get(), userdesc.get());
  3546. }
  3547. catch(IException* e)
  3548. {
  3549. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3550. }
  3551. return true;
  3552. }
  3553. const int INTEGELSIZE = 20;
  3554. const int REALSIZE = 32;
  3555. const int STRINGSIZE = 128;
  3556. bool CWsDfuEx::onDFUGetDataColumns(IEspContext &context, IEspDFUGetDataColumnsRequest &req, IEspDFUGetDataColumnsResponse &resp)
  3557. {
  3558. try
  3559. {
  3560. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUGetDataColumns: Permission denied.");
  3561. StringBuffer logicalNameStr;
  3562. char* logicalName0 = (char*) req.getOpenLogicalName();
  3563. if (logicalName0 && *logicalName0)
  3564. {
  3565. logicalNameStr.append(logicalName0);
  3566. logicalNameStr.trim();
  3567. }
  3568. if (logicalNameStr.length() > 0)
  3569. {
  3570. PROGLOG("DFUGetDataColumns: %s", logicalNameStr.str());
  3571. __int64 startIndex = req.getStartIndex();
  3572. __int64 endIndex = req.getEndIndex();
  3573. if (startIndex < 1)
  3574. startIndex = 1;
  3575. if (endIndex < 1)
  3576. endIndex = 100;
  3577. StringArray filterByNames, filterByValues;
  3578. double version = context.getClientVersion();
  3579. if (version > 1.04)
  3580. {
  3581. const char* filterBy = req.getFilterBy();
  3582. if (filterBy && *filterBy)
  3583. {
  3584. parseTwoStringArrays(filterBy, filterByNames, filterByValues);
  3585. }
  3586. const char* showColumns = req.getShowColumns();
  3587. if (showColumns && *showColumns)
  3588. {
  3589. resp.setShowColumns(showColumns);
  3590. }
  3591. }
  3592. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  3593. Owned<INewResultSet> result;
  3594. if (m_clusterName.length() > 0)
  3595. {
  3596. result.setown(resultSetFactory->createNewFileResultSet(logicalNameStr.str(), m_clusterName.str()));
  3597. }
  3598. else
  3599. {
  3600. result.setown(resultSetFactory->createNewFileResultSet(logicalNameStr.str(), NULL));
  3601. }
  3602. __int64 total=result->getNumRows();
  3603. {
  3604. IArrayOf<IEspDFUDataColumn> dataKeyedColumns[MAX_KEY_ROWS];
  3605. IArrayOf<IEspDFUDataColumn> dataNonKeyedColumns[MAX_KEY_ROWS];
  3606. const IResultSetMetaData & meta = result->getMetaData();
  3607. int columnCount = meta.getColumnCount();
  3608. int keyedColumnCount = meta.getNumKeyedColumns();
  3609. unsigned columnSize = 0;
  3610. int lineSizeCount = 0;
  3611. int lineCount = 0;
  3612. for (int i = 0; i < keyedColumnCount; i++)
  3613. {
  3614. Owned<IEspDFUDataColumn> item = createDFUDataColumn("","");
  3615. bool bNaturalColumn = true;
  3616. SCMStringBuffer columnLabel;
  3617. if (meta.hasSetTranslation(i))
  3618. {
  3619. meta.getNaturalColumnLabel(columnLabel, i);
  3620. }
  3621. if (columnLabel.length() < 1)
  3622. {
  3623. meta.getColumnLabel(columnLabel, i);
  3624. bNaturalColumn = false;
  3625. }
  3626. item->setColumnLabel(columnLabel.str());
  3627. if (version > 1.04 && filterByNames.length() > 0)
  3628. {
  3629. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  3630. {
  3631. const char* name = filterByNames.item(ii);
  3632. if (name && !stricmp(name, columnLabel.str()))
  3633. {
  3634. const char* value = filterByValues.item(ii);
  3635. if (value && *value)
  3636. {
  3637. item->setColumnValue(value);
  3638. break;
  3639. }
  3640. }
  3641. }
  3642. }
  3643. DisplayType columnType = meta.getColumnDisplayType(i);
  3644. if (bNaturalColumn)
  3645. {
  3646. item->setColumnType("Others");
  3647. item->setColumnSize(STRINGSIZE);
  3648. columnSize = STRINGSIZE;
  3649. item->setMaxSize(columnSize);
  3650. }
  3651. else if (columnType == TypeBoolean)
  3652. {
  3653. item->setColumnType("Boolean");
  3654. item->setMaxSize(1);
  3655. item->setColumnSize(strlen(columnLabel.str()));
  3656. columnSize = 2;
  3657. }
  3658. else
  3659. {
  3660. if (columnType == TypeInteger || columnType == TypeUnsignedInteger)
  3661. {
  3662. item->setColumnType("Integer");
  3663. item->setMaxSize(INTEGELSIZE);
  3664. columnSize = INTEGELSIZE;
  3665. if (strlen(columnLabel.str()) > columnSize)
  3666. columnSize = strlen(columnLabel.str());
  3667. item->setColumnSize(columnSize);
  3668. }
  3669. else if (columnType == TypeReal)
  3670. {
  3671. item->setColumnType("Real");
  3672. item->setMaxSize(REALSIZE);
  3673. columnSize = REALSIZE;
  3674. if (strlen(columnLabel.str()) > columnSize)
  3675. columnSize = strlen(columnLabel.str());
  3676. item->setColumnSize(columnSize);
  3677. }
  3678. else if (columnType == TypeString)
  3679. {
  3680. columnSize = meta.getColumnRawSize(i);
  3681. columnSize = rtlQStrLength(columnSize);
  3682. if (columnSize < 1)
  3683. columnSize = STRINGSIZE;
  3684. else if (columnSize > STRINGSIZE)
  3685. columnSize = STRINGSIZE;
  3686. item->setColumnType("String");
  3687. item->setMaxSize(columnSize);
  3688. if (strlen(columnLabel.str()) > columnSize)
  3689. columnSize = strlen(columnLabel.str());
  3690. item->setColumnSize(columnSize);
  3691. }
  3692. else if (columnType == TypeUnicode)
  3693. {
  3694. item->setColumnType("Others");
  3695. columnSize = (int) (meta.getColumnRawSize(i) * 0.5);
  3696. if (columnSize > STRINGSIZE)
  3697. columnSize = STRINGSIZE;
  3698. item->setColumnSize(columnSize);
  3699. item->setMaxSize(columnSize);
  3700. }
  3701. else
  3702. {
  3703. item->setColumnType("Others");
  3704. columnSize = STRINGSIZE;
  3705. item->setColumnSize(columnSize);
  3706. item->setMaxSize(columnSize);
  3707. }
  3708. }
  3709. columnSize += 7;
  3710. if ((lineSizeCount == 0) && (columnSize > STRINGSIZE)) //One field is big enough to use one line
  3711. {
  3712. if (lineCount >= MAX_KEY_ROWS)
  3713. break;
  3714. dataKeyedColumns[lineCount].append(*item.getLink());
  3715. lineCount++;
  3716. }
  3717. else
  3718. {
  3719. if (lineSizeCount + columnSize < STRINGSIZE)
  3720. {
  3721. lineSizeCount += columnSize;
  3722. }
  3723. else //too big in this line...so, switch to another line
  3724. {
  3725. lineCount++;
  3726. lineSizeCount = columnSize;
  3727. }
  3728. if (lineCount >= MAX_KEY_ROWS)
  3729. break;
  3730. dataKeyedColumns[lineCount].append(*item.getLink());
  3731. }
  3732. }
  3733. columnSize = 0;
  3734. lineSizeCount = 0;
  3735. lineCount = 0;
  3736. for (int ii = keyedColumnCount; ii < columnCount; ii++)
  3737. {
  3738. Owned<IEspDFUDataColumn> item = createDFUDataColumn("","");
  3739. bool bNaturalColumn = true;
  3740. SCMStringBuffer columnLabel;
  3741. if (meta.hasSetTranslation(ii))
  3742. {
  3743. meta.getNaturalColumnLabel(columnLabel, ii);
  3744. }
  3745. if (columnLabel.length() < 1)
  3746. {
  3747. meta.getColumnLabel(columnLabel, ii);
  3748. bNaturalColumn = false;
  3749. }
  3750. item->setColumnLabel(columnLabel.str());
  3751. if (version > 1.04 && filterByNames.length() > 0)
  3752. {
  3753. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  3754. {
  3755. const char* name = filterByNames.item(ii);
  3756. if (name && !stricmp(name, columnLabel.str()))
  3757. {
  3758. const char* value = filterByValues.item(ii);
  3759. if (value && *value)
  3760. {
  3761. item->setColumnValue(value);
  3762. break;
  3763. }
  3764. }
  3765. }
  3766. }
  3767. DisplayType columnType = meta.getColumnDisplayType(ii);
  3768. if (bNaturalColumn)
  3769. {
  3770. item->setColumnType("Others");
  3771. item->setColumnSize(STRINGSIZE);
  3772. columnSize = STRINGSIZE;
  3773. }
  3774. else if (columnType == TypeBoolean)
  3775. {
  3776. item->setColumnType("Boolean");
  3777. item->setMaxSize(1);
  3778. item->setColumnSize(strlen(columnLabel.str()));
  3779. columnSize = 2;
  3780. }
  3781. else
  3782. {
  3783. if (columnType == TypeInteger || columnType == TypeUnsignedInteger)
  3784. {
  3785. item->setColumnType("Integer");
  3786. item->setMaxSize(INTEGELSIZE);
  3787. columnSize = INTEGELSIZE;
  3788. if (strlen(columnLabel.str()) > columnSize)
  3789. columnSize = strlen(columnLabel.str());
  3790. item->setColumnSize(columnSize);
  3791. }
  3792. else if (columnType == TypeReal)
  3793. {
  3794. item->setColumnType("Real");
  3795. item->setMaxSize(REALSIZE);
  3796. columnSize = REALSIZE;
  3797. if (strlen(columnLabel.str()) > columnSize)
  3798. columnSize = strlen(columnLabel.str());
  3799. item->setColumnSize(columnSize);
  3800. }
  3801. else if (columnType == TypeString)
  3802. {
  3803. columnSize = meta.getColumnRawSize(ii);
  3804. columnSize = rtlQStrLength(columnSize);
  3805. if (columnSize < 1)
  3806. columnSize = STRINGSIZE;
  3807. else if (columnSize > STRINGSIZE)
  3808. columnSize = STRINGSIZE;
  3809. item->setColumnType("String");
  3810. item->setMaxSize(columnSize);
  3811. if (strlen(columnLabel.str()) > columnSize)
  3812. columnSize = strlen(columnLabel.str());
  3813. item->setColumnSize(columnSize);
  3814. }
  3815. else if (columnType == TypeUnicode)
  3816. {
  3817. item->setColumnType("Others");
  3818. columnSize = (int) (meta.getColumnRawSize(ii) * 0.5);
  3819. if (columnSize > STRINGSIZE)
  3820. columnSize = STRINGSIZE;
  3821. item->setColumnSize(columnSize);
  3822. item->setMaxSize(columnSize);
  3823. }
  3824. else
  3825. {
  3826. item->setColumnType("Others");
  3827. columnSize = STRINGSIZE;
  3828. item->setColumnSize(columnSize);
  3829. item->setMaxSize(columnSize);
  3830. }
  3831. }
  3832. columnSize += 7;
  3833. if ((lineSizeCount == 0) && (columnSize > STRINGSIZE))
  3834. {
  3835. if (lineCount >= MAX_KEY_ROWS)
  3836. break;
  3837. dataNonKeyedColumns[lineCount].append(*item.getLink());
  3838. lineCount++;
  3839. }
  3840. else
  3841. {
  3842. if (lineSizeCount + columnSize < STRINGSIZE)
  3843. {
  3844. lineSizeCount += columnSize;
  3845. }
  3846. else
  3847. {
  3848. lineCount++;
  3849. lineSizeCount = columnSize;
  3850. }
  3851. if (lineCount >= MAX_KEY_ROWS)
  3852. break;
  3853. dataNonKeyedColumns[lineCount].append(*item.getLink());
  3854. }
  3855. }
  3856. if (dataKeyedColumns[0].length() > 0)
  3857. resp.setDFUDataKeyedColumns1(dataKeyedColumns[0]);
  3858. if (dataKeyedColumns[1].length() > 0)
  3859. resp.setDFUDataKeyedColumns2(dataKeyedColumns[1]);
  3860. if (dataKeyedColumns[2].length() > 0)
  3861. resp.setDFUDataKeyedColumns3(dataKeyedColumns[2]);
  3862. if (dataKeyedColumns[3].length() > 0)
  3863. resp.setDFUDataKeyedColumns4(dataKeyedColumns[3]);
  3864. if (dataKeyedColumns[4].length() > 0)
  3865. resp.setDFUDataKeyedColumns5(dataKeyedColumns[4]);
  3866. if (dataKeyedColumns[5].length() > 0)
  3867. resp.setDFUDataKeyedColumns6(dataKeyedColumns[5]);
  3868. if (dataKeyedColumns[6].length() > 0)
  3869. resp.setDFUDataKeyedColumns7(dataKeyedColumns[6]);
  3870. if (dataKeyedColumns[7].length() > 0)
  3871. resp.setDFUDataKeyedColumns8(dataKeyedColumns[7]);
  3872. if (dataKeyedColumns[8].length() > 0)
  3873. resp.setDFUDataKeyedColumns9(dataKeyedColumns[8]);
  3874. if (dataKeyedColumns[9].length() > 0)
  3875. resp.setDFUDataKeyedColumns10(dataKeyedColumns[9]);
  3876. if (version > 1.14)
  3877. {
  3878. if (dataKeyedColumns[10].length() > 0)
  3879. resp.setDFUDataKeyedColumns11(dataKeyedColumns[10]);
  3880. if (dataKeyedColumns[11].length() > 0)
  3881. resp.setDFUDataKeyedColumns12(dataKeyedColumns[11]);
  3882. if (dataKeyedColumns[12].length() > 0)
  3883. resp.setDFUDataKeyedColumns13(dataKeyedColumns[12]);
  3884. if (dataKeyedColumns[13].length() > 0)
  3885. resp.setDFUDataKeyedColumns14(dataKeyedColumns[13]);
  3886. if (dataKeyedColumns[14].length() > 0)
  3887. resp.setDFUDataKeyedColumns15(dataKeyedColumns[14]);
  3888. if (dataKeyedColumns[15].length() > 0)
  3889. resp.setDFUDataKeyedColumns16(dataKeyedColumns[15]);
  3890. if (dataKeyedColumns[16].length() > 0)
  3891. resp.setDFUDataKeyedColumns17(dataKeyedColumns[16]);
  3892. if (dataKeyedColumns[17].length() > 0)
  3893. resp.setDFUDataKeyedColumns18(dataKeyedColumns[17]);
  3894. if (dataKeyedColumns[18].length() > 0)
  3895. resp.setDFUDataKeyedColumns19(dataKeyedColumns[18]);
  3896. if (dataKeyedColumns[19].length() > 0)
  3897. resp.setDFUDataKeyedColumns20(dataKeyedColumns[19]);
  3898. }
  3899. if (dataNonKeyedColumns[0].length() > 0)
  3900. resp.setDFUDataNonKeyedColumns1(dataNonKeyedColumns[0]);
  3901. if (dataNonKeyedColumns[1].length() > 0)
  3902. resp.setDFUDataNonKeyedColumns2(dataNonKeyedColumns[1]);
  3903. if (dataNonKeyedColumns[2].length() > 0)
  3904. resp.setDFUDataNonKeyedColumns3(dataNonKeyedColumns[2]);
  3905. if (dataNonKeyedColumns[3].length() > 0)
  3906. resp.setDFUDataNonKeyedColumns4(dataNonKeyedColumns[3]);
  3907. if (dataNonKeyedColumns[4].length() > 0)
  3908. resp.setDFUDataNonKeyedColumns5(dataNonKeyedColumns[4]);
  3909. if (dataNonKeyedColumns[5].length() > 0)
  3910. resp.setDFUDataNonKeyedColumns6(dataNonKeyedColumns[5]);
  3911. if (dataNonKeyedColumns[6].length() > 0)
  3912. resp.setDFUDataNonKeyedColumns7(dataNonKeyedColumns[6]);
  3913. if (dataNonKeyedColumns[7].length() > 0)
  3914. resp.setDFUDataNonKeyedColumns8(dataNonKeyedColumns[7]);
  3915. if (dataNonKeyedColumns[8].length() > 0)
  3916. resp.setDFUDataNonKeyedColumns9(dataNonKeyedColumns[8]);
  3917. if (dataNonKeyedColumns[9].length() > 0)
  3918. resp.setDFUDataNonKeyedColumns10(dataNonKeyedColumns[9]);
  3919. if (version > 1.14)
  3920. {
  3921. if (dataNonKeyedColumns[10].length() > 0)
  3922. resp.setDFUDataNonKeyedColumns11(dataNonKeyedColumns[10]);
  3923. if (dataNonKeyedColumns[11].length() > 0)
  3924. resp.setDFUDataNonKeyedColumns12(dataNonKeyedColumns[11]);
  3925. if (dataNonKeyedColumns[12].length() > 0)
  3926. resp.setDFUDataNonKeyedColumns13(dataNonKeyedColumns[12]);
  3927. if (dataNonKeyedColumns[13].length() > 0)
  3928. resp.setDFUDataNonKeyedColumns14(dataNonKeyedColumns[13]);
  3929. if (dataNonKeyedColumns[14].length() > 0)
  3930. resp.setDFUDataNonKeyedColumns15(dataNonKeyedColumns[14]);
  3931. if (dataNonKeyedColumns[15].length() > 0)
  3932. resp.setDFUDataNonKeyedColumns16(dataNonKeyedColumns[15]);
  3933. if (dataNonKeyedColumns[16].length() > 0)
  3934. resp.setDFUDataNonKeyedColumns17(dataNonKeyedColumns[16]);
  3935. if (dataNonKeyedColumns[17].length() > 0)
  3936. resp.setDFUDataNonKeyedColumns18(dataNonKeyedColumns[17]);
  3937. if (dataNonKeyedColumns[18].length() > 0)
  3938. resp.setDFUDataNonKeyedColumns19(dataNonKeyedColumns[18]);
  3939. if (dataNonKeyedColumns[19].length() > 0)
  3940. resp.setDFUDataNonKeyedColumns20(dataNonKeyedColumns[19]);
  3941. }
  3942. //resp.setColumnCount(columnCount);
  3943. resp.setRowCount(total);
  3944. }
  3945. resp.setLogicalName(logicalNameStr.str());
  3946. resp.setStartIndex(startIndex);
  3947. resp.setEndIndex(endIndex);
  3948. if (version > 1.11)
  3949. {
  3950. if (req.getCluster() && *req.getCluster())
  3951. {
  3952. resp.setCluster(req.getCluster());
  3953. }
  3954. if (req.getClusterType() && *req.getClusterType())
  3955. {
  3956. resp.setClusterType(req.getClusterType());
  3957. }
  3958. }
  3959. }
  3960. if (req.getChooseFile())
  3961. resp.setChooseFile(1);
  3962. else
  3963. resp.setChooseFile(0);
  3964. }
  3965. catch(IException* e)
  3966. {
  3967. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3968. }
  3969. return true;
  3970. }
  3971. bool CWsDfuEx::onDFUSearchData(IEspContext &context, IEspDFUSearchDataRequest &req, IEspDFUSearchDataResponse &resp)
  3972. {
  3973. try
  3974. {
  3975. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUSearchData: Permission denied.");
  3976. double version = context.getClientVersion();
  3977. resp.setCluster(req.getCluster());
  3978. resp.setClusterType(req.getClusterType());
  3979. resp.setFile(req.getFile());
  3980. resp.setKey(req.getKey());
  3981. const char* selectedKey = req.getSelectedKey();
  3982. if (strlen(selectedKey) > 0)
  3983. {
  3984. resp.setSelectedKey(req.getSelectedKey());
  3985. }
  3986. else
  3987. {
  3988. resp.setSelectedKey(req.getKey());
  3989. }
  3990. resp.setParentName(req.getParentName());
  3991. resp.setRoxieSelections(req.getRoxieSelections());
  3992. resp.setDisableUppercaseTranslation(req.getDisableUppercaseTranslation());
  3993. const char* openLogicalName = req.getOpenLogicalName();
  3994. if (strlen(openLogicalName) > 0)
  3995. {
  3996. PROGLOG("DFUSearchData: %s", openLogicalName);
  3997. Owned<IEspDFUGetDataColumnsRequest> DataColumnsRequest = createDFUGetDataColumnsRequest();
  3998. Owned<IEspDFUGetDataColumnsResponse> DataColumnsResponse = createDFUGetDataColumnsResponse();
  3999. DataColumnsRequest->setOpenLogicalName(req.getOpenLogicalName());
  4000. DataColumnsRequest->setFilterBy(req.getFilterBy());
  4001. DataColumnsRequest->setShowColumns(req.getShowColumns());
  4002. DataColumnsRequest->setChooseFile(req.getChooseFile());
  4003. DataColumnsRequest->setCluster(req.getCluster());
  4004. DataColumnsRequest->setClusterType(req.getClusterType());
  4005. try
  4006. {
  4007. onDFUGetDataColumns(context, *DataColumnsRequest, *DataColumnsResponse);
  4008. }
  4009. catch(IException* e)
  4010. {
  4011. if (version < 1.08)
  4012. throw e;
  4013. StringBuffer emsg;
  4014. e->errorMessage(emsg);
  4015. e->Release();
  4016. resp.setMsgToDisplay(emsg);
  4017. return true;
  4018. }
  4019. resp.setOpenLogicalName(req.getOpenLogicalName());
  4020. resp.setLogicalName(DataColumnsResponse->getLogicalName());
  4021. resp.setStartIndex(DataColumnsResponse->getStartIndex());
  4022. resp.setEndIndex(DataColumnsResponse->getEndIndex());
  4023. resp.setDFUDataKeyedColumns1(DataColumnsResponse->getDFUDataKeyedColumns1());
  4024. resp.setDFUDataKeyedColumns2(DataColumnsResponse->getDFUDataKeyedColumns2());
  4025. resp.setDFUDataKeyedColumns3(DataColumnsResponse->getDFUDataKeyedColumns3());
  4026. resp.setDFUDataKeyedColumns4(DataColumnsResponse->getDFUDataKeyedColumns4());
  4027. resp.setDFUDataKeyedColumns5(DataColumnsResponse->getDFUDataKeyedColumns5());
  4028. resp.setDFUDataKeyedColumns6(DataColumnsResponse->getDFUDataKeyedColumns6());
  4029. resp.setDFUDataKeyedColumns7(DataColumnsResponse->getDFUDataKeyedColumns7());
  4030. resp.setDFUDataKeyedColumns8(DataColumnsResponse->getDFUDataKeyedColumns8());
  4031. resp.setDFUDataKeyedColumns9(DataColumnsResponse->getDFUDataKeyedColumns9());
  4032. resp.setDFUDataKeyedColumns10(DataColumnsResponse->getDFUDataKeyedColumns10());
  4033. if (version > 1.14)
  4034. {
  4035. resp.setDFUDataKeyedColumns11(DataColumnsResponse->getDFUDataKeyedColumns11());
  4036. resp.setDFUDataKeyedColumns12(DataColumnsResponse->getDFUDataKeyedColumns12());
  4037. resp.setDFUDataKeyedColumns13(DataColumnsResponse->getDFUDataKeyedColumns13());
  4038. resp.setDFUDataKeyedColumns14(DataColumnsResponse->getDFUDataKeyedColumns14());
  4039. resp.setDFUDataKeyedColumns15(DataColumnsResponse->getDFUDataKeyedColumns15());
  4040. resp.setDFUDataKeyedColumns16(DataColumnsResponse->getDFUDataKeyedColumns16());
  4041. resp.setDFUDataKeyedColumns17(DataColumnsResponse->getDFUDataKeyedColumns17());
  4042. resp.setDFUDataKeyedColumns18(DataColumnsResponse->getDFUDataKeyedColumns18());
  4043. resp.setDFUDataKeyedColumns19(DataColumnsResponse->getDFUDataKeyedColumns19());
  4044. resp.setDFUDataKeyedColumns20(DataColumnsResponse->getDFUDataKeyedColumns20());
  4045. }
  4046. resp.setDFUDataNonKeyedColumns1(DataColumnsResponse->getDFUDataNonKeyedColumns1());
  4047. resp.setDFUDataNonKeyedColumns2(DataColumnsResponse->getDFUDataNonKeyedColumns2());
  4048. resp.setDFUDataNonKeyedColumns3(DataColumnsResponse->getDFUDataNonKeyedColumns3());
  4049. resp.setDFUDataNonKeyedColumns4(DataColumnsResponse->getDFUDataNonKeyedColumns4());
  4050. resp.setDFUDataNonKeyedColumns5(DataColumnsResponse->getDFUDataNonKeyedColumns5());
  4051. resp.setDFUDataNonKeyedColumns6(DataColumnsResponse->getDFUDataNonKeyedColumns6());
  4052. resp.setDFUDataNonKeyedColumns7(DataColumnsResponse->getDFUDataNonKeyedColumns7());
  4053. resp.setDFUDataNonKeyedColumns8(DataColumnsResponse->getDFUDataNonKeyedColumns8());
  4054. resp.setDFUDataNonKeyedColumns9(DataColumnsResponse->getDFUDataNonKeyedColumns9());
  4055. resp.setDFUDataNonKeyedColumns10(DataColumnsResponse->getDFUDataNonKeyedColumns10());
  4056. if (version > 1.14)
  4057. {
  4058. resp.setDFUDataNonKeyedColumns11(DataColumnsResponse->getDFUDataNonKeyedColumns11());
  4059. resp.setDFUDataNonKeyedColumns12(DataColumnsResponse->getDFUDataNonKeyedColumns12());
  4060. resp.setDFUDataNonKeyedColumns13(DataColumnsResponse->getDFUDataNonKeyedColumns13());
  4061. resp.setDFUDataNonKeyedColumns14(DataColumnsResponse->getDFUDataNonKeyedColumns14());
  4062. resp.setDFUDataNonKeyedColumns15(DataColumnsResponse->getDFUDataNonKeyedColumns15());
  4063. resp.setDFUDataNonKeyedColumns16(DataColumnsResponse->getDFUDataNonKeyedColumns16());
  4064. resp.setDFUDataNonKeyedColumns17(DataColumnsResponse->getDFUDataNonKeyedColumns17());
  4065. resp.setDFUDataNonKeyedColumns18(DataColumnsResponse->getDFUDataNonKeyedColumns18());
  4066. resp.setDFUDataNonKeyedColumns19(DataColumnsResponse->getDFUDataNonKeyedColumns19());
  4067. resp.setDFUDataNonKeyedColumns20(DataColumnsResponse->getDFUDataNonKeyedColumns20());
  4068. }
  4069. resp.setRowCount(DataColumnsResponse->getRowCount());
  4070. resp.setShowColumns(DataColumnsResponse->getShowColumns());
  4071. resp.setChooseFile(DataColumnsResponse->getChooseFile());
  4072. }
  4073. const char* logicalName = req.getLogicalName();
  4074. if (strlen(logicalName) == 0 && strlen(openLogicalName) > 0)
  4075. {
  4076. logicalName = openLogicalName;
  4077. }
  4078. if (strlen(logicalName) > 0)
  4079. {
  4080. Owned<IEspDFUBrowseDataRequest> browseDataRequest = createDFUBrowseDataRequest();
  4081. Owned<IEspDFUBrowseDataResponse> browseDataResponse = createDFUBrowseDataResponse();
  4082. browseDataRequest->setLogicalName(logicalName);
  4083. const char* parentName = req.getParentName();
  4084. if (parentName && *parentName)
  4085. browseDataRequest->setParentName(parentName);
  4086. browseDataRequest->setFilterBy(req.getFilterBy());
  4087. browseDataRequest->setShowColumns(req.getShowColumns());
  4088. browseDataRequest->setStartForGoback(req.getStartForGoback());
  4089. browseDataRequest->setCountForGoback(req.getCountForGoback());
  4090. browseDataRequest->setChooseFile(req.getChooseFile());
  4091. browseDataRequest->setStart(req.getStart());
  4092. browseDataRequest->setCount(req.getCount());
  4093. browseDataRequest->setSchemaOnly(req.getSchemaOnly());
  4094. browseDataRequest->setCluster(req.getCluster());
  4095. browseDataRequest->setClusterType(req.getClusterType());
  4096. browseDataRequest->setDisableUppercaseTranslation(req.getDisableUppercaseTranslation());
  4097. onDFUBrowseData(context, *browseDataRequest, *browseDataResponse);
  4098. resp.setName(browseDataResponse->getName());
  4099. resp.setLogicalName(browseDataResponse->getLogicalName());
  4100. resp.setFilterBy(browseDataResponse->getFilterBy());
  4101. resp.setFilterForGoBack(browseDataResponse->getFilterForGoBack());
  4102. resp.setColumnsHidden(browseDataResponse->getColumnsHidden());
  4103. resp.setColumnsHidden(browseDataResponse->getColumnsHidden());
  4104. resp.setColumnCount(browseDataResponse->getColumnCount());
  4105. resp.setStartForGoback(browseDataResponse->getStartForGoback());
  4106. resp.setCountForGoback(browseDataResponse->getCountForGoback());
  4107. resp.setChooseFile(browseDataResponse->getChooseFile());
  4108. resp.setStart(browseDataResponse->getStart());
  4109. resp.setCount(browseDataResponse->getCount());
  4110. resp.setPageSize(browseDataResponse->getPageSize());
  4111. resp.setTotal(browseDataResponse->getTotal());
  4112. resp.setResult(browseDataResponse->getResult());
  4113. resp.setMsgToDisplay(browseDataResponse->getMsgToDisplay());
  4114. resp.setSchemaOnly(browseDataResponse->getSchemaOnly());
  4115. resp.setAutoUppercaseTranslation(!m_disableUppercaseTranslation);
  4116. }
  4117. }
  4118. catch(IException* e)
  4119. {
  4120. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4121. }
  4122. return true;
  4123. }
  4124. static const char * const columnTypes[] = { "Boolean", "Integer", "Unsigned Integer", "Real", "String",
  4125. "Data", "Unicode", "Unknown", "BeginIfBlock", "EndIfBlock", "BeginRecord", "EndRecord", "Set", "Dataset", NULL };
  4126. bool CWsDfuEx::onDFUGetFileMetaData(IEspContext &context, IEspDFUGetFileMetaDataRequest & req, IEspDFUGetFileMetaDataResponse & resp)
  4127. {
  4128. class CDFUFileMetaDataReader
  4129. {
  4130. unsigned totalColumnCount;
  4131. unsigned keyedColumnCount;
  4132. StringBuffer XmlSchema, XmlXPathSchema;
  4133. IArrayOf<IEspDFUDataColumn> dataColumns;
  4134. const IResultSetMetaData& metaRoot;
  4135. bool readRootLevelColumns;
  4136. IEspContext &context;
  4137. bool readColumnLabel(const IResultSetMetaData* meta, unsigned columnID, IEspDFUDataColumn* out)
  4138. {
  4139. SCMStringBuffer columnLabel;
  4140. bool isNaturalColumn = true;
  4141. if (meta->hasSetTranslation(columnID))
  4142. meta->getNaturalColumnLabel(columnLabel, columnID);
  4143. if (columnLabel.length() < 1)
  4144. {
  4145. meta->getColumnLabel(columnLabel, columnID);
  4146. isNaturalColumn = false;
  4147. }
  4148. out->setColumnLabel(columnLabel.str());
  4149. out->setIsNaturalColumn(isNaturalColumn);
  4150. return isNaturalColumn;
  4151. }
  4152. void readColumn(const IResultSetMetaData* meta, unsigned& columnID, const bool isKeyed,
  4153. IArrayOf<IEspDFUDataColumn>& dataColumns)
  4154. {
  4155. double version = context.getClientVersion();
  4156. Owned<IEspDFUDataColumn> dataItem = createDFUDataColumn();
  4157. dataItem->setColumnID(columnID+1);
  4158. dataItem->setIsKeyedColumn(isKeyed);
  4159. SCMStringBuffer s;
  4160. dataItem->setColumnEclType(meta->getColumnEclType(s, columnID).str());
  4161. DisplayType columnType = meta->getColumnDisplayType(columnID);
  4162. if ((columnType == TypeUnicode) || columnType == TypeString)
  4163. dataItem->setColumnRawSize(meta->getColumnRawSize(columnID));
  4164. if (readColumnLabel(meta, columnID, dataItem))
  4165. dataItem->setColumnType("Others");
  4166. else if (columnType == TypeBeginRecord)
  4167. dataItem->setColumnType("Record");
  4168. else
  4169. dataItem->setColumnType(columnTypes[columnType]);
  4170. if ((version >= 1.31) && ((columnType == TypeSet) || (columnType == TypeDataset) || (columnType == TypeBeginRecord)))
  4171. checkAndReadNestedColumn(meta, columnID, columnType, dataItem);
  4172. dataColumns.append(*dataItem.getClear());
  4173. }
  4174. void readColumns(const IResultSetMetaData* meta, IArrayOf<IEspDFUDataColumn>& dataColumnArray)
  4175. {
  4176. if (!meta)
  4177. return;
  4178. if (readRootLevelColumns)
  4179. {
  4180. readRootLevelColumns = false;
  4181. totalColumnCount = (unsigned)meta->getColumnCount();
  4182. keyedColumnCount = meta->getNumKeyedColumns();
  4183. unsigned i = 0;
  4184. for (; i < keyedColumnCount; i++)
  4185. readColumn(meta, i, true, dataColumnArray);
  4186. for (i = keyedColumnCount; i < totalColumnCount; i++)
  4187. readColumn(meta, i, false, dataColumnArray);
  4188. }
  4189. else
  4190. {
  4191. unsigned columnCount = (unsigned)meta->getColumnCount();
  4192. for (unsigned i = 0; i < columnCount; i++)
  4193. readColumn(meta, i, false, dataColumnArray);
  4194. }
  4195. }
  4196. void checkAndReadNestedColumn(const IResultSetMetaData* meta, unsigned& columnID,
  4197. DisplayType columnType, IEspDFUDataColumn* dataItem)
  4198. {
  4199. IArrayOf<IEspDFUDataColumn> curDataColumnArray;
  4200. if (columnType == TypeBeginRecord)
  4201. {
  4202. columnID++;
  4203. do
  4204. {
  4205. readColumn(meta, columnID, false, curDataColumnArray);
  4206. } while (meta->getColumnDisplayType(++columnID) != TypeEndRecord);
  4207. }
  4208. else
  4209. readColumns(meta->getChildMeta(columnID), curDataColumnArray);
  4210. dataItem->setDataColumns(curDataColumnArray);
  4211. }
  4212. public:
  4213. CDFUFileMetaDataReader(IEspContext& _context, const IResultSetMetaData& _meta)
  4214. : context(_context), metaRoot(_meta), readRootLevelColumns(true)
  4215. {
  4216. readColumns(&metaRoot, dataColumns);
  4217. };
  4218. inline unsigned getTotalColumnCount() { return totalColumnCount; }
  4219. inline unsigned getKeyedColumnCount() { return keyedColumnCount; }
  4220. inline IArrayOf<IEspDFUDataColumn>& getDataColumns() { return dataColumns; }
  4221. inline StringBuffer& getXmlSchema(StringBuffer& s, const bool addHeader)
  4222. {
  4223. StringBufferAdaptor schema(s);
  4224. metaRoot.getXmlSchema(schema, addHeader);
  4225. return s;
  4226. }
  4227. inline StringBuffer& getXmlXPathSchema(StringBuffer& s, const bool addHeader)
  4228. {
  4229. StringBufferAdaptor XPathSchema(s);
  4230. metaRoot.getXmlXPathSchema(XPathSchema, addHeader);
  4231. return s;
  4232. }
  4233. };
  4234. try
  4235. {
  4236. StringBuffer fileNameStr = req.getLogicalFileName();
  4237. const char* fileName = fileNameStr.trim().str();
  4238. if (!fileName || !*fileName)
  4239. throw MakeStringException(ECLWATCH_INVALID_INPUT, "CWsDfuEx::onDFUGetFileMetaData: LogicalFileName not set");
  4240. const char* cluster = NULL;
  4241. StringBuffer clusterNameStr = req.getClusterName();
  4242. if (clusterNameStr.trim().length() > 0)
  4243. cluster = clusterNameStr.str();
  4244. PROGLOG("DFUGetFileMetaData: %s", fileName);
  4245. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  4246. Owned<INewResultSet> result = resultSetFactory->createNewFileResultSet(fileName, cluster);
  4247. if (!result)
  4248. throw MakeStringException(ECLWATCH_INVALID_INPUT, "CWsDfuEx::onDFUGetFileMetaData: Failed to access FileResultSet for %s.", fileName);
  4249. CDFUFileMetaDataReader dataReader(context, result->getMetaData());
  4250. resp.setTotalColumnCount(dataReader.getTotalColumnCount());
  4251. resp.setKeyedColumnCount(dataReader.getKeyedColumnCount());
  4252. resp.setDataColumns(dataReader.getDataColumns());
  4253. StringBuffer s, s1;
  4254. if (req.getIncludeXmlSchema())
  4255. resp.setXmlSchema(dataReader.getXmlSchema(s, req.getAddHeaderInXmlSchema()).str());
  4256. if (req.getIncludeXmlXPathSchema())
  4257. resp.setXmlXPathSchema(dataReader.getXmlXPathSchema(s1, req.getAddHeaderInXmlXPathSchema()).str());
  4258. resp.setTotalResultRows(result->getNumRows());
  4259. }
  4260. catch(IException* e)
  4261. {
  4262. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4263. }
  4264. return true;
  4265. }
  4266. bool CWsDfuEx::onDFUBrowseData(IEspContext &context, IEspDFUBrowseDataRequest &req, IEspDFUBrowseDataResponse &resp)
  4267. {
  4268. try
  4269. {
  4270. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUBrowseData: Permission denied.");
  4271. const char* logicalName0 = req.getLogicalName();
  4272. const char* parentName = req.getParentName();
  4273. if (!logicalName0 || !*logicalName0)
  4274. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No LogicalName defined.");
  4275. StringBuffer logicalNameStr;
  4276. if (logicalName0 && *logicalName0)
  4277. {
  4278. logicalNameStr.append(logicalName0);
  4279. logicalNameStr.trim();
  4280. if (logicalNameStr.length() < 1)
  4281. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No LogicalName defined.");
  4282. }
  4283. PROGLOG("DFUBrowseData: %s", logicalNameStr.str());
  4284. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  4285. __int64 count=req.getCount() ? req.getCount() : 20, requested=count;
  4286. if (count > MAX_VIEWKEYFILE_ROWS)
  4287. throw MakeStringException(ECLWATCH_TOO_MANY_DATA_ROWS,"Browser Cannot display more than %d data rows.", MAX_VIEWKEYFILE_ROWS);
  4288. bool bSchemaOnly=req.getSchemaOnly() ? req.getSchemaOnly() : false;
  4289. bool bDisableUppercaseTranslation = req.getDisableUppercaseTranslation() ? req.getDisableUppercaseTranslation() : false;
  4290. const char* filterBy = req.getFilterBy();
  4291. const char* showColumns = req.getShowColumns();
  4292. __int64 read=0;
  4293. __int64 total = 0;
  4294. StringBuffer msg;
  4295. StringArray columnLabels, columnLabelsType;
  4296. IArrayOf<IEspDFUData> DataList;
  4297. int iRet = GetIndexData(context, bSchemaOnly, logicalNameStr.str(), parentName, filterBy, start, count, read, total, msg, columnLabels, columnLabelsType, DataList, bDisableUppercaseTranslation);
  4298. if (iRet > 0)
  4299. resp.setMsgToDisplay("This search has timed out due to the restrictive filter. There may be more records.");
  4300. //GetIndexData(context, bSchemaOnly, logicalNameStr.str(), "roxie::thor_data400::key::bankruptcyv2::20090721::search::tmsid", filterBy, start, count, read, total, msg, columnLabels, columnLabelsType, DataList);
  4301. resp.setResult(DataList.item(0).getData());
  4302. unsigned int max_name_length = 3; //max length for name length
  4303. unsigned int max_value_length = 4; //max length for value length:
  4304. StringBuffer filterByStr, filterByStr0;
  4305. filterByStr0.appendf("%d%d", max_name_length, max_value_length);
  4306. unsigned columnCount = columnLabels.length();
  4307. IArrayOf<IEspDFUDataColumn> dataColumns;
  4308. double version = context.getClientVersion();
  4309. if (version > 1.04 && columnCount > 0)
  4310. {
  4311. //Find out which columns need to be displayed
  4312. int lenShowCols = 0, showCols[1024];
  4313. const char* showColumns = req.getShowColumns();
  4314. char *pShowColumns = (char*) showColumns;
  4315. while (pShowColumns && *pShowColumns)
  4316. {
  4317. StringBuffer buf;
  4318. while (pShowColumns && isdigit(pShowColumns[0]))
  4319. {
  4320. buf.append(pShowColumns[0]);
  4321. pShowColumns++;
  4322. }
  4323. if (buf.length() > 0)
  4324. {
  4325. showCols[lenShowCols] = atoi(buf.str());
  4326. lenShowCols++;
  4327. }
  4328. if (!pShowColumns || !*pShowColumns)
  4329. break;
  4330. pShowColumns++;
  4331. }
  4332. for(unsigned col = 0; col < columnCount; col++)
  4333. {
  4334. const char* label = columnLabels.item(col);
  4335. const char* type = columnLabelsType.item(col);
  4336. if (!label || !*label || !type || !*type)
  4337. continue;
  4338. Owned<IEspDFUDataColumn> item = createDFUDataColumn("","");
  4339. item->setColumnLabel(label);
  4340. item->setColumnType(type);
  4341. item->setColumnSize(0); //not show this column
  4342. if (!showColumns || !*showColumns)
  4343. {
  4344. item->setColumnSize(1); //Show this column
  4345. }
  4346. else
  4347. {
  4348. for(int col1 = 0; col1 < lenShowCols; col1++)
  4349. {
  4350. if (col == showCols[col1])
  4351. {
  4352. item->setColumnSize(1); //Show this column
  4353. break;
  4354. }
  4355. }
  4356. }
  4357. dataColumns.append(*item.getLink());
  4358. }
  4359. //Re-build filters
  4360. if (filterBy && *filterBy)
  4361. {
  4362. StringArray filterByNames, filterByValues;
  4363. parseTwoStringArrays(filterBy, filterByNames, filterByValues);
  4364. if (filterByNames.length() > 0)
  4365. {
  4366. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  4367. {
  4368. const char* columnName = filterByNames.item(ii);
  4369. const char* columnValue = filterByValues.item(ii);
  4370. if (columnName && *columnName && columnValue && *columnValue)
  4371. {
  4372. filterByStr.appendf("%s[%s]", columnName, columnValue);
  4373. filterByStr0.appendf("%03d%04d%s%s", (int) strlen(columnName), (int) strlen(columnValue), columnName, columnValue);
  4374. }
  4375. }
  4376. }
  4377. }
  4378. if (req.getStartForGoback())
  4379. resp.setStartForGoback(req.getStartForGoback());
  4380. if (req.getCountForGoback())
  4381. resp.setCountForGoback(req.getCountForGoback());
  4382. }
  4383. //resp.setFilterBy(filterByStr.str());
  4384. if (filterByStr.length() > 0)
  4385. {
  4386. const char* oldStr = "&";
  4387. const char* newStr = "&amp;";
  4388. filterByStr.replaceString(oldStr, newStr);
  4389. resp.setFilterBy(filterByStr.str());
  4390. }
  4391. if (version > 1.04)
  4392. {
  4393. //resp.setFilterForGoBack(filterByStr0.str());
  4394. if (filterByStr0.length() > 0)
  4395. {
  4396. const char* oldStr = "&";
  4397. const char* newStr = "&amp;";
  4398. filterByStr0.replaceString(oldStr, newStr);
  4399. resp.setFilterForGoBack(filterByStr0.str());
  4400. }
  4401. resp.setColumnCount(columnCount);
  4402. if (dataColumns.length() > 0)
  4403. resp.setColumnsHidden(dataColumns);
  4404. }
  4405. if (version > 1.10)
  4406. {
  4407. resp.setSchemaOnly(bSchemaOnly);
  4408. }
  4409. //resp.setName(name.str());
  4410. resp.setLogicalName(logicalNameStr.str());
  4411. resp.setStart(start);
  4412. //if (requested > read)
  4413. // requested = read;
  4414. resp.setPageSize(requested);
  4415. if (count > read)
  4416. {
  4417. count = read;
  4418. }
  4419. resp.setCount(count);
  4420. if (total != UNKNOWN_NUM_ROWS)
  4421. resp.setTotal(total);
  4422. else
  4423. resp.setTotal(-1);
  4424. if (req.getChooseFile())
  4425. resp.setChooseFile(1);
  4426. else
  4427. resp.setChooseFile(0);
  4428. if (version > 1.11)
  4429. {
  4430. if (req.getCluster() && *req.getCluster())
  4431. {
  4432. resp.setCluster(req.getCluster());
  4433. }
  4434. if (req.getClusterType() && *req.getClusterType())
  4435. {
  4436. resp.setClusterType(req.getClusterType());
  4437. }
  4438. }
  4439. if ((version > 1.12) && parentName && *parentName)
  4440. {
  4441. resp.setParentName(parentName);
  4442. }
  4443. }
  4444. catch(IException* e)
  4445. {
  4446. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4447. }
  4448. return true;
  4449. }
  4450. void storeHistoryTreeToArray(IPropertyTree *history, IArrayOf<IEspHistory>& arrHistory)
  4451. {
  4452. Owned<IPropertyTreeIterator> historyIter = history->getElements("*");
  4453. ForEach(*historyIter)
  4454. {
  4455. Owned<IEspHistory> historyRecord = createHistory();
  4456. IPropertyTree & item = historyIter->query();
  4457. historyRecord->setIP(item.queryProp("@ip"));
  4458. historyRecord->setName(item.queryProp("@name"));
  4459. historyRecord->setOperation(item.queryProp("@operation"));
  4460. historyRecord->setOwner(item.queryProp("@owner"));
  4461. historyRecord->setPath(item.queryProp("@path"));
  4462. historyRecord->setTimestamp(item.queryProp("@timestamp"));
  4463. historyRecord->setWorkunit(item.queryProp("@workunit"));
  4464. arrHistory.append(*historyRecord.getClear());
  4465. }
  4466. }
  4467. bool CWsDfuEx::onListHistory(IEspContext &context, IEspListHistoryRequest &req, IEspListHistoryResponse &resp)
  4468. {
  4469. try
  4470. {
  4471. StringBuffer username;
  4472. context.getUserID(username);
  4473. Owned<IUserDescriptor> userdesc;
  4474. if (username.length() > 0)
  4475. {
  4476. userdesc.setown(createUserDescriptor());
  4477. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  4478. }
  4479. if (!req.getName() || !*req.getName())
  4480. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Name required");
  4481. PROGLOG("onListHistory: %s", req.getName());
  4482. MemoryBuffer xmlmap;
  4483. IArrayOf<IEspHistory> arrHistory;
  4484. Owned<IDistributedFile> file = queryDistributedFileDirectory().lookup(req.getName(),userdesc.get());
  4485. if (file)
  4486. {
  4487. IPropertyTree *history = file->queryHistory();
  4488. if (history)
  4489. {
  4490. storeHistoryTreeToArray(history, arrHistory);
  4491. if (context.getClientVersion() < 1.36)
  4492. history->serialize(xmlmap);
  4493. }
  4494. if (arrHistory.ordinality())
  4495. resp.setHistory(arrHistory);
  4496. }
  4497. else
  4498. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"CWsDfuEx::onListHistory: Could not find file '%s'.", req.getName());
  4499. if (xmlmap.length())
  4500. resp.setXmlmap(xmlmap);
  4501. }
  4502. catch(IException* e)
  4503. {
  4504. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4505. }
  4506. return true;
  4507. }
  4508. bool CWsDfuEx::onEraseHistory(IEspContext &context, IEspEraseHistoryRequest &req, IEspEraseHistoryResponse &resp)
  4509. {
  4510. try
  4511. {
  4512. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Full, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::EraseHistory: Permission denied.");
  4513. StringBuffer username;
  4514. context.getUserID(username);
  4515. Owned<IUserDescriptor> userdesc;
  4516. if (username.length() > 0)
  4517. {
  4518. userdesc.setown(createUserDescriptor());
  4519. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  4520. }
  4521. if (!req.getName() || !*req.getName())
  4522. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Name required");
  4523. PROGLOG("onEraseHistory: %s", req.getName());
  4524. MemoryBuffer xmlmap;
  4525. IArrayOf<IEspHistory> arrHistory;
  4526. Owned<IDistributedFile> file = queryDistributedFileDirectory().lookup(req.getName(),userdesc.get());
  4527. if (file)
  4528. {
  4529. IPropertyTree *history = file->queryHistory();
  4530. if (history)
  4531. {
  4532. storeHistoryTreeToArray(history, arrHistory);
  4533. if (context.getClientVersion() < 1.36)
  4534. history->serialize(xmlmap);
  4535. file->resetHistory();
  4536. }
  4537. if (arrHistory.ordinality())
  4538. resp.setHistory(arrHistory);
  4539. }
  4540. else
  4541. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"CWsDfuEx::onEraseHistory: Could not find file '%s'.", req.getName());
  4542. if (xmlmap.length())
  4543. resp.setXmlmap(xmlmap);
  4544. }
  4545. catch(IException* e)
  4546. {
  4547. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4548. }
  4549. return true;
  4550. }
  4551. //////////////////////HPCC Browser//////////////////////////
  4552. static const char* SCHEMANAME = "myschema";
  4553. //void CWsDfuEx::setRootFilter(INewResultSet* result, const char* filterBy, IFilteredResultSet* filter)
  4554. void CWsDfuEx::setRootFilter(INewResultSet* result, const char* filterBy, IResultSetFilter* filter, bool disableUppercaseTranslation)
  4555. {
  4556. if (!filterBy || !*filterBy || !result)
  4557. return;
  4558. //Owned<IFilteredResultSet> filter = result->createFiltered();
  4559. filter->clearFilters();
  4560. const IResultSetMetaData &meta = result->getMetaData();
  4561. unsigned columnCount = meta.getColumnCount();
  4562. if (columnCount < 1)
  4563. return;
  4564. StringArray filterByNames, filterByValues;
  4565. parseTwoStringArrays(filterBy, filterByNames, filterByValues);
  4566. if (filterByNames.length() < 1)
  4567. return;
  4568. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  4569. {
  4570. const char* columnName = filterByNames.item(ii);
  4571. const char* columnValue0 = filterByValues.item(ii);
  4572. if (!columnName || !*columnName || !columnValue0 || !*columnValue0)
  4573. continue;
  4574. StringBuffer buf(columnValue0);
  4575. if (!disableUppercaseTranslation)
  4576. buf.toUpperCase();
  4577. const char* columnValue = buf.str();
  4578. for(unsigned col = 0; col < columnCount; col++)
  4579. {
  4580. bool hasSetTranslation = false;
  4581. SCMStringBuffer scmbuf;
  4582. if (meta.hasSetTranslation(col))
  4583. {
  4584. hasSetTranslation = true;
  4585. meta.getNaturalColumnLabel(scmbuf, col);
  4586. }
  4587. if (scmbuf.length() < 1)
  4588. {
  4589. meta.getColumnLabel(scmbuf, col);
  4590. }
  4591. if (!stricmp(scmbuf.str(), columnName))
  4592. {
  4593. //filter->addFilter(col, columnValue);
  4594. //filterByStr.appendf("%s[%s]", columnName, columnValue);
  4595. //filterByStr0.appendf("%03d%04d%s%s", strlen(columnName), strlen(columnValue), columnName, columnValue);
  4596. if (hasSetTranslation)
  4597. filter->addNaturalFilter(col, strlen(columnValue), columnValue);
  4598. else
  4599. filter->addFilter(col, strlen(columnValue), columnValue);
  4600. break;
  4601. }
  4602. }
  4603. }
  4604. //result.setown(filter->create());
  4605. return;
  4606. }
  4607. void CWsDfuEx::getMappingColumns(IRelatedBrowseFile * file, bool isPrimary, UnsignedArray& cols)
  4608. {
  4609. const char* logicalName = file->queryDefinition()->queryDistributedFile()->queryLogicalName();
  4610. const char* primaryName = file->queryParentRelation()->queryFileRelationship()->queryPrimaryFilename();
  4611. if (!logicalName || !primaryName || strcmp(logicalName, primaryName))
  4612. return;
  4613. IViewRelation* parentRelation = file->queryParentRelation();
  4614. for (unsigned i=0; i < parentRelation->numMappingFields(); i++)
  4615. {
  4616. //find out the column numbers to remove
  4617. unsigned col = parentRelation->queryMappingField(i, isPrimary);
  4618. cols.append(col);
  4619. }
  4620. #ifdef TESTDATASET
  4621. cols.kill();
  4622. cols.append(2);
  4623. cols.append(3);
  4624. #endif
  4625. return;
  4626. }
  4627. void CWsDfuEx::readColumnsForDisplay(StringBuffer& schemaText, StringArray& columnsDisplay, StringArray& columnsDisplayType)
  4628. {
  4629. if (schemaText.length() < 1)
  4630. return;
  4631. Owned<IPropertyTree> schema = createPTreeFromXMLString(schemaText.str());
  4632. if (!schema)
  4633. return;
  4634. //Find out labels from the second schema used for column mapping
  4635. columnsDisplay.kill();
  4636. Owned<IPropertyTreeIterator> rows4 = schema->getElements("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence/*");
  4637. ForEach(*rows4)
  4638. {
  4639. IPropertyTree &e = rows4->query();
  4640. const char* name = e.queryProp("@name");
  4641. const char* type = e.queryProp("@type");
  4642. bool hasChildren = e.hasChildren();
  4643. if (!name || !*name)
  4644. continue;
  4645. columnsDisplay.append(name); //Display this column
  4646. if (type && *type)
  4647. columnsDisplayType.append(type);
  4648. else if (hasChildren)
  4649. columnsDisplayType.append("Object");
  4650. else
  4651. columnsDisplayType.append("Unknown");
  4652. }
  4653. return;
  4654. }
  4655. void CWsDfuEx::mergeSchema(IRelatedBrowseFile * file, StringBuffer& schemaText, StringBuffer schemaText2,
  4656. StringArray& columnsDisplay, StringArray& columnsDisplayType, StringArray& columnsHide)
  4657. {
  4658. if (schemaText.length() < 1)
  4659. return;
  4660. if (schemaText2.length() < 1)
  4661. return;
  4662. Owned<IPropertyTree> schema = createPTreeFromXMLString(schemaText.str());
  4663. Owned<IPropertyTree> schema2 = createPTreeFromXMLString(schemaText2.str());
  4664. if (!schema || !schema2)
  4665. return;
  4666. //Process simpleType part
  4667. Owned<IPropertyTreeIterator> rows1 = schema->getElements("xs:simpleType");
  4668. Owned<IPropertyTreeIterator> rows2 = schema2->getElements("xs:simpleType");
  4669. if (!rows1 || !rows2)
  4670. return;
  4671. ForEach(*rows2)
  4672. {
  4673. IPropertyTree &e = rows2->query();
  4674. const char* name = e.queryProp("@name");
  4675. if (!name || !*name)
  4676. continue;
  4677. bool bFound = false;
  4678. ForEach(*rows1)
  4679. {
  4680. IPropertyTree &e1 = rows1->query();
  4681. const char* name1 = e1.queryProp("@name");
  4682. if (!name1 || !*name1 || stricmp(name1, name))
  4683. continue;
  4684. bFound = true;
  4685. break;
  4686. }
  4687. if (!bFound)
  4688. schema->addPropTree(e.queryName(), LINK(&e));
  4689. }
  4690. IPropertyTree* rows = schema->queryBranch("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence");
  4691. if (!rows)
  4692. return;
  4693. //Find out labels used for column mapping
  4694. columnsDisplay.kill();
  4695. columnsDisplayType.kill();
  4696. columnsHide.kill();
  4697. Owned<IPropertyTreeIterator> rows4 = schema->getElements("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence/*");
  4698. ForEach(*rows4)
  4699. {
  4700. IPropertyTree &e = rows4->query();
  4701. const char* name = e.queryProp("@name");
  4702. const char* type = e.queryProp("@type");
  4703. bool hasChildren = e.hasChildren();
  4704. if (!name || !*name)
  4705. continue;
  4706. columnsDisplay.append(name); //Display this column
  4707. if (type && *type)
  4708. columnsDisplayType.append(type);
  4709. else if (hasChildren)
  4710. columnsDisplayType.append("Object");
  4711. else
  4712. columnsDisplayType.append("Unknown");
  4713. }
  4714. UnsignedArray cols;
  4715. bool isPrimary = true;
  4716. getMappingColumns(file, isPrimary, cols);
  4717. //Process complexType part for labels
  4718. unsigned col0 = 0;
  4719. Owned<IPropertyTreeIterator> rows3 = schema2->getElements("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence/*");
  4720. ForEach(*rows3)
  4721. {
  4722. IPropertyTree &e = rows3->query();
  4723. const char* name = e.queryProp("@name");
  4724. const char* type = e.queryProp("@type");
  4725. bool hasChildren = e.hasChildren();
  4726. if (!name || !*name)
  4727. continue;
  4728. bool bAdd = true;
  4729. bool bRename = false;
  4730. if (cols.ordinality() != 0)
  4731. {
  4732. ForEachItemIn(i1,cols)
  4733. {
  4734. unsigned col = cols.item(i1);
  4735. if (col == col0)
  4736. {
  4737. bAdd = false;
  4738. break;
  4739. }
  4740. }
  4741. }
  4742. #define RENAMESAMECOLUMN
  4743. #ifdef RENAMESAMECOLUMN
  4744. if (columnsDisplay.length() > 0)
  4745. {
  4746. for (unsigned i = 0; i < columnsDisplay.length(); i++)
  4747. {
  4748. const char* label = columnsDisplay.item(i);
  4749. if (!label || strcmp(label, name))
  4750. continue;
  4751. bRename = true;
  4752. break;
  4753. }
  4754. }
  4755. #endif
  4756. if (!bAdd)
  4757. {
  4758. columnsHide.append(name); //hide this column
  4759. }
  4760. else
  4761. {
  4762. if (type && *type)
  4763. columnsDisplayType.append(type);
  4764. else if (hasChildren)
  4765. columnsDisplayType.append("Object");
  4766. else
  4767. columnsDisplayType.append("Unknown");
  4768. #ifdef RENAMESAMECOLUMN
  4769. if (bRename)
  4770. {
  4771. StringBuffer newName(name);
  4772. newName.append("-2");
  4773. columnsDisplay.append(newName.str()); //Display this column
  4774. e.setProp("@name", newName.str());
  4775. rows->addPropTree(e.queryName(), LINK(&e));
  4776. }
  4777. else
  4778. {
  4779. #endif
  4780. columnsDisplay.append(name); //Display this column
  4781. rows->addPropTree(e.queryName(), LINK(&e));
  4782. #ifdef RENAMESAMECOLUMN
  4783. }
  4784. #endif
  4785. }
  4786. col0++;
  4787. }
  4788. //Convert schema tree to schame now
  4789. schemaText.clear();
  4790. toXML(schema, schemaText);
  4791. return;
  4792. }
  4793. void CWsDfuEx::mergeDataRow(StringBuffer& newRow, int depth, IPropertyTreeIterator* it, StringArray& columnsHide, StringArray& columnsUsed)
  4794. {
  4795. if (!it)
  4796. return;
  4797. it->first();
  4798. while(it->isValid())
  4799. {
  4800. IPropertyTree* e = &it->query();
  4801. if (e)
  4802. {
  4803. const char* label = e->queryName();
  4804. if (label && *label)
  4805. {
  4806. #ifdef RENAMESAMECOLUMN
  4807. if (depth < 1)
  4808. columnsUsed.append(label);
  4809. #endif
  4810. bool bHide = false;
  4811. if (columnsHide.length() > 0)
  4812. {
  4813. for (unsigned i = 0 ; i < columnsHide.length(); i++)
  4814. {
  4815. const char* key = columnsHide.item(i);
  4816. if (!key || strcmp(key, label))
  4817. continue;
  4818. bHide = true;
  4819. break;
  4820. }
  4821. }
  4822. #ifdef RENAMESAMECOLUMN
  4823. if (!bHide && depth > 0 && columnsUsed.length() > 0)
  4824. {
  4825. for (unsigned i = 0 ; i < columnsUsed.length(); i++)
  4826. {
  4827. const char* key = columnsUsed.item(i);
  4828. if (!key || strcmp(key, label))
  4829. continue;
  4830. StringBuffer newName(label);
  4831. newName.append("-2");
  4832. e->renameProp("/", newName.str());
  4833. break;
  4834. }
  4835. }
  4836. #endif
  4837. if (!bHide)
  4838. {
  4839. StringBuffer dataRow;
  4840. toXML(e, dataRow);
  4841. newRow.append(dataRow);
  4842. }
  4843. }
  4844. }
  4845. it->next();
  4846. }
  4847. return;
  4848. }
  4849. void CWsDfuEx::mergeDataRow(StringBuffer& newRow, StringBuffer dataRow1, StringBuffer dataRow2, StringArray& columnsHide)
  4850. {
  4851. if (dataRow1.length() < 1)
  4852. return;
  4853. if (dataRow2.length() < 1)
  4854. return;
  4855. Owned<IPropertyTree> data1 = createPTreeFromXMLString(dataRow1.str());
  4856. Owned<IPropertyTree> data2 = createPTreeFromXMLString(dataRow2.str());
  4857. if (!data1 || !data2)
  4858. return;
  4859. newRow.clear();
  4860. newRow.append("<Row>");
  4861. StringArray columnLabels;
  4862. Owned<IPropertyTreeIterator> it = data1->getElements("*");
  4863. if (it)
  4864. {
  4865. StringArray columnLabels0;
  4866. mergeDataRow(newRow, 0, it, columnLabels0, columnLabels);
  4867. }
  4868. Owned<IPropertyTreeIterator> it2 = data2->getElements("*");
  4869. if (it2)
  4870. {
  4871. mergeDataRow(newRow, 1, it2, columnsHide, columnLabels);
  4872. }
  4873. newRow.append("</Row>");
  4874. return;
  4875. }
  4876. void CWsDfuEx::browseRelatedFileSchema(IRelatedBrowseFile * file, const char* parentName, unsigned depth, StringBuffer& schemaText,
  4877. StringArray& columnsDisplay, StringArray& columnsDisplayType, StringArray& columnsHide)
  4878. {
  4879. //if (file in set of files to display or iterate)
  4880. IResultSetCursor * cursor = file->queryCursor();
  4881. if (cursor && cursor->first())
  4882. {
  4883. if (depth < 1)
  4884. {
  4885. const IResultSetMetaData & meta = cursor->queryResultSet()->getMetaData();
  4886. StringBufferAdaptor adaptor(schemaText);
  4887. meta.getXmlSchema(adaptor, false);
  4888. #ifdef TESTDATASET
  4889. schemaText.clear();
  4890. schemaText.append("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\"");
  4891. schemaText.append(" attributeFormDefault=\"unqualified\">");
  4892. schemaText.append("<xs:element name=\"Dataset\"><xs:complexType><xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">");
  4893. schemaText.append("<xs:element name=\"Row\"><xs:complexType><xs:sequence>");
  4894. schemaText.append("<xs:element name=\"state\" type=\"string2\"/>");
  4895. schemaText.append("<xs:element name=\"rtype\" type=\"string2\"/>");
  4896. schemaText.append("<xs:element name=\"id\" type=\"string20\"/>");
  4897. schemaText.append("<xs:element name=\"seq\" type=\"xs:nonNegativeInteger\"/>");
  4898. schemaText.append("<xs:element name=\"num\" type=\"xs:nonNegativeInteger\"/>");
  4899. schemaText.append("<xs:element name=\"date\" type=\"string8\"/>");
  4900. schemaText.append("<xs:element name=\"imglength\" type=\"xs:nonNegativeInteger\"/>");
  4901. schemaText.append("<xs:element name=\"__filepos\" type=\"xs:nonNegativeInteger\"/>");
  4902. schemaText.append("</xs:sequence></xs:complexType></xs:element>");
  4903. schemaText.append("</xs:sequence></xs:complexType></xs:element>");
  4904. schemaText.append("<xs:simpleType name=\"string2\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"2\"/>");
  4905. schemaText.append("</xs:restriction></xs:simpleType>");
  4906. schemaText.append("<xs:simpleType name=\"string20\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"20\"/>");
  4907. schemaText.append("</xs:restriction></xs:simpleType>");
  4908. schemaText.append("<xs:simpleType name=\"string8\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"8\"/>");
  4909. schemaText.append("</xs:restriction></xs:simpleType>");
  4910. schemaText.append("</xs:schema>");
  4911. #endif
  4912. readColumnsForDisplay(schemaText, columnsDisplay, columnsDisplayType);
  4913. }
  4914. else
  4915. {
  4916. StringBuffer schemaText0;
  4917. const IResultSetMetaData & meta = cursor->queryResultSet()->getMetaData();
  4918. StringBufferAdaptor adaptor(schemaText0);
  4919. meta.getXmlSchema(adaptor, false);
  4920. #ifdef TESTDATASET
  4921. schemaText0.clear();
  4922. schemaText0.append("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\"");
  4923. schemaText0.append(" attributeFormDefault=\"unqualified\">");
  4924. schemaText0.append("<xs:element name=\"Dataset\"><xs:complexType><xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">");
  4925. schemaText0.append("<xs:element name=\"Row\"><xs:complexType><xs:sequence>");
  4926. schemaText0.append("<xs:element name=\"date_first_reported\" type=\"string12\"/>");
  4927. schemaText0.append("<xs:element name=\"msa\" type=\"string8\"/>");
  4928. schemaText0.append("<xs:element name=\"sid\" type=\"string20\"/>");
  4929. schemaText0.append("<xs:element name=\"seq\" type=\"xs:nonNegativeInteger\"/>"); //not add
  4930. schemaText0.append("</xs:sequence></xs:complexType></xs:element>");
  4931. schemaText0.append("</xs:sequence></xs:complexType></xs:element>");
  4932. schemaText0.append("<xs:simpleType name=\"string12\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"12\"/>");
  4933. schemaText0.append("</xs:restriction></xs:simpleType>");
  4934. schemaText0.append("</xs:schema>");
  4935. #endif
  4936. mergeSchema(file, schemaText, schemaText0, columnsDisplay, columnsDisplayType, columnsHide);
  4937. }
  4938. if (parentName && *parentName)
  4939. {
  4940. for (unsigned i = 0;;i++)
  4941. {
  4942. IRelatedBrowseFile * next = file->queryChild(i);
  4943. if (!next)
  4944. break;
  4945. IViewRelatedFile * viewRelatedFile = next->queryDefinition();
  4946. if (!viewRelatedFile)
  4947. continue;
  4948. IDistributedFile * file = viewRelatedFile->queryDistributedFile();
  4949. if (!file)
  4950. continue;
  4951. const char* logicName0 = file->queryLogicalName();
  4952. if (logicName0 && !strcmp(logicName0, parentName))
  4953. browseRelatedFileSchema(next, NULL, depth+1, schemaText, columnsDisplay, columnsDisplayType, columnsHide);
  4954. }
  4955. }
  4956. }
  4957. return;
  4958. }
  4959. int CWsDfuEx::browseRelatedFileDataSet(double version, IRelatedBrowseFile * file, const char* parentName, unsigned depth, __int64 start, __int64& count, __int64& read,
  4960. StringArray& columnsHide, StringArray& dataSetOutput)
  4961. {
  4962. int iRet = 0;
  4963. int rows = 0;
  4964. try
  4965. {
  4966. //if (file in set of files to display or iterate)
  4967. IResultSetCursor * cursor = file->queryCursor();
  4968. if (cursor->first())
  4969. {
  4970. for(bool ok=cursor->absolute(start);ok;ok=cursor->next())
  4971. {
  4972. StringBuffer text;
  4973. StringBufferAdaptor adaptor2(text);
  4974. cursor->getXmlRow(adaptor2);
  4975. StringArray dataSetOutput0;
  4976. if (parentName && *parentName)
  4977. {
  4978. for (unsigned i = 0;;i++)
  4979. {
  4980. IRelatedBrowseFile * next = file->queryChild(i);
  4981. if (!next)
  4982. break;
  4983. IViewRelatedFile * viewRelatedFile = next->queryDefinition();
  4984. if (!viewRelatedFile)
  4985. continue;
  4986. IDistributedFile * file = viewRelatedFile->queryDistributedFile();
  4987. if (!file)
  4988. continue;
  4989. const char* logicName0 = file->queryLogicalName();
  4990. if (logicName0 && !strcmp(logicName0, parentName))
  4991. iRet = browseRelatedFileDataSet(version, next, NULL, depth+1, 0, count, read, columnsHide, dataSetOutput0);
  4992. }
  4993. }
  4994. if (dataSetOutput0.length() < 1)
  4995. {
  4996. dataSetOutput.append(text);
  4997. }
  4998. else
  4999. {
  5000. for (unsigned ii = 0; ii<dataSetOutput0.length(); ii++)
  5001. {
  5002. StringBuffer text0;
  5003. StringBuffer text1 = dataSetOutput0.item(ii);
  5004. if (text1.length() > 0)
  5005. {
  5006. mergeDataRow(text0, text, text1, columnsHide);
  5007. }
  5008. dataSetOutput.append(text0);
  5009. }
  5010. }
  5011. if (depth < 1)
  5012. {
  5013. read++;
  5014. if(read>=count)
  5015. break;
  5016. }
  5017. }
  5018. if (depth < 1)
  5019. {
  5020. if (count > read)
  5021. count = read;
  5022. }
  5023. }
  5024. }
  5025. catch(IException* e)
  5026. {
  5027. if ((version < 1.08) || (e->errorCode() != FVERR_FilterTooRestrictive))
  5028. throw e;
  5029. e->Release();
  5030. iRet = 1;
  5031. }
  5032. return iRet;
  5033. }
  5034. //sample filterBy: 340020001id1
  5035. //sample data: <XmlSchema name="myschema">...</XmlSchema><Dataset xmlSchema="myschema">...</Dataset>
  5036. int CWsDfuEx::GetIndexData(IEspContext &context, bool bSchemaOnly, const char* indexName, const char* parentName, const char* filterBy, __int64 start,
  5037. __int64& count, __int64& read, __int64& total, StringBuffer& message, StringArray& columnLabels,
  5038. StringArray& columnLabelsType, IArrayOf<IEspDFUData>& DataList, bool webDisableUppercaseTranslation)
  5039. {
  5040. if (!indexName || !*indexName)
  5041. return -1;
  5042. double version = context.getClientVersion();
  5043. StringBuffer username;
  5044. context.getUserID(username);
  5045. StringBuffer cluster;
  5046. Owned<IUserDescriptor> userdesc;
  5047. bool disableUppercaseTranslation = false;
  5048. Owned<IDistributedFile> df;
  5049. try
  5050. {
  5051. userdesc.setown(createUserDescriptor());
  5052. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  5053. df.setown(queryDistributedFileDirectory().lookup(indexName, userdesc));
  5054. if(!df)
  5055. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Could not find file %s.", indexName);
  5056. //Check disableUppercaseTranslation
  5057. StringBuffer mapping;
  5058. df->getColumnMapping(mapping);
  5059. if (mapping.length() > 37 && strstr(mapping.str(), "word{set(stringlib.StringToLowerCase)}"))
  5060. disableUppercaseTranslation = true;
  5061. else if (webDisableUppercaseTranslation)
  5062. disableUppercaseTranslation = webDisableUppercaseTranslation;
  5063. else
  5064. disableUppercaseTranslation = m_disableUppercaseTranslation;
  5065. const char* wuid = df->queryAttributes().queryProp("@workunit");
  5066. if (wuid && *wuid)
  5067. {
  5068. CWUWrapper wu(wuid, context);
  5069. if (wu)
  5070. cluster.append(wu->queryClusterName());
  5071. }
  5072. }
  5073. catch (IException *e)
  5074. {
  5075. DBGLOG(e);
  5076. e->Release();
  5077. }
  5078. catch(...)
  5079. {
  5080. DBGLOG("Unknown Exception - view data file: %s", indexName);
  5081. }
  5082. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  5083. Owned<IViewFileWeb> web;
  5084. Owned<IUserDescriptor> udesc;
  5085. ISecUser * secUser = context.queryUser();
  5086. if(secUser && secUser->getName() && *secUser->getName())
  5087. {
  5088. udesc.setown(createUserDescriptor());
  5089. udesc->set(secUser->getName(), secUser->credentials().getPassword(), context.querySignature());
  5090. }
  5091. if (cluster.length())
  5092. {
  5093. web.setown(createViewFileWeb(*resultSetFactory, cluster, udesc.getLink()));
  5094. }
  5095. else if (m_clusterName.length() > 0)
  5096. {
  5097. web.setown(createViewFileWeb(*resultSetFactory, m_clusterName.str(), udesc.getLink()));
  5098. }
  5099. else
  5100. {
  5101. web.setown(createViewFileWeb(*resultSetFactory, NULL, udesc.getLink()));
  5102. }
  5103. ViewGatherOptions options;
  5104. options.primaryDepth = 100; // we want to traverse secondary->primary, but not the reverse
  5105. options.secondaryDepth = 0;
  5106. options.setPayloadFilter(true); // we're only interested in payload links
  5107. char *indexName0 = (char *) indexName;
  5108. Owned<IFileTreeBrowser> browser;
  5109. try
  5110. {
  5111. web->gatherWeb(indexName0, df, options);
  5112. browser.setown(web->createBrowseTree(indexName0));
  5113. }
  5114. catch(IException* e)
  5115. {
  5116. if ((e->errorCode() != FVERR_CouldNotResolveX) || (indexName[0] != '~'))
  5117. {
  5118. throw e;
  5119. }
  5120. else
  5121. {
  5122. e->Release();
  5123. indexName0 = (char *) (indexName+1);
  5124. web->gatherWeb(indexName0, df, options);
  5125. browser.setown(web->createBrowseTree(indexName0));
  5126. }
  5127. }
  5128. Owned<INewResultSet> result;
  5129. if (cluster && *cluster)
  5130. {
  5131. result.setown(resultSetFactory->createNewFileResultSet(indexName0, cluster));
  5132. }
  5133. else if (m_clusterName.length() > 0)
  5134. {
  5135. result.setown(resultSetFactory->createNewFileResultSet(indexName0, m_clusterName.str()));
  5136. }
  5137. else
  5138. {
  5139. result.setown(resultSetFactory->createNewFileResultSet(indexName0, NULL));
  5140. }
  5141. // Apply the filter to the root node
  5142. if (filterBy && *filterBy)
  5143. {
  5144. //Owned<IFilteredResultSet> filter = result->createFiltered();
  5145. IResultSetFilter* filter = browser->queryRootFilter();
  5146. setRootFilter(result, filterBy, filter, disableUppercaseTranslation);
  5147. ///result.setown(filter->create());
  5148. }
  5149. StringBuffer text, schemaText;
  5150. StringArray columnsHide;
  5151. browseRelatedFileSchema(browser->queryRootFile(), parentName, 0, schemaText, columnLabels, columnLabelsType, columnsHide);
  5152. text.appendf("<XmlSchema name=\"%s\">", SCHEMANAME);
  5153. text.append(schemaText);
  5154. text.append("</XmlSchema>").newline();
  5155. int iRet = 0;
  5156. if (!bSchemaOnly)
  5157. {
  5158. StringArray dataSetOutput;
  5159. iRet = browseRelatedFileDataSet(version, browser->queryRootFile(), parentName, 0, start, count, read, columnsHide, dataSetOutput);
  5160. StringBuffer dataSetText;
  5161. dataSetText.appendf("<Dataset xmlSchema=\"%s\" >", SCHEMANAME);
  5162. dataSetText.newline();
  5163. for (unsigned i = 0; i<dataSetOutput.length(); i++)
  5164. {
  5165. StringBuffer text0 = dataSetOutput.item(i);
  5166. if (text0.length() > 0)
  5167. {
  5168. dataSetText.append(text0);
  5169. dataSetText.newline();
  5170. }
  5171. }
  5172. dataSetText.append("</Dataset>");
  5173. text.append(dataSetText.str());
  5174. }
  5175. MemoryBuffer data;
  5176. struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
  5177. {
  5178. MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
  5179. IMPLEMENT_IINTERFACE;
  5180. virtual const char * str() const { UNIMPLEMENTED; }
  5181. virtual void set(const char *val) { buffer.append(strlen(val),val); }
  5182. virtual void clear() { } // clearing when appending does nothing
  5183. virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
  5184. virtual unsigned length() const { return buffer.length(); };
  5185. MemoryBuffer & buffer;
  5186. } adaptor0(data);
  5187. adaptor0.set(text.str());
  5188. data.append(0);
  5189. total=result->getNumRows();
  5190. Owned<IEspDFUData> item = createDFUData("","");
  5191. item->setName(indexName);
  5192. item->setNumRows(total);
  5193. item->setData(data.toByteArray());
  5194. DataList.append(*item.getClear());
  5195. return iRet;
  5196. }
  5197. void CWsDfuEx::getFilePartsInfo(IEspContext &context, IFileDescriptor *fdesc, unsigned numParts, bool forFileCreate, IEspDFUFileAccessInfo &accessInfo)
  5198. {
  5199. IArrayOf<IEspDFUFilePart> dfuParts;
  5200. IArrayOf<IEspDFUPartLocation> dfuPartLocations;
  5201. unsigned newLocationIndex = 0;
  5202. MapStringTo<unsigned> partLocationMap;
  5203. // NB: both CopyIndex and PartIndex are 1 based in response.
  5204. Owned<IPartDescriptorIterator> pi = fdesc->getIterator();
  5205. ForEach(*pi)
  5206. {
  5207. IPartDescriptor& part = pi->query();
  5208. if (isPartTLK(&part))
  5209. continue;
  5210. IArrayOf<IEspDFUFileCopy> fileCopies;
  5211. for (unsigned int i=0; i<part.numCopies(); i++)
  5212. {
  5213. StringBuffer host, path;
  5214. part.getPath(path, i);
  5215. Owned<IEspDFUFileCopy> fileCopy = createDFUFileCopy();
  5216. if (forFileCreate)
  5217. fileCopy->setPath(path.str());
  5218. fileCopy->setCopyIndex(i + 1);
  5219. part.queryNode(i)->endpoint().getUrlStr(host);
  5220. unsigned *locationIndex = partLocationMap.getValue(host.str());
  5221. if (locationIndex)
  5222. fileCopy->setLocationIndex(*locationIndex);
  5223. else
  5224. {
  5225. partLocationMap.setValue(host.str(), ++newLocationIndex);
  5226. fileCopy->setLocationIndex(newLocationIndex);
  5227. Owned<IEspDFUPartLocation> partLocation = createDFUPartLocation();
  5228. partLocation->setLocationIndex(newLocationIndex);
  5229. partLocation->setHost(host.str());
  5230. dfuPartLocations.append(*partLocation.getClear());
  5231. }
  5232. fileCopies.append(*fileCopy.getClear());
  5233. }
  5234. Owned<IEspDFUFilePart> filePart = createDFUFilePart();
  5235. filePart->setPartIndex(part.queryPartIndex() + 1);
  5236. filePart->setCopies(fileCopies);
  5237. dfuParts.append(*filePart.getClear());
  5238. }
  5239. accessInfo.setNumParts(numParts);
  5240. accessInfo.setFileParts(dfuParts);
  5241. accessInfo.setFileLocations(dfuPartLocations);
  5242. }
  5243. static const char *securityInfoVersion="1";
  5244. void CWsDfuEx::getFileMeta(StringBuffer &metaInfoStr, StringBuffer &expiryTime, const char *fileName,
  5245. IFileDescriptor *fDesc, IUserDescriptor *user, const char *jobId, const char *keyPairName, IConstDFUFileAccessRequestBase &req)
  5246. {
  5247. // setup "expiryTime"
  5248. unsigned expirySecs = req.getExpirySeconds();
  5249. if (expirySecs > maxFileAccessExpirySeconds)
  5250. expirySecs = maxFileAccessExpirySeconds;
  5251. time_t now;
  5252. time(&now);
  5253. CDateTime expiryDt;
  5254. expiryDt.set(now + expirySecs);
  5255. expiryDt.getString(expiryTime);
  5256. Owned<IPropertyTree> metaInfoEnvelope = createPTree();
  5257. Owned<IPropertyTree> metaInfo = createPTree();
  5258. extractFilePartInfo(*metaInfo, *fDesc);
  5259. MemoryBuffer metaInfoMb;
  5260. /* NB: If file access security is disabled in the environment, or on a per cluster basis
  5261. * keyPairName will be blank. In that case the meta data is returned in plain format.
  5262. * NB2: Dafilesrv's would also require file access security to be disabled in that case,
  5263. * otherwise they will be denied access.
  5264. * Should be part of the same configuration setup.
  5265. */
  5266. #ifdef _USE_OPENSSL
  5267. if (!isEmptyString(keyPairName)) // without it, meta data is not encrypted
  5268. {
  5269. metaInfo->setProp("version", securityInfoVersion);
  5270. metaInfo->setProp("logicalFilename", fileName);
  5271. metaInfo->setProp("jobId", jobId);
  5272. metaInfo->setProp("accessType", req.getAccessTypeAsString());
  5273. StringBuffer userStr;
  5274. if (user)
  5275. metaInfo->setProp("user", user->getUserName(userStr).str());
  5276. metaInfo->setProp("keyPairName", keyPairName);
  5277. metaInfo->setProp("expiryTime", expiryTime);
  5278. MemoryBuffer metaInfoBlob;
  5279. metaInfo->serialize(metaInfoBlob);
  5280. const char *privateKeyFName = env->getPrivateKeyPath(keyPairName);
  5281. Owned<CLoadedKey> privateKey = loadPrivateKeyFromFile(privateKeyFName, nullptr);
  5282. StringBuffer metaInfoSignature;
  5283. digiSign(metaInfoSignature, metaInfoBlob.length(), metaInfoBlob.bytes(), *privateKey);
  5284. metaInfoEnvelope->setProp("signature", metaInfoSignature);
  5285. metaInfoEnvelope->setPropBin("metaInfoBlob", metaInfoBlob.length(), metaInfoBlob.bytes());
  5286. metaInfoEnvelope->serialize(metaInfoMb.clear());
  5287. }
  5288. else
  5289. #endif
  5290. metaInfo->serialize(metaInfoMb);
  5291. MemoryBuffer compressedMetaInfoMb;
  5292. fastLZCompressToBuffer(compressedMetaInfoMb, metaInfoMb.length(), metaInfoMb.bytes());
  5293. JBASE64_Encode(compressedMetaInfoMb.bytes(), compressedMetaInfoMb.length(), metaInfoStr, false);
  5294. }
  5295. void CWsDfuEx::getFileDafilesrvConfiguration(StringBuffer &keyPairName, unsigned &port, bool &secure, const char *cluster)
  5296. {
  5297. port = DEFAULT_ROWSERVICE_PORT;
  5298. secure = false;
  5299. keyPairName.set(env->getClusterKeyPairName(cluster));
  5300. Owned<IConstDaFileSrvInfo> daFileSrvInfo = env->getDaFileSrvGroupInfo(cluster);
  5301. if (daFileSrvInfo)
  5302. {
  5303. port = daFileSrvInfo->getPort();
  5304. secure = daFileSrvInfo->getSecure();
  5305. }
  5306. }
  5307. void CWsDfuEx::getFileDafilesrvConfiguration(StringBuffer &keyPairName, unsigned &retPort, bool &retSecure, IDistributedFile &file)
  5308. {
  5309. retPort = DEFAULT_ROWSERVICE_PORT;
  5310. retSecure = false;
  5311. unsigned numClusters = file.numClusters();
  5312. for (unsigned c=0; c<numClusters; c++)
  5313. {
  5314. StringBuffer clusterName;
  5315. const char *cluster = file.getClusterName(c, clusterName.clear()).str();
  5316. StringBuffer _keyPairName;
  5317. unsigned port;
  5318. bool secure;
  5319. getFileDafilesrvConfiguration(_keyPairName, port, secure, cluster);
  5320. if (0 == c)
  5321. {
  5322. keyPairName.set(_keyPairName);
  5323. retPort = port;
  5324. retSecure = secure;
  5325. }
  5326. else
  5327. {
  5328. if (!strsame(keyPairName, _keyPairName))
  5329. throwStringExceptionV(0, "Configuration issue - file '%s' is on multiple clusters, keys for file access must match", file.queryLogicalName());
  5330. if (retPort != port)
  5331. throwStringExceptionV(0, "Configuration issue - file '%s' is on multiple clusters, dafilesrv's port for file access must match", file.queryLogicalName());
  5332. if (retSecure != secure)
  5333. throwStringExceptionV(0, "Configuration issue - file '%s' is on multiple clusters, dafilesrv's security setting for file access must match", file.queryLogicalName());
  5334. }
  5335. }
  5336. }
  5337. void CWsDfuEx::getFileAccess(IEspContext &context, IUserDescriptor *udesc, SecAccessFlags accessType, IConstDFUFileAccessRequestBase &req, IEspDFUFileAccessInfo &accessInfo)
  5338. {
  5339. bool writePermissions = (accessType == SecAccess_Write) || (accessType == SecAccess_Full);
  5340. bool readPermissions = true; // by implication
  5341. StringBuffer fileName = req.getName();
  5342. if (!isEmptyString(req.getCluster()))
  5343. fileName.append("@").append(req.getCluster());
  5344. checkLogicalName(fileName, udesc, readPermissions, writePermissions, false, nullptr);
  5345. switch (accessType)
  5346. {
  5347. case SecAccess_Access:
  5348. case SecAccess_Read:
  5349. break;
  5350. default:
  5351. {
  5352. // NB - no handling for write/full at moment
  5353. return;
  5354. }
  5355. }
  5356. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(fileName, udesc, false, false, true); // lock super-owners
  5357. if (!df)
  5358. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file '%s'.", fileName.str());
  5359. Owned<IFileDescriptor> fileDesc = df->getFileDescriptor(req.getCluster());
  5360. CFileAccessRole role = req.getAccessRole();
  5361. switch (role)
  5362. {
  5363. case CFileAccessRole_Token:
  5364. {
  5365. break;
  5366. }
  5367. case CFileAccessRole_Engine:
  5368. {
  5369. /* JCSMORE - for now do nothing
  5370. * Ideally, would get the file tree here and add it to 'metaInfo' tree, i.e. outside of uncrypted secureInfo blob
  5371. * Then client could construct a IDistributeFile from it etc.
  5372. * However, the way the engines and IDistributedFile work at the moment, means that using this info
  5373. * at the client side would require a significant amount of refactoring of the IDistributedFile implementation.
  5374. * Not least because IDF allows updates via IPT -> Dali.
  5375. *
  5376. * So for now don't send anything, and rely on engine fetching the legacy way, i.e. direct from Dali, via lazy fetching etc.
  5377. */
  5378. break;
  5379. }
  5380. case CFileAccessRole_External:
  5381. {
  5382. getFilePartsInfo(context, fileDesc, df->numParts(), false, accessInfo);
  5383. if (req.getReturnJsonTypeInfo() || req.getReturnJsonTypeInfo())
  5384. {
  5385. MemoryBuffer binLayout;
  5386. StringBuffer jsonLayout;
  5387. if (!getRecordFormatFromRtlType(binLayout, jsonLayout, df->queryAttributes(), req.getReturnJsonTypeInfo(), req.getReturnJsonTypeInfo()))
  5388. getRecordFormatFromECL(binLayout, jsonLayout, df->queryAttributes(), req.getReturnJsonTypeInfo(), req.getReturnJsonTypeInfo());
  5389. if (req.getReturnJsonTypeInfo() && jsonLayout.length())
  5390. accessInfo.setRecordTypeInfoJson(jsonLayout.str());
  5391. if (req.getReturnBinTypeInfo() && binLayout.length())
  5392. accessInfo.setRecordTypeInfoBin(binLayout);
  5393. }
  5394. break;
  5395. }
  5396. default:
  5397. throwUnexpected();
  5398. }
  5399. StringBuffer keyPairName;
  5400. unsigned port;
  5401. bool secure;
  5402. getFileDafilesrvConfiguration(keyPairName, port, secure, *df);
  5403. StringBuffer metaInfo, expiryTime;
  5404. getFileMeta(metaInfo, expiryTime, fileName, fileDesc, udesc, req.getJobId(), keyPairName, req);
  5405. accessInfo.setMetaInfoBlob(metaInfo);
  5406. accessInfo.setExpiryTime(expiryTime);
  5407. accessInfo.setFileAccessPort(port);
  5408. accessInfo.setFileAccessSSL(secure);
  5409. StringBuffer userName;
  5410. if (udesc)
  5411. udesc->getUserName(userName);
  5412. LOG(daliAuditLogCat,",FileAccess,EspProcess,READ,%s,%s,%s,jobid=%s,expirySecs=%d", req.getCluster(),
  5413. userName.str(), fileName.str(), req.getJobId(), req.getExpirySeconds());
  5414. }
  5415. SecAccessFlags translateToSecAccessFlags(CSecAccessType from)
  5416. {
  5417. switch (from)
  5418. {
  5419. case CSecAccessType_Access:
  5420. return SecAccess_Access;
  5421. case CSecAccessType_Read:
  5422. return SecAccess_Read;
  5423. case CSecAccessType_Write:
  5424. return SecAccess_Write;
  5425. case CSecAccessType_Full:
  5426. return SecAccess_Full;
  5427. case CSecAccessType_None:
  5428. default:
  5429. return SecAccess_None;
  5430. }
  5431. }
  5432. bool CWsDfuEx::onDFUFileAccess(IEspContext &context, IEspDFUFileAccessRequest &req, IEspDFUFileAccessResponse &resp)
  5433. {
  5434. try
  5435. {
  5436. IConstDFUFileAccessRequestBase &requestBase = req.getRequestBase();
  5437. SecAccessFlags accessType = translateToSecAccessFlags(requestBase.getAccessType());
  5438. if (SecAccess_None == accessType)
  5439. {
  5440. context.setAuthStatus(AUTH_STATUS_NOACCESS);
  5441. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUFileAccess - Permission denied.");
  5442. }
  5443. context.ensureFeatureAccess(FEATURE_URL, accessType, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUFileAccess: Permission denied.");
  5444. if (isEmptyString(requestBase.getName()))
  5445. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No Name defined.");
  5446. StringBuffer userID;
  5447. context.getUserID(userID);
  5448. Owned<IUserDescriptor> userDesc;
  5449. if (!userID.isEmpty())
  5450. {
  5451. userDesc.setown(createUserDescriptor());
  5452. userDesc->set(userID.str(), context.queryPassword(), context.querySignature());
  5453. }
  5454. getFileAccess(context, userDesc, accessType, requestBase, resp.updateAccessInfo());
  5455. }
  5456. catch (IException *e)
  5457. {
  5458. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  5459. }
  5460. return true;
  5461. }
  5462. IGroup *CWsDfuEx::getDFUFileIGroup(const char *clusterName, ClusterType clusterType, const char *clusterTypeEx, StringArray &locations, StringBuffer &groupName)
  5463. {
  5464. GroupType groupType;
  5465. StringBuffer basedir;
  5466. getClusterGroupName(groupName, clusterName);
  5467. Owned<IGroup> groupFound = queryNamedGroupStore().lookup(groupName.str(), basedir, groupType);
  5468. if (!groupFound)
  5469. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed to get Group for Group %s.", groupName.str());
  5470. if (!locations.ordinality())
  5471. return groupFound.getClear();
  5472. StringBuffer locationStr;
  5473. SocketEndpointArray epa;
  5474. ForEachItemIn(i, locations)
  5475. {
  5476. SocketEndpoint ep(locations.item(i));
  5477. if (ep.isNull())
  5478. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid location '%s'.", locations.item(i));
  5479. epa.append(ep);
  5480. locationStr.append(locations.item(i)).append(";");
  5481. }
  5482. Owned<IGroup> group = createIGroup(epa);
  5483. if (group->equals(groupFound))
  5484. return group.getClear();
  5485. groupName.set(DFUFileCreate_GroupNamePrefix).append(hashc((unsigned char*) locationStr.str(), locationStr.length(), 0));
  5486. bool foundGroup = false;
  5487. unsigned groupNameLength = groupName.length();
  5488. while (true)
  5489. {
  5490. GroupType groupType;
  5491. StringBuffer basedir;
  5492. Owned<IGroup> groupFound = queryNamedGroupStore().lookup(groupName.str(), basedir, groupType);
  5493. if (!groupFound)
  5494. break;
  5495. if (group->equals(groupFound))
  5496. {
  5497. foundGroup = true;
  5498. ESPLOG(LogMax, "Found DFUFileIGroup %s", groupName.str());
  5499. break;
  5500. }
  5501. //The original group name is used by another group. Rename it to: 'original name + _ + a random number'.
  5502. //We have to check if the new name is also used by another group. If yes, rename it to:
  5503. //'the original name + _ + another random number' until we find out a name which is not used.
  5504. groupName.setLength(groupNameLength); //remove _rand if any
  5505. groupName.append("_").append(rand());
  5506. }
  5507. if (!foundGroup)
  5508. {
  5509. StringBuffer defaultDir;
  5510. if (!getConfigurationDirectory(nullptr, ConfigurationDirectoryForDataCategory, clusterTypeEx, groupName.str(), defaultDir))
  5511. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed to get ConfigurationDirectory: %s.", groupName.str());
  5512. GroupType grpType = (clusterType == ThorLCRCluster) ? grp_thor : ((clusterType == HThorCluster) ? grp_hthor : grp_roxie);
  5513. queryNamedGroupStore().add(groupName.str(), group, false, defaultDir.str(), grpType);
  5514. ESPLOG(LogMin, "DFUFileIGroup %s added", groupName.str());
  5515. }
  5516. return group.getClear();
  5517. }
  5518. void CWsDfuEx::exportRecordDefinitionBinaryType(const char *recordDefinition, MemoryBuffer &layoutBin)
  5519. {
  5520. MultiErrorReceiver errs;
  5521. Owned<IHqlExpression> expr = parseQuery(recordDefinition, &errs);
  5522. if (errs.errCount() > 0)
  5523. {
  5524. StringBuffer errorMsg;
  5525. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed in parsing ECL %s: %s.", recordDefinition, errs.toString(errorMsg).str());
  5526. }
  5527. if (!expr)
  5528. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed in parsing ECL: %s.", recordDefinition);
  5529. if (!exportBinaryType(layoutBin, expr, false))
  5530. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed in exportBinaryType.");
  5531. }
  5532. void CWsDfuEx::getFileAccessBeforePublish(IEspContext &context, const char *fileName, const char *cluster,
  5533. const char *jobId, MemoryBuffer& layoutBin, IFileDescriptor *fileDesc, IUserDescriptor *udesc,
  5534. IConstDFUFileAccessRequestBase &req, IEspDFUFileCreateResponse &resp)
  5535. {
  5536. IEspDFUFileAccessInfo &accessInfo = resp.updateAccessInfo();
  5537. getFilePartsInfo(context, fileDesc, fileDesc->numParts(), true, accessInfo);
  5538. StringBuffer keyPairName;
  5539. unsigned port;
  5540. bool secure;
  5541. getFileDafilesrvConfiguration(keyPairName, port, secure, cluster);
  5542. StringBuffer metaInfo, expiryTime;
  5543. getFileMeta(metaInfo, expiryTime, fileName, fileDesc, udesc, jobId, keyPairName, req);
  5544. accessInfo.setMetaInfoBlob(metaInfo);
  5545. accessInfo.setExpiryTime(expiryTime);
  5546. if (layoutBin.length() == 0)
  5547. {
  5548. if (!req.getReturnJsonTypeInfo() && !req.getReturnBinTypeInfo())
  5549. return;
  5550. resp.setWarning("RecordTypeInfoBin or RecordTypeInfoJson requested, but no type info found from ECLRecordDefinition");
  5551. }
  5552. if (req.getReturnJsonTypeInfo())
  5553. {
  5554. StringBuffer jsonLayout;
  5555. Owned<IRtlFieldTypeDeserializer> deserializer(createRtlFieldTypeDeserializer());
  5556. const RtlTypeInfo *typeInfo = deserializer->deserialize(layoutBin);
  5557. dumpTypeInfo(jsonLayout, typeInfo);
  5558. if (jsonLayout.length())
  5559. accessInfo.setRecordTypeInfoJson(jsonLayout.str());
  5560. }
  5561. if (req.getReturnBinTypeInfo())
  5562. {
  5563. MemoryBuffer binLayout;
  5564. layoutBin.swapWith(binLayout);
  5565. if (binLayout.length())
  5566. accessInfo.setRecordTypeInfoBin(binLayout);
  5567. }
  5568. }
  5569. bool CWsDfuEx::onDFUFileCreate(IEspContext &context, IEspDFUFileCreateRequest &req, IEspDFUFileCreateResponse &resp)
  5570. {
  5571. try
  5572. {
  5573. IConstDFUFileAccessRequestBase &requestBase = req.getRequestBase();
  5574. SecAccessFlags accessType = translateToSecAccessFlags(requestBase.getAccessType());
  5575. if (SecAccess_None == accessType)
  5576. {
  5577. context.setAuthStatus(AUTH_STATUS_NOACCESS);
  5578. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUFileCreate - Permission denied.");
  5579. }
  5580. context.ensureFeatureAccess(FEATURE_URL, accessType, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUFileCreate: Permission denied.");
  5581. const char *fileName = requestBase.getName();
  5582. const char *clusterName = requestBase.getCluster();
  5583. const char *recordDefinition = req.getECLRecordDefinition();
  5584. if (isEmptyString(fileName))
  5585. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No Name defined.");
  5586. if (isEmptyString(clusterName))
  5587. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No Cluster defined.");
  5588. if (isEmptyString(recordDefinition))
  5589. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No ECLRecordDefinition defined.");
  5590. ClusterType clusterType = getClusterTypeByClusterName(clusterName);
  5591. if (clusterType == NoCluster)
  5592. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found.", clusterName);
  5593. const char *clusterTypeEx = clusterTypeString(clusterType, false);
  5594. StringBuffer groupName;
  5595. Owned<IGroup> group = getDFUFileIGroup(clusterName, clusterType, clusterTypeEx, req.getPartLocations(), groupName);
  5596. MemoryBuffer layoutBin;
  5597. exportRecordDefinitionBinaryType(recordDefinition, layoutBin);
  5598. StringBuffer userId;
  5599. Owned<IUserDescriptor> userDesc;
  5600. context.getUserID(userId);
  5601. if (!userId.isEmpty())
  5602. {
  5603. userDesc.setown(createUserDescriptor());
  5604. userDesc->set(userId.str(), context.queryPassword(), context.querySignature());
  5605. }
  5606. StringBuffer tempFileName = fileName;
  5607. tempFileName.append(DFUFileCreate_FileNamePostfix);
  5608. StringBuffer jobId = requestBase.getJobId();
  5609. if (jobId.isEmpty())
  5610. jobId.appendf("Create %s on %s", tempFileName.str(), clusterName);
  5611. Owned<IFileDescriptor> fileDesc = createFileDescriptor(tempFileName, clusterTypeEx, groupName, group);
  5612. fileDesc->queryProperties().setProp("@job", jobId);
  5613. if (!userId.isEmpty())
  5614. fileDesc->queryProperties().setProp("@owner", userId);
  5615. Owned<IDistributedFile> file = queryDistributedFileDirectory().createNew(fileDesc);
  5616. file->setAccessed();
  5617. file->setECL(recordDefinition);
  5618. file->queryAttributes().setPropBin("_rtlType", layoutBin.length(), layoutBin.toByteArray());
  5619. file->queryAttributes().setPropInt64("@recordCount", 0);
  5620. file->queryAttributes().setPropInt64("@size", 0);
  5621. getFileAccessBeforePublish(context, tempFileName, clusterName, jobId, layoutBin, fileDesc, userDesc, requestBase, resp);
  5622. //create FileId
  5623. StringBuffer fileID;
  5624. fileID.set(groupName.str()).append(DFUFileIdSeparator).append(clusterName).append(DFUFileIdSeparator).append(tempFileName.str());
  5625. resp.setFileId(fileID.str());
  5626. }
  5627. catch (IException *e)
  5628. {
  5629. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  5630. }
  5631. return true;
  5632. }
  5633. bool CWsDfuEx::onDFUFilePublish(IEspContext &context, IEspDFUFilePublishRequest &req, IEspDFUFilePublishResponse &resp)
  5634. {
  5635. try
  5636. {
  5637. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Write, ECLWATCH_DFU_ACCESS_DENIED, "WsDfu::DFUFilePublish: Permission denied.");
  5638. const char *fileId = req.getFileId();
  5639. const char *recordDefinition = req.getECLRecordDefinition();
  5640. if (isEmptyString(fileId))
  5641. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No FileId defined.");
  5642. if (isEmptyString(recordDefinition))
  5643. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No ECLRecordDefinition defined.");
  5644. StringArray fileIdItems;
  5645. fileIdItems.appendList(fileId, DFUFileIdSeparator);
  5646. if (fileIdItems.ordinality() < 3)
  5647. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid FileId '%s'.", fileId);
  5648. const char *groupName = fileIdItems.item(0);
  5649. const char *clusterName = fileIdItems.item(1);
  5650. const char *tempFileName = fileIdItems.item(2);
  5651. if (isEmptyString(groupName))
  5652. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid FileId: empty groupName.");
  5653. if (isEmptyString(clusterName))
  5654. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid FileId: empty clusterName.");
  5655. if (isEmptyString(tempFileName))
  5656. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid FileId: empty FileName.");
  5657. StringBuffer userId, newFileName;
  5658. newFileName.set(tempFileName);
  5659. if (newFileName.length() <= strlen(DFUFileCreate_FileNamePostfix))
  5660. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid FileId: cannot read FileName from %s.", tempFileName);
  5661. newFileName.setLength(newFileName.length() - strlen(DFUFileCreate_FileNamePostfix)); //remove DFUFileCreate_FileNamePostfix
  5662. ClusterType clusterType = getClusterTypeByClusterName(clusterName);
  5663. if (clusterType == NoCluster)
  5664. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found.", clusterName);
  5665. const char *clusterTypeEx = clusterTypeString(clusterType, false);
  5666. GroupType groupType;
  5667. StringBuffer basedir;
  5668. Owned<IGroup> group = queryNamedGroupStore().lookup(groupName, basedir, groupType);
  5669. if (!group)
  5670. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST, "Failed to find group %s.", groupName);
  5671. MemoryBuffer layoutBin;
  5672. exportRecordDefinitionBinaryType(recordDefinition, layoutBin);
  5673. Owned<IUserDescriptor> userDesc;
  5674. context.getUserID(userId);
  5675. if (!userId.isEmpty())
  5676. {
  5677. userDesc.setown(createUserDescriptor());
  5678. userDesc->set(userId.str(), context.queryPassword(), context.querySignature());
  5679. }
  5680. VStringBuffer jobId("Publish %s on %s", newFileName.str(), clusterName);
  5681. Owned<IFileDescriptor> fileDesc = createFileDescriptor(tempFileName, clusterTypeEx, groupName, group);
  5682. Owned<IDistributedFile> oldFile = queryDistributedFileDirectory().createNew(fileDesc);
  5683. oldFile->validate();
  5684. if (!oldFile->renamePhysicalPartFiles(newFileName.str(), nullptr, nullptr, fileDesc->queryDefaultDir()))
  5685. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST, "Failed in renamePhysicalPartFiles %s.", newFileName.str());
  5686. Owned<IFileDescriptor> newFileDesc = createFileDescriptor(newFileName, clusterTypeEx, groupName, group);
  5687. newFileDesc->queryProperties().setProp("@job", jobId);
  5688. if (!userId.isEmpty())
  5689. newFileDesc->queryProperties().setProp("@owner", userId);
  5690. Owned<IDistributedFile> newFile = queryDistributedFileDirectory().createNew(newFileDesc);
  5691. newFile->setAccessed();
  5692. newFile->setECL(recordDefinition);
  5693. newFile->queryAttributes().setPropBin("_rtlType", layoutBin.length(), layoutBin.toByteArray());
  5694. if (!req.getRecordCount_isNull())
  5695. newFile->queryAttributes().setPropInt64("@recordCount", req.getRecordCount());
  5696. if (!req.getFileSize_isNull())
  5697. newFile->queryAttributes().setPropInt64("@size", req.getFileSize());
  5698. newFile->attach(newFileName.str(), userDesc);
  5699. LOG(daliAuditLogCat,",FileAccess,EspProcess,CREATED,%s,%s,%s", groupName, userId.str(), newFileName.str());
  5700. }
  5701. catch (IException *e)
  5702. {
  5703. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  5704. }
  5705. return true;
  5706. }
  5707. //////////////////////HPCC Browser//////////////////////////