ws_dfuService.cpp 209 KB

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