cl5_api.c 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651
  1. /** BEGIN COPYRIGHT BLOCK
  2. * This Program is free software; you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation; version 2 of the License.
  5. *
  6. * This Program is distributed in the hope that it will be useful, but WITHOUT
  7. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. *
  10. * You should have received a copy of the GNU General Public License along with
  11. * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
  12. * Place, Suite 330, Boston, MA 02111-1307 USA.
  13. *
  14. * In addition, as a special exception, Red Hat, Inc. gives You the additional
  15. * right to link the code of this Program with code not covered under the GNU
  16. * General Public License ("Non-GPL Code") and to distribute linked combinations
  17. * including the two, subject to the limitations in this paragraph. Non-GPL Code
  18. * permitted under this exception must only link to the code of this Program
  19. * through those well defined interfaces identified in the file named EXCEPTION
  20. * found in the source code files (the "Approved Interfaces"). The files of
  21. * Non-GPL Code may instantiate templates or use macros or inline functions from
  22. * the Approved Interfaces without causing the resulting work to be covered by
  23. * the GNU General Public License. Only Red Hat, Inc. may make changes or
  24. * additions to the list of Approved Interfaces. You must obey the GNU General
  25. * Public License in all respects for all of the Program code and other code used
  26. * in conjunction with the Program except the Non-GPL Code covered by this
  27. * exception. If you modify this file, you may extend this exception to your
  28. * version of the file, but you are not obligated to do so. If you do not wish to
  29. * provide this exception without modification, you must delete this exception
  30. * statement from your version and license this file solely under the GPL without
  31. * exception.
  32. *
  33. *
  34. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  35. * Copyright (C) 2005 Red Hat, Inc.
  36. * Copyright (C) 2010 Hewlett-Packard Development Company, L.P.
  37. * All rights reserved.
  38. * END COPYRIGHT BLOCK **/
  39. #ifdef HAVE_CONFIG_H
  40. # include <config.h>
  41. #endif
  42. /* cl5_api.c - implementation of 5.0 style changelog API */
  43. #include <unistd.h>
  44. #include <errno.h>
  45. #include <sys/stat.h>
  46. #if defined( OS_solaris ) || defined( hpux )
  47. #include <sys/types.h>
  48. #include <sys/statvfs.h>
  49. #endif
  50. #if defined( linux )
  51. #include <sys/vfs.h>
  52. #endif
  53. #include "cl5.h"
  54. #include "cl_crypt.h"
  55. #include "plhash.h"
  56. #include "plstr.h"
  57. #include "db.h"
  58. #include "cl5_clcache.h" /* To use the Changelog Cache */
  59. #include "repl5.h" /* for agmt_get_consumer_rid() */
  60. #define GUARDIAN_FILE "guardian" /* name of the guardian file */
  61. #define VERSION_FILE "DBVERSION" /* name of the version file */
  62. #define V_5 5 /* changelog entry version */
  63. #define CHUNK_SIZE 64*1024
  64. #define DBID_SIZE 64
  65. #define FILE_SEP "_" /* separates parts of the db file name */
  66. #define T_CSNSTR "csn"
  67. #define T_UNIQUEIDSTR "nsuniqueid"
  68. #define T_PARENTIDSTR "parentuniqueid"
  69. #define T_NEWSUPERIORDNSTR "newsuperiordn"
  70. #define T_NEWSUPERIORIDSTR "newsuperioruniqueid"
  71. #define T_REPLGEN "replgen"
  72. #define ENTRY_COUNT_TIME 111 /* this time is used to construct csn
  73. used to store/retrieve entry count */
  74. #define PURGE_RUV_TIME 222 /* this time is used to construct csn
  75. used to store purge RUV vector */
  76. #define MAX_RUV_TIME 333 /* this time is used to construct csn
  77. used to store upper boundary RUV vector */
  78. #define DB_EXTENSION_DB3 "db3"
  79. #define DB_EXTENSION_DB4 "db4"
  80. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 5000
  81. #define DB_EXTENSION "db"
  82. #else
  83. #define DB_EXTENSION "db4"
  84. #endif
  85. #define HASH_BACKETS_COUNT 16 /* number of buckets in a hash table */
  86. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 4100
  87. #define USE_DB_TXN 1 /* use transactions */
  88. #define DEFAULT_DB_ENV_OP_FLAGS DB_AUTO_COMMIT
  89. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR <= 4300
  90. /* we are enabling transactions everywhere - since we are opening databases
  91. with DB_AUTO_COMMIT we must either open and pass a valid txn handle to
  92. all operations that modify the database (put, del) or we must pass the
  93. DB_AUTO_COMMIT flag to those operations */
  94. #define DEFAULT_DB_OP_FLAGS(txn) (txn ? 0 : DB_AUTO_COMMIT)
  95. #else
  96. #define DEFAULT_DB_OP_FLAGS(txn) 0
  97. #endif
  98. #define DB_OPEN(oflags, db, txnid, file, database, type, flags, mode, rval) \
  99. { \
  100. if (((oflags) & DB_INIT_TXN) && ((oflags) & DB_INIT_LOG)) \
  101. { \
  102. (rval) = (db)->open((db), (txnid), (file), (database), (type), (flags)|DB_AUTO_COMMIT, (mode)); \
  103. } \
  104. else \
  105. { \
  106. (rval) = (db)->open((db), (txnid), (file), (database), (type), (flags), (mode)); \
  107. } \
  108. }
  109. #else /* older then db 41 */
  110. #define DEFAULT_DB_OP_FLAGS(txn) 0
  111. #define DB_OPEN(oflags, db, txnid, file, database, type, flags, mode, rval) \
  112. (rval) = (db)->open((db), (file), (database), (type), (flags), (mode))
  113. #endif
  114. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 4000
  115. #define DB_ENV_SET_REGION_INIT(env) (env)->set_flags((env), DB_REGION_INIT, 1)
  116. #define TXN_BEGIN(env, parent_txn, tid, flags) \
  117. (env)->txn_begin((env), (parent_txn), (tid), (flags))
  118. #define TXN_COMMIT(txn, flags) (txn)->commit((txn), (flags))
  119. #define TXN_ABORT(txn) (txn)->abort(txn)
  120. #define MEMP_STAT(env, gsp, fsp, flags, malloc) \
  121. (env)->memp_stat((env), (gsp), (fsp), (flags))
  122. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 4400 /* db4.4 or later */
  123. #define DB_ENV_SET_TAS_SPINS(env, tas_spins) \
  124. (env)->mutex_set_tas_spins((env), (tas_spins))
  125. #else
  126. #define DB_ENV_SET_TAS_SPINS(env, tas_spins) \
  127. (env)->set_tas_spins((env), (tas_spins))
  128. #endif
  129. #else /* older than db 4.0 */
  130. #define DB_ENV_SET_REGION_INIT(env) db_env_set_region_init(1)
  131. #define DB_ENV_SET_TAS_SPINS(env, tas_spins) \
  132. db_env_set_tas_spins((tas_spins))
  133. #define TXN_BEGIN(env, parent_txn, tid, flags) \
  134. txn_begin((env), (parent_txn), (tid), (flags))
  135. #define TXN_COMMIT(txn, flags) txn_commit((txn), (flags))
  136. #define TXN_ABORT(txn) txn_abort((txn))
  137. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 3300
  138. #define MEMP_STAT(env, gsp, fsp, flags, malloc) memp_stat((env), (gsp), (fsp))
  139. #else /* older than db 3.3 */
  140. #define MEMP_STAT(env, gsp, fsp, flags, malloc) \
  141. memp_stat((env), (gsp), (fsp), (malloc))
  142. #endif
  143. #endif
  144. /*
  145. * The defult thread stacksize for nspr21 is 64k. For OSF, we require
  146. * a larger stacksize as actual storage allocation is higher i.e
  147. * pointers are allocated 8 bytes but lower 4 bytes are used.
  148. * The value 0 means use the default stacksize.
  149. */
  150. #if defined (OSF1) || defined (__LP64__) || defined (_LP64) /* 64-bit architectures need bigger stacks */
  151. #if defined(__hpux) && defined(__ia64)
  152. #define DEFAULT_THREAD_STACKSIZE 524288L
  153. #else
  154. #define DEFAULT_THREAD_STACKSIZE 131072L
  155. #endif
  156. #else
  157. #define DEFAULT_THREAD_STACKSIZE 0
  158. #endif
  159. #ifdef _WIN32
  160. #define FILE_CREATE_MODE S_IREAD | S_IWRITE
  161. #define DIR_CREATE_MODE 0755
  162. #else /* _WIN32 */
  163. #define FILE_CREATE_MODE S_IRUSR | S_IWUSR
  164. #define DIR_CREATE_MODE 0755
  165. #endif
  166. #define NO_DISK_SPACE 1024
  167. #define MIN_DISK_SPACE 10485760 /* 10 MB */
  168. /***** Data Definitions *****/
  169. /* possible changelog open modes */
  170. typedef enum
  171. {
  172. CL5_OPEN_NONE, /* nothing specified */
  173. CL5_OPEN_NORMAL, /* open for normal read/write use */
  174. CL5_OPEN_RESTORE_RECOVER, /* restore from archive and recover */
  175. CL5_OPEN_RESTORE, /* restore, but no recovery */
  176. CL5_OPEN_LDIF2CL, /* open as part of ldif2cl: no locking,
  177. recovery, checkpointing */
  178. CL5_OPEN_CLEAN_RECOVER /* remove env after recover open (upgrade) */
  179. } CL5OpenMode;
  180. #define DB_FILE_DELETED 0x1
  181. #define DB_FILE_INIT 0x2
  182. /* this structure represents one changelog file, Each changelog file contains
  183. changes applied to a single backend. Files are named by the database id */
  184. typedef struct cl5dbfile
  185. {
  186. char *name; /* file name (with the extension) */
  187. char *replGen; /* replica generation of the data */
  188. char *replName; /* replica name */
  189. DB *db; /* db handle to the changelog file*/
  190. int entryCount; /* number of entries in the file */
  191. int flags; /* currently used to mark the file as deleted
  192. * or as initialized */
  193. RUV *purgeRUV; /* ruv to which the file has been purged */
  194. RUV *maxRUV; /* ruv that marks the upper boundary of the data */
  195. char *semaName; /* semaphore name */
  196. PRSem *sema; /* semaphore for max concurrent cl writes */
  197. }CL5DBFile;
  198. /* structure that allows to iterate through entries to be sent to a consumer
  199. that originated on a particular supplier. */
  200. struct cl5replayiterator
  201. {
  202. Object *fileObj;
  203. CLC_Buffer *clcache; /* changelog cache */
  204. ReplicaId consumerRID; /* consumer's RID */
  205. const RUV *consumerRuv; /* consumer's update vector */
  206. Object *supplierRuvObj;/* supplier's update vector object */
  207. };
  208. typedef struct cl5iterator
  209. {
  210. DBC *cursor; /* current position in the db file */
  211. Object *file; /* handle to release db file object */
  212. }CL5Iterator;
  213. /* changelog trimming configuration */
  214. typedef struct cl5trim
  215. {
  216. time_t maxAge; /* maximum entry age in seconds */
  217. int maxEntries; /* maximum number of entries across all changelog files */
  218. PRLock* lock; /* controls access to trimming configuration */
  219. } CL5Trim;
  220. /* this structure defines 5.0 changelog internals */
  221. typedef struct cl5desc
  222. {
  223. char *dbDir; /* absolute path to changelog directory */
  224. DB_ENV *dbEnv; /* db environment shared by all db files */
  225. int dbEnvOpenFlags;/* openflag used for env->open */
  226. Objset *dbFiles; /* ref counted set of changelog files (CL5DBFile) */
  227. PRLock *fileLock; /* ensures that changelog file is not added twice */
  228. CL5OpenMode dbOpenMode; /* how we open db */
  229. CL5DBConfig dbConfig; /* database configuration params */
  230. CL5Trim dbTrim; /* trimming parameters */
  231. CL5State dbState; /* changelog current state */
  232. Slapi_RWLock *stLock; /* lock that controls access to the changelog state */
  233. PRBool dbRmOnClose;/* indicates whether changelog should be removed when
  234. it is closed */
  235. PRBool fatalError; /* bad stuff happened like out of disk space; don't
  236. write guardian file on close - UnUsed so far */
  237. int threadCount;/* threads that globally access changelog like
  238. deadlock detection, etc. */
  239. PRLock *clLock; /* Lock associated to clVar, used to notify threads on close */
  240. PRCondVar *clCvar; /* Condition Variable used to notify threads on close */
  241. void *clcrypt_handle; /* for cl encryption */
  242. } CL5Desc;
  243. typedef void (*VFP)(void *);
  244. /***** Global Variables *****/
  245. static CL5Desc s_cl5Desc;
  246. /***** Forward Declarations *****/
  247. /* changelog initialization and cleanup */
  248. static int _cl5Open (const char *dir, const CL5DBConfig *config, CL5OpenMode openMode);
  249. static int _cl5AppInit (void);
  250. static int _cl5DBOpen (void);
  251. static void _cl5SetDefaultDBConfig ();
  252. static void _cl5SetDBConfig (const CL5DBConfig *config);
  253. static int _cl5CheckDBVersion ();
  254. static int _cl5ReadDBVersion (const char *dir, char *clVersion, int buflen);
  255. static int _cl5WriteDBVersion ();
  256. static void _cl5Close ();
  257. static int _cl5Delete (const char *dir, PRBool rmDir);
  258. static void _cl5DBClose ();
  259. /* thread management */
  260. static int _cl5DispatchDBThreads ();
  261. static int _cl5AddThread ();
  262. static void _cl5RemoveThread ();
  263. /* functions that work with individual changelog files */
  264. static int _cl5NewDBFile (const char *replName, const char *replGen, CL5DBFile** dbFile);
  265. static int _cl5DBOpenFile (Object *replica, Object **obj, PRBool checkDups);
  266. static int _cl5DBOpenFileByReplicaName (const char *replName, const char *replGen,
  267. Object **obj, PRBool checkDups);
  268. static void _cl5DBCloseFile (void **data);
  269. static void _cl5DBDeleteFile (Object *obj);
  270. static void _cl5DBFileInitialized (Object *obj);
  271. static int _cl5GetDBFile (Object *replica, Object **obj);
  272. static int _cl5GetDBFileByReplicaName (const char *replName, const char *replGen,
  273. Object **obj);
  274. static int _cl5AddDBFile (CL5DBFile *file, Object **obj);
  275. static int _cl5CompareDBFile (Object *el1, const void *el2);
  276. static char* _cl5Replica2FileName (Object *replica);
  277. static char* _cl5MakeFileName (const char *replName, const char *replGen);
  278. static PRBool _cl5FileName2Replica (const char *fileName, Object **replica);
  279. static int _cl5ExportFile (PRFileDesc *prFile, Object *obj);
  280. static PRBool _cl5ReplicaInList (Object *replica, Object **replicas);
  281. /* data storage and retrieval */
  282. static int _cl5Entry2DBData (const CL5Entry *entry, char **data, PRUint32 *len);
  283. static int _cl5WriteOperation(const char *replName, const char *replGen,
  284. const slapi_operation_parameters *op, PRBool local);
  285. static int _cl5WriteOperationTxn(const char *replName, const char *replGen,
  286. const slapi_operation_parameters *op, PRBool local, void *txn);
  287. static int _cl5GetFirstEntry (Object *obj, CL5Entry *entry, void **iterator, DB_TXN *txnid);
  288. static int _cl5GetNextEntry (CL5Entry *entry, void *iterator);
  289. static int _cl5CurrentDeleteEntry (void *iterator);
  290. static PRBool _cl5IsValidIterator (const CL5Iterator *iterator);
  291. static int _cl5GetOperation (Object *replica, slapi_operation_parameters *op);
  292. static const char* _cl5OperationType2Str (int type);
  293. static int _cl5Str2OperationType (const char *str);
  294. static void _cl5WriteString (const char *str, char **buff);
  295. static void _cl5ReadString (char **str, char **buff);
  296. static void _cl5WriteMods (LDAPMod **mods, char **buff);
  297. static int _cl5WriteMod (LDAPMod *mod, char **buff);
  298. static int _cl5ReadMods (LDAPMod ***mods, char **buff);
  299. static int _cl5ReadMod (Slapi_Mod *mod, char **buff);
  300. static int _cl5GetModsSize (LDAPMod **mods);
  301. static int _cl5GetModSize (LDAPMod *mod);
  302. static void _cl5ReadBerval (struct berval *bv, char** buff);
  303. static void _cl5WriteBerval (struct berval *bv, char** buff);
  304. static int _cl5ReadBervals (struct berval ***bv, char** buff, unsigned int size);
  305. static int _cl5WriteBervals (struct berval **bv, char** buff, unsigned int *size);
  306. /* replay iteration */
  307. #ifdef FOR_DEBUGGING
  308. static PRBool _cl5ValidReplayIterator (const CL5ReplayIterator *iterator);
  309. #endif
  310. static int _cl5PositionCursorForReplay (ReplicaId consumerRID, const RUV *consumerRuv,
  311. Object *replica, Object *fileObject, CL5ReplayIterator **iterator);
  312. static int _cl5CheckMissingCSN (const CSN *minCsn, const RUV *supplierRUV, CL5DBFile *file);
  313. /* changelog trimming */
  314. static int _cl5TrimInit ();
  315. static void _cl5TrimCleanup ();
  316. static int _cl5TrimMain (void *param);
  317. static void _cl5DoTrimming (ReplicaId rid);
  318. static void _cl5TrimFile (Object *obj, long *numToTrim, ReplicaId cleaned_rid);
  319. static PRBool _cl5CanTrim (time_t time, long *numToTrim);
  320. static int _cl5ReadRUV (const char *replGen, Object *obj, PRBool purge);
  321. static int _cl5WriteRUV (CL5DBFile *file, PRBool purge);
  322. static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge);
  323. static int _cl5UpdateRUV (Object *obj, CSN *csn, PRBool newReplica, PRBool purge);
  324. static int _cl5GetRUV2Purge2 (Object *fileObj, RUV **ruv);
  325. void trigger_cl_trimming_thread(void *rid);
  326. /* bakup/recovery, import/export */
  327. static int _cl5LDIF2Operation (char *ldifEntry, slapi_operation_parameters *op,
  328. char **replGen);
  329. static int _cl5Operation2LDIF (const slapi_operation_parameters *op, const char *replGen,
  330. char **ldifEntry, PRInt32 *lenLDIF);
  331. /* entry count */
  332. static int _cl5GetEntryCount (CL5DBFile *file);
  333. static int _cl5WriteEntryCount (CL5DBFile *file);
  334. /* misc */
  335. static char* _cl5GetHelperEntryKey (int type, char *csnStr);
  336. static Object* _cl5GetReplica (const slapi_operation_parameters *op, const char* replGen);
  337. static int _cl5FileEndsWith(const char *filename, const char *ext);
  338. static PRLock *cl5_diskfull_lock = NULL;
  339. static int cl5_diskfull_flag = 0;
  340. static void cl5_set_diskfull();
  341. static void cl5_set_no_diskfull();
  342. /***** Module APIs *****/
  343. /* Name: cl5Init
  344. Description: initializes changelog module; must be called by a single thread
  345. before any other changelog function.
  346. Parameters: none
  347. Return: CL5_SUCCESS if function is successful;
  348. CL5_SYSTEM_ERROR error if NSPR call fails.
  349. */
  350. int cl5Init ()
  351. {
  352. s_cl5Desc.stLock = slapi_new_rwlock();
  353. if (s_cl5Desc.stLock == NULL)
  354. {
  355. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  356. "cl5Init: failed to create state lock; NSPR error - %d\n",
  357. PR_GetError ());
  358. return CL5_SYSTEM_ERROR;
  359. }
  360. if ((s_cl5Desc.clLock = PR_NewLock()) == NULL)
  361. {
  362. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  363. "cl5Init: failed to create on close lock; NSPR error - %d\n",
  364. PR_GetError ());
  365. return CL5_SYSTEM_ERROR;
  366. }
  367. if ((s_cl5Desc.clCvar = PR_NewCondVar(s_cl5Desc.clLock)) == NULL)
  368. {
  369. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  370. "cl5Init: failed to create on close cvar; NSPR error - %d\n",
  371. PR_GetError ());
  372. return CL5_SYSTEM_ERROR;
  373. }
  374. if (( clcache_init (&s_cl5Desc.dbEnv) != 0 )) {
  375. return CL5_SYSTEM_ERROR;
  376. }
  377. s_cl5Desc.dbState = CL5_STATE_CLOSED;
  378. s_cl5Desc.fatalError = PR_FALSE;
  379. s_cl5Desc.dbRmOnClose = PR_FALSE;
  380. s_cl5Desc.threadCount = 0;
  381. if (NULL == cl5_diskfull_lock)
  382. {
  383. cl5_diskfull_lock = PR_NewLock ();
  384. }
  385. return CL5_SUCCESS;
  386. }
  387. /* Name: cl5Cleanup
  388. Description: performs cleanup of the changelog module; must be called by a single
  389. thread; it closes changelog if it is still open.
  390. Parameters: none
  391. Return: none
  392. */
  393. void cl5Cleanup ()
  394. {
  395. /* close db if it is still open */
  396. if (s_cl5Desc.dbState == CL5_STATE_OPEN)
  397. {
  398. cl5Close ();
  399. }
  400. if (s_cl5Desc.stLock)
  401. slapi_destroy_rwlock (s_cl5Desc.stLock);
  402. s_cl5Desc.stLock = NULL;
  403. if (cl5_diskfull_lock)
  404. {
  405. PR_DestroyLock (cl5_diskfull_lock);
  406. cl5_diskfull_lock = NULL;
  407. }
  408. memset (&s_cl5Desc, 0, sizeof (s_cl5Desc));
  409. }
  410. /* Name: cl5Open
  411. Description: opens changelog; must be called after changelog is
  412. initialized using cl5Init. It is thread safe and the second
  413. call is ignored.
  414. Parameters: dir - changelog dir
  415. config - db configuration parameters; currently not used
  416. Return: CL5_SUCCESS if successfull;
  417. CL5_BAD_DATA if invalid directory is passed;
  418. CL5_BAD_STATE if changelog is not initialized;
  419. CL5_BAD_DBVERSION if dbversion file is missing or has unexpected data
  420. CL5_SYSTEM_ERROR if NSPR error occured (during db directory creation);
  421. CL5_MEMORY_ERROR if memory allocation fails;
  422. CL5_DB_ERROR if db initialization fails.
  423. */
  424. int cl5Open (const char *dir, const CL5DBConfig *config)
  425. {
  426. int rc;
  427. if (dir == NULL)
  428. {
  429. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "cl5Open: null directory\n");
  430. return CL5_BAD_DATA;
  431. }
  432. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  433. {
  434. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  435. "cl5Open: changelog is not initialized\n");
  436. return CL5_BAD_STATE;
  437. }
  438. /* prevent state from changing */
  439. slapi_rwlock_wrlock (s_cl5Desc.stLock);
  440. /* already open - ignore */
  441. if (s_cl5Desc.dbState == CL5_STATE_OPEN)
  442. {
  443. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  444. "cl5Open: changelog already opened; request ignored\n");
  445. rc = CL5_SUCCESS;
  446. goto done;
  447. }
  448. else if (s_cl5Desc.dbState != CL5_STATE_CLOSED)
  449. {
  450. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  451. "cl5Open: invalid state - %d\n", s_cl5Desc.dbState);
  452. rc = CL5_BAD_STATE;
  453. goto done;
  454. }
  455. rc = _cl5Open (dir, config, CL5_OPEN_NORMAL);
  456. if (rc != CL5_SUCCESS)
  457. {
  458. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  459. "cl5Open: failed to open changelog\n");
  460. goto done;
  461. }
  462. /* dispatch global threads like deadlock detection, trimming, etc */
  463. rc = _cl5DispatchDBThreads ();
  464. if (rc != CL5_SUCCESS)
  465. {
  466. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  467. "cl5Open: failed to start database monitoring threads\n");
  468. _cl5Close ();
  469. }
  470. else
  471. {
  472. s_cl5Desc.dbState = CL5_STATE_OPEN;
  473. clcache_set_config();
  474. /* Set the cl encryption algorithm (if configured) */
  475. rc = clcrypt_init(config, &s_cl5Desc.clcrypt_handle);
  476. }
  477. done:
  478. slapi_rwlock_unlock (s_cl5Desc.stLock);
  479. return rc;
  480. }
  481. /* Name: cl5Close
  482. Description: closes changelog; waits until all threads are done using changelog;
  483. call is ignored if changelog is already closed.
  484. Parameters: none
  485. Return: CL5_SUCCESS if successful;
  486. CL5_BAD_STATE if db is not in the open or closed state;
  487. CL5_SYSTEM_ERROR if NSPR call fails;
  488. CL5_DB_ERROR if db shutdown fails
  489. */
  490. int cl5Close ()
  491. {
  492. int rc = CL5_SUCCESS;
  493. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  494. {
  495. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  496. "cl5Close: changelog is not initialized\n");
  497. return CL5_BAD_STATE;
  498. }
  499. slapi_rwlock_wrlock (s_cl5Desc.stLock);
  500. /* already closed - ignore */
  501. if (s_cl5Desc.dbState == CL5_STATE_CLOSED)
  502. {
  503. slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl,
  504. "cl5Close: changelog closed; request ignored\n");
  505. slapi_rwlock_unlock (s_cl5Desc.stLock);
  506. return CL5_SUCCESS;
  507. }
  508. else if (s_cl5Desc.dbState != CL5_STATE_OPEN)
  509. {
  510. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  511. "cl5Close: invalid state - %d\n", s_cl5Desc.dbState);
  512. slapi_rwlock_unlock (s_cl5Desc.stLock);
  513. return CL5_BAD_STATE;
  514. }
  515. /* signal changelog closing to all threads */
  516. s_cl5Desc.dbState = CL5_STATE_CLOSING;
  517. PR_Lock(s_cl5Desc.clLock);
  518. PR_NotifyCondVar(s_cl5Desc.clCvar);
  519. PR_Unlock(s_cl5Desc.clLock);
  520. _cl5Close ();
  521. s_cl5Desc.dbState = CL5_STATE_CLOSED;
  522. slapi_rwlock_unlock (s_cl5Desc.stLock);
  523. return rc;
  524. }
  525. /* Name: cl5Delete
  526. Description: removes changelog; changelog must be in the closed state.
  527. Parameters: dir - changelog directory
  528. Return: CL5_SUCCESS if successful;
  529. CL5_BAD_STATE if the changelog is not in closed state;
  530. CL5_BAD_DATA if invalid directory supplied
  531. CL5_SYSTEM_ERROR if NSPR call fails
  532. */
  533. int cl5Delete (const char *dir)
  534. {
  535. int rc;
  536. if (dir == NULL)
  537. {
  538. slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl, "cl5Delete: null directory\n");
  539. return CL5_BAD_DATA;
  540. }
  541. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  542. {
  543. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  544. "cl5Delete: changelog is not initialized\n");
  545. return CL5_BAD_STATE;
  546. }
  547. slapi_rwlock_wrlock (s_cl5Desc.stLock);
  548. if (s_cl5Desc.dbState != CL5_STATE_CLOSED)
  549. {
  550. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  551. "cl5Delete: invalid state - %d\n", s_cl5Desc.dbState);
  552. slapi_rwlock_unlock (s_cl5Desc.stLock);
  553. return CL5_BAD_STATE;
  554. }
  555. rc = _cl5Delete (dir, PR_TRUE /* remove changelog dir */);
  556. if (rc != CL5_SUCCESS)
  557. {
  558. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  559. "cl5Delete: failed to remove changelog\n");
  560. }
  561. slapi_rwlock_unlock (s_cl5Desc.stLock);
  562. return rc;
  563. }
  564. /* Name: cl5DeleteDBSync
  565. Description: The same as cl5DeleteDB except the function does not return
  566. until the file is removed.
  567. */
  568. int cl5DeleteDBSync (Object *replica)
  569. {
  570. Object *obj;
  571. int rc;
  572. CL5DBFile *file;
  573. if (replica == NULL)
  574. {
  575. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  576. "cl5DeleteDBSync: invalid database id\n");
  577. return CL5_BAD_DATA;
  578. }
  579. /* changelog is not initialized */
  580. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  581. {
  582. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5DeleteDBSync: "
  583. "changelog is not initialized\n");
  584. return CL5_BAD_STATE;
  585. }
  586. /* make sure that changelog stays open while operation is in progress */
  587. rc = _cl5AddThread ();
  588. if (rc != CL5_SUCCESS)
  589. return rc;
  590. rc = _cl5GetDBFile (replica, &obj);
  591. if (rc == CL5_SUCCESS)
  592. {
  593. char *filename = NULL;
  594. file = (CL5DBFile*)object_get_data (obj);
  595. PR_ASSERT (file);
  596. /* file->name is freed in _cl5DBDeleteFile */
  597. filename = slapi_ch_strdup(file->name);
  598. _cl5DBDeleteFile (obj);
  599. /* wait until the file is gone */
  600. while (PR_Access (filename, PR_ACCESS_EXISTS) == PR_SUCCESS)
  601. {
  602. DS_Sleep (PR_MillisecondsToInterval(100));
  603. }
  604. slapi_ch_free_string(&filename);
  605. }
  606. else
  607. {
  608. Replica *r = (Replica*)object_get_data (replica);
  609. PR_ASSERT (r);
  610. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5DeleteDBSync: "
  611. "file for replica at (%s) not found\n",
  612. slapi_sdn_get_dn (replica_get_root (r)));
  613. }
  614. _cl5RemoveThread ();
  615. return rc;
  616. }
  617. /* Name: cl5GetUpperBoundRUV
  618. Description: retrieves vector for that represents the upper bound of the changes for a replica.
  619. Parameters: r - replica for which the purge vector is requested
  620. ruv - contains a copy of the purge ruv if function is successful;
  621. unchanged otherwise. It is responsibility of the caller to free
  622. the ruv when it is no longer is in use
  623. Return: CL5_SUCCESS if function is successful
  624. CL5_BAD_STATE if the changelog is not initialized;
  625. CL5_BAD_DATA - if NULL id is supplied
  626. CL5_NOTFOUND, if changelog file for replica is not found
  627. */
  628. int cl5GetUpperBoundRUV (Replica *r, RUV **ruv)
  629. {
  630. int rc;
  631. Object *r_obj, *file_obj;
  632. CL5DBFile *file;
  633. if (r == NULL || ruv == NULL)
  634. {
  635. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  636. "cl5GetUpperBoundRUV: invalid parameters\n");
  637. return CL5_BAD_DATA;
  638. }
  639. /* changelog is not initialized */
  640. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  641. {
  642. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetUpperBoundRUV: "
  643. "changelog is not initialized\n");
  644. return CL5_BAD_STATE;
  645. }
  646. /* make sure that changelog stays open while operation is in progress */
  647. rc = _cl5AddThread ();
  648. if (rc != CL5_SUCCESS)
  649. return rc;
  650. /* create a temporary replica object because of the interface we have */
  651. r_obj = object_new (r, NULL);
  652. rc = _cl5GetDBFile (r_obj, &file_obj);
  653. if (rc == CL5_SUCCESS)
  654. {
  655. file = (CL5DBFile*)object_get_data (file_obj);
  656. PR_ASSERT (file && file->maxRUV);
  657. *ruv = ruv_dup (file->maxRUV);
  658. object_release (file_obj);
  659. }
  660. else
  661. {
  662. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetUpperBoundRUV: "
  663. "could not find DB object for replica\n");
  664. }
  665. object_release (r_obj);
  666. _cl5RemoveThread ();
  667. return rc;
  668. }
  669. /* Name: cl5ExportLDIF
  670. Description: dumps changelog to an LDIF file; changelog can be open or closed.
  671. Parameters: clDir - changelog dir
  672. ldifFile - full path to ldif file to write
  673. replicas - optional list of replicas whose changes should be exported;
  674. if the list is NULL, entire changelog is exported.
  675. Return: CL5_SUCCESS if function is successfull;
  676. CL5_BAD_DATA if invalid parameter is passed;
  677. CL5_BAD_STATE if changelog is not initialized;
  678. CL5_DB_ERROR if db api fails;
  679. CL5_SYSTEM_ERROR if NSPR call fails;
  680. CL5_MEMORY_ERROR if memory allocation fials.
  681. */
  682. int cl5ExportLDIF (const char *ldifFile, Object **replicas)
  683. {
  684. int i;
  685. int rc;
  686. PRFileDesc *prFile = NULL;
  687. Object *obj;
  688. if (ldifFile == NULL)
  689. {
  690. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  691. "cl5ExportLDIF: null ldif file name\n");
  692. return CL5_BAD_DATA;
  693. }
  694. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  695. {
  696. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  697. "cl5ExportLDIF: changelog is not initialized\n");
  698. return CL5_BAD_STATE;
  699. }
  700. /* make sure that changelog is open while operation is in progress */
  701. rc = _cl5AddThread ();
  702. if (rc != CL5_SUCCESS)
  703. return rc;
  704. prFile = PR_Open (ldifFile, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0600);
  705. if (prFile == NULL)
  706. {
  707. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  708. "cl5ExportLDIF: failed to open (%s) file; NSPR error - %d\n",
  709. ldifFile, PR_GetError ());
  710. rc = CL5_SYSTEM_ERROR;
  711. goto done;
  712. }
  713. slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl,
  714. "cl5ExportLDIF: starting changelog export to (%s) ...\n", ldifFile);
  715. if (replicas) /* export only selected files */
  716. {
  717. for (i = 0; replicas[i]; i++)
  718. {
  719. rc = _cl5GetDBFile (replicas[i], &obj);
  720. if (rc == CL5_SUCCESS)
  721. {
  722. rc = _cl5ExportFile (prFile, obj);
  723. object_release (obj);
  724. }
  725. else
  726. {
  727. Replica *r = (Replica*)object_get_data (replicas[i]);
  728. PR_ASSERT (r);
  729. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "cl5ExportLDIF: "
  730. "failed to locate changelog file for replica at (%s)\n",
  731. slapi_sdn_get_dn (replica_get_root (r)));
  732. }
  733. }
  734. }
  735. else /* export all files */
  736. {
  737. for (obj = objset_first_obj(s_cl5Desc.dbFiles); obj;
  738. obj = objset_next_obj(s_cl5Desc.dbFiles, obj))
  739. {
  740. rc = _cl5ExportFile (prFile, obj);
  741. }
  742. }
  743. rc = CL5_SUCCESS;
  744. done:;
  745. _cl5RemoveThread ();
  746. if (rc == CL5_SUCCESS)
  747. slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl,
  748. "cl5ExportLDIF: changelog export is finished.\n");
  749. if (prFile)
  750. PR_Close (prFile);
  751. return rc;
  752. }
  753. /* Name: cl5ImportLDIF
  754. Description: imports ldif file into changelog; changelog must be in the closed state
  755. Parameters: clDir - changelog dir
  756. ldifFile - absolute path to the ldif file to import
  757. replicas - list of replicas whose data should be imported.
  758. Return: CL5_SUCCESS if function is successfull;
  759. CL5_BAD_DATA if invalid parameter is passed;
  760. CL5_BAD_STATE if changelog is open or not inititalized;
  761. CL5_DB_ERROR if db api fails;
  762. CL5_SYSTEM_ERROR if NSPR call fails;
  763. CL5_MEMORY_ERROR if memory allocation fials.
  764. */
  765. int
  766. cl5ImportLDIF (const char *clDir, const char *ldifFile, Object **replicas)
  767. {
  768. #if defined(USE_OPENLDAP)
  769. LDIFFP *file = NULL;
  770. int buflen;
  771. ldif_record_lineno_t lineno = 0;
  772. #else
  773. FILE *file = NULL;
  774. int lineno = 0;
  775. #endif
  776. int rc;
  777. char *buff = NULL;
  778. slapi_operation_parameters op;
  779. Object *prim_replica_obj = NULL;
  780. Object *replica_obj = NULL;
  781. Object *file_obj = NULL;
  782. Replica *prim_replica = NULL;
  783. char *replGen = NULL;
  784. CL5DBFile *dbfile = NULL;
  785. struct berval **purgevals = NULL;
  786. struct berval **maxvals = NULL;
  787. int purgeidx = 0;
  788. int maxidx = 0;
  789. int maxpurgesz = 0;
  790. int maxmaxsz = 0;
  791. int entryCount = 0;
  792. /* validate params */
  793. if (ldifFile == NULL)
  794. {
  795. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  796. "cl5ImportLDIF: null ldif file name\n");
  797. return CL5_BAD_DATA;
  798. }
  799. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  800. {
  801. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  802. "cl5ImportLDIF: changelog is not initialized\n");
  803. return CL5_BAD_STATE;
  804. }
  805. if (replicas == NULL)
  806. {
  807. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  808. "cl5ImportLDIF: null list of replicas\n");
  809. return CL5_BAD_DATA;
  810. }
  811. prim_replica_obj = replicas[0];
  812. if (NULL == prim_replica_obj)
  813. {
  814. /* Never happens for now. (see replica_execute_ldif2cl_task) */
  815. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  816. "cl5ImportLDIF: empty replica list\n");
  817. return CL5_BAD_DATA;
  818. }
  819. prim_replica = (Replica*)object_get_data(prim_replica_obj);
  820. /* make sure that nobody change changelog state while import is in progress */
  821. slapi_rwlock_wrlock (s_cl5Desc.stLock);
  822. /* make sure changelog is closed */
  823. if (s_cl5Desc.dbState != CL5_STATE_CLOSED)
  824. {
  825. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  826. "cl5ImportLDIF: invalid state - %d \n", s_cl5Desc.dbState);
  827. slapi_rwlock_unlock (s_cl5Desc.stLock);
  828. return CL5_BAD_STATE;
  829. }
  830. /* open LDIF file */
  831. #if defined(USE_OPENLDAP)
  832. file = ldif_open (ldifFile, "r");
  833. #else
  834. file = fopen (ldifFile, "r"); /* XXXggood Does fopen reliably work if > 255 files open? */
  835. #endif
  836. if (file == NULL)
  837. {
  838. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  839. "cl5ImportLDIF: failed to open (%s) ldif file; system error - %d\n",
  840. ldifFile, errno);
  841. rc = CL5_SYSTEM_ERROR;
  842. goto done;
  843. }
  844. /* remove changelog */
  845. rc = _cl5Delete (clDir, PR_FALSE);
  846. if (rc != CL5_SUCCESS)
  847. {
  848. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  849. "cl5ImportLDIF: failed to remove changelog\n");
  850. goto done;
  851. }
  852. /* open changelog */
  853. rc = _cl5Open (clDir, NULL, CL5_OPEN_LDIF2CL);
  854. if (rc != CL5_SUCCESS)
  855. {
  856. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  857. "cl5ImportLDIF: failed to open changelog\n");
  858. goto done;
  859. }
  860. s_cl5Desc.dbState = CL5_STATE_OPEN; /* force to change the state */
  861. /* read entries and write them to changelog */
  862. #if defined(USE_OPENLDAP)
  863. while (ldif_read_record( file, &lineno, &buff, &buflen ))
  864. #else
  865. while ((buff = ldif_get_entry( file, &lineno )) != NULL)
  866. #endif
  867. {
  868. rc = _cl5LDIF2Operation (buff, &op, &replGen);
  869. if (rc != CL5_SUCCESS)
  870. {
  871. /*
  872. * clpurgeruv: {replicageneration} 4d13a124000000010000
  873. * clpurgeruv: {replica 2 ldap://host:port}
  874. * clpurgeruv: {replica 1 ldap://host:port}
  875. * clmaxruv: {replicageneration} 4d13a124000000010000
  876. * clmaxruv: {replica 2} <mincsn> <maxcsn> <timestamp>
  877. * clmaxruv: {replica 1} <mincsn> <maxcsn> <timestamp>
  878. */
  879. char *line;
  880. char *next = buff;
  881. struct berval type, value;
  882. int freeval = 0;
  883. while ((line = ldif_getline(&next)) != NULL) {
  884. rc = slapi_ldif_parse_line(line, &type, &value, &freeval);
  885. /* ruv_dump (dbfile->purgeRUV, "clpurgeruv", prFile); */
  886. if (0 == strcasecmp (type.bv_val, "clpurgeruv")) {
  887. if (maxpurgesz < purgeidx + 2) {
  888. if (!maxpurgesz) {
  889. maxpurgesz = 4 * (purgeidx + 2);
  890. } else {
  891. maxpurgesz *= 2;
  892. }
  893. purgevals = (struct berval **)slapi_ch_realloc(
  894. (char *)purgevals,
  895. sizeof(struct berval *) * maxpurgesz);
  896. }
  897. purgevals[purgeidx++] = slapi_ch_bvdup(&value);
  898. purgevals[purgeidx] = NULL; /* make sure NULL terminated */
  899. }
  900. /* ruv_dump (dbfile->maxRUV, "clmaxruv", prFile); */
  901. else if (0 == strcasecmp (type.bv_val, "clmaxruv")) {
  902. if (maxmaxsz < maxidx + 2) {
  903. if (!maxmaxsz) {
  904. maxmaxsz = 4 * (maxidx + 2);
  905. } else {
  906. maxmaxsz *= 2;
  907. }
  908. maxvals = (struct berval **)slapi_ch_realloc(
  909. (char *)maxvals,
  910. sizeof(struct berval *) * maxmaxsz);
  911. }
  912. /* {replica #} min_csn csn [last_modified] */
  913. /* get rid of last_modified, if any */
  914. maxvals[maxidx++] = slapi_ch_bvdup(&value);
  915. maxvals[maxidx] = NULL; /* make sure NULL terminated */
  916. }
  917. if (freeval) {
  918. slapi_ch_free_string(&value.bv_val);
  919. }
  920. }
  921. slapi_ch_free_string(&buff);
  922. #if defined(USE_OPENLDAP)
  923. buflen = 0;
  924. #endif
  925. goto next;
  926. }
  927. slapi_ch_free_string(&buff);
  928. #if defined(USE_OPENLDAP)
  929. buflen = 0;
  930. #endif
  931. /* if we perform selective import, check if the operation should be wriiten to changelog */
  932. replica_obj = _cl5GetReplica (&op, replGen);
  933. if (replica_obj == NULL)
  934. {
  935. /*
  936. * changetype: delete
  937. * replgen: 4d13a124000000010000
  938. * csn: 4d23b909000000020000
  939. * nsuniqueid: 00000000-00000000-00000000-00000000
  940. * dn: cn=start iteration
  941. */
  942. rc = _cl5WriteOperation (replica_get_name(prim_replica),
  943. replGen, &op, 1);
  944. if (rc != CL5_SUCCESS)
  945. {
  946. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  947. "cl5ImportLDIF: "
  948. "failed to write operation to the changelog: "
  949. "type: %lu, dn: %s\n",
  950. op.operation_type, REPL_GET_DN(&op.target_address));
  951. slapi_ch_free_string(&replGen);
  952. operation_parameters_done (&op);
  953. goto done;
  954. }
  955. entryCount++;
  956. goto next;
  957. }
  958. if (!replicas || _cl5ReplicaInList (replica_obj, replicas))
  959. {
  960. /* write operation creates the file if it does not exist */
  961. rc = _cl5WriteOperation (replica_get_name ((Replica*)object_get_data(replica_obj)),
  962. replGen, &op, 1);
  963. if (rc != CL5_SUCCESS)
  964. {
  965. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  966. "cl5ImportLDIF: "
  967. "failed to write operation to the changelog: "
  968. "type: %lu, dn: %s\n",
  969. op.operation_type, REPL_GET_DN(&op.target_address));
  970. object_release (replica_obj);
  971. slapi_ch_free_string(&replGen);
  972. operation_parameters_done (&op);
  973. goto done;
  974. }
  975. entryCount++;
  976. }
  977. next:
  978. if (replica_obj) {
  979. object_release (replica_obj);
  980. }
  981. slapi_ch_free_string(&replGen);
  982. operation_parameters_done (&op);
  983. }
  984. /* Set RUVs and entry count */
  985. file_obj = objset_first_obj(s_cl5Desc.dbFiles);
  986. while (file_obj)
  987. {
  988. dbfile = (CL5DBFile *)object_get_data(file_obj);
  989. if (0 == strcasecmp(dbfile->replName, replica_get_name(prim_replica))) {
  990. break;
  991. }
  992. dbfile = NULL;
  993. file_obj = objset_next_obj(s_cl5Desc.dbFiles, file_obj);
  994. }
  995. if (dbfile) {
  996. if (purgeidx > 0) {
  997. ruv_destroy (&dbfile->purgeRUV);
  998. rc = ruv_init_from_bervals(purgevals, &dbfile->purgeRUV);
  999. }
  1000. if (maxidx > 0) {
  1001. ruv_destroy (&dbfile->maxRUV);
  1002. rc = ruv_init_from_bervals(maxvals, &dbfile->maxRUV);
  1003. }
  1004. dbfile->entryCount = entryCount;
  1005. }
  1006. if (file_obj) {
  1007. object_release (file_obj);
  1008. }
  1009. done:
  1010. for (purgeidx = 0; purgevals && purgevals[purgeidx]; purgeidx++) {
  1011. slapi_ch_bvfree(&purgevals[purgeidx]);
  1012. }
  1013. slapi_ch_free((void **)&purgevals);
  1014. for (maxidx = 0; maxvals && maxvals[maxidx]; maxidx++) {
  1015. slapi_ch_bvfree(&maxvals[maxidx]);
  1016. }
  1017. slapi_ch_free((void **)&maxvals);
  1018. if (file) {
  1019. #if defined(USE_OPENLDAP)
  1020. ldif_close(file);
  1021. #else
  1022. fclose(file);
  1023. #endif
  1024. }
  1025. if (CL5_STATE_OPEN == s_cl5Desc.dbState) {
  1026. _cl5Close ();
  1027. s_cl5Desc.dbState = CL5_STATE_CLOSED; /* force to change the state */
  1028. }
  1029. slapi_rwlock_unlock (s_cl5Desc.stLock);
  1030. return rc;
  1031. }
  1032. /* Name: cl5GetState
  1033. Description: returns database state
  1034. Parameters: none
  1035. Return: changelog state
  1036. */
  1037. int cl5GetState ()
  1038. {
  1039. return s_cl5Desc.dbState;
  1040. }
  1041. /* Name: cl5ConfigTrimming
  1042. Description: sets changelog trimming parameters; changelog must be open.
  1043. Parameters: maxEntries - maximum number of entries in the chnagelog (in all files);
  1044. maxAge - maximum entry age;
  1045. Return: CL5_SUCCESS if successful;
  1046. CL5_BAD_STATE if changelog is not open
  1047. */
  1048. int cl5ConfigTrimming (int maxEntries, const char *maxAge)
  1049. {
  1050. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  1051. {
  1052. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  1053. "cl5ConfigTrimming: changelog is not initialized\n");
  1054. return CL5_BAD_STATE;
  1055. }
  1056. /* make sure changelog is not closed while trimming configuration
  1057. is updated.*/
  1058. if (CL5_SUCCESS != _cl5AddThread ()) {
  1059. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  1060. "cl5ConfigTrimming: could not start changelog trimming thread\n");
  1061. return CL5_BAD_STATE;
  1062. }
  1063. PR_Lock (s_cl5Desc.dbTrim.lock);
  1064. if (maxAge)
  1065. {
  1066. /* don't ignore this argument */
  1067. if (strcmp (maxAge, CL5_STR_IGNORE) != 0)
  1068. {
  1069. s_cl5Desc.dbTrim.maxAge = age_str2time (maxAge);
  1070. }
  1071. }
  1072. else
  1073. {
  1074. /* unlimited */
  1075. s_cl5Desc.dbTrim.maxAge = 0;
  1076. }
  1077. if (maxEntries != CL5_NUM_IGNORE)
  1078. {
  1079. s_cl5Desc.dbTrim.maxEntries = maxEntries;
  1080. }
  1081. PR_Unlock (s_cl5Desc.dbTrim.lock);
  1082. _cl5RemoveThread ();
  1083. return CL5_SUCCESS;
  1084. }
  1085. /* Name: cl5GetOperation
  1086. Description: retireves operation specified by its csn and databaseid
  1087. Parameters: op - must contain csn and databaseid; the rest of data is
  1088. filled if function is successfull
  1089. Return: CL5_SUCCESS if function is successfull;
  1090. CL5_BAD_DATA if invalid op is passed;
  1091. CL5_BAD_STATE if db has not been initialized;
  1092. CL5_NOTFOUND if entry was not found;
  1093. CL5_DB_ERROR if any other db error occured;
  1094. CL5_BADFORMAT if db data format does not match entry format.
  1095. */
  1096. int cl5GetOperation (Object *replica, slapi_operation_parameters *op)
  1097. {
  1098. int rc;
  1099. char *agmt_name;
  1100. agmt_name = get_thread_private_agmtname();
  1101. if (replica == NULL)
  1102. {
  1103. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetOperation: NULL replica\n");
  1104. return CL5_BAD_DATA;
  1105. }
  1106. if (op == NULL)
  1107. {
  1108. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetOperation: NULL operation\n");
  1109. return CL5_BAD_DATA;
  1110. }
  1111. if (op->csn == NULL)
  1112. {
  1113. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "%s: cl5GetOperation: operation contains no CSN\n", agmt_name);
  1114. return CL5_BAD_DATA;
  1115. }
  1116. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  1117. {
  1118. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1119. "%s: cl5GetOperation: changelog is not initialized\n", agmt_name);
  1120. return CL5_BAD_STATE;
  1121. }
  1122. /* make sure that changelog is open while operation is in progress */
  1123. rc = _cl5AddThread ();
  1124. if (rc != CL5_SUCCESS)
  1125. return rc;
  1126. rc = _cl5GetOperation (replica, op);
  1127. _cl5RemoveThread ();
  1128. return rc;
  1129. }
  1130. /* Name: cl5GetFirstOperation
  1131. Description: retrieves first operation for a particular database
  1132. replica - replica for which the operation should be retrieved.
  1133. Parameters: op - buffer to store the operation;
  1134. iterator - to be passed to the call to cl5GetNextOperation
  1135. Return: CL5_SUCCESS, if successful
  1136. CL5_BADDATA, if operation is NULL
  1137. CL5_BAD_STATE, if changelog is not open
  1138. CL5_DB_ERROR, if db call fails
  1139. */
  1140. int cl5GetFirstOperation (Object *replica, slapi_operation_parameters *op, void **iterator)
  1141. {
  1142. int rc;
  1143. CL5Entry entry;
  1144. Object *obj;
  1145. char *agmt_name;
  1146. if (replica == NULL || op == NULL || iterator == NULL)
  1147. {
  1148. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1149. "cl5GetFirstOperation: invalid argument\n");
  1150. return CL5_BAD_DATA;
  1151. }
  1152. *iterator = NULL;
  1153. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  1154. {
  1155. agmt_name = get_thread_private_agmtname();
  1156. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1157. "%s: cl5GetFirstOperation: changelog is not initialized\n", agmt_name);
  1158. return CL5_BAD_STATE;
  1159. }
  1160. /* make sure that changelog stays open while operation is in progress */
  1161. rc = _cl5AddThread ();
  1162. if (rc != CL5_SUCCESS)
  1163. return rc;
  1164. rc = _cl5GetDBFile (replica, &obj);
  1165. if (rc != CL5_SUCCESS)
  1166. {
  1167. _cl5RemoveThread ();
  1168. return rc;
  1169. }
  1170. entry.op = op;
  1171. /* Callers of this function should cl5_operation_parameters_done(op) */
  1172. rc = _cl5GetFirstEntry (obj, &entry, iterator, NULL);
  1173. object_release (obj);
  1174. _cl5RemoveThread ();
  1175. return rc;
  1176. }
  1177. /* Name: cl5GetNextOperation
  1178. Description: retrieves the next op from the changelog as defined by the iterator;
  1179. changelog must be open.
  1180. Parameters: op - returned operation, if function is successful
  1181. iterator - in: identifies op to retrieve; out: identifies next op
  1182. Return: CL5_SUCCESS, if successful
  1183. CL5_BADDATA, if op is NULL
  1184. CL5_BAD_STATE, if changelog is not open
  1185. CL5_NOTFOUND, empty changelog
  1186. CL5_DB_ERROR, if db call fails
  1187. */
  1188. int cl5GetNextOperation (slapi_operation_parameters *op, void *iterator)
  1189. {
  1190. CL5Entry entry;
  1191. if (op == NULL || iterator == NULL || !_cl5IsValidIterator (iterator))
  1192. {
  1193. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1194. "cl5GetNextOperation: invalid argument\n");
  1195. return CL5_BAD_DATA;
  1196. }
  1197. if (s_cl5Desc.dbState != CL5_STATE_OPEN)
  1198. {
  1199. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1200. "cl5GetNextOperation: changelog is not open\n");
  1201. return CL5_BAD_STATE;
  1202. }
  1203. /* we don't need to increment thread count since cl5GetFirstOperation
  1204. locked the file through which we are iterating */
  1205. entry.op = op;
  1206. /* Callers of this function should cl5_operation_parameters_done(op) */
  1207. return _cl5GetNextEntry (&entry, iterator);
  1208. }
  1209. /* Name: cl5DestroyIterator
  1210. Description: destroys iterator once iteration through changelog is done
  1211. Parameters: iterator - iterator to destroy
  1212. Return: none
  1213. */
  1214. void cl5DestroyIterator (void *iterator)
  1215. {
  1216. CL5Iterator *it = (CL5Iterator*)iterator;
  1217. if (it == NULL)
  1218. return;
  1219. /* close cursor */
  1220. if (it->cursor)
  1221. it->cursor->c_close (it->cursor);
  1222. if (it->file)
  1223. object_release (it->file);
  1224. slapi_ch_free ((void**)&it);
  1225. }
  1226. /* Name: cl5WriteOperationTxn
  1227. Description: writes operation to changelog
  1228. Parameters: replName - name of the replica to which operation applies
  1229. replGen - replica generation for the operation
  1230. !!!Note that we pass name and generation rather than
  1231. replica object since generation can change while operation
  1232. is in progress (if the data is reloaded). !!!
  1233. op - operation to write
  1234. local - this is a non-replicated operation
  1235. txn - the transaction containing this operation
  1236. Return: CL5_SUCCESS if function is successfull;
  1237. CL5_BAD_DATA if invalid op is passed;
  1238. CL5_BAD_STATE if db has not been initialized;
  1239. CL5_MEMORY_ERROR if memory allocation failed;
  1240. CL5_DB_ERROR if any other db error occured;
  1241. */
  1242. int cl5WriteOperationTxn(const char *replName, const char *replGen,
  1243. const slapi_operation_parameters *op, PRBool local, void *txn)
  1244. {
  1245. int rc;
  1246. if (op == NULL)
  1247. {
  1248. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1249. "cl5WriteOperation: NULL operation passed\n");
  1250. return CL5_BAD_DATA;
  1251. }
  1252. if (!IsValidOperation (op))
  1253. {
  1254. return CL5_BAD_DATA;
  1255. }
  1256. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  1257. {
  1258. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1259. "cl5WriteOperation: changelog is not initialized\n");
  1260. return CL5_BAD_STATE;
  1261. }
  1262. /* make sure that changelog is open while operation is in progress */
  1263. rc = _cl5AddThread ();
  1264. if (rc != CL5_SUCCESS)
  1265. return rc;
  1266. rc = _cl5WriteOperationTxn(replName, replGen, op, local, txn);
  1267. /* update the upper bound ruv vector */
  1268. if (rc == CL5_SUCCESS)
  1269. {
  1270. Object *file_obj = NULL;
  1271. if ( _cl5GetDBFileByReplicaName (replName, replGen, &file_obj) == CL5_SUCCESS) {
  1272. rc = _cl5UpdateRUV (file_obj, op->csn, PR_FALSE, PR_FALSE);
  1273. object_release (file_obj);
  1274. }
  1275. }
  1276. _cl5RemoveThread ();
  1277. return rc;
  1278. }
  1279. /* Name: cl5WriteOperation
  1280. Description: writes operation to changelog
  1281. Parameters: replName - name of the replica to which operation applies
  1282. replGen - replica generation for the operation
  1283. !!!Note that we pass name and generation rather than
  1284. replica object since generation can change while operation
  1285. is in progress (if the data is reloaded). !!!
  1286. op - operation to write
  1287. local - this is a non-replicated operation
  1288. Return: CL5_SUCCESS if function is successfull;
  1289. CL5_BAD_DATA if invalid op is passed;
  1290. CL5_BAD_STATE if db has not been initialized;
  1291. CL5_MEMORY_ERROR if memory allocation failed;
  1292. CL5_DB_ERROR if any other db error occured;
  1293. */
  1294. int cl5WriteOperation(const char *replName, const char *replGen,
  1295. const slapi_operation_parameters *op, PRBool local)
  1296. {
  1297. return cl5WriteOperationTxn(replName, replGen, op, local, NULL);
  1298. }
  1299. /* Name: cl5CreateReplayIterator
  1300. Description: creates an iterator that allows to retrieve changes that should
  1301. to be sent to the consumer identified by ruv. The iteration is performed by
  1302. repeated calls to cl5GetNextOperationToReplay.
  1303. Parameters: replica - replica whose data we wish to iterate;
  1304. ruv - consumer ruv;
  1305. iterator - iterator to be passed to cl5GetNextOperationToReplay call
  1306. Return: CL5_SUCCESS, if function is successful;
  1307. CL5_MISSING_DATA, if data that should be in the changelog is missing
  1308. CL5_PURGED_DATA, if some data that consumer needs has been purged.
  1309. Note that the iterator can be non null if the supplier contains
  1310. some data that needs to be sent to the consumer
  1311. CL5_NOTFOUND if the consumer is up to data with respect to the supplier
  1312. CL5_BAD_DATA if invalid parameter is passed;
  1313. CL5_BAD_STATE if db has not been open;
  1314. CL5_DB_ERROR if any other db error occurred;
  1315. CL5_MEMORY_ERROR if memory allocation fails.
  1316. Algorithm: Build a list of csns from consumer's and supplier's ruv. For each element
  1317. of the consumer's ruv put max csn into the csn list. For each element
  1318. of the supplier's ruv not in the consumer's ruv put min csn from the
  1319. supplier's ruv into the list. The list contains, for each known replica,
  1320. the starting point for changes to be sent to the consumer.
  1321. Sort the list in ascending order.
  1322. Build a hash which contains, for each known replica, whether the
  1323. supplier can bring the consumer up to data with respect to that replica.
  1324. The hash is used to decide whether a change can be sent to the consumer
  1325. Find the replica with the smallest csn in the list for which
  1326. we can bring the consumer up to date.
  1327. Position the db cursor on the change entry that corresponds to this csn.
  1328. Hash entries are created for each replica traversed so far. sendChanges
  1329. flag is set to FALSE for all replicas except the last traversed.
  1330. */
  1331. int cl5CreateReplayIteratorEx (Private_Repl_Protocol *prp, const RUV *consumerRuv,
  1332. CL5ReplayIterator **iterator, ReplicaId consumerRID )
  1333. {
  1334. int rc;
  1335. Object *replica;
  1336. Object *obj = NULL;
  1337. replica = prp->replica_object;
  1338. if (replica == NULL || consumerRuv == NULL || iterator == NULL)
  1339. {
  1340. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1341. "cl5CreateReplayIteratorEx: invalid parameter\n");
  1342. return CL5_BAD_DATA;
  1343. }
  1344. *iterator = NULL;
  1345. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  1346. {
  1347. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1348. "cl5CreateReplayIteratorEx: changelog is not initialized\n");
  1349. return CL5_BAD_STATE;
  1350. }
  1351. /* make sure that changelog is open while operation is in progress */
  1352. rc = _cl5AddThread ();
  1353. if (rc != CL5_SUCCESS ) return rc;
  1354. rc = _cl5GetDBFile (replica, &obj);
  1355. if (rc == CL5_SUCCESS && obj)
  1356. {
  1357. /* iterate through the ruv in csn order to find first master for which
  1358. we can replay changes */
  1359. rc = _cl5PositionCursorForReplay (consumerRID, consumerRuv, replica, obj, iterator);
  1360. }
  1361. else
  1362. {
  1363. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1364. "cl5CreateReplayIteratorEx: could not find DB object for replica\n");
  1365. }
  1366. if (rc != CL5_SUCCESS)
  1367. {
  1368. if (obj) object_release (obj);
  1369. /* release the thread */
  1370. _cl5RemoveThread ();
  1371. }
  1372. return rc;
  1373. }
  1374. /* cl5CreateReplayIterator is now a wrapper for cl5CreateReplayIteratorEx */
  1375. int cl5CreateReplayIterator (Private_Repl_Protocol *prp, const RUV *consumerRuv,
  1376. CL5ReplayIterator **iterator)
  1377. {
  1378. /* DBDB : I thought it should be possible to refactor this like so, but it seems to not work.
  1379. Possibly the ordering of the calls is significant.
  1380. ReplicaId consumerRID = agmt_get_consumer_rid ( prp->agmt, prp->conn );
  1381. return cl5CreateReplayIteratorEx(prp,consumerRuv,iterator,consumerRID); */
  1382. int rc;
  1383. Object *replica;
  1384. Object *obj = NULL;
  1385. replica = prp->replica_object;
  1386. if (replica == NULL || consumerRuv == NULL || iterator == NULL)
  1387. {
  1388. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1389. "cl5CreateReplayIterator: invalid parameter\n");
  1390. return CL5_BAD_DATA;
  1391. }
  1392. *iterator = NULL;
  1393. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  1394. {
  1395. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1396. "cl5CreateReplayIterator: changelog is not initialized\n");
  1397. return CL5_BAD_STATE;
  1398. }
  1399. /* make sure that changelog is open while operation is in progress */
  1400. rc = _cl5AddThread ();
  1401. if (rc != CL5_SUCCESS ) return rc;
  1402. rc = _cl5GetDBFile (replica, &obj);
  1403. if (rc == CL5_SUCCESS && obj)
  1404. {
  1405. /* iterate through the ruv in csn order to find first master for which
  1406. we can replay changes */
  1407. ReplicaId consumerRID = agmt_get_consumer_rid ( prp->agmt, prp->conn );
  1408. rc = _cl5PositionCursorForReplay (consumerRID, consumerRuv, replica, obj, iterator);
  1409. }
  1410. else
  1411. {
  1412. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1413. "cl5CreateReplayIterator: could not find DB object for replica\n");
  1414. }
  1415. if (rc != CL5_SUCCESS)
  1416. {
  1417. if (obj) object_release (obj);
  1418. /* release the thread */
  1419. _cl5RemoveThread ();
  1420. }
  1421. return rc;
  1422. }
  1423. /* Name: cl5GetNextOperationToReplay
  1424. Description: retrieves next operation to be sent to a particular consumer and
  1425. that was created on a particular master. Consumer and master info
  1426. is encoded in the iterator parameter that must be created by call
  1427. to cl5CreateReplayIterator.
  1428. Parameters: iterator - iterator that identifies next entry to retrieve;
  1429. op - operation retrieved if function is successful
  1430. Return: CL5_SUCCESS if function is successfull;
  1431. CL5_BAD_DATA if invalid parameter is passed;
  1432. CL5_NOTFOUND if end of iteration list is reached
  1433. CL5_DB_ERROR if any other db error occured;
  1434. CL5_BADFORMAT if data in db is of unrecognized format;
  1435. CL5_MEMORY_ERROR if memory allocation fails.
  1436. Algorithm: Iterate through changelog entries until a change is found that
  1437. originated at the replica for which we are sending changes
  1438. (based on the information in the iteration hash) and
  1439. whose csn is larger than the csn already seen by the consumer
  1440. If change originated at the replica not in the hash,
  1441. determine whether we should send changes originated at the replica
  1442. and add replica entry into the hash. We can send the changes for
  1443. the replica if the current csn is smaller or equal to the csn
  1444. in the consumer's ruv (if present) or if it is equal to the min
  1445. csn in the supplier's ruv.
  1446. */
  1447. int
  1448. cl5GetNextOperationToReplay (CL5ReplayIterator *iterator, CL5Entry *entry)
  1449. {
  1450. CSN *csn;
  1451. char *key, *data;
  1452. size_t keylen, datalen;
  1453. char *agmt_name;
  1454. int rc = 0;
  1455. agmt_name = get_thread_private_agmtname();
  1456. if (entry == NULL)
  1457. {
  1458. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1459. "%s: cl5GetNextOperationToReplay: invalid parameter passed\n", agmt_name);
  1460. return CL5_BAD_DATA;
  1461. }
  1462. rc = clcache_get_next_change (iterator->clcache, (void **)&key, &keylen, (void **)&data, &datalen, &csn);
  1463. if (rc == DB_NOTFOUND)
  1464. {
  1465. /*
  1466. * Abort means we've figured out that we've passed the replica Min CSN,
  1467. * so we should stop looping through the changelog
  1468. */
  1469. return CL5_NOTFOUND;
  1470. }
  1471. if (rc != 0)
  1472. {
  1473. slapi_log_error(SLAPI_LOG_FATAL, NULL, "%s: cl5GetNextOperationToReplay: "
  1474. "failed to read next entry; DB error %d\n", agmt_name, rc);
  1475. return CL5_DB_ERROR;
  1476. }
  1477. if(is_cleaned_rid(csn_get_replicaid(csn))){
  1478. /*
  1479. * This operation is from a deleted replica. During the cleanallruv task the
  1480. * replicas are cleaned first before this instance is. This can cause the
  1481. * server to basically do a full update over and over. So we have to watch for
  1482. * this, and not send these operations out.
  1483. */
  1484. return CL5_IGNORE_OP;
  1485. }
  1486. /* there is an entry we should return */
  1487. /* Callers of this function should cl5_operation_parameters_done(op) */
  1488. if ( 0 != cl5DBData2Entry ( data, datalen, entry ) )
  1489. {
  1490. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  1491. "%s: cl5GetNextOperationToReplay: failed to format entry rc=%d\n", agmt_name, rc);
  1492. return rc;
  1493. }
  1494. return CL5_SUCCESS;
  1495. }
  1496. /* Name: cl5DestroyReplayIterator
  1497. Description: destorys iterator
  1498. Parameters: iterator - iterator to destory
  1499. Return: none
  1500. */
  1501. void cl5DestroyReplayIterator (CL5ReplayIterator **iterator)
  1502. {
  1503. if (iterator == NULL)
  1504. {
  1505. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1506. "cl5DestroyReplayIterator: invalid iterartor passed\n");
  1507. return;
  1508. }
  1509. clcache_return_buffer ( &(*iterator)->clcache );
  1510. if ((*iterator)->fileObj) {
  1511. object_release ((*iterator)->fileObj);
  1512. (*iterator)->fileObj = NULL;
  1513. }
  1514. /* release supplier's ruv */
  1515. if ((*iterator)->supplierRuvObj) {
  1516. object_release ((*iterator)->supplierRuvObj);
  1517. (*iterator)->supplierRuvObj = NULL;
  1518. }
  1519. slapi_ch_free ((void **)iterator);
  1520. /* this thread no longer holds a db reference, release it */
  1521. _cl5RemoveThread();
  1522. }
  1523. /* Name: cl5DeleteOnClose
  1524. Description: marks changelog for deletion when it is closed
  1525. Parameters: flag; if flag = 1 then delete else don't
  1526. Return: none
  1527. */
  1528. void cl5DeleteOnClose (PRBool rm)
  1529. {
  1530. s_cl5Desc.dbRmOnClose = rm;
  1531. }
  1532. /* Name: cl5GetDir
  1533. Description: returns changelog directory
  1534. Parameters: none
  1535. Return: copy of the directory; caller needs to free the string
  1536. */
  1537. char *cl5GetDir ()
  1538. {
  1539. if (s_cl5Desc.dbDir == NULL)
  1540. {
  1541. return NULL;
  1542. }
  1543. else
  1544. {
  1545. return slapi_ch_strdup (s_cl5Desc.dbDir);
  1546. }
  1547. }
  1548. /* Name: cl5Exist
  1549. Description: checks if a changelog exists in the specified directory;
  1550. We consider changelog to exist if it contains the dbversion file.
  1551. Parameters: clDir - directory to check
  1552. Return: 1 - if changelog exists; 0 - otherwise
  1553. */
  1554. PRBool cl5Exist (const char *clDir)
  1555. {
  1556. char fName [MAXPATHLEN + 1];
  1557. int rc;
  1558. PR_snprintf (fName, MAXPATHLEN, "%s/%s", clDir, VERSION_FILE);
  1559. rc = PR_Access (fName, PR_ACCESS_EXISTS);
  1560. return (rc == PR_SUCCESS);
  1561. }
  1562. /* Name: cl5GetOperationCount
  1563. Description: returns number of entries in the changelog. The changelog must be
  1564. open for the value to be meaningful.
  1565. Parameters: replica - optional parameter that specifies the replica whose operations
  1566. we wish to count; if NULL all changelog entries are counted
  1567. Return: number of entries in the changelog
  1568. */
  1569. int cl5GetOperationCount (Object *replica)
  1570. {
  1571. Object *obj;
  1572. CL5DBFile *file;
  1573. int count = 0;
  1574. int rc;
  1575. if (s_cl5Desc.dbState == CL5_STATE_NONE)
  1576. {
  1577. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1578. "cl5GetOperationCount: changelog is not initialized\n");
  1579. return -1;
  1580. }
  1581. /* make sure that changelog is open while operation is in progress */
  1582. rc = _cl5AddThread ();
  1583. if (rc != CL5_SUCCESS)
  1584. return -1;
  1585. if (replica == NULL) /* compute total entry count */
  1586. {
  1587. obj = objset_first_obj (s_cl5Desc.dbFiles);
  1588. while (obj)
  1589. {
  1590. file = (CL5DBFile*)object_get_data (obj);
  1591. PR_ASSERT (file);
  1592. count += file->entryCount;
  1593. obj = objset_next_obj (s_cl5Desc.dbFiles, obj);
  1594. }
  1595. }
  1596. else /* return count for particular db */
  1597. {
  1598. /* select correct db file */
  1599. rc = _cl5GetDBFile (replica, &obj);
  1600. if (rc == CL5_SUCCESS)
  1601. {
  1602. file = (CL5DBFile*)object_get_data (obj);
  1603. PR_ASSERT (file);
  1604. count = file->entryCount;
  1605. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1606. "cl5GetOperationCount: found DB object %p\n", obj);
  1607. object_release (obj);
  1608. }
  1609. else
  1610. {
  1611. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1612. "cl5GetOperationCount: could not get DB object for replica\n");
  1613. count = 0;
  1614. }
  1615. }
  1616. _cl5RemoveThread ();
  1617. return count;
  1618. }
  1619. /***** Helper Functions *****/
  1620. /* this call happens under state lock */
  1621. static int _cl5Open (const char *dir, const CL5DBConfig *config, CL5OpenMode openMode)
  1622. {
  1623. int rc;
  1624. PR_ASSERT (dir);
  1625. /* setup db configuration parameters */
  1626. if (config)
  1627. {
  1628. _cl5SetDBConfig (config);
  1629. }
  1630. else
  1631. {
  1632. _cl5SetDefaultDBConfig ();
  1633. }
  1634. /* initialize trimming */
  1635. rc = _cl5TrimInit ();
  1636. if (rc != CL5_SUCCESS)
  1637. {
  1638. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1639. "_cl5Open: failed to initialize trimming\n");
  1640. goto done;
  1641. }
  1642. /* create the changelog directory if it does not exist */
  1643. rc = cl5CreateDirIfNeeded (dir);
  1644. if (rc != CL5_SUCCESS)
  1645. {
  1646. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1647. "_cl5Open: failed to create changelog directory (%s)\n", dir);
  1648. goto done;
  1649. }
  1650. if (s_cl5Desc.dbDir) {
  1651. slapi_ch_free_string (&s_cl5Desc.dbDir);
  1652. }
  1653. s_cl5Desc.dbDir = slapi_ch_strdup (dir);
  1654. /* check database version */
  1655. rc = _cl5CheckDBVersion ();
  1656. if (rc != CL5_SUCCESS)
  1657. {
  1658. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5Open: invalid db version\n");
  1659. goto done;
  1660. }
  1661. s_cl5Desc.dbOpenMode = openMode;
  1662. /* initialize db environment */
  1663. rc = _cl5AppInit ();
  1664. if (rc != CL5_SUCCESS)
  1665. {
  1666. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1667. "_cl5Open: failed to initialize db environment\n");
  1668. goto done;
  1669. }
  1670. /* init the clcache */
  1671. if (( clcache_init (&s_cl5Desc.dbEnv) != 0 )) {
  1672. rc = CL5_SYSTEM_ERROR;
  1673. goto done;
  1674. }
  1675. /* open database files */
  1676. rc = _cl5DBOpen ();
  1677. if (rc != CL5_SUCCESS)
  1678. {
  1679. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1680. "_cl5Open: failed to open changelog database\n");
  1681. goto done;
  1682. }
  1683. done:;
  1684. if (rc != CL5_SUCCESS)
  1685. {
  1686. _cl5Close ();
  1687. }
  1688. return rc;
  1689. }
  1690. int cl5CreateDirIfNeeded (const char *dirName)
  1691. {
  1692. int rc;
  1693. char buff [MAXPATHLEN + 1];
  1694. char *t;
  1695. PR_ASSERT (dirName);
  1696. rc = PR_Access(dirName, PR_ACCESS_EXISTS);
  1697. if (rc == PR_SUCCESS)
  1698. {
  1699. return CL5_SUCCESS;
  1700. }
  1701. /* directory does not exist - try to create */
  1702. PL_strncpyz (buff, dirName, sizeof(buff)-1);
  1703. t = strchr (buff, '/');
  1704. /* skip first slash */
  1705. if (t)
  1706. {
  1707. t = strchr (t+1, '/');
  1708. }
  1709. while (t)
  1710. {
  1711. *t = '\0';
  1712. if (PR_Access (buff, PR_ACCESS_EXISTS) != PR_SUCCESS)
  1713. {
  1714. rc = PR_MkDir (buff, DIR_CREATE_MODE);
  1715. if (rc != PR_SUCCESS)
  1716. {
  1717. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1718. "cl5CreateDirIfNeeded: failed to create dir (%s); NSPR error - %d\n",
  1719. dirName, PR_GetError ());
  1720. return CL5_SYSTEM_ERROR;
  1721. }
  1722. }
  1723. *t++ = FILE_PATHSEP;
  1724. t = strchr (t, '/');
  1725. }
  1726. /* last piece */
  1727. rc = PR_MkDir (buff, DIR_CREATE_MODE);
  1728. if (rc != PR_SUCCESS)
  1729. {
  1730. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1731. "cl5CreateDirIfNeeded: failed to create dir; NSPR error - %d\n",
  1732. PR_GetError ());
  1733. return CL5_SYSTEM_ERROR;
  1734. }
  1735. return CL5_SUCCESS;
  1736. }
  1737. static int _cl5AppInit (void)
  1738. {
  1739. int rc = -1; /* initialize to failure */
  1740. DB_ENV *dbEnv = NULL;
  1741. size_t pagesize = 0;
  1742. int openflags = 0;
  1743. char *cookie = NULL;
  1744. Slapi_Backend *be = slapi_get_first_backend(&cookie);
  1745. while (be) {
  1746. rc = slapi_back_get_info(be, BACK_INFO_DBENV, (void **)&dbEnv);
  1747. if ((LDAP_SUCCESS == rc) && dbEnv) {
  1748. rc = slapi_back_get_info(be,
  1749. BACK_INFO_INDEXPAGESIZE, (void **)&pagesize);
  1750. if ((LDAP_SUCCESS == rc) && pagesize) {
  1751. rc = slapi_back_get_info(be,
  1752. BACK_INFO_DBENV_OPENFLAGS, (void **)&openflags);
  1753. if (LDAP_SUCCESS == rc) {
  1754. break; /* Successfully fetched */
  1755. }
  1756. }
  1757. }
  1758. be = slapi_get_next_backend(cookie);
  1759. }
  1760. slapi_ch_free((void **)&cookie);
  1761. if (rc == 0 && dbEnv && pagesize)
  1762. {
  1763. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1764. "_cl5AppInit: fetched backend dbEnv (%p)\n", dbEnv);
  1765. s_cl5Desc.dbEnv = dbEnv;
  1766. s_cl5Desc.dbEnvOpenFlags = openflags;
  1767. s_cl5Desc.dbConfig.pageSize = pagesize;
  1768. return CL5_SUCCESS;
  1769. }
  1770. else
  1771. {
  1772. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  1773. "_cl5AppInit: failed to fetch backend dbenv (%p) and/or "
  1774. "index page size (%lu)\n", dbEnv, (long unsigned int)pagesize);
  1775. return CL5_DB_ERROR;
  1776. }
  1777. }
  1778. static int _cl5DBOpen ()
  1779. {
  1780. PRBool dbFile;
  1781. PRDir *dir;
  1782. PRDirEntry *entry = NULL;
  1783. int rc = -1; /* initialize to failure */
  1784. Object *replica;
  1785. int count = 0;
  1786. /* create lock that guarantees that each file is only added once to the list */
  1787. s_cl5Desc.fileLock = PR_NewLock ();
  1788. /* loop over all db files and open them; file name format is cl5_<dbid>.<dbext> */
  1789. dir = PR_OpenDir(s_cl5Desc.dbDir);
  1790. if (dir == NULL)
  1791. {
  1792. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1793. "_cl5DBOpen: failed to open changelog dir; NSPR error - %d\n",
  1794. PR_GetError ());
  1795. return CL5_SYSTEM_ERROR;
  1796. }
  1797. /* initialize set of db file objects */
  1798. s_cl5Desc.dbFiles = objset_new(NULL);
  1799. while (NULL != (entry = PR_ReadDir(dir, PR_SKIP_DOT | PR_SKIP_DOT_DOT)))
  1800. {
  1801. if (NULL == entry->name)
  1802. {
  1803. break;
  1804. }
  1805. dbFile = _cl5FileName2Replica (entry->name, &replica);
  1806. if (dbFile) /* this is db file, not a log or dbversion; those are just skipped */
  1807. {
  1808. /* we only open files for existing replicas */
  1809. if (replica)
  1810. {
  1811. rc = _cl5DBOpenFile (replica, NULL /* file object */,
  1812. PR_FALSE /* check for duplicates */);
  1813. if (rc != CL5_SUCCESS)
  1814. {
  1815. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBOpen: "
  1816. "Error opening file %s\n",
  1817. entry->name);
  1818. return rc;
  1819. }
  1820. object_release (replica);
  1821. count++;
  1822. }
  1823. else /* there is no matching replica for the file - remove */
  1824. {
  1825. char fullpathname[MAXPATHLEN];
  1826. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBOpen: "
  1827. "file %s has no matching replica; removing\n", entry->name);
  1828. PR_snprintf(fullpathname, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, entry->name);
  1829. rc = s_cl5Desc.dbEnv->dbremove(s_cl5Desc.dbEnv,
  1830. 0, fullpathname, 0,
  1831. DEFAULT_DB_ENV_OP_FLAGS);
  1832. if (rc != 0)
  1833. {
  1834. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  1835. "_cl5DBOpen: failed to remove (%s) file; "
  1836. "libdb error - %d (%s)\n",
  1837. fullpathname, rc, db_strerror(rc));
  1838. if (PR_Delete(fullpathname) != PR_SUCCESS) {
  1839. PRErrorCode prerr = PR_GetError();
  1840. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  1841. "_cl5DBOpen: failed to remove (%s) file; "
  1842. "nspr error - %d (%s)\n",
  1843. fullpathname, prerr, slapd_pr_strerror(prerr));
  1844. }
  1845. }
  1846. }
  1847. }
  1848. }
  1849. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBOpen: "
  1850. "opened %d existing databases in %s\n", count, s_cl5Desc.dbDir);
  1851. PR_CloseDir(dir);
  1852. return CL5_SUCCESS;
  1853. }
  1854. /* this function assumes that the entry was validated
  1855. using IsValidOperation
  1856. Data in db format:
  1857. ------------------
  1858. <1 byte version><1 byte change_type><sizeof time_t time><null terminated csn>
  1859. <null terminated uniqueid><null terminated targetdn>
  1860. [<null terminated newrdn><1 byte deleteoldrdn>][<4 byte mod count><mod1><mod2>....]
  1861. mod format:
  1862. -----------
  1863. <1 byte modop><null terminated attr name><4 byte value count>
  1864. <4 byte value size><value1><4 byte value size><value2>
  1865. */
  1866. static int _cl5Entry2DBData (const CL5Entry *entry, char **data, PRUint32 *len)
  1867. {
  1868. int size = 1 /* version */ + 1 /* operation type */ + sizeof (time_t);
  1869. char *pos;
  1870. PRUint32 t;
  1871. slapi_operation_parameters *op;
  1872. LDAPMod **add_mods = NULL;
  1873. char *rawDN = NULL;
  1874. char s[CSN_STRSIZE];
  1875. PR_ASSERT (entry && entry->op && data && len);
  1876. op = entry->op;
  1877. PR_ASSERT (op->target_address.uniqueid);
  1878. /* compute size of the buffer needed to hold the data */
  1879. size += CSN_STRSIZE;
  1880. size += strlen (op->target_address.uniqueid) + 1;
  1881. switch (op->operation_type)
  1882. {
  1883. case SLAPI_OPERATION_ADD: if (op->p.p_add.parentuniqueid)
  1884. size += strlen (op->p.p_add.parentuniqueid) + 1;
  1885. else
  1886. size ++; /* we just store NULL char */
  1887. slapi_entry2mods (op->p.p_add.target_entry, &rawDN/* dn */, &add_mods);
  1888. size += strlen (rawDN) + 1;
  1889. /* Need larger buffer for the encrypted changelog */
  1890. if (s_cl5Desc.clcrypt_handle) {
  1891. size += (_cl5GetModsSize (add_mods) * (1 + BACK_CRYPT_OUTBUFF_EXTLEN));
  1892. } else {
  1893. size += _cl5GetModsSize (add_mods);
  1894. }
  1895. break;
  1896. case SLAPI_OPERATION_MODIFY: size += REPL_GET_DN_LEN(&op->target_address) + 1;
  1897. /* Need larger buffer for the encrypted changelog */
  1898. if (s_cl5Desc.clcrypt_handle) {
  1899. size += (_cl5GetModsSize (op->p.p_modify.modify_mods) * (1 + BACK_CRYPT_OUTBUFF_EXTLEN));
  1900. } else {
  1901. size += _cl5GetModsSize (op->p.p_modify.modify_mods);
  1902. }
  1903. break;
  1904. case SLAPI_OPERATION_MODRDN: size += REPL_GET_DN_LEN(&op->target_address) + 1;
  1905. /* 1 for deleteoldrdn */
  1906. size += strlen (op->p.p_modrdn.modrdn_newrdn) + 2;
  1907. if (REPL_GET_DN(&op->p.p_modrdn.modrdn_newsuperior_address))
  1908. size += REPL_GET_DN_LEN(&op->p.p_modrdn.modrdn_newsuperior_address) + 1;
  1909. else
  1910. size ++; /* for NULL char */
  1911. if (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid)
  1912. size += strlen (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid) + 1;
  1913. else
  1914. size ++; /* for NULL char */
  1915. /* Need larger buffer for the encrypted changelog */
  1916. if (s_cl5Desc.clcrypt_handle) {
  1917. size += (_cl5GetModsSize (op->p.p_modrdn.modrdn_mods) * (1 + BACK_CRYPT_OUTBUFF_EXTLEN));
  1918. } else {
  1919. size += _cl5GetModsSize (op->p.p_modrdn.modrdn_mods);
  1920. }
  1921. break;
  1922. case SLAPI_OPERATION_DELETE: size += REPL_GET_DN_LEN(&op->target_address) + 1;
  1923. break;
  1924. }
  1925. /* allocate data buffer */
  1926. (*data) = slapi_ch_malloc (size);
  1927. if ((*data) == NULL)
  1928. {
  1929. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  1930. "_cl5Entry2DBData: failed to allocate data buffer\n");
  1931. return CL5_MEMORY_ERROR;
  1932. }
  1933. /* fill in the data buffer */
  1934. pos = *data;
  1935. /* write a byte of version */
  1936. (*pos) = V_5;
  1937. pos ++;
  1938. /* write change type */
  1939. (*pos) = (unsigned char)op->operation_type;
  1940. pos ++;
  1941. /* write time */
  1942. t = PR_htonl((PRUint32)entry->time);
  1943. memcpy (pos, &t, sizeof (t));
  1944. pos += sizeof (t);
  1945. /* write csn */
  1946. _cl5WriteString (csn_as_string(op->csn,PR_FALSE,s), &pos);
  1947. /* write UniqueID */
  1948. _cl5WriteString (op->target_address.uniqueid, &pos);
  1949. /* figure out what else we need to write depending on the operation type */
  1950. switch (op->operation_type)
  1951. {
  1952. case SLAPI_OPERATION_ADD: _cl5WriteString (op->p.p_add.parentuniqueid, &pos);
  1953. _cl5WriteString (rawDN, &pos);
  1954. _cl5WriteMods (add_mods, &pos);
  1955. slapi_ch_free ((void**)&rawDN);
  1956. ldap_mods_free (add_mods, 1);
  1957. break;
  1958. case SLAPI_OPERATION_MODIFY: _cl5WriteString (REPL_GET_DN(&op->target_address), &pos);
  1959. _cl5WriteMods (op->p.p_modify.modify_mods, &pos);
  1960. break;
  1961. case SLAPI_OPERATION_MODRDN: _cl5WriteString (REPL_GET_DN(&op->target_address), &pos);
  1962. _cl5WriteString (op->p.p_modrdn.modrdn_newrdn, &pos);
  1963. *pos = (PRUint8)op->p.p_modrdn.modrdn_deloldrdn;
  1964. pos ++;
  1965. _cl5WriteString (REPL_GET_DN(&op->p.p_modrdn.modrdn_newsuperior_address), &pos);
  1966. _cl5WriteString (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid, &pos);
  1967. _cl5WriteMods (op->p.p_modrdn.modrdn_mods, &pos);
  1968. break;
  1969. case SLAPI_OPERATION_DELETE: _cl5WriteString (REPL_GET_DN(&op->target_address), &pos);
  1970. break;
  1971. }
  1972. /* (*len) != size in case encrypted */
  1973. (*len) = pos - *data;
  1974. if (*len > size) {
  1975. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  1976. "_cl5Entry2DBData: real len %d > estimated size %d\n",
  1977. *len, size);
  1978. return CL5_MEMORY_ERROR;
  1979. }
  1980. return CL5_SUCCESS;
  1981. }
  1982. /*
  1983. Data in db format:
  1984. ------------------
  1985. <1 byte version><1 byte change_type><sizeof time_t time><null terminated dbid>
  1986. <null terminated csn><null terminated uniqueid><null terminated targetdn>
  1987. [<null terminated newrdn><1 byte deleteoldrdn>][<4 byte mod count><mod1><mod2>....]
  1988. mod format:
  1989. -----------
  1990. <1 byte modop><null terminated attr name><4 byte value count>
  1991. <4 byte value size><value1><4 byte value size><value2>
  1992. */
  1993. int
  1994. cl5DBData2Entry (const char *data, PRUint32 len, CL5Entry *entry)
  1995. {
  1996. int rc;
  1997. PRUint8 version;
  1998. char *pos = (char *)data;
  1999. char *strCSN;
  2000. PRUint32 thetime;
  2001. slapi_operation_parameters *op;
  2002. LDAPMod **add_mods;
  2003. char *rawDN = NULL;
  2004. char s[CSN_STRSIZE];
  2005. PR_ASSERT (data && entry && entry->op);
  2006. /* ONREPL - check that we do not go beyond the end of the buffer */
  2007. /* read byte of version */
  2008. version = (PRUint8)(*pos);
  2009. if (version != V_5)
  2010. {
  2011. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2012. "cl5DBData2Entry: invalid data version\n");
  2013. return CL5_BAD_FORMAT;
  2014. }
  2015. op = entry->op;
  2016. pos += sizeof(version);
  2017. /* read change type */
  2018. op->operation_type = (PRUint8)(*pos);
  2019. pos ++;
  2020. /* need to do the copy first, to skirt around alignment problems on
  2021. certain architectures */
  2022. memcpy((char *)&thetime,pos,sizeof(thetime));
  2023. entry->time = (time_t)PR_ntohl(thetime);
  2024. pos += sizeof (thetime);
  2025. /* read csn */
  2026. _cl5ReadString (&strCSN, &pos);
  2027. if (op->csn == NULL || strcmp (strCSN, csn_as_string(op->csn,PR_FALSE,s)) != 0)
  2028. {
  2029. op->csn = csn_new_by_string (strCSN);
  2030. }
  2031. slapi_ch_free ((void**)&strCSN);
  2032. /* read UniqueID */
  2033. _cl5ReadString (&op->target_address.uniqueid, &pos);
  2034. /* figure out what else we need to read depending on the operation type */
  2035. switch (op->operation_type)
  2036. {
  2037. case SLAPI_OPERATION_ADD: _cl5ReadString (&op->p.p_add.parentuniqueid, &pos);
  2038. /* richm: need to free parentuniqueid */
  2039. _cl5ReadString (&rawDN, &pos);
  2040. op->target_address.sdn = slapi_sdn_new_dn_passin(rawDN);
  2041. /* convert mods to entry */
  2042. rc = _cl5ReadMods (&add_mods, &pos);
  2043. slapi_mods2entry (&(op->p.p_add.target_entry), rawDN, add_mods);
  2044. ldap_mods_free (add_mods, 1);
  2045. break;
  2046. case SLAPI_OPERATION_MODIFY: _cl5ReadString (&rawDN, &pos);
  2047. op->target_address.sdn = slapi_sdn_new_dn_passin(rawDN);
  2048. rc = _cl5ReadMods (&op->p.p_modify.modify_mods, &pos);
  2049. break;
  2050. case SLAPI_OPERATION_MODRDN: _cl5ReadString (&rawDN, &pos);
  2051. op->target_address.sdn = slapi_sdn_new_dn_passin(rawDN);
  2052. _cl5ReadString (&op->p.p_modrdn.modrdn_newrdn, &pos);
  2053. op->p.p_modrdn.modrdn_deloldrdn = *pos;
  2054. pos ++;
  2055. _cl5ReadString (&rawDN, &pos);
  2056. op->p.p_modrdn.modrdn_newsuperior_address.sdn = slapi_sdn_new_dn_passin(rawDN);
  2057. _cl5ReadString (&op->p.p_modrdn.modrdn_newsuperior_address.uniqueid, &pos);
  2058. rc = _cl5ReadMods (&op->p.p_modrdn.modrdn_mods, &pos);
  2059. break;
  2060. case SLAPI_OPERATION_DELETE: _cl5ReadString (&rawDN, &pos);
  2061. op->target_address.sdn = slapi_sdn_new_dn_passin(rawDN);
  2062. rc = CL5_SUCCESS;
  2063. break;
  2064. default: rc = CL5_BAD_FORMAT;
  2065. slapi_log_error(SLAPI_LOG_FATAL,
  2066. repl_plugin_name_cl,
  2067. "cl5DBData2Entry: failed to format entry\n");
  2068. break;
  2069. }
  2070. return rc;
  2071. }
  2072. /* thread management functions */
  2073. static int _cl5DispatchDBThreads ()
  2074. {
  2075. PRThread *pth = NULL;
  2076. pth = PR_CreateThread(PR_USER_THREAD, (VFP)(void*)_cl5TrimMain,
  2077. NULL, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
  2078. PR_UNJOINABLE_THREAD, DEFAULT_THREAD_STACKSIZE);
  2079. if (NULL == pth)
  2080. {
  2081. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2082. "_cl5DispatchDBThreads: failed to create trimming "
  2083. "thread; NSPR error - %d\n", PR_GetError ());
  2084. return CL5_SYSTEM_ERROR;
  2085. }
  2086. return CL5_SUCCESS;
  2087. }
  2088. static int _cl5AddThread ()
  2089. {
  2090. /* lock the state lock so that nobody can change the state
  2091. while backup is in progress
  2092. */
  2093. slapi_rwlock_rdlock (s_cl5Desc.stLock);
  2094. /* open changelog if it is not already open */
  2095. if (s_cl5Desc.dbState != CL5_STATE_OPEN)
  2096. {
  2097. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2098. "_cl5AddThread: invalid changelog state - %d\n", s_cl5Desc.dbState);
  2099. slapi_rwlock_unlock (s_cl5Desc.stLock);
  2100. return CL5_BAD_STATE;
  2101. }
  2102. slapi_rwlock_unlock (s_cl5Desc.stLock);
  2103. /* increment global thread count to make sure that changelog does not close while
  2104. backup is in progress */
  2105. PR_AtomicIncrement (&s_cl5Desc.threadCount);
  2106. return CL5_SUCCESS;
  2107. }
  2108. static void _cl5RemoveThread ()
  2109. {
  2110. PR_ASSERT (s_cl5Desc.threadCount > 0);
  2111. PR_AtomicDecrement (&s_cl5Desc.threadCount);
  2112. }
  2113. /* data conversion functions */
  2114. static void _cl5WriteString (const char *str, char **buff)
  2115. {
  2116. if (str)
  2117. {
  2118. strcpy (*buff, str);
  2119. (*buff) += strlen (str) + 1;
  2120. }
  2121. else /* just write NULL char */
  2122. {
  2123. (**buff) = '\0';
  2124. (*buff) ++;
  2125. }
  2126. }
  2127. static void _cl5ReadString (char **str, char **buff)
  2128. {
  2129. if (str)
  2130. {
  2131. int len = strlen (*buff);
  2132. if (len)
  2133. {
  2134. *str = slapi_ch_strdup (*buff);
  2135. (*buff) += len + 1;
  2136. }
  2137. else /* just null char - skip it */
  2138. {
  2139. *str = NULL;
  2140. (*buff) ++;
  2141. }
  2142. }
  2143. else /* just skip this string */
  2144. {
  2145. (*buff) += strlen (*buff) + 1;
  2146. }
  2147. }
  2148. /* mods format:
  2149. -----------
  2150. <4 byte mods count><mod1><mod2>...
  2151. mod format:
  2152. -----------
  2153. <1 byte modop><null terminated attr name><4 byte count>
  2154. <4 byte size><value1><4 byte size><value2>...
  2155. */
  2156. static void _cl5WriteMods (LDAPMod **mods, char **buff)
  2157. {
  2158. PRInt32 i;
  2159. char *mod_start;
  2160. PRInt32 count = 0;
  2161. if (mods == NULL)
  2162. return;
  2163. /* skip mods count */
  2164. mod_start = (*buff) + sizeof (count);
  2165. /* write mods*/
  2166. for (i = 0; mods[i]; i++) {
  2167. if (0 <= _cl5WriteMod (mods[i], &mod_start)) {
  2168. count++;
  2169. }
  2170. }
  2171. count = PR_htonl(count);
  2172. memcpy (*buff, &count, sizeof (count));
  2173. (*buff) = mod_start;
  2174. }
  2175. /*
  2176. * return values:
  2177. * positive: no need to encrypt && succeeded to write a mod
  2178. * 0: succeeded to encrypt && write a mod
  2179. * netative: failed to encrypt && no write to the changelog
  2180. */
  2181. static int
  2182. _cl5WriteMod (LDAPMod *mod, char **buff)
  2183. {
  2184. char *orig_pos;
  2185. char *pos;
  2186. PRInt32 count;
  2187. struct berval *bv;
  2188. struct berval *encbv;
  2189. struct berval *bv_to_use;
  2190. Slapi_Mod smod;
  2191. int rc = -1;
  2192. if (NULL == mod) {
  2193. return rc;
  2194. }
  2195. if (SLAPD_UNHASHED_PW_NOLOG == slapi_config_get_unhashed_pw_switch()) {
  2196. if (0 == strcasecmp(mod->mod_type, PSEUDO_ATTR_UNHASHEDUSERPASSWORD)) {
  2197. /* If nsslapd-unhashed-pw-switch == nolog, skip writing it to cl. */
  2198. return rc;
  2199. }
  2200. }
  2201. slapi_mod_init_byref(&smod, mod);
  2202. orig_pos = pos = *buff;
  2203. /* write mod op */
  2204. *pos = (PRUint8)slapi_mod_get_operation (&smod);
  2205. pos ++;
  2206. /* write attribute name */
  2207. _cl5WriteString (slapi_mod_get_type (&smod), &pos);
  2208. /* write value count */
  2209. count = PR_htonl(slapi_mod_get_num_values(&smod));
  2210. memcpy (pos, &count, sizeof (count));
  2211. pos += sizeof (PRInt32);
  2212. /* if the mod has no values, eg delete attr or replace attr without values
  2213. * do not reset buffer
  2214. */
  2215. rc = 0;
  2216. bv = slapi_mod_get_first_value (&smod);
  2217. while (bv)
  2218. {
  2219. encbv = NULL;
  2220. rc = clcrypt_encrypt_value(s_cl5Desc.clcrypt_handle,
  2221. bv, &encbv);
  2222. if (rc > 0) {
  2223. /* no encryption needed. use the original bv */
  2224. bv_to_use = bv;
  2225. } else if ((0 == rc) && encbv) {
  2226. /* successfully encrypted. use the encrypted bv */
  2227. bv_to_use = encbv;
  2228. } else { /* failed */
  2229. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2230. "_cl5WriteMod: encrypting \"%s: %s\" failed\n",
  2231. slapi_mod_get_type(&smod), bv->bv_val);
  2232. bv_to_use = NULL;
  2233. rc = -1;
  2234. break;
  2235. }
  2236. if (bv_to_use) {
  2237. _cl5WriteBerval (bv_to_use, &pos);
  2238. }
  2239. slapi_ch_bvfree(&encbv);
  2240. bv = slapi_mod_get_next_value (&smod);
  2241. }
  2242. if (rc < 0) {
  2243. (*buff) = orig_pos;
  2244. } else {
  2245. (*buff) = pos;
  2246. }
  2247. slapi_mod_done (&smod);
  2248. return rc;
  2249. }
  2250. /* mods format:
  2251. -----------
  2252. <4 byte mods count><mod1><mod2>...
  2253. mod format:
  2254. -----------
  2255. <1 byte modop><null terminated attr name><4 byte count>
  2256. {<4 byte size><value1><4 byte size><value2>... ||
  2257. <null terminated str1> <null terminated str2>...}
  2258. */
  2259. static int _cl5ReadMods (LDAPMod ***mods, char **buff)
  2260. {
  2261. char *pos = *buff;
  2262. int i;
  2263. int rc;
  2264. PRInt32 mod_count;
  2265. Slapi_Mods smods;
  2266. Slapi_Mod smod;
  2267. /* need to copy first, to skirt around alignment problems on certain
  2268. architectures */
  2269. memcpy((char *)&mod_count,*buff,sizeof(mod_count));
  2270. mod_count = PR_ntohl(mod_count);
  2271. pos += sizeof (mod_count);
  2272. slapi_mods_init (&smods , mod_count);
  2273. for (i = 0; i < mod_count; i++)
  2274. {
  2275. rc = _cl5ReadMod (&smod, &pos);
  2276. if (rc != CL5_SUCCESS)
  2277. {
  2278. slapi_mods_done(&smods);
  2279. return rc;
  2280. }
  2281. slapi_mods_add_smod(&smods, &smod);
  2282. }
  2283. *buff = pos;
  2284. *mods = slapi_mods_get_ldapmods_passout (&smods);
  2285. slapi_mods_done(&smods);
  2286. return CL5_SUCCESS;
  2287. }
  2288. static int _cl5ReadMod (Slapi_Mod *smod, char **buff)
  2289. {
  2290. char *pos = *buff;
  2291. int i;
  2292. PRInt32 val_count;
  2293. char *type;
  2294. int op;
  2295. struct berval bv;
  2296. struct berval *decbv;
  2297. struct berval *bv_to_use;
  2298. int rc = 0;
  2299. op = (*pos) & 0x000000FF;
  2300. pos ++;
  2301. _cl5ReadString (&type, &pos);
  2302. /* need to do the copy first, to skirt around alignment problems on
  2303. certain architectures */
  2304. memcpy((char *)&val_count,pos,sizeof(val_count));
  2305. val_count = PR_ntohl(val_count);
  2306. pos += sizeof (PRInt32);
  2307. slapi_mod_init(smod, val_count);
  2308. slapi_mod_set_operation (smod, op|LDAP_MOD_BVALUES);
  2309. slapi_mod_set_type (smod, type);
  2310. slapi_ch_free ((void**)&type);
  2311. for (i = 0; i < val_count; i++)
  2312. {
  2313. _cl5ReadBerval (&bv, &pos);
  2314. decbv = NULL;
  2315. rc = 0;
  2316. rc = clcrypt_decrypt_value(s_cl5Desc.clcrypt_handle,
  2317. &bv, &decbv);
  2318. if (rc > 0) {
  2319. /* not encrypted. use the original bv */
  2320. bv_to_use = &bv;
  2321. } else if ((0 == rc) && decbv) {
  2322. /* successfully decrypted. use the decrypted bv */
  2323. bv_to_use = decbv;
  2324. } else { /* failed */
  2325. char encstr[128];
  2326. char *encend = encstr + 128;
  2327. char *ptr;
  2328. int i;
  2329. for (i = 0, ptr = encstr; (i < bv.bv_len) && (ptr < encend - 4);
  2330. i++, ptr += 3) {
  2331. sprintf(ptr, "%x", 0xff & bv.bv_val[i]);
  2332. }
  2333. if (ptr >= encend - 4) {
  2334. sprintf(ptr, "...");
  2335. ptr += 3;
  2336. }
  2337. *ptr = '\0';
  2338. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2339. "_cl5ReadMod: decrypting \"%s: %s\" failed\n",
  2340. slapi_mod_get_type(smod), encstr);
  2341. bv_to_use = NULL;
  2342. }
  2343. if (bv_to_use) {
  2344. slapi_mod_add_value (smod, bv_to_use);
  2345. }
  2346. slapi_ch_bvfree(&decbv);
  2347. slapi_ch_free((void **) &bv.bv_val);
  2348. }
  2349. (*buff) = pos;
  2350. return CL5_SUCCESS;
  2351. }
  2352. static int _cl5GetModsSize (LDAPMod **mods)
  2353. {
  2354. int size;
  2355. int i;
  2356. if (mods == NULL)
  2357. return 0;
  2358. size = sizeof (PRInt32);
  2359. for (i=0; mods[i]; i++)
  2360. {
  2361. size += _cl5GetModSize (mods[i]);
  2362. }
  2363. return size;
  2364. }
  2365. static int _cl5GetModSize (LDAPMod *mod)
  2366. {
  2367. int size;
  2368. int i;
  2369. size = 1 + strlen (mod->mod_type) + 1 + sizeof (mod->mod_op);
  2370. i = 0;
  2371. if (mod->mod_op & LDAP_MOD_BVALUES) /* values are in binary form */
  2372. {
  2373. while (mod->mod_bvalues != NULL && mod->mod_bvalues[i] != NULL)
  2374. {
  2375. size += mod->mod_bvalues[i]->bv_len + sizeof (mod->mod_bvalues[i]->bv_len);
  2376. i++;
  2377. }
  2378. }
  2379. else /* string data */
  2380. {
  2381. PR_ASSERT(0); /* ggood string values should never be used in the server */
  2382. }
  2383. return size;
  2384. }
  2385. static void _cl5ReadBerval (struct berval *bv, char** buff)
  2386. {
  2387. PRUint32 length = 0;
  2388. PRUint32 net_length = 0;
  2389. PR_ASSERT (bv && buff);
  2390. /***PINAKI need to do the copy first, to skirt around alignment problems on
  2391. certain architectures */
  2392. /* DBDB : struct berval.bv_len is defined as unsigned long
  2393. * But code here expects it to be 32-bits in size.
  2394. * On 64-bit machines, this is not the case.
  2395. * I changed the code to consistently use 32-bit (4-byte)
  2396. * values on the encoded side. This means that it's
  2397. * possible to generate a huge berval that will not
  2398. * be encoded properly. However, this seems unlikely
  2399. * to happen in reality, and I felt that retaining the
  2400. * old on-disk format for the changely in the 64-bit
  2401. * version of the server was important.
  2402. */
  2403. memcpy((char *)&net_length, *buff, sizeof(net_length));
  2404. length = PR_ntohl(net_length);
  2405. *buff += sizeof(net_length);
  2406. bv->bv_len = length;
  2407. if (bv->bv_len > 0) {
  2408. bv->bv_val = slapi_ch_malloc (bv->bv_len);
  2409. memcpy (bv->bv_val, *buff, bv->bv_len);
  2410. *buff += bv->bv_len;
  2411. }
  2412. else {
  2413. bv->bv_val = NULL;
  2414. }
  2415. }
  2416. static void _cl5WriteBerval (struct berval *bv, char** buff)
  2417. {
  2418. PRUint32 length = 0;
  2419. PRUint32 net_length = 0;
  2420. length = (PRUint32) bv->bv_len;
  2421. net_length = PR_htonl(length);
  2422. memcpy(*buff, &net_length, sizeof (net_length));
  2423. *buff += sizeof (net_length);
  2424. memcpy (*buff, bv->bv_val, length);
  2425. *buff += length;
  2426. }
  2427. /* data format: <value count> <value size> <value> <value size> <value> ..... */
  2428. static int _cl5ReadBervals (struct berval ***bv, char** buff, unsigned int size)
  2429. {
  2430. PRInt32 count;
  2431. int i;
  2432. char *pos;
  2433. PR_ASSERT (bv && buff);
  2434. /* ONREPL - need to check that we don't go beyond the end of the buffer */
  2435. pos = *buff;
  2436. memcpy((char *)&count, pos, sizeof(count));
  2437. count = PR_htonl (count);
  2438. pos += sizeof(count);
  2439. /* allocate bervals */
  2440. *bv = (struct berval **)slapi_ch_malloc ((count + 1) * sizeof (struct berval*));
  2441. if (*bv == NULL)
  2442. {
  2443. return CL5_MEMORY_ERROR;
  2444. }
  2445. for (i = 0; i < count; i++)
  2446. {
  2447. (*bv)[i] = (struct berval *)slapi_ch_malloc (sizeof (struct berval));
  2448. if ((*bv)[i] == NULL)
  2449. {
  2450. ber_bvecfree(*bv);
  2451. return CL5_MEMORY_ERROR;
  2452. }
  2453. _cl5ReadBerval ((*bv)[i], &pos);
  2454. }
  2455. (*bv)[count] = NULL;
  2456. *buff = pos;
  2457. return CL5_SUCCESS;
  2458. }
  2459. /* data format: <value count> <value size> <value> <value size> <value> ..... */
  2460. static int _cl5WriteBervals (struct berval **bv, char** buff, unsigned int *size)
  2461. {
  2462. PRInt32 count, net_count;
  2463. char *pos;
  2464. int i;
  2465. PR_ASSERT (bv && buff && size);
  2466. /* compute number of values and size of the buffer to hold them */
  2467. *size = sizeof (count);
  2468. for (count = 0; bv[count]; count ++)
  2469. {
  2470. *size += sizeof (bv[count]->bv_len) + bv[count]->bv_len;
  2471. }
  2472. /* allocate buffer */
  2473. *buff = (char*) slapi_ch_malloc (*size);
  2474. if (*buff == NULL)
  2475. {
  2476. *size = 0;
  2477. return CL5_MEMORY_ERROR;
  2478. }
  2479. /* fill the buffer */
  2480. pos = *buff;
  2481. net_count = PR_htonl(count);
  2482. memcpy (pos, &net_count, sizeof (net_count));
  2483. pos += sizeof (net_count);
  2484. for (i = 0; i < count; i ++)
  2485. {
  2486. _cl5WriteBerval (bv[i], &pos);
  2487. }
  2488. return CL5_SUCCESS;
  2489. }
  2490. /* upgrade from db33 to db41
  2491. * 1. Run recovery on the database environment using the DB_ENV->open method
  2492. * 2. Remove any Berkeley DB environment using the DB_ENV->remove method
  2493. * 3. Remove any Berkeley DB transaction log files
  2494. * 4. extention .db3 -> .db4
  2495. */
  2496. static int _cl5UpgradeMajor(char *fromVersion, char *toVersion)
  2497. {
  2498. PRDir *dir = NULL;
  2499. PRDirEntry *entry = NULL;
  2500. DB *thisdb = NULL;
  2501. CL5OpenMode backup;
  2502. int rc = 0;
  2503. backup = s_cl5Desc.dbOpenMode;
  2504. s_cl5Desc.dbOpenMode = CL5_OPEN_CLEAN_RECOVER;
  2505. /* CL5_OPEN_CLEAN_RECOVER does 1 and 2 */
  2506. rc = _cl5AppInit ();
  2507. if (rc != CL5_SUCCESS)
  2508. {
  2509. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2510. "_cl5UpgradeMajor: failed to open the db env\n");
  2511. return rc;
  2512. }
  2513. s_cl5Desc.dbOpenMode = backup;
  2514. dir = PR_OpenDir(s_cl5Desc.dbDir);
  2515. if (dir == NULL)
  2516. {
  2517. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2518. "_cl5UpgradeMajor: failed to open changelog dir %s; NSPR error - %d\n",
  2519. s_cl5Desc.dbDir, PR_GetError ());
  2520. goto out;
  2521. }
  2522. while (NULL != (entry = PR_ReadDir(dir, PR_SKIP_DOT | PR_SKIP_DOT_DOT)))
  2523. {
  2524. if (NULL == entry->name)
  2525. {
  2526. break;
  2527. }
  2528. if (_cl5FileEndsWith(entry->name, DB_EXTENSION_DB3) ||
  2529. _cl5FileEndsWith(entry->name, DB_EXTENSION_DB4))
  2530. {
  2531. char oName [MAXPATHLEN + 1];
  2532. char nName [MAXPATHLEN + 1];
  2533. char *p = NULL;
  2534. char c;
  2535. int baselen = 0;
  2536. PR_snprintf(oName, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, entry->name);
  2537. p = strstr(oName, DB_EXTENSION_DB3);
  2538. if (NULL == p)
  2539. {
  2540. p = strstr(oName, DB_EXTENSION_DB4);
  2541. if (NULL == p) {
  2542. continue;
  2543. }
  2544. }
  2545. /* db->rename closes DB; need to create every time */
  2546. rc = db_create(&thisdb, s_cl5Desc.dbEnv, 0);
  2547. if (0 != rc) {
  2548. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2549. "_cl5UpgradeMajor: failed to get db handle\n");
  2550. goto out;
  2551. }
  2552. baselen = p - oName;
  2553. c = *p;
  2554. *p = '\0';
  2555. PR_snprintf(nName, MAXPATHLEN+1, "%s", oName);
  2556. PR_snprintf(nName + baselen, MAXPATHLEN+1-baselen, "%s", DB_EXTENSION);
  2557. *p = c;
  2558. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2559. "_cl5UpgradeMajor: renaming %s to %s\n", oName, nName);
  2560. rc = thisdb->rename(thisdb, (const char *)oName, NULL /* subdb */,
  2561. (const char *)nName, 0);
  2562. if (rc != PR_SUCCESS)
  2563. {
  2564. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2565. "_cl5UpgradeMajor: failed to rename file (%s -> %s); "
  2566. "db error - %d %s\n", oName, nName, rc, db_strerror(rc));
  2567. break;
  2568. }
  2569. }
  2570. }
  2571. /* update the version file */
  2572. _cl5WriteDBVersion ();
  2573. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2574. "Upgrading from %s to %s is successfully done (%s)\n",
  2575. fromVersion, toVersion, s_cl5Desc.dbDir);
  2576. out:
  2577. if (NULL != dir)
  2578. {
  2579. PR_CloseDir(dir);
  2580. }
  2581. return rc;
  2582. }
  2583. /* upgrade from db41 -> db42 -> db43 -> db44 -> db45
  2584. * 1. Run recovery on the database environment using the DB_ENV->open method
  2585. * 2. Remove any Berkeley DB environment using the DB_ENV->remove method
  2586. * 3. Remove any Berkeley DB transaction log files
  2587. */
  2588. static int _cl5UpgradeMinor(char *fromVersion, char *toVersion)
  2589. {
  2590. CL5OpenMode backup;
  2591. int rc = 0;
  2592. backup = s_cl5Desc.dbOpenMode;
  2593. s_cl5Desc.dbOpenMode = CL5_OPEN_CLEAN_RECOVER;
  2594. /* CL5_OPEN_CLEAN_RECOVER does 1 and 2 */
  2595. rc = _cl5AppInit ();
  2596. if (rc != CL5_SUCCESS)
  2597. {
  2598. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2599. "_cl5UpgradeMinor: failed to open the db env\n");
  2600. return rc;
  2601. }
  2602. s_cl5Desc.dbOpenMode = backup;
  2603. /* update the version file */
  2604. _cl5WriteDBVersion ();
  2605. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2606. "Upgrading from %s to %s is successfully done (%s)\n",
  2607. fromVersion, toVersion, s_cl5Desc.dbDir);
  2608. return rc;
  2609. }
  2610. static int _cl5CheckDBVersion ()
  2611. {
  2612. char clVersion [VERSION_SIZE + 1];
  2613. char dbVersion [VERSION_SIZE + 1];
  2614. int rc;
  2615. if (!cl5Exist (s_cl5Desc.dbDir))
  2616. {
  2617. /* this is new changelog - write DB version and guardian file */
  2618. rc = _cl5WriteDBVersion ();
  2619. }
  2620. else
  2621. {
  2622. char *versionp = NULL;
  2623. char *versionendp = NULL;
  2624. char *dotp = NULL;
  2625. int dbmajor = 0;
  2626. int dbminor = 0;
  2627. PR_snprintf (clVersion, VERSION_SIZE, "%s/%d.%d/%s",
  2628. BDB_IMPL, DB_VERSION_MAJOR, DB_VERSION_MINOR, BDB_REPLPLUGIN);
  2629. rc = _cl5ReadDBVersion (s_cl5Desc.dbDir, dbVersion, sizeof(dbVersion));
  2630. if (rc != CL5_SUCCESS)
  2631. {
  2632. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2633. "_cl5CheckDBVersion: invalid dbversion\n");
  2634. rc = CL5_BAD_DBVERSION;
  2635. goto bailout;
  2636. }
  2637. versionendp = dbVersion + strlen(dbVersion);
  2638. /* get the version number */
  2639. /* old DBVERSION string: CL5_TYPE/REPL_PLUGIN_NAME/#.# */
  2640. if (PL_strncmp(dbVersion, CL5_TYPE, strlen(CL5_TYPE)) == 0)
  2641. {
  2642. versionp = strrchr(dbVersion, '/');
  2643. }
  2644. /* new DBVERSION string: bdb/#.#/libreplication-plugin */
  2645. else if (PL_strncmp(dbVersion, BDB_IMPL, strlen(BDB_IMPL)) == 0)
  2646. {
  2647. versionp = strchr(dbVersion, '/');
  2648. }
  2649. if (NULL == versionp || versionp == versionendp)
  2650. {
  2651. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2652. "_cl5CheckDBVersion: invalid dbversion: %s\n", dbVersion);
  2653. rc = CL5_BAD_DBVERSION;
  2654. goto bailout;
  2655. }
  2656. dotp = strchr(++versionp, '.');
  2657. if (NULL != dotp)
  2658. {
  2659. *dotp = '\0';
  2660. dbmajor = strtol(versionp, (char **)NULL, 10);
  2661. dbminor = strtol(dotp+1, (char **)NULL, 10);
  2662. *dotp = '.';
  2663. }
  2664. else
  2665. {
  2666. dbmajor = strtol(versionp, (char **)NULL, 10);
  2667. }
  2668. if (dbmajor < DB_VERSION_MAJOR)
  2669. {
  2670. /* upgrade */
  2671. rc = _cl5UpgradeMajor(dbVersion, clVersion);
  2672. if (rc != CL5_SUCCESS)
  2673. {
  2674. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2675. "_cl5CheckDBVersion: upgrade %s -> %s failed\n",
  2676. dbVersion, clVersion);
  2677. rc = CL5_BAD_DBVERSION;
  2678. }
  2679. }
  2680. else if (dbminor < DB_VERSION_MINOR)
  2681. {
  2682. /* minor upgrade */
  2683. rc = _cl5UpgradeMinor(dbVersion, clVersion);
  2684. if (rc != CL5_SUCCESS)
  2685. {
  2686. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2687. "_cl5CheckDBVersion: upgrade %s -> %s failed\n",
  2688. dbVersion, clVersion);
  2689. rc = CL5_BAD_DBVERSION;
  2690. }
  2691. }
  2692. }
  2693. bailout:
  2694. return rc;
  2695. }
  2696. static int _cl5ReadDBVersion (const char *dir, char *clVersion, int buflen)
  2697. {
  2698. int rc;
  2699. PRFileDesc *file;
  2700. char fName [MAXPATHLEN + 1];
  2701. char buff [BUFSIZ];
  2702. PRInt32 size;
  2703. char *tok;
  2704. char * iter = NULL;
  2705. if (clVersion)
  2706. {
  2707. clVersion [0] = '\0';
  2708. }
  2709. PR_snprintf (fName, MAXPATHLEN, "%s/%s", dir, VERSION_FILE);
  2710. file = PR_Open (fName, PR_RDONLY, 777);
  2711. if (file == NULL)
  2712. {
  2713. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2714. "_cl5ReadDBVersion: failed to open DBVERSION; NSPR error - %d\n",
  2715. PR_GetError ());
  2716. return CL5_SYSTEM_ERROR;
  2717. }
  2718. size = slapi_read_buffer (file, buff, BUFSIZ);
  2719. if (size < 0)
  2720. {
  2721. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2722. "_cl5ReadDBVersion: failed to read DBVERSION; NSPR error - %d\n",
  2723. PR_GetError ());
  2724. PR_Close (file);
  2725. return CL5_SYSTEM_ERROR;
  2726. }
  2727. /* parse the data */
  2728. buff[size]= '\0';
  2729. tok = ldap_utf8strtok_r (buff, "\n", &iter);
  2730. if (tok)
  2731. {
  2732. if (clVersion)
  2733. {
  2734. PL_strncpyz(clVersion, tok, buflen);
  2735. }
  2736. }
  2737. rc = PR_Close (file);
  2738. if (rc != PR_SUCCESS)
  2739. {
  2740. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2741. "_cl5ReadDBVersion: failed to close DBVERSION; NSPR error - %d\n",
  2742. PR_GetError ());
  2743. return CL5_SYSTEM_ERROR;
  2744. }
  2745. return CL5_SUCCESS;
  2746. }
  2747. static int _cl5WriteDBVersion ()
  2748. {
  2749. int rc;
  2750. PRFileDesc *file;
  2751. char fName [MAXPATHLEN + 1];
  2752. char clVersion [VERSION_SIZE + 1];
  2753. PRInt32 len, size;
  2754. PR_snprintf (fName, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, VERSION_FILE);
  2755. file = PR_Open (fName, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
  2756. s_cl5Desc.dbConfig.fileMode);
  2757. if (file == NULL)
  2758. {
  2759. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2760. "_cl5WriteDBVersion: failed to open DBVERSION; NSPR error - %d\n",
  2761. PR_GetError ());
  2762. return CL5_SYSTEM_ERROR;
  2763. }
  2764. /* write changelog version */
  2765. PR_snprintf (clVersion, VERSION_SIZE, "%s/%d.%d/%s\n",
  2766. BDB_IMPL, DB_VERSION_MAJOR, DB_VERSION_MINOR, BDB_REPLPLUGIN);
  2767. len = strlen(clVersion);
  2768. size = slapi_write_buffer (file, clVersion, len);
  2769. if (size != len)
  2770. {
  2771. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2772. "_cl5WriteDBVersion: failed to write DBVERSION; NSPR error - %d\n",
  2773. PR_GetError ());
  2774. PR_Close (file);
  2775. return CL5_SYSTEM_ERROR;
  2776. }
  2777. rc = PR_Close (file);
  2778. if (rc != PR_SUCCESS)
  2779. {
  2780. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2781. "_cl5WriteDBVersion: failed to close DBVERSION; NSPR error - %d\n",
  2782. PR_GetError ());
  2783. return CL5_SYSTEM_ERROR;
  2784. }
  2785. return CL5_SUCCESS;
  2786. }
  2787. /* must be called under the state lock */
  2788. static void _cl5Close ()
  2789. {
  2790. PRIntervalTime interval;
  2791. if (s_cl5Desc.dbState != CL5_STATE_CLOSED) /* Don't try to close twice */
  2792. {
  2793. /* cl5Close() set the state flag to CL5_STATE_CLOSING, which should
  2794. trigger all of the db housekeeping threads to exit, and which will
  2795. eventually cause no new update threads to start - so we wait here
  2796. for those other threads to finish before we proceed */
  2797. interval = PR_MillisecondsToInterval(100);
  2798. while (s_cl5Desc.threadCount > 0)
  2799. {
  2800. slapi_log_error( SLAPI_LOG_REPL, repl_plugin_name_cl,
  2801. "_cl5Close: waiting for threads to exit: %d thread(s) still active\n",
  2802. s_cl5Desc.threadCount);
  2803. DS_Sleep(interval);
  2804. }
  2805. /* There should now be no threads accessing any of the changelog databases -
  2806. it is safe to remove those databases */
  2807. _cl5DBClose ();
  2808. /* cleanup trimming */
  2809. _cl5TrimCleanup ();
  2810. /* remove changelog if requested */
  2811. if (s_cl5Desc.dbRmOnClose)
  2812. {
  2813. if (_cl5Delete (s_cl5Desc.dbDir, 1) != CL5_SUCCESS)
  2814. {
  2815. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2816. "cl5Close: failed to remove changelog\n");
  2817. }
  2818. s_cl5Desc.dbRmOnClose = PR_FALSE;
  2819. }
  2820. slapi_ch_free ((void **)&s_cl5Desc.dbDir);
  2821. memset (&s_cl5Desc.dbConfig, 0, sizeof (s_cl5Desc.dbConfig));
  2822. s_cl5Desc.fatalError = PR_FALSE;
  2823. s_cl5Desc.threadCount = 0;
  2824. s_cl5Desc.dbOpenMode = CL5_OPEN_NONE;
  2825. }
  2826. }
  2827. static void _cl5DBClose ()
  2828. {
  2829. if (NULL != s_cl5Desc.dbFiles)
  2830. {
  2831. Object *obj;
  2832. for (obj = objset_first_obj(s_cl5Desc.dbFiles); obj;
  2833. obj = objset_next_obj(s_cl5Desc.dbFiles, obj)) {
  2834. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2835. "_cl5DBClose: deleting DB object %p\n", obj);
  2836. }
  2837. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2838. "_cl5DBClose: closing databases in %s\n", s_cl5Desc.dbDir);
  2839. objset_delete (&s_cl5Desc.dbFiles);
  2840. }
  2841. if (NULL != s_cl5Desc.fileLock)
  2842. {
  2843. PR_DestroyLock (s_cl5Desc.fileLock);
  2844. s_cl5Desc.fileLock = NULL;
  2845. }
  2846. }
  2847. /* see if the given file is a changelog db file */
  2848. static int
  2849. _cl5IsDbFile(const char *fname)
  2850. {
  2851. if (!fname || !*fname) {
  2852. return 0;
  2853. }
  2854. if (!strcmp(fname, VERSION_FILE)) {
  2855. return 1;
  2856. }
  2857. if (_cl5FileEndsWith(fname, DB_EXTENSION)) {
  2858. return 1;
  2859. }
  2860. return 0; /* not a filename we recognize as being associated with the db */
  2861. }
  2862. /* state lock must be locked */
  2863. static int _cl5Delete (const char *clDir, int rmDir)
  2864. {
  2865. PRDir *dir;
  2866. char filename[MAXPATHLEN + 1];
  2867. PRDirEntry *entry = NULL;
  2868. int rc;
  2869. int dirisempty = 1;
  2870. /* remove all files in the directory and the directory */
  2871. dir = PR_OpenDir(clDir);
  2872. if (dir == NULL)
  2873. {
  2874. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2875. "_cl5Delete: failed to open changelog dir; NSPR error - %d\n",
  2876. PR_GetError ());
  2877. return CL5_SYSTEM_ERROR;
  2878. }
  2879. while (NULL != (entry = PR_ReadDir(dir, PR_SKIP_DOT | PR_SKIP_DOT_DOT)))
  2880. {
  2881. if (NULL == entry->name)
  2882. {
  2883. break;
  2884. }
  2885. if (!_cl5IsDbFile(entry->name)) {
  2886. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2887. "_cl5Delete: Skipping file [%s/%s] because it is not a changelogdb file.\n",
  2888. clDir, entry->name);
  2889. dirisempty = 0; /* skipped at least one file - dir not empty */
  2890. continue;
  2891. }
  2892. PR_snprintf(filename, MAXPATHLEN, "%s/%s", clDir, entry->name);
  2893. /* _cl5Delete deletes the whole changelog directory with all the files
  2894. * underneath. Thus, we can just remove them physically. */
  2895. if (0 == strcmp(entry->name, VERSION_FILE)) {
  2896. /* DBVERSION */
  2897. rc = PR_Delete(filename) != PR_SUCCESS;
  2898. if (PR_SUCCESS != rc) {
  2899. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2900. "_cl5Delete: failed to remove \"%s\"; NSPR error - %d\n",
  2901. filename, PR_GetError ());
  2902. }
  2903. } else {
  2904. /* DB files */
  2905. rc = s_cl5Desc.dbEnv->dbremove(s_cl5Desc.dbEnv, 0, filename, 0,
  2906. DEFAULT_DB_ENV_OP_FLAGS);
  2907. if (rc) {
  2908. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  2909. "_cl5Delete: failed to remove \"%s\"; "
  2910. "libdb error - %d (%s)\n",
  2911. filename, rc, db_strerror(rc));
  2912. }
  2913. }
  2914. }
  2915. rc = PR_CloseDir(dir);
  2916. if (rc != PR_SUCCESS)
  2917. {
  2918. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2919. "_cl5Delete: failed to close changelog dir (%s); NSPR error - %d\n",
  2920. clDir, PR_GetError ());
  2921. return CL5_SYSTEM_ERROR;
  2922. }
  2923. if (rmDir && dirisempty)
  2924. {
  2925. rc = PR_RmDir (clDir);
  2926. if (rc != 0)
  2927. {
  2928. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2929. "_cl5Delete: failed to remove changelog dir (%s); errno = %d\n",
  2930. clDir, errno);
  2931. return CL5_SYSTEM_ERROR;
  2932. }
  2933. } else if (rmDir && !dirisempty) {
  2934. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2935. "_cl5Delete: changelog dir (%s) is not empty - cannot remove\n",
  2936. clDir);
  2937. }
  2938. /* invalidate the clcache */
  2939. clcache_destroy();
  2940. return CL5_SUCCESS;
  2941. }
  2942. static void _cl5SetDefaultDBConfig ()
  2943. {
  2944. s_cl5Desc.dbConfig.maxConcurrentWrites= CL5_DEFAULT_CONFIG_MAX_CONCURRENT_WRITES;
  2945. s_cl5Desc.dbConfig.fileMode = FILE_CREATE_MODE;
  2946. }
  2947. static void _cl5SetDBConfig (const CL5DBConfig *config)
  2948. {
  2949. /* s_cl5Desc.dbConfig.pageSize is retrieved from backend */
  2950. /* Some other configuration parameters are hardcoded... */
  2951. s_cl5Desc.dbConfig.maxConcurrentWrites = config->maxConcurrentWrites;
  2952. s_cl5Desc.dbConfig.fileMode = FILE_CREATE_MODE;
  2953. }
  2954. /* Trimming helper functions */
  2955. static int _cl5TrimInit ()
  2956. {
  2957. /* just create the lock while we are singlethreaded */
  2958. s_cl5Desc.dbTrim.lock = PR_NewLock();
  2959. if (s_cl5Desc.dbTrim.lock == NULL)
  2960. {
  2961. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  2962. "_cl5InitTrimming: failed to create lock; NSPR error - %d\n",
  2963. PR_GetError ());
  2964. return CL5_SYSTEM_ERROR;
  2965. }
  2966. else
  2967. {
  2968. return CL5_SUCCESS;
  2969. }
  2970. }
  2971. static void _cl5TrimCleanup ()
  2972. {
  2973. if (s_cl5Desc.dbTrim.lock)
  2974. PR_DestroyLock (s_cl5Desc.dbTrim.lock);
  2975. memset (&s_cl5Desc.dbTrim, 0, sizeof (s_cl5Desc.dbTrim));
  2976. }
  2977. static int _cl5TrimMain (void *param)
  2978. {
  2979. PRIntervalTime interval;
  2980. time_t timePrev = current_time ();
  2981. time_t timeNow;
  2982. PR_AtomicIncrement (&s_cl5Desc.threadCount);
  2983. interval = PR_SecondsToInterval(CHANGELOGDB_TRIM_INTERVAL);
  2984. while (s_cl5Desc.dbState != CL5_STATE_CLOSING)
  2985. {
  2986. timeNow = current_time ();
  2987. if (timeNow - timePrev >= CHANGELOGDB_TRIM_INTERVAL)
  2988. {
  2989. /* time to trim */
  2990. timePrev = timeNow;
  2991. _cl5DoTrimming (0 /* there's no cleaned rid */);
  2992. }
  2993. if (NULL == s_cl5Desc.clLock)
  2994. {
  2995. /* most likely, emergency */
  2996. break;
  2997. }
  2998. PR_Lock(s_cl5Desc.clLock);
  2999. PR_WaitCondVar(s_cl5Desc.clCvar, interval);
  3000. PR_Unlock(s_cl5Desc.clLock);
  3001. }
  3002. PR_AtomicDecrement (&s_cl5Desc.threadCount);
  3003. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5TrimMain: exiting\n");
  3004. return 0;
  3005. }
  3006. /* We remove an entry if it has been replayed to all consumers and
  3007. and the number of entries in the changelog is larger than maxEntries
  3008. or age of the entry is larger than maxAge.
  3009. Also we can't purge entries which correspond to max csns in the
  3010. supplier's ruv. Here is a example where we can get into trouble:
  3011. The server is setup with time based trimming and no consumer's
  3012. At some point all the entries are trimmed from the changelog.
  3013. At a later point a consumer is added and initialized online
  3014. Then a change is made on the supplier.
  3015. To update the consumer, the supplier would attempt to locate
  3016. the last change sent to the consumer in the changelog and will
  3017. fail because the change was removed.
  3018. */
  3019. static void _cl5DoTrimming (ReplicaId rid)
  3020. {
  3021. Object *obj;
  3022. long numToTrim;
  3023. PR_Lock (s_cl5Desc.dbTrim.lock);
  3024. /* ONREPL We trim file by file which means that some files will be
  3025. trimmed more often than other. We might have to fix that by, for
  3026. example, randomizing starting point */
  3027. obj = objset_first_obj (s_cl5Desc.dbFiles);
  3028. while (obj && _cl5CanTrim ((time_t)0, &numToTrim))
  3029. {
  3030. _cl5TrimFile (obj, &numToTrim, rid);
  3031. obj = objset_next_obj (s_cl5Desc.dbFiles, obj);
  3032. }
  3033. if (obj)
  3034. object_release (obj);
  3035. PR_Unlock (s_cl5Desc.dbTrim.lock);
  3036. return;
  3037. }
  3038. /* Note that each file contains changes for a single replicated area.
  3039. trimming algorithm:
  3040. */
  3041. #define CL5_TRIM_MAX_PER_TRANSACTION 10
  3042. static void _cl5TrimFile (Object *obj, long *numToTrim, ReplicaId cleaned_rid)
  3043. {
  3044. DB_TXN *txnid;
  3045. RUV *ruv = NULL;
  3046. CL5Entry entry;
  3047. slapi_operation_parameters op = {0};
  3048. ReplicaId csn_rid;
  3049. void *it;
  3050. int finished = 0, totalTrimmed = 0, count;
  3051. PRBool abort;
  3052. char strCSN[CSN_STRSIZE];
  3053. int rc;
  3054. PR_ASSERT (obj);
  3055. /* construct the ruv up to which we can purge */
  3056. rc = _cl5GetRUV2Purge2 (obj, &ruv);
  3057. if (rc != CL5_SUCCESS || ruv == NULL)
  3058. {
  3059. return;
  3060. }
  3061. entry.op = &op;
  3062. while ( !finished && !slapi_is_shutting_down() )
  3063. {
  3064. it = NULL;
  3065. count = 0;
  3066. txnid = NULL;
  3067. abort = PR_FALSE;
  3068. /* DB txn lock accessed pages until the end of the transaction. */
  3069. rc = TXN_BEGIN(s_cl5Desc.dbEnv, NULL, &txnid, 0);
  3070. if (rc != 0)
  3071. {
  3072. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3073. "_cl5TrimFile: failed to begin transaction; db error - %d %s\n",
  3074. rc, db_strerror(rc));
  3075. finished = PR_TRUE;
  3076. break;
  3077. }
  3078. finished = _cl5GetFirstEntry (obj, &entry, &it, txnid);
  3079. while ( !finished )
  3080. {
  3081. /*
  3082. * This change can be trimmed if it exceeds purge
  3083. * parameters and has been seen by all consumers.
  3084. */
  3085. if(op.csn == NULL){
  3086. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "_cl5TrimFile: "
  3087. "Operation missing csn, moving on to next entry.\n");
  3088. cl5_operation_parameters_done (&op);
  3089. finished =_cl5GetNextEntry (&entry, it);
  3090. continue;
  3091. }
  3092. csn_rid = csn_get_replicaid (op.csn);
  3093. if ( (*numToTrim > 0 || _cl5CanTrim (entry.time, numToTrim)) &&
  3094. ruv_covers_csn_strict (ruv, op.csn) )
  3095. {
  3096. rc = _cl5CurrentDeleteEntry (it);
  3097. if ( rc == CL5_SUCCESS && cleaned_rid != csn_rid)
  3098. {
  3099. rc = _cl5UpdateRUV (obj, op.csn, PR_FALSE, PR_TRUE);
  3100. }
  3101. if ( rc == CL5_SUCCESS)
  3102. {
  3103. if (*numToTrim > 0) (*numToTrim)--;
  3104. count++;
  3105. }
  3106. else
  3107. {
  3108. /* The above two functions have logged the error */
  3109. abort = PR_TRUE;
  3110. }
  3111. }
  3112. else
  3113. {
  3114. /* The changelog DB is time ordered. If we can not trim
  3115. * a CSN, we will not be allowed to trim the rest of the
  3116. * CSNs generally. However, the maxcsn of each replica ID
  3117. * is always kept in the changelog as an anchor for
  3118. * replaying future changes. We have to skip those anchor
  3119. * CSNs, otherwise a non-active replica ID could block
  3120. * the trim forever.
  3121. */
  3122. CSN *maxcsn = NULL;
  3123. ruv_get_largest_csn_for_replica (ruv, csn_rid, &maxcsn);
  3124. if ( csn_compare (op.csn, maxcsn) != 0 )
  3125. {
  3126. /* op.csn is not anchor CSN */
  3127. finished = 1;
  3128. }
  3129. else
  3130. {
  3131. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  3132. slapi_log_error (SLAPI_LOG_REPL, NULL,
  3133. "Changelog purge skipped anchor csn %s\n",
  3134. csn_as_string (maxcsn, PR_FALSE, strCSN));
  3135. }
  3136. /* extra read to skip the current record */
  3137. cl5_operation_parameters_done (&op);
  3138. finished =_cl5GetNextEntry (&entry, it);
  3139. }
  3140. if (maxcsn) csn_free (&maxcsn);
  3141. }
  3142. cl5_operation_parameters_done (&op);
  3143. if (finished || abort || count >= CL5_TRIM_MAX_PER_TRANSACTION)
  3144. {
  3145. /* If we reach CL5_TRIM_MAX_PER_TRANSACTION,
  3146. * we close the cursor,
  3147. * commit the transaction and restart a new transaction
  3148. */
  3149. break;
  3150. }
  3151. finished = _cl5GetNextEntry (&entry, it);
  3152. }
  3153. /* MAB: We need to close the cursor BEFORE the txn commits/aborts.
  3154. * If we don't respect this order, we'll screw up the database,
  3155. * placing it in DB_RUNRECOVERY mode
  3156. */
  3157. cl5DestroyIterator (it);
  3158. if (abort)
  3159. {
  3160. finished = 1;
  3161. rc = TXN_ABORT (txnid);
  3162. if (rc != 0)
  3163. {
  3164. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3165. "_cl5TrimFile: failed to abort transaction; db error - %d %s\n",
  3166. rc, db_strerror(rc));
  3167. }
  3168. }
  3169. else
  3170. {
  3171. rc = TXN_COMMIT (txnid, 0);
  3172. if (rc != 0)
  3173. {
  3174. finished = 1;
  3175. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3176. "_cl5TrimFile: failed to commit transaction; db error - %d %s\n",
  3177. rc, db_strerror(rc));
  3178. }
  3179. else
  3180. {
  3181. totalTrimmed += count;
  3182. }
  3183. }
  3184. } /* While (!finished) */
  3185. if (ruv)
  3186. ruv_destroy (&ruv);
  3187. if (totalTrimmed)
  3188. {
  3189. slapi_log_error (SLAPI_LOG_REPL, NULL, "Trimmed %d changes from the changelog\n", totalTrimmed);
  3190. }
  3191. }
  3192. static PRBool _cl5CanTrim (time_t time, long *numToTrim)
  3193. {
  3194. *numToTrim = 0;
  3195. if (s_cl5Desc.dbTrim.maxAge == 0 && s_cl5Desc.dbTrim.maxEntries == 0)
  3196. return PR_FALSE;
  3197. if (s_cl5Desc.dbTrim.maxAge == 0)
  3198. {
  3199. *numToTrim = cl5GetOperationCount (NULL) - s_cl5Desc.dbTrim.maxEntries;
  3200. return ( *numToTrim > 0 );
  3201. }
  3202. if (s_cl5Desc.dbTrim.maxEntries > 0 &&
  3203. (*numToTrim = cl5GetOperationCount (NULL) - s_cl5Desc.dbTrim.maxEntries) > 0)
  3204. return PR_TRUE;
  3205. if (time)
  3206. return (current_time () - time > s_cl5Desc.dbTrim.maxAge);
  3207. else
  3208. return PR_TRUE;
  3209. }
  3210. static int _cl5ReadRUV (const char *replGen, Object *obj, PRBool purge)
  3211. {
  3212. int rc;
  3213. char csnStr [CSN_STRSIZE];
  3214. DBT key={0}, data={0};
  3215. struct berval **vals = NULL;
  3216. CL5DBFile *file;
  3217. char *pos;
  3218. char *agmt_name;
  3219. PR_ASSERT (replGen && obj);
  3220. file = (CL5DBFile*)object_get_data (obj);
  3221. PR_ASSERT (file);
  3222. agmt_name = get_thread_private_agmtname();
  3223. if (purge) /* read purge vector entry */
  3224. key.data = _cl5GetHelperEntryKey (PURGE_RUV_TIME, csnStr);
  3225. else /* read upper bound vector */
  3226. key.data = _cl5GetHelperEntryKey (MAX_RUV_TIME, csnStr);
  3227. key.size = CSN_STRSIZE;
  3228. data.flags = DB_DBT_MALLOC;
  3229. rc = file->db->get(file->db, NULL/*txn*/, &key, &data, 0);
  3230. switch (rc)
  3231. {
  3232. case 0: pos = data.data;
  3233. rc = _cl5ReadBervals (&vals, &pos, data.size);
  3234. slapi_ch_free (&(data.data));
  3235. if (rc != CL5_SUCCESS)
  3236. goto done;
  3237. if (purge)
  3238. rc = ruv_init_from_bervals(vals, &file->purgeRUV);
  3239. else
  3240. rc = ruv_init_from_bervals(vals, &file->maxRUV);
  3241. if (rc != RUV_SUCCESS)
  3242. {
  3243. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  3244. "%s: _cl5ReadRUV: failed to initialize %s ruv; "
  3245. "RUV error %d\n", agmt_name, purge? "purge" : "upper bound", rc);
  3246. rc = CL5_RUV_ERROR;
  3247. goto done;
  3248. }
  3249. /* delete the entry; it is re-added when file
  3250. is successfully closed */
  3251. file->db->del (file->db, NULL, &key, DEFAULT_DB_OP_FLAGS(NULL));
  3252. rc = CL5_SUCCESS;
  3253. goto done;
  3254. case DB_NOTFOUND: /* RUV is lost - need to construct */
  3255. rc = _cl5ConstructRUV (replGen, obj, purge);
  3256. goto done;
  3257. default: slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3258. "%s: _cl5ReadRUV: failed to get purge RUV; "
  3259. "db error - %d %s\n", agmt_name, rc, db_strerror(rc));
  3260. rc = CL5_DB_ERROR;
  3261. goto done;
  3262. }
  3263. done:
  3264. ber_bvecfree(vals);
  3265. return rc;
  3266. }
  3267. static int _cl5WriteRUV (CL5DBFile *file, PRBool purge)
  3268. {
  3269. int rc;
  3270. DBT key={0}, data={0};
  3271. char csnStr [CSN_STRSIZE];
  3272. struct berval **vals;
  3273. DB_TXN *txnid = NULL;
  3274. char *buff;
  3275. if ((purge && file->purgeRUV == NULL) || (!purge && file->maxRUV == NULL))
  3276. return CL5_SUCCESS;
  3277. if (purge)
  3278. {
  3279. /* Set the minimum CSN of each vector to a dummy CSN that contains
  3280. * just a replica ID, e.g. 00000000000000010000.
  3281. * The minimum CSN in a purge RUV is not used so the value doesn't
  3282. * matter, but it needs to be set to something so that it can be
  3283. * flushed to changelog at shutdown and parsed at startup with the
  3284. * regular string-to-RUV parsing routines. */
  3285. ruv_insert_dummy_min_csn(file->purgeRUV);
  3286. key.data = _cl5GetHelperEntryKey (PURGE_RUV_TIME, csnStr);
  3287. rc = ruv_to_bervals(file->purgeRUV, &vals);
  3288. }
  3289. else
  3290. {
  3291. key.data = _cl5GetHelperEntryKey (MAX_RUV_TIME, csnStr);
  3292. rc = ruv_to_bervals(file->maxRUV, &vals);
  3293. }
  3294. key.size = CSN_STRSIZE;
  3295. rc = _cl5WriteBervals (vals, &buff, &data.size);
  3296. data.data = buff;
  3297. ber_bvecfree(vals);
  3298. if (rc != CL5_SUCCESS)
  3299. {
  3300. return rc;
  3301. }
  3302. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
  3303. rc = txn_begin(s_cl5Desc.dbEnv, NULL, &txnid, 0);
  3304. if (rc != 0)
  3305. {
  3306. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3307. "_cl5WriteRUV: failed to begin transaction; db error - %d %s\n",
  3308. rc, db_strerror(rc));
  3309. return CL5_DB_ERROR;
  3310. }
  3311. #endif
  3312. rc = file->db->put(file->db, txnid, &key, &data, DEFAULT_DB_OP_FLAGS(txnid));
  3313. slapi_ch_free (&(data.data));
  3314. if ( rc == 0 )
  3315. {
  3316. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
  3317. rc = txn_commit (txnid, 0);
  3318. if (rc != 0)
  3319. {
  3320. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3321. "_cl5WriteRUV: failed to commit transaction; db error - %d %s\n",
  3322. rc, db_strerror(rc));
  3323. return CL5_DB_ERROR;
  3324. }
  3325. #endif
  3326. return CL5_SUCCESS;
  3327. }
  3328. else
  3329. {
  3330. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3331. "_cl5WriteRUV: failed to write %s RUV for file %s; db error - %d (%s)\n",
  3332. purge? "purge" : "upper bound", file->name, rc, db_strerror(rc));
  3333. if (CL5_OS_ERR_IS_DISKFULL(rc))
  3334. {
  3335. cl5_set_diskfull();
  3336. return CL5_DB_ERROR;
  3337. }
  3338. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
  3339. rc = txn_abort (txnid);
  3340. if (rc != 0)
  3341. {
  3342. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3343. "_cl5WriteRUV: failed to abort transaction; db error - %d %s\n",
  3344. rc, db_strerror(rc));
  3345. }
  3346. #endif
  3347. return CL5_DB_ERROR;
  3348. }
  3349. }
  3350. /* This is a very slow process since we have to read every changelog entry.
  3351. Hopefully, this function is not called too often */
  3352. static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge)
  3353. {
  3354. int rc;
  3355. CL5Entry entry;
  3356. void *iterator = NULL;
  3357. slapi_operation_parameters op = {0};
  3358. CL5DBFile *file;
  3359. ReplicaId rid;
  3360. PR_ASSERT (replGen && obj);
  3361. file = (CL5DBFile*)object_get_data (obj);
  3362. PR_ASSERT (file);
  3363. /* construct the RUV */
  3364. if (purge)
  3365. rc = ruv_init_new (replGen, 0, NULL, &file->purgeRUV);
  3366. else
  3367. rc = ruv_init_new (replGen, 0, NULL, &file->maxRUV);
  3368. if (rc != RUV_SUCCESS)
  3369. {
  3370. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV: "
  3371. "failed to initialize %s RUV for file %s; ruv error - %d\n",
  3372. purge? "purge" : "upper bound", file->name, rc);
  3373. return CL5_RUV_ERROR;
  3374. }
  3375. entry.op = &op;
  3376. rc = _cl5GetFirstEntry (obj, &entry, &iterator, NULL);
  3377. while (rc == CL5_SUCCESS)
  3378. {
  3379. if(op.csn){
  3380. rid = csn_get_replicaid (op.csn);
  3381. } else {
  3382. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "_cl5ConstructRUV: "
  3383. "Operation missing csn, moving on to next entry.\n");
  3384. cl5_operation_parameters_done (&op);
  3385. rc = _cl5GetNextEntry (&entry, iterator);
  3386. continue;
  3387. }
  3388. if(is_cleaned_rid(rid)){
  3389. /* skip this entry as the rid is invalid */
  3390. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV: "
  3391. "skipping entry because its csn contains a cleaned rid(%d)\n", rid);
  3392. cl5_operation_parameters_done (&op);
  3393. rc = _cl5GetNextEntry (&entry, iterator);
  3394. continue;
  3395. }
  3396. if (purge)
  3397. rc = ruv_set_csns_keep_smallest(file->purgeRUV, op.csn);
  3398. else
  3399. rc = ruv_set_csns (file->maxRUV, op.csn, NULL);
  3400. cl5_operation_parameters_done (&op);
  3401. if (rc != RUV_SUCCESS)
  3402. {
  3403. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV: "
  3404. "failed to updated %s RUV for file %s; ruv error - %d\n",
  3405. purge ? "purge" : "upper bound", file->name, rc);
  3406. rc = CL5_RUV_ERROR;
  3407. continue;
  3408. }
  3409. rc = _cl5GetNextEntry (&entry, iterator);
  3410. }
  3411. cl5_operation_parameters_done (&op);
  3412. if (iterator)
  3413. cl5DestroyIterator (iterator);
  3414. if (rc == CL5_NOTFOUND)
  3415. {
  3416. rc = CL5_SUCCESS;
  3417. }
  3418. else
  3419. {
  3420. if (purge)
  3421. ruv_destroy (&file->purgeRUV);
  3422. else
  3423. ruv_destroy (&file->maxRUV);
  3424. }
  3425. return rc;
  3426. }
  3427. static int _cl5UpdateRUV (Object *obj, CSN *csn, PRBool newReplica, PRBool purge)
  3428. {
  3429. ReplicaId rid;
  3430. int rc = RUV_SUCCESS; /* initialize rc to avoid erroneous logs */
  3431. CL5DBFile *file;
  3432. PR_ASSERT (obj && csn);
  3433. file = (CL5DBFile*)object_get_data (obj);
  3434. /*
  3435. * if purge is TRUE, file->purgeRUV must be set;
  3436. * if purge is FALSE, maxRUV must be set
  3437. */
  3438. PR_ASSERT (file && ((purge && file->purgeRUV) || (!purge && file->maxRUV)));
  3439. rid = csn_get_replicaid(csn);
  3440. /* update vector only if this replica is not yet part of RUV */
  3441. if (purge && newReplica)
  3442. {
  3443. if (ruv_contains_replica (file->purgeRUV, rid)){
  3444. return CL5_SUCCESS;
  3445. } else {
  3446. /* if the replica is not part of the purgeRUV yet, add it unless it's from a cleaned rid */
  3447. ruv_add_replica (file->purgeRUV, rid, multimaster_get_local_purl());
  3448. }
  3449. }
  3450. else
  3451. {
  3452. if (purge){
  3453. rc = ruv_set_csns(file->purgeRUV, csn, NULL);
  3454. } else {
  3455. rc = ruv_set_csns(file->maxRUV, csn, NULL);
  3456. }
  3457. }
  3458. if (rc != RUV_SUCCESS)
  3459. {
  3460. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5UpdatePurgeRUV: "
  3461. "failed to update %s RUV for file %s; ruv error - %d\n",
  3462. purge ? "purge" : "upper bound", file->name, rc);
  3463. return CL5_RUV_ERROR;
  3464. }
  3465. return CL5_SUCCESS;
  3466. }
  3467. static int _cl5EnumConsumerRUV (const ruv_enum_data *element, void *arg)
  3468. {
  3469. int rc;
  3470. RUV *ruv;
  3471. CSN *csn = NULL;
  3472. PR_ASSERT (element && element->csn && arg);
  3473. ruv = (RUV*)arg;
  3474. rc = ruv_get_largest_csn_for_replica(ruv, csn_get_replicaid (element->csn), &csn);
  3475. if (rc != RUV_SUCCESS || csn == NULL || csn_compare (element->csn, csn) < 0)
  3476. {
  3477. ruv_set_max_csn(ruv, element->csn, NULL);
  3478. }
  3479. if (csn)
  3480. csn_free (&csn);
  3481. return 0;
  3482. }
  3483. static int _cl5GetRUV2Purge2 (Object *fileObj, RUV **ruv)
  3484. {
  3485. int rc = CL5_SUCCESS;
  3486. CL5DBFile *dbFile;
  3487. Object *rObj = NULL;
  3488. Replica *r = NULL;
  3489. Object *agmtObj = NULL;
  3490. Repl_Agmt *agmt;
  3491. Object *consRUVObj, *supRUVObj;
  3492. RUV *consRUV, *supRUV;
  3493. CSN *csn;
  3494. PR_ASSERT (fileObj && ruv);
  3495. if (!ruv) {
  3496. rc = CL5_UNKNOWN_ERROR;
  3497. goto done;
  3498. }
  3499. dbFile = (CL5DBFile*)object_get_data (fileObj);
  3500. PR_ASSERT (dbFile);
  3501. rObj = replica_get_by_name (dbFile->replName);
  3502. PR_ASSERT (rObj);
  3503. if (!rObj) {
  3504. rc = CL5_NOTFOUND;
  3505. goto done;
  3506. }
  3507. r = (Replica*)object_get_data (rObj);
  3508. PR_ASSERT (r);
  3509. /* We start with this replica's RUV. See note in _cl5DoTrimming */
  3510. supRUVObj = replica_get_ruv (r);
  3511. PR_ASSERT (supRUVObj);
  3512. supRUV = (RUV*)object_get_data (supRUVObj);
  3513. PR_ASSERT (supRUV);
  3514. *ruv = ruv_dup (supRUV);
  3515. object_release (supRUVObj);
  3516. agmtObj = agmtlist_get_first_agreement_for_replica (r);
  3517. while (agmtObj)
  3518. {
  3519. agmt = (Repl_Agmt*)object_get_data (agmtObj);
  3520. PR_ASSERT (agmt);
  3521. if(!agmt_is_enabled(agmt)){
  3522. agmtObj = agmtlist_get_next_agreement_for_replica(r, agmtObj);
  3523. continue;
  3524. }
  3525. consRUVObj = agmt_get_consumer_ruv (agmt);
  3526. if (consRUVObj)
  3527. {
  3528. consRUV = (RUV*)object_get_data (consRUVObj);
  3529. rc = ruv_enumerate_elements (consRUV, _cl5EnumConsumerRUV, *ruv);
  3530. if (rc != RUV_SUCCESS)
  3531. {
  3532. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetRUV2Purge2: "
  3533. "failed to construct ruv; ruv error - %d\n", rc);
  3534. rc = CL5_RUV_ERROR;
  3535. object_release (consRUVObj);
  3536. object_release (agmtObj);
  3537. break;
  3538. }
  3539. object_release (consRUVObj);
  3540. }
  3541. agmtObj = agmtlist_get_next_agreement_for_replica (r, agmtObj);
  3542. }
  3543. /* check if there is any data in the constructed ruv - otherwise get rid of it */
  3544. if (ruv_get_max_csn(*ruv, &csn) != RUV_SUCCESS || csn == NULL)
  3545. {
  3546. ruv_destroy (ruv);
  3547. }
  3548. else
  3549. {
  3550. csn_free (&csn);
  3551. }
  3552. done:
  3553. if (rObj)
  3554. object_release (rObj);
  3555. if (rc != CL5_SUCCESS && ruv)
  3556. ruv_destroy (ruv);
  3557. return rc;
  3558. }
  3559. static int _cl5GetEntryCount (CL5DBFile *file)
  3560. {
  3561. int rc;
  3562. char csnStr [CSN_STRSIZE];
  3563. DBT key={0}, data={0};
  3564. DB_BTREE_STAT *stats = NULL;
  3565. PR_ASSERT (file);
  3566. /* read entry count. if the entry is there - the file was successfully closed
  3567. last time it was used */
  3568. key.data = _cl5GetHelperEntryKey (ENTRY_COUNT_TIME, csnStr);
  3569. key.size = CSN_STRSIZE;
  3570. data.flags = DB_DBT_MALLOC;
  3571. rc = file->db->get(file->db, NULL/*txn*/, &key, &data, 0);
  3572. switch (rc)
  3573. {
  3574. case 0: file->entryCount = *(int*)data.data;
  3575. slapi_ch_free (&(data.data));
  3576. /* delete the entry. the entry is re-added when file
  3577. is successfully closed */
  3578. file->db->del (file->db, NULL, &key, DEFAULT_DB_OP_FLAGS(NULL));
  3579. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  3580. "_cl5GetEntryCount: %d changes for replica %s\n",
  3581. file->entryCount, file->replName);
  3582. return CL5_SUCCESS;
  3583. case DB_NOTFOUND: file->entryCount = 0;
  3584. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 4300
  3585. rc = file->db->stat(file->db, NULL, (void*)&stats, 0);
  3586. #elif 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 3300
  3587. rc = file->db->stat(file->db, (void*)&stats, 0);
  3588. #else
  3589. rc = file->db->stat(file->db, (void*)&stats, (void *)slapi_ch_malloc, 0);
  3590. #endif
  3591. if (rc != 0)
  3592. {
  3593. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3594. "_cl5GetEntryCount: failed to get changelog statistics; "
  3595. "db error - %d %s\n", rc, db_strerror(rc));
  3596. return CL5_DB_ERROR;
  3597. }
  3598. #ifdef DB30
  3599. file->entryCount = stats->bt_nrecs;
  3600. #else /* DB31 */
  3601. file->entryCount = stats->bt_ndata;
  3602. #endif
  3603. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  3604. "_cl5GetEntryCount: %d changes for replica %s\n",
  3605. file->entryCount, file->replName);
  3606. slapi_ch_free ((void **)&stats);
  3607. return CL5_SUCCESS;
  3608. default: slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3609. "_cl5GetEntryCount: failed to get count entry; "
  3610. "db error - %d %s\n", rc, db_strerror(rc));
  3611. return CL5_DB_ERROR;
  3612. }
  3613. }
  3614. static int _cl5WriteEntryCount (CL5DBFile *file)
  3615. {
  3616. int rc;
  3617. DBT key={0}, data={0};
  3618. char csnStr [CSN_STRSIZE];
  3619. DB_TXN *txnid = NULL;
  3620. key.data = _cl5GetHelperEntryKey (ENTRY_COUNT_TIME, csnStr);
  3621. key.size = CSN_STRSIZE;
  3622. data.data = (void*)&file->entryCount;
  3623. data.size = sizeof (file->entryCount);
  3624. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
  3625. rc = txn_begin(s_cl5Desc.dbEnv, NULL, &txnid, 0);
  3626. if (rc != 0)
  3627. {
  3628. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3629. "_cl5WriteEntryCount: failed to begin transaction; db error - %d %s\n",
  3630. rc, db_strerror(rc));
  3631. return CL5_DB_ERROR;
  3632. }
  3633. #endif
  3634. rc = file->db->put(file->db, txnid, &key, &data, DEFAULT_DB_OP_FLAGS(txnid));
  3635. if (rc == 0)
  3636. {
  3637. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
  3638. rc = txn_commit (txnid, 0);
  3639. if (rc != 0)
  3640. {
  3641. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3642. "_cl5WriteEntryCount: failed to commit transaction; db error - %d %s\n",
  3643. rc, db_strerror(rc));
  3644. return CL5_DB_ERROR;
  3645. }
  3646. #endif
  3647. return CL5_SUCCESS;
  3648. }
  3649. else
  3650. {
  3651. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3652. "_cl5WriteEntryCount: "
  3653. "failed to write count entry for file %s; db error - %d %s\n",
  3654. file->name, rc, db_strerror(rc));
  3655. if (CL5_OS_ERR_IS_DISKFULL(rc))
  3656. {
  3657. cl5_set_diskfull();
  3658. return CL5_DB_ERROR;
  3659. }
  3660. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
  3661. rc = txn_abort (txnid);
  3662. if (rc != 0)
  3663. {
  3664. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3665. "_cl5WriteEntryCount: failed to abort transaction; db error - %d %s\n",
  3666. rc, db_strerror(rc));
  3667. }
  3668. #endif
  3669. return CL5_DB_ERROR;
  3670. }
  3671. }
  3672. static const char* _cl5OperationType2Str (int type)
  3673. {
  3674. switch (type)
  3675. {
  3676. case SLAPI_OPERATION_ADD: return T_ADDCTSTR;
  3677. case SLAPI_OPERATION_MODIFY: return T_MODIFYCTSTR;
  3678. case SLAPI_OPERATION_MODRDN: return T_MODRDNCTSTR;
  3679. case SLAPI_OPERATION_DELETE: return T_DELETECTSTR;
  3680. default: return NULL;
  3681. }
  3682. }
  3683. static int _cl5Str2OperationType (const char *str)
  3684. {
  3685. if (strcasecmp (str, T_ADDCTSTR) == 0)
  3686. return SLAPI_OPERATION_ADD;
  3687. if (strcasecmp (str, T_MODIFYCTSTR) == 0)
  3688. return SLAPI_OPERATION_MODIFY;
  3689. if (strcasecmp (str, T_MODRDNCTSTR) == 0)
  3690. return SLAPI_OPERATION_MODRDN;
  3691. if (strcasecmp (str, T_DELETECTSTR) == 0)
  3692. return SLAPI_OPERATION_DELETE;
  3693. return -1;
  3694. }
  3695. static int _cl5Operation2LDIF (const slapi_operation_parameters *op, const char *replGen,
  3696. char **ldifEntry, PRInt32 *lenLDIF)
  3697. {
  3698. int len = 2;
  3699. lenstr *l = NULL;
  3700. const char *strType;
  3701. const char *strDeleteOldRDN = "false";
  3702. char *buff, *start;
  3703. LDAPMod **add_mods;
  3704. char *rawDN = NULL;
  3705. char strCSN[CSN_STRSIZE];
  3706. PR_ASSERT (op && replGen && ldifEntry && IsValidOperation (op));
  3707. strType = _cl5OperationType2Str (op->operation_type);
  3708. csn_as_string(op->csn,PR_FALSE,strCSN);
  3709. /* find length of the buffer */
  3710. len += LDIF_SIZE_NEEDED(strlen (T_CHANGETYPESTR), strlen (strType));
  3711. len += LDIF_SIZE_NEEDED(strlen (T_REPLGEN), strlen (replGen));
  3712. len += LDIF_SIZE_NEEDED(strlen (T_CSNSTR), strlen (strCSN));
  3713. len += LDIF_SIZE_NEEDED(strlen (T_UNIQUEIDSTR), strlen (op->target_address.uniqueid));
  3714. switch (op->operation_type)
  3715. {
  3716. case SLAPI_OPERATION_ADD: if (NULL == op->p.p_add.target_entry) {
  3717. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3718. "_cl5Operation2LDIF(ADD): entry is NULL\n");
  3719. return CL5_BAD_FORMAT;
  3720. }
  3721. if (op->p.p_add.parentuniqueid)
  3722. len += LDIF_SIZE_NEEDED(strlen (T_PARENTIDSTR),
  3723. strlen (op->p.p_add.parentuniqueid));
  3724. slapi_entry2mods (op->p.p_add.target_entry, &rawDN, &add_mods);
  3725. len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), strlen (rawDN));
  3726. l = make_changes_string(add_mods, NULL);
  3727. len += LDIF_SIZE_NEEDED(strlen (T_CHANGESTR), l->ls_len);
  3728. ldap_mods_free (add_mods, 1);
  3729. break;
  3730. case SLAPI_OPERATION_MODIFY: if (NULL == op->p.p_modify.modify_mods) {
  3731. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3732. "_cl5Operation2LDIF(MODIFY): mods are NULL\n");
  3733. return CL5_BAD_FORMAT;
  3734. }
  3735. len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), REPL_GET_DN_LEN(&op->target_address));
  3736. l = make_changes_string(op->p.p_modify.modify_mods, NULL);
  3737. len += LDIF_SIZE_NEEDED(strlen (T_CHANGESTR), l->ls_len);
  3738. break;
  3739. case SLAPI_OPERATION_MODRDN: if (NULL == op->p.p_modrdn.modrdn_mods) {
  3740. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3741. "_cl5Operation2LDIF(MODRDN): mods are NULL\n");
  3742. return CL5_BAD_FORMAT;
  3743. }
  3744. len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), REPL_GET_DN_LEN(&op->target_address));
  3745. len += LDIF_SIZE_NEEDED(strlen (T_NEWRDNSTR),
  3746. strlen (op->p.p_modrdn.modrdn_newrdn));
  3747. strDeleteOldRDN = (op->p.p_modrdn.modrdn_deloldrdn ? "true" : "false");
  3748. len += LDIF_SIZE_NEEDED(strlen (T_DRDNFLAGSTR),
  3749. strlen (strDeleteOldRDN));
  3750. if (REPL_GET_DN(&op->p.p_modrdn.modrdn_newsuperior_address))
  3751. len += LDIF_SIZE_NEEDED(strlen (T_NEWSUPERIORDNSTR),
  3752. REPL_GET_DN_LEN(&op->p.p_modrdn.modrdn_newsuperior_address));
  3753. if (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid)
  3754. len += LDIF_SIZE_NEEDED(strlen (T_NEWSUPERIORIDSTR),
  3755. strlen (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid));
  3756. l = make_changes_string(op->p.p_modrdn.modrdn_mods, NULL);
  3757. len += LDIF_SIZE_NEEDED(strlen (T_CHANGESTR), l->ls_len);
  3758. break;
  3759. case SLAPI_OPERATION_DELETE: if (NULL == REPL_GET_DN(&op->target_address)) {
  3760. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3761. "_cl5Operation2LDIF(DELETE): target dn is NULL\n");
  3762. return CL5_BAD_FORMAT;
  3763. }
  3764. len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), REPL_GET_DN_LEN(&op->target_address));
  3765. break;
  3766. default: slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3767. "_cl5Operation2LDIF: invalid operation type - %lu\n", op->operation_type);
  3768. return CL5_BAD_FORMAT;
  3769. }
  3770. /* allocate buffer */
  3771. buff = slapi_ch_malloc (len);
  3772. start = buff;
  3773. if (buff == NULL)
  3774. {
  3775. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3776. "_cl5Operation2LDIF: memory allocation failed\n");
  3777. return CL5_MEMORY_ERROR;
  3778. }
  3779. /* fill buffer */
  3780. slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGETYPESTR, (char*)strType, strlen (strType), 0);
  3781. slapi_ldif_put_type_and_value_with_options(&buff, T_REPLGEN, (char*)replGen, strlen (replGen), 0);
  3782. slapi_ldif_put_type_and_value_with_options(&buff, T_CSNSTR, (char*)strCSN, strlen (strCSN), 0);
  3783. slapi_ldif_put_type_and_value_with_options(&buff, T_UNIQUEIDSTR, op->target_address.uniqueid,
  3784. strlen (op->target_address.uniqueid), 0);
  3785. switch (op->operation_type)
  3786. {
  3787. case SLAPI_OPERATION_ADD: if (op->p.p_add.parentuniqueid)
  3788. slapi_ldif_put_type_and_value_with_options(&buff, T_PARENTIDSTR,
  3789. op->p.p_add.parentuniqueid, strlen (op->p.p_add.parentuniqueid), 0);
  3790. slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, rawDN, strlen (rawDN), 0);
  3791. slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGESTR, l->ls_buf, l->ls_len, 0);
  3792. slapi_ch_free ((void**)&rawDN);
  3793. break;
  3794. case SLAPI_OPERATION_MODIFY: slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, REPL_GET_DN(&op->target_address),
  3795. REPL_GET_DN_LEN(&op->target_address), 0);
  3796. slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGESTR, l->ls_buf, l->ls_len, 0);
  3797. break;
  3798. case SLAPI_OPERATION_MODRDN: slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, REPL_GET_DN(&op->target_address),
  3799. REPL_GET_DN_LEN(&op->target_address), 0);
  3800. slapi_ldif_put_type_and_value_with_options(&buff, T_NEWRDNSTR, op->p.p_modrdn.modrdn_newrdn,
  3801. strlen (op->p.p_modrdn.modrdn_newrdn), 0);
  3802. slapi_ldif_put_type_and_value_with_options(&buff, T_DRDNFLAGSTR, strDeleteOldRDN,
  3803. strlen (strDeleteOldRDN), 0);
  3804. if (REPL_GET_DN(&op->p.p_modrdn.modrdn_newsuperior_address))
  3805. slapi_ldif_put_type_and_value_with_options(&buff, T_NEWSUPERIORDNSTR,
  3806. REPL_GET_DN(&op->p.p_modrdn.modrdn_newsuperior_address),
  3807. REPL_GET_DN_LEN(&op->p.p_modrdn.modrdn_newsuperior_address), 0);
  3808. if (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid)
  3809. slapi_ldif_put_type_and_value_with_options(&buff, T_NEWSUPERIORIDSTR,
  3810. op->p.p_modrdn.modrdn_newsuperior_address.uniqueid,
  3811. strlen (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid), 0);
  3812. slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGESTR, l->ls_buf, l->ls_len, 0);
  3813. break;
  3814. case SLAPI_OPERATION_DELETE: slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, REPL_GET_DN(&op->target_address),
  3815. REPL_GET_DN_LEN(&op->target_address), 0);
  3816. break;
  3817. }
  3818. *buff = '\n';
  3819. buff ++;
  3820. *buff = '\0';
  3821. *ldifEntry = start;
  3822. *lenLDIF = buff - start;
  3823. if (l)
  3824. lenstr_free(&l);
  3825. return CL5_SUCCESS;
  3826. }
  3827. static int
  3828. _cl5LDIF2Operation (char *ldifEntry, slapi_operation_parameters *op, char **replGen)
  3829. {
  3830. int rc;
  3831. int rval = CL5_BAD_FORMAT;
  3832. char *next, *line;
  3833. struct berval type, value;
  3834. struct berval bv_null = {0, NULL};
  3835. int freeval = 0;
  3836. Slapi_Mods *mods;
  3837. char *rawDN = NULL;
  3838. char *ldifEntryWork = slapi_ch_strdup(ldifEntry);
  3839. PR_ASSERT (op && ldifEntry && replGen);
  3840. memset (op, 0, sizeof (*op));
  3841. next = ldifEntryWork;
  3842. while ((line = ldif_getline(&next)) != NULL)
  3843. {
  3844. if ( *line == '\n' || *line == '\0' )
  3845. {
  3846. break;
  3847. }
  3848. /* this call modifies ldifEntry */
  3849. type = bv_null;
  3850. value = bv_null;
  3851. rc = slapi_ldif_parse_line(line, &type, &value, &freeval);
  3852. if (rc != 0)
  3853. {
  3854. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  3855. "_cl5LDIF2Operation: warning - failed to parse ldif line\n");
  3856. continue;
  3857. }
  3858. if (strncasecmp (type.bv_val, T_CHANGETYPESTR,
  3859. strlen(T_CHANGETYPESTR)>type.bv_len?
  3860. strlen(T_CHANGETYPESTR):type.bv_len) == 0)
  3861. {
  3862. op->operation_type = _cl5Str2OperationType (value.bv_val);
  3863. }
  3864. else if (strncasecmp (type.bv_val, T_REPLGEN, type.bv_len) == 0)
  3865. {
  3866. *replGen = slapi_ch_strdup (value.bv_val);
  3867. }
  3868. else if (strncasecmp (type.bv_val, T_CSNSTR, type.bv_len) == 0)
  3869. {
  3870. op->csn = csn_new_by_string(value.bv_val);
  3871. }
  3872. else if (strncasecmp (type.bv_val, T_UNIQUEIDSTR, type.bv_len) == 0)
  3873. {
  3874. op->target_address.uniqueid = slapi_ch_strdup (value.bv_val);
  3875. }
  3876. else if (strncasecmp (type.bv_val, T_DNSTR, type.bv_len) == 0)
  3877. {
  3878. PR_ASSERT (op->operation_type);
  3879. if (op->operation_type == SLAPI_OPERATION_ADD)
  3880. {
  3881. rawDN = slapi_ch_strdup (value.bv_val);
  3882. op->target_address.sdn = slapi_sdn_new_dn_byval(rawDN);
  3883. }
  3884. else
  3885. op->target_address.sdn = slapi_sdn_new_dn_byval(value.bv_val);
  3886. }
  3887. else if (strncasecmp (type.bv_val, T_PARENTIDSTR, type.bv_len) == 0)
  3888. {
  3889. op->p.p_add.parentuniqueid = slapi_ch_strdup (value.bv_val);
  3890. }
  3891. else if (strncasecmp (type.bv_val, T_NEWRDNSTR, type.bv_len) == 0)
  3892. {
  3893. op->p.p_modrdn.modrdn_newrdn = slapi_ch_strdup (value.bv_val);
  3894. }
  3895. else if (strncasecmp (type.bv_val, T_DRDNFLAGSTR, type.bv_len) == 0)
  3896. {
  3897. op->p.p_modrdn.modrdn_deloldrdn = (strncasecmp (value.bv_val, "true", value.bv_len) ? PR_FALSE : PR_TRUE);
  3898. }
  3899. else if (strncasecmp (type.bv_val, T_NEWSUPERIORDNSTR, type.bv_len) == 0)
  3900. {
  3901. op->p.p_modrdn.modrdn_newsuperior_address.sdn = slapi_sdn_new_dn_byval(value.bv_val);
  3902. }
  3903. else if (strncasecmp (type.bv_val, T_NEWSUPERIORIDSTR, type.bv_len) == 0)
  3904. {
  3905. op->p.p_modrdn.modrdn_newsuperior_address.uniqueid = slapi_ch_strdup (value.bv_val);
  3906. }
  3907. else if (strncasecmp (type.bv_val, T_CHANGESTR,
  3908. strlen(T_CHANGESTR)>type.bv_len?
  3909. strlen(T_CHANGESTR):type.bv_len) == 0)
  3910. {
  3911. PR_ASSERT (op->operation_type);
  3912. switch (op->operation_type)
  3913. {
  3914. case SLAPI_OPERATION_ADD: /*
  3915. * When it comes here, case T_DNSTR is already
  3916. * passed and rawDN is supposed to set.
  3917. * But it's a good idea to make sure it is
  3918. * not NULL.
  3919. */
  3920. if (NULL == rawDN) {
  3921. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3922. "_cl5LDIF2Operation: corrupted format "
  3923. "for operation type - %lu\n",
  3924. op->operation_type);
  3925. slapi_ch_free_string(&ldifEntryWork);
  3926. return CL5_BAD_FORMAT;
  3927. }
  3928. mods = parse_changes_string(value.bv_val);
  3929. PR_ASSERT (mods);
  3930. slapi_mods2entry (&(op->p.p_add.target_entry), rawDN,
  3931. slapi_mods_get_ldapmods_byref(mods));
  3932. slapi_ch_free ((void**)&rawDN);
  3933. slapi_mods_free (&mods);
  3934. break;
  3935. case SLAPI_OPERATION_MODIFY: mods = parse_changes_string(value.bv_val);
  3936. PR_ASSERT (mods);
  3937. op->p.p_modify.modify_mods = slapi_mods_get_ldapmods_passout (mods);
  3938. slapi_mods_free (&mods);
  3939. break;
  3940. case SLAPI_OPERATION_MODRDN: mods = parse_changes_string(value.bv_val);
  3941. PR_ASSERT (mods);
  3942. op->p.p_modrdn.modrdn_mods = slapi_mods_get_ldapmods_passout (mods);
  3943. slapi_mods_free (&mods);
  3944. break;
  3945. default: slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3946. "_cl5LDIF2Operation: invalid operation type - %lu\n",
  3947. op->operation_type);
  3948. if (freeval) {
  3949. slapi_ch_free_string(&value.bv_val);
  3950. }
  3951. slapi_ch_free_string(&ldifEntryWork);
  3952. return CL5_BAD_FORMAT;
  3953. }
  3954. }
  3955. if (freeval) {
  3956. slapi_ch_free_string(&value.bv_val);
  3957. }
  3958. }
  3959. if ((0 != strncmp(ldifEntryWork, "clpurgeruv", 10)) && /* skip RUV; */
  3960. (0 != strncmp(ldifEntryWork, "clmaxruv", 8))) /* RUV has NULL op */
  3961. {
  3962. if (IsValidOperation (op))
  3963. {
  3964. rval = CL5_SUCCESS;
  3965. }
  3966. else
  3967. {
  3968. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  3969. "_cl5LDIF2Operation: invalid data format\n");
  3970. }
  3971. }
  3972. slapi_ch_free_string(&ldifEntryWork);
  3973. return rval;
  3974. }
  3975. static int _cl5WriteOperationTxn(const char *replName, const char *replGen,
  3976. const slapi_operation_parameters *op, PRBool local, void *txn)
  3977. {
  3978. int rc;
  3979. int cnt;
  3980. DBT key={0};
  3981. DBT * data=NULL;
  3982. char csnStr [CSN_STRSIZE];
  3983. PRIntervalTime interval;
  3984. CL5Entry entry;
  3985. CL5DBFile *file = NULL;
  3986. Object *file_obj = NULL;
  3987. DB_TXN *txnid = NULL;
  3988. DB_TXN *parent_txnid = (DB_TXN *)txn;
  3989. rc = _cl5GetDBFileByReplicaName (replName, replGen, &file_obj);
  3990. if (rc == CL5_NOTFOUND)
  3991. {
  3992. rc = _cl5DBOpenFileByReplicaName (replName, replGen, &file_obj,
  3993. PR_TRUE /* check for duplicates */);
  3994. if (rc != CL5_SUCCESS)
  3995. {
  3996. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  3997. "_cl5WriteOperationTxn: failed to find or open DB object for replica %s\n", replName);
  3998. return rc;
  3999. }
  4000. }
  4001. else if (rc != CL5_SUCCESS)
  4002. {
  4003. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4004. "_cl5WriteOperationTxn: failed to get db file for target dn (%s)",
  4005. REPL_GET_DN(&op->target_address));
  4006. return CL5_OBJSET_ERROR;
  4007. }
  4008. /* assign entry time - used for trimming */
  4009. entry.time = current_time ();
  4010. entry.op = (slapi_operation_parameters *)op;
  4011. /* construct the key */
  4012. key.data = csn_as_string(op->csn, PR_FALSE, csnStr);
  4013. key.size = CSN_STRSIZE;
  4014. /* construct the data */
  4015. data = (DBT *) slapi_ch_calloc(1, sizeof(DBT));
  4016. rc = _cl5Entry2DBData (&entry, (char**)&data->data, &data->size);
  4017. if (rc != CL5_SUCCESS)
  4018. {
  4019. char s[CSN_STRSIZE];
  4020. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4021. "_cl5WriteOperationTxn: failed to convert entry with csn (%s) "
  4022. "to db format\n", csn_as_string(op->csn,PR_FALSE,s));
  4023. goto done;
  4024. }
  4025. file = (CL5DBFile*)object_get_data (file_obj);
  4026. PR_ASSERT (file);
  4027. /* if this is part of ldif2cl - just write the entry without transaction */
  4028. if (s_cl5Desc.dbOpenMode == CL5_OPEN_LDIF2CL)
  4029. {
  4030. rc = file->db->put(file->db, NULL, &key, data, 0);
  4031. if (rc != 0)
  4032. {
  4033. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4034. "_cl5WriteOperationTxn: failed to write entry; db error - %d %s\n",
  4035. rc, db_strerror(rc));
  4036. if (CL5_OS_ERR_IS_DISKFULL(rc))
  4037. {
  4038. cl5_set_diskfull();
  4039. }
  4040. rc = CL5_DB_ERROR;
  4041. }
  4042. goto done;
  4043. }
  4044. /* write the entry */
  4045. rc = EAGAIN;
  4046. cnt = 0;
  4047. while ((rc == EAGAIN || rc == DB_LOCK_DEADLOCK) && cnt < MAX_TRIALS)
  4048. {
  4049. if (cnt != 0)
  4050. {
  4051. #if USE_DB_TXN
  4052. /* abort previous transaction */
  4053. rc = TXN_ABORT (txnid);
  4054. if (rc != 0)
  4055. {
  4056. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4057. "_cl5WriteOperationTxn: failed to abort transaction; db error - %d %s\n",
  4058. rc, db_strerror(rc));
  4059. rc = CL5_DB_ERROR;
  4060. goto done;
  4061. }
  4062. #endif
  4063. /* back off */
  4064. interval = PR_MillisecondsToInterval(slapi_rand() % 100);
  4065. DS_Sleep(interval);
  4066. }
  4067. #if USE_DB_TXN
  4068. /* begin transaction */
  4069. rc = TXN_BEGIN(s_cl5Desc.dbEnv, parent_txnid, &txnid, 0);
  4070. if (rc != 0)
  4071. {
  4072. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4073. "_cl5WriteOperationTxn: failed to start transaction; db error - %d %s\n",
  4074. rc, db_strerror(rc));
  4075. rc = CL5_DB_ERROR;
  4076. goto done;
  4077. }
  4078. #endif
  4079. if ( file->sema )
  4080. {
  4081. PR_WaitSemaphore(file->sema);
  4082. }
  4083. rc = file->db->put(file->db, txnid, &key, data, DEFAULT_DB_OP_FLAGS(txnid));
  4084. if ( file->sema )
  4085. {
  4086. PR_PostSemaphore(file->sema);
  4087. }
  4088. if (CL5_OS_ERR_IS_DISKFULL(rc))
  4089. {
  4090. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4091. "_cl5WriteOperationTxn: changelog (%s) DISK FULL; db error - %d %s\n",
  4092. s_cl5Desc.dbDir, rc, db_strerror(rc));
  4093. cl5_set_diskfull();
  4094. rc = CL5_DB_ERROR;
  4095. goto done;
  4096. }
  4097. if (cnt != 0)
  4098. {
  4099. if (rc == 0)
  4100. {
  4101. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "_cl5WriteOperationTxn: retry (%d) the transaction (csn=%s) succeeded\n", cnt, (char*)key.data);
  4102. }
  4103. else if ((cnt + 1) >= MAX_TRIALS)
  4104. {
  4105. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "_cl5WriteOperationTxn: retry (%d) the transaction (csn=%s) failed (rc=%d (%s))\n", cnt, (char*)key.data, rc, db_strerror(rc));
  4106. }
  4107. }
  4108. cnt ++;
  4109. }
  4110. if (rc == 0) /* we successfully added entry */
  4111. {
  4112. #if USE_DB_TXN
  4113. rc = TXN_COMMIT (txnid, 0);
  4114. #endif
  4115. }
  4116. else
  4117. {
  4118. char s[CSN_STRSIZE];
  4119. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4120. "_cl5WriteOperationTxn: failed to write entry with csn (%s); "
  4121. "db error - %d %s\n", csn_as_string(op->csn,PR_FALSE,s),
  4122. rc, db_strerror(rc));
  4123. #if USE_DB_TXN
  4124. rc = TXN_ABORT (txnid);
  4125. if (rc != 0)
  4126. {
  4127. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4128. "_cl5WriteOperationTxn: failed to abort transaction; db error - %d %s\n",
  4129. rc, db_strerror(rc));
  4130. }
  4131. #endif
  4132. rc = CL5_DB_ERROR;
  4133. goto done;
  4134. }
  4135. /* update entry count - we assume that all entries are new */
  4136. PR_AtomicIncrement (&file->entryCount);
  4137. /* update purge vector if we have not seen any changes from this replica before */
  4138. _cl5UpdateRUV (file_obj, op->csn, PR_TRUE, PR_TRUE);
  4139. slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl,
  4140. "cl5WriteOperationTxn: successfully written entry with csn (%s)\n", csnStr);
  4141. rc = CL5_SUCCESS;
  4142. done:
  4143. if (data->data)
  4144. slapi_ch_free (&(data->data));
  4145. slapi_ch_free((void**) &data);
  4146. if (file_obj)
  4147. object_release (file_obj);
  4148. return rc;
  4149. }
  4150. static int _cl5WriteOperation(const char *replName, const char *replGen,
  4151. const slapi_operation_parameters *op, PRBool local)
  4152. {
  4153. return _cl5WriteOperationTxn(replName, replGen, op, local, NULL);
  4154. }
  4155. static int _cl5GetFirstEntry (Object *obj, CL5Entry *entry, void **iterator, DB_TXN *txnid)
  4156. {
  4157. int rc;
  4158. DBC *cursor = NULL;
  4159. DBT key={0}, data={0};
  4160. CL5Iterator *it;
  4161. CL5DBFile *file;
  4162. PR_ASSERT (obj && entry && iterator);
  4163. file = (CL5DBFile*)object_get_data (obj);
  4164. PR_ASSERT (file);
  4165. /* create cursor */
  4166. rc = file->db->cursor(file->db, txnid, &cursor, 0);
  4167. if (rc != 0)
  4168. {
  4169. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4170. "_cl5GetFirstEntry: failed to create cursor; db error - %d %s\n", rc, db_strerror(rc));
  4171. rc = CL5_DB_ERROR;
  4172. goto done;
  4173. }
  4174. key.flags = DB_DBT_MALLOC;
  4175. data.flags = DB_DBT_MALLOC;
  4176. while ((rc = cursor->c_get(cursor, &key, &data, DB_NEXT)) == 0)
  4177. {
  4178. /* skip service entries */
  4179. if (cl5HelperEntry ((char*)key.data, NULL))
  4180. {
  4181. slapi_ch_free (&(key.data));
  4182. slapi_ch_free (&(data.data));
  4183. continue;
  4184. }
  4185. /* format entry */
  4186. slapi_ch_free (&(key.data));
  4187. rc = cl5DBData2Entry (data.data, data.size, entry);
  4188. slapi_ch_free (&(data.data));
  4189. if (rc != 0)
  4190. {
  4191. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4192. "_cl5GetFirstOperation: failed to format entry: %d\n", rc);
  4193. goto done;
  4194. }
  4195. it = (CL5Iterator*)slapi_ch_malloc (sizeof (CL5Iterator));
  4196. it->cursor = cursor;
  4197. object_acquire (obj);
  4198. it->file = obj;
  4199. *(CL5Iterator**)iterator = it;
  4200. return CL5_SUCCESS;
  4201. }
  4202. /*
  4203. * Bug 430172 - memory leaks after db "get" deadlocks, e.g. in CL5 trim
  4204. * Even when db->c_get() does not return success, memory may have been
  4205. * allocated in the DBT. This seems to happen when DB_DBT_MALLOC was set,
  4206. * the data being retrieved is larger than the page size, and we got
  4207. * DB_LOCK_DEADLOCK. libdb allocates the memory and then finds itself
  4208. * deadlocked trying to go through the overflow page list. It returns
  4209. * DB_LOCK_DEADLOCK which we've assumed meant that no memory was allocated
  4210. * for the DBT.
  4211. *
  4212. * The following slapi_ch_free frees the memory only when the value is
  4213. * non NULL, which is true if the situation described above occurs.
  4214. */
  4215. slapi_ch_free ((void **)&key.data);
  4216. slapi_ch_free ((void **)&data.data);
  4217. /* walked of the end of the file */
  4218. if (rc == DB_NOTFOUND)
  4219. {
  4220. rc = CL5_NOTFOUND;
  4221. goto done;
  4222. }
  4223. /* db error occured while iterating */
  4224. /* On this path, the condition "rc != 0" cannot be false */
  4225. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4226. "_cl5GetFirstEntry: failed to get entry; db error - %d %s\n",
  4227. rc, db_strerror(rc));
  4228. rc = CL5_DB_ERROR;
  4229. done:
  4230. /* error occured */
  4231. /* We didn't success in assigning this cursor to the iterator,
  4232. * so we need to free the cursor here */
  4233. if (cursor)
  4234. cursor->c_close(cursor);
  4235. return rc;
  4236. }
  4237. static int _cl5GetNextEntry (CL5Entry *entry, void *iterator)
  4238. {
  4239. int rc;
  4240. CL5Iterator *it;
  4241. DBT key={0}, data={0};
  4242. PR_ASSERT (entry && iterator);
  4243. it = (CL5Iterator*) iterator;
  4244. key.flags = DB_DBT_MALLOC;
  4245. data.flags = DB_DBT_MALLOC;
  4246. while ((rc = it->cursor->c_get(it->cursor, &key, &data, DB_NEXT)) == 0)
  4247. {
  4248. if (cl5HelperEntry ((char*)key.data, NULL))
  4249. {
  4250. slapi_ch_free (&(key.data));
  4251. slapi_ch_free (&(data.data));
  4252. continue;
  4253. }
  4254. slapi_ch_free (&(key.data));
  4255. /* format entry */
  4256. rc = cl5DBData2Entry (data.data, data.size, entry);
  4257. slapi_ch_free (&(data.data));
  4258. if (rc != 0)
  4259. {
  4260. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4261. "_cl5GetNextEntry: failed to format entry: %d\n", rc);
  4262. }
  4263. return rc;
  4264. }
  4265. /*
  4266. * Bug 430172 - memory leaks after db "get" deadlocks, e.g. in CL5 trim
  4267. * Even when db->c_get() does not return success, memory may have been
  4268. * allocated in the DBT. This seems to happen when DB_DBT_MALLOC was set,
  4269. * the data being retrieved is larger than the page size, and we got
  4270. * DB_LOCK_DEADLOCK. libdb allocates the memory and then finds itself
  4271. * deadlocked trying to go through the overflow page list. It returns
  4272. * DB_LOCK_DEADLOCK which we've assumed meant that no memory was allocated
  4273. * for the DBT.
  4274. *
  4275. * The following slapi_ch_free frees the memory only when the value is
  4276. * non NULL, which is true if the situation described above occurs.
  4277. */
  4278. slapi_ch_free ((void **)&key.data);
  4279. slapi_ch_free ((void **)&data.data);
  4280. /* walked of the end of the file or entry is out of range */
  4281. if (rc == 0 || rc == DB_NOTFOUND)
  4282. {
  4283. return CL5_NOTFOUND;
  4284. }
  4285. /* cursor operation failed */
  4286. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4287. "_cl5GetNextEntry: failed to get entry; db error - %d %s\n",
  4288. rc, db_strerror(rc));
  4289. return CL5_DB_ERROR;
  4290. }
  4291. static int _cl5CurrentDeleteEntry (void *iterator)
  4292. {
  4293. int rc;
  4294. CL5Iterator *it;
  4295. CL5DBFile *file;
  4296. PR_ASSERT (iterator);
  4297. it = (CL5Iterator*)iterator;
  4298. rc = it->cursor->c_del (it->cursor, 0);
  4299. if (rc == 0) {
  4300. /* decrement entry count */
  4301. file = (CL5DBFile*)object_get_data (it->file);
  4302. PR_AtomicDecrement (&file->entryCount);
  4303. return CL5_SUCCESS;
  4304. } else {
  4305. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4306. "_cl5CurrentDeleteEntry failed, err=%d %s\n",
  4307. rc, db_strerror(rc));
  4308. /* We don't free(close) the cursor here, as the caller will free it by a call to cl5DestroyIterator */
  4309. /* Freeing it here is a potential bug, as the cursor can't be referenced later once freed */
  4310. return CL5_DB_ERROR;
  4311. }
  4312. }
  4313. static PRBool _cl5IsValidIterator (const CL5Iterator *iterator)
  4314. {
  4315. return (iterator && iterator->cursor && iterator->file);
  4316. }
  4317. static int _cl5GetOperation (Object *replica, slapi_operation_parameters *op)
  4318. {
  4319. int rc;
  4320. DBT key={0}, data={0};
  4321. CL5DBFile *file;
  4322. CL5Entry entry;
  4323. Object *obj = NULL;
  4324. char csnStr[CSN_STRSIZE];
  4325. rc = _cl5GetDBFile (replica, &obj);
  4326. if (rc != CL5_SUCCESS || !obj)
  4327. {
  4328. goto done;
  4329. }
  4330. file = (CL5DBFile*)object_get_data (obj);
  4331. PR_ASSERT (file);
  4332. /* construct the key */
  4333. key.data = csn_as_string(op->csn, PR_FALSE, csnStr);
  4334. key.size = CSN_STRSIZE;
  4335. data.flags = DB_DBT_MALLOC;
  4336. rc = file->db->get(file->db, NULL/*txn*/, &key, &data, 0);
  4337. switch (rc)
  4338. {
  4339. case 0: entry.op = op;
  4340. /* Callers of this function should cl5_operation_parameters_done(op) */
  4341. rc = cl5DBData2Entry (data.data, data.size, &entry);
  4342. if (rc == CL5_SUCCESS)
  4343. {
  4344. slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl,
  4345. "_cl5GetOperation: successfully retrieved operation with csn (%s)\n",
  4346. csnStr);
  4347. }
  4348. else
  4349. {
  4350. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4351. "_cl5GetOperation: failed to convert db data to operation;"
  4352. " csn - %s\n", csnStr);
  4353. }
  4354. goto done;
  4355. case DB_NOTFOUND: slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4356. "_cl5GetOperation: operation for csn (%s) is not found in db that should contain dn (%s)\n",
  4357. csnStr, REPL_GET_DN(&op->target_address));
  4358. rc = CL5_NOTFOUND;
  4359. goto done;
  4360. default: slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4361. "_cl5GetOperation: failed to get entry for csn (%s); "
  4362. "db error - %d %s\n", csnStr, rc, db_strerror(rc));
  4363. rc = CL5_DB_ERROR;
  4364. goto done;
  4365. }
  4366. done:
  4367. if (obj)
  4368. object_release (obj);
  4369. slapi_ch_free (&(data.data));
  4370. return rc;
  4371. }
  4372. PRBool cl5HelperEntry (const char *csnstr, CSN *csnp)
  4373. {
  4374. CSN *csn;
  4375. time_t csnTime;
  4376. PRBool retval = PR_FALSE;
  4377. if (csnp)
  4378. {
  4379. csn = csnp;
  4380. }
  4381. else
  4382. {
  4383. csn= csn_new_by_string(csnstr);
  4384. }
  4385. if (csn == NULL)
  4386. {
  4387. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4388. "cl5HelperEntry: failed to get csn time; csn error\n");
  4389. return PR_FALSE;
  4390. }
  4391. csnTime= csn_get_time(csn);
  4392. if (csnTime == ENTRY_COUNT_TIME || csnTime == PURGE_RUV_TIME)
  4393. {
  4394. retval = PR_TRUE;
  4395. }
  4396. if (NULL == csnp)
  4397. csn_free(&csn);
  4398. return retval;
  4399. }
  4400. #ifdef FOR_DEBUGGING
  4401. /* Replay iteration helper functions */
  4402. static PRBool _cl5ValidReplayIterator (const CL5ReplayIterator *iterator)
  4403. {
  4404. if (iterator == NULL ||
  4405. iterator->consumerRuv == NULL || iterator->supplierRuvObj == NULL ||
  4406. iterator->fileObj == NULL)
  4407. return PR_FALSE;
  4408. return PR_TRUE;
  4409. }
  4410. #endif
  4411. /* Algorithm: ONREPL!!!
  4412. */
  4413. struct replica_hash_entry
  4414. {
  4415. ReplicaId rid; /* replica id */
  4416. PRBool sendChanges; /* indicates whether changes should be sent for this replica */
  4417. };
  4418. static int _cl5PositionCursorForReplay (ReplicaId consumerRID, const RUV *consumerRuv,
  4419. Object *replica, Object *fileObj, CL5ReplayIterator **iterator)
  4420. {
  4421. CLC_Buffer *clcache = NULL;
  4422. CL5DBFile *file;
  4423. int i;
  4424. CSN **csns = NULL;
  4425. CSN *startCSN = NULL;
  4426. char csnStr [CSN_STRSIZE];
  4427. int rc = CL5_SUCCESS;
  4428. Object *supplierRuvObj = NULL;
  4429. RUV *supplierRuv = NULL;
  4430. PRBool newReplica;
  4431. PRBool haveChanges = PR_FALSE;
  4432. char *agmt_name;
  4433. ReplicaId rid;
  4434. PR_ASSERT (consumerRuv && replica && fileObj && iterator);
  4435. csnStr[0] = '\0';
  4436. file = (CL5DBFile*)object_get_data (fileObj);
  4437. /* get supplier's RUV */
  4438. supplierRuvObj = replica_get_ruv((Replica*)object_get_data(replica));
  4439. PR_ASSERT (supplierRuvObj);
  4440. if (!supplierRuvObj) {
  4441. rc = CL5_UNKNOWN_ERROR;
  4442. goto done;
  4443. }
  4444. supplierRuv = (RUV*)object_get_data (supplierRuvObj);
  4445. PR_ASSERT (supplierRuv);
  4446. agmt_name = get_thread_private_agmtname();
  4447. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4448. slapi_log_error(SLAPI_LOG_REPL, NULL, "_cl5PositionCursorForReplay (%s): Consumer RUV:\n", agmt_name);
  4449. ruv_dump (consumerRuv, agmt_name, NULL);
  4450. slapi_log_error(SLAPI_LOG_REPL, NULL, "_cl5PositionCursorForReplay (%s): Supplier RUV:\n", agmt_name);
  4451. ruv_dump (supplierRuv, agmt_name, NULL);
  4452. }
  4453. /*
  4454. * get the sorted list of SupplierMinCSN (if no ConsumerMaxCSN)
  4455. * and ConsumerMaxCSN for those RIDs where consumer is not
  4456. * up-to-date.
  4457. */
  4458. csns = cl5BuildCSNList (consumerRuv, supplierRuv);
  4459. if (csns == NULL)
  4460. {
  4461. rc = CL5_NOTFOUND;
  4462. goto done;
  4463. }
  4464. /* iterate over elements of consumer's (and/or supplier's) ruv */
  4465. for (i = 0; csns[i]; i++)
  4466. {
  4467. CSN *consumerMaxCSN = NULL;
  4468. rid = csn_get_replicaid(csns[i]);
  4469. /*
  4470. * Skip CSN that is originated from the consumer.
  4471. * If RID==65535, the CSN is originated from a
  4472. * legacy consumer. In this case the supplier
  4473. * and the consumer may have the same RID.
  4474. */
  4475. if ((rid == consumerRID && rid != MAX_REPLICA_ID) || (is_cleaned_rid(rid)) )
  4476. continue;
  4477. startCSN = csns[i];
  4478. rc = clcache_get_buffer ( &clcache, file->db, consumerRID, consumerRuv, supplierRuv );
  4479. if ( rc != 0 ) goto done;
  4480. /* This is the first loading of this iteration. For replicas
  4481. * already known to the consumer, we exclude the last entry
  4482. * sent to the consumer by using DB_NEXT. However, for
  4483. * replicas new to the consumer, we include the first change
  4484. * ever generated by that replica.
  4485. */
  4486. newReplica = ruv_get_largest_csn_for_replica (consumerRuv, rid, &consumerMaxCSN);
  4487. csn_free(&consumerMaxCSN);
  4488. rc = clcache_load_buffer (clcache, startCSN, (newReplica ? DB_SET : DB_NEXT));
  4489. /* there is a special case which can occur just after migration - in this case,
  4490. the consumer RUV will contain the last state of the supplier before migration,
  4491. but the supplier will have an empty changelog, or the supplier changelog will
  4492. not contain any entries within the consumer min and max CSN - also, since
  4493. the purge RUV contains no CSNs, the changelog has never been purged
  4494. ASSUMPTIONS - it is assumed that the supplier had no pending changes to send
  4495. to any consumers; that is, we can assume that no changes were lost due to
  4496. either changelog purging or database reload - bug# 603061 - [email protected]
  4497. */
  4498. if ((rc == DB_NOTFOUND) && !ruv_has_csns(file->purgeRUV))
  4499. {
  4500. /* use the supplier min csn for the buffer start csn - we know
  4501. this csn is in our changelog */
  4502. if ((RUV_SUCCESS == ruv_get_min_csn(supplierRuv, &startCSN)) &&
  4503. startCSN)
  4504. { /* must now free startCSN */
  4505. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4506. csn_as_string(startCSN, PR_FALSE, csnStr);
  4507. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4508. "%s: CSN %s not found and no purging, probably a reinit\n",
  4509. agmt_name, csnStr);
  4510. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4511. "%s: Will try to use supplier min CSN %s to load changelog\n",
  4512. agmt_name, csnStr);
  4513. }
  4514. rc = clcache_load_buffer (clcache, startCSN, DB_SET);
  4515. }
  4516. else
  4517. {
  4518. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4519. csn_as_string(startCSN, PR_FALSE, csnStr);
  4520. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4521. "%s: CSN %s not found and no purging, probably a reinit\n",
  4522. agmt_name, csnStr);
  4523. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4524. "%s: Could not get the min csn from the supplier RUV\n",
  4525. agmt_name);
  4526. }
  4527. rc = CL5_RUV_ERROR;
  4528. goto done;
  4529. }
  4530. }
  4531. if (rc == 0) {
  4532. haveChanges = PR_TRUE;
  4533. rc = CL5_SUCCESS;
  4534. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4535. csn_as_string(startCSN, PR_FALSE, csnStr);
  4536. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4537. "%s: CSN %s found, position set for replay\n", agmt_name, csnStr);
  4538. }
  4539. if (startCSN != csns[i]) {
  4540. csn_free(&startCSN);
  4541. }
  4542. break;
  4543. }
  4544. else if (rc == DB_NOTFOUND) /* entry not found */
  4545. {
  4546. /* check whether this csn should be present */
  4547. rc = _cl5CheckMissingCSN (startCSN, supplierRuv, file);
  4548. if (rc == CL5_MISSING_DATA) /* we should have had the change but we don't */
  4549. {
  4550. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4551. csn_as_string(startCSN, PR_FALSE, csnStr);
  4552. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4553. "%s: CSN %s not found, seems to be missing\n", agmt_name, csnStr);
  4554. }
  4555. }
  4556. else /* we are not as up to date or we purged */
  4557. {
  4558. csn_as_string(startCSN, PR_FALSE, csnStr);
  4559. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4560. "%s: CSN %s not found, we aren't as up to date, or we purged\n",
  4561. agmt_name, csnStr);
  4562. }
  4563. if (startCSN != csns[i]) {
  4564. csn_free(&startCSN);
  4565. }
  4566. if (rc == CL5_MISSING_DATA) /* we should have had the change but we don't */
  4567. {
  4568. break;
  4569. }
  4570. else /* we are not as up to date or we purged */
  4571. {
  4572. continue;
  4573. }
  4574. }
  4575. else
  4576. {
  4577. csn_as_string(startCSN, PR_FALSE, csnStr);
  4578. /* db error */
  4579. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4580. "%s: Failed to retrieve change with CSN %s; db error - %d %s\n",
  4581. agmt_name, csnStr, rc, db_strerror(rc));
  4582. if (startCSN != csns[i]) {
  4583. csn_free(&startCSN);
  4584. }
  4585. rc = CL5_DB_ERROR;
  4586. break;
  4587. }
  4588. } /* end for */
  4589. /* setup the iterator */
  4590. if (haveChanges)
  4591. {
  4592. *iterator = (CL5ReplayIterator*) slapi_ch_calloc (1, sizeof (CL5ReplayIterator));
  4593. if (*iterator == NULL)
  4594. {
  4595. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  4596. "%s: _cl5PositionCursorForReplay: failed to allocate iterator\n", agmt_name);
  4597. rc = CL5_MEMORY_ERROR;
  4598. goto done;
  4599. }
  4600. /* ONREPL - should we make a copy of both RUVs here ?*/
  4601. (*iterator)->fileObj = fileObj;
  4602. (*iterator)->clcache = clcache; clcache = NULL;
  4603. (*iterator)->consumerRID = consumerRID;
  4604. (*iterator)->consumerRuv = consumerRuv;
  4605. (*iterator)->supplierRuvObj = supplierRuvObj;
  4606. }
  4607. else if (rc == CL5_SUCCESS)
  4608. {
  4609. /* we have no changes to send */
  4610. rc = CL5_NOTFOUND;
  4611. }
  4612. done:
  4613. if ( clcache )
  4614. clcache_return_buffer ( &clcache );
  4615. if (csns)
  4616. cl5DestroyCSNList (&csns);
  4617. if (rc != CL5_SUCCESS)
  4618. {
  4619. if (supplierRuvObj)
  4620. object_release (supplierRuvObj);
  4621. }
  4622. return rc;
  4623. }
  4624. struct ruv_it
  4625. {
  4626. CSN **csns; /* csn list */
  4627. int alloc; /* allocated size */
  4628. int pos; /* position in the list */
  4629. };
  4630. static int ruv_consumer_iterator (const ruv_enum_data *enum_data, void *arg)
  4631. {
  4632. struct ruv_it *data = (struct ruv_it*)arg;
  4633. PR_ASSERT (data);
  4634. /* check if we have space for one more element */
  4635. if (data->pos >= data->alloc - 2)
  4636. {
  4637. data->alloc += 4;
  4638. data->csns = (CSN**) slapi_ch_realloc ((void*)data->csns, data->alloc * sizeof (CSN*));
  4639. }
  4640. data->csns [data->pos] = csn_dup (enum_data->csn);
  4641. data->pos ++;
  4642. return 0;
  4643. }
  4644. static int ruv_supplier_iterator (const ruv_enum_data *enum_data, void *arg)
  4645. {
  4646. int i;
  4647. PRBool found = PR_FALSE;
  4648. ReplicaId rid;
  4649. struct ruv_it *data = (struct ruv_it*)arg;
  4650. PR_ASSERT (data);
  4651. rid = csn_get_replicaid (enum_data->min_csn);
  4652. /* check if the replica that generated the csn is already in the list */
  4653. for (i = 0; i < data->pos; i++)
  4654. {
  4655. if (rid == csn_get_replicaid (data->csns[i]))
  4656. {
  4657. found = PR_TRUE;
  4658. /* remove datacsn[i] if it is greater or equal to the supplier's maxcsn */
  4659. if ( csn_compare ( data->csns[i], enum_data->csn ) >= 0 )
  4660. {
  4661. int j;
  4662. csn_free ( & data->csns[i] );
  4663. for (j = i+1; j < data->pos; j++)
  4664. {
  4665. data->csns [j-1] = data->csns [j];
  4666. }
  4667. data->pos --;
  4668. }
  4669. break;
  4670. }
  4671. }
  4672. if (!found)
  4673. {
  4674. /* check if we have space for one more element */
  4675. if (data->pos >= data->alloc - 2)
  4676. {
  4677. data->alloc += 4;
  4678. data->csns = (CSN**)slapi_ch_realloc ((void*)data->csns,
  4679. data->alloc * sizeof (CSN*));
  4680. }
  4681. data->csns [data->pos] = csn_dup (enum_data->min_csn);
  4682. data->pos ++;
  4683. }
  4684. return 0;
  4685. }
  4686. static int
  4687. my_csn_compare(const void *arg1, const void *arg2)
  4688. {
  4689. return(csn_compare(*((CSN **)arg1), *((CSN **)arg2)));
  4690. }
  4691. /* builds CSN ordered list of all csns in the RUV */
  4692. CSN** cl5BuildCSNList (const RUV *consRuv, const RUV *supRuv)
  4693. {
  4694. struct ruv_it data;
  4695. int count, rc;
  4696. CSN **csns;
  4697. PR_ASSERT (consRuv);
  4698. count = ruv_replica_count (consRuv);
  4699. csns = (CSN**)slapi_ch_calloc (count + 1, sizeof (CSN*));
  4700. data.csns = csns;
  4701. data.alloc = count + 1;
  4702. data.pos = 0;
  4703. /* add consumer elements to the list */
  4704. rc = ruv_enumerate_elements (consRuv, ruv_consumer_iterator, &data);
  4705. if (rc == 0 && supRuv)
  4706. {
  4707. /* add supplier elements to the list */
  4708. rc = ruv_enumerate_elements (supRuv, ruv_supplier_iterator, &data);
  4709. }
  4710. /* we have no csns */
  4711. if (data.csns[0] == NULL)
  4712. {
  4713. /* csns might have been realloced in ruv_supplier_iterator() */
  4714. slapi_ch_free ((void**)&data.csns);
  4715. csns = NULL;
  4716. }
  4717. else
  4718. {
  4719. csns = data.csns;
  4720. data.csns [data.pos] = NULL;
  4721. if (rc == 0)
  4722. {
  4723. qsort (csns, data.pos, sizeof (CSN*), my_csn_compare);
  4724. }
  4725. else
  4726. {
  4727. cl5DestroyCSNList (&csns);
  4728. }
  4729. }
  4730. return csns;
  4731. }
  4732. void cl5DestroyCSNList (CSN*** csns)
  4733. {
  4734. if (csns && *csns)
  4735. {
  4736. int i;
  4737. for (i = 0; (*csns)[i]; i++)
  4738. {
  4739. csn_free (&(*csns)[i]);
  4740. }
  4741. slapi_ch_free ((void**)csns);
  4742. }
  4743. }
  4744. /* A csn should be in the changelog if it is larger than purge vector csn for the same
  4745. replica and is smaller than the csn in supplier's ruv for the same replica.
  4746. The functions returns
  4747. CL5_PURGED if data was purged from the changelog or was never logged
  4748. because it was loaded as part of replica initialization
  4749. CL5_MISSING if the data erouneously missing
  4750. CL5_SUCCESS if that has not and should not been seen by the server
  4751. */
  4752. static int _cl5CheckMissingCSN (const CSN *csn, const RUV *supplierRuv, CL5DBFile *file)
  4753. {
  4754. ReplicaId rid;
  4755. CSN *supplierCsn = NULL;
  4756. CSN *purgeCsn = NULL;
  4757. int rc = CL5_SUCCESS;
  4758. char csnStr [CSN_STRSIZE];
  4759. PR_ASSERT (csn && supplierRuv && file);
  4760. rid = csn_get_replicaid (csn);
  4761. ruv_get_largest_csn_for_replica (supplierRuv, rid, &supplierCsn);
  4762. if (supplierCsn == NULL)
  4763. {
  4764. /* we have not seen any changes from this replica so it is
  4765. ok not to have this csn */
  4766. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4767. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
  4768. "can't locate %s csn: we have not seen any changes for replica %d\n",
  4769. csn_as_string (csn, PR_FALSE, csnStr), rid);
  4770. }
  4771. return CL5_SUCCESS;
  4772. }
  4773. ruv_get_largest_csn_for_replica (file->purgeRUV, rid, &purgeCsn);
  4774. if (purgeCsn == NULL)
  4775. {
  4776. /* changelog never contained any changes for this replica */
  4777. if (csn_compare (csn, supplierCsn) <= 0)
  4778. {
  4779. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4780. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
  4781. "the change with %s csn was never logged because it was imported "
  4782. "during replica initialization\n", csn_as_string (csn, PR_FALSE, csnStr));
  4783. }
  4784. rc = CL5_PURGED_DATA; /* XXXggood is that the correct return value? */
  4785. }
  4786. else
  4787. {
  4788. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4789. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
  4790. "change with %s csn has not yet been seen by this server; "
  4791. " last csn seen from that replica is %s\n",
  4792. csn_as_string (csn, PR_FALSE, csnStr),
  4793. csn_as_string (supplierCsn, PR_FALSE, csnStr));
  4794. }
  4795. rc = CL5_SUCCESS;
  4796. }
  4797. }
  4798. else /* we have both purge and supplier csn */
  4799. {
  4800. if (csn_compare (csn, purgeCsn) < 0) /* the csn is below the purge point */
  4801. {
  4802. rc = CL5_PURGED_DATA;
  4803. }
  4804. else
  4805. {
  4806. if (csn_compare (csn, supplierCsn) <= 0) /* we should have the data but we don't */
  4807. {
  4808. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4809. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
  4810. "change with %s csn has been purged by this server; "
  4811. "the current purge point for that replica is %s\n",
  4812. csn_as_string (csn, PR_FALSE, csnStr),
  4813. csn_as_string (purgeCsn, PR_FALSE, csnStr));
  4814. }
  4815. rc = CL5_MISSING_DATA;
  4816. }
  4817. else
  4818. {
  4819. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  4820. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
  4821. "change with %s csn has not yet been seen by this server; "
  4822. " last csn seen from that replica is %s\n",
  4823. csn_as_string (csn, PR_FALSE, csnStr),
  4824. csn_as_string (supplierCsn, PR_FALSE, csnStr));
  4825. }
  4826. rc = CL5_SUCCESS;
  4827. }
  4828. }
  4829. }
  4830. if (supplierCsn)
  4831. csn_free (&supplierCsn);
  4832. if (purgeCsn)
  4833. csn_free (&purgeCsn);
  4834. return rc;
  4835. }
  4836. /* Helper functions that work with individual changelog files */
  4837. /* file name format : <replica name>_<replica generation>db{2,3,...} */
  4838. static PRBool
  4839. _cl5FileName2Replica (const char *file_name, Object **replica)
  4840. {
  4841. Replica *r;
  4842. char *repl_name, *file_gen, *repl_gen;
  4843. int len;
  4844. PR_ASSERT (file_name && replica);
  4845. *replica = NULL;
  4846. /* this is database file */
  4847. if (_cl5FileEndsWith (file_name, DB_EXTENSION) ||
  4848. _cl5FileEndsWith (file_name, DB_EXTENSION_DB4) ||
  4849. _cl5FileEndsWith (file_name, DB_EXTENSION_DB3) )
  4850. {
  4851. repl_name = slapi_ch_strdup (file_name);
  4852. file_gen = strstr(repl_name, FILE_SEP);
  4853. if (file_gen)
  4854. {
  4855. int extlen = strlen(DB_EXTENSION);
  4856. *file_gen = '\0';
  4857. file_gen += strlen (FILE_SEP);
  4858. len = strlen (file_gen);
  4859. if (len <= extlen + 1)
  4860. {
  4861. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4862. "_cl5FileName2Replica "
  4863. "invalid file name (%s)\n", file_name);
  4864. }
  4865. else
  4866. {
  4867. /* get rid of the file extension */
  4868. file_gen [len - extlen - 1] = '\0';
  4869. *replica = replica_get_by_name (repl_name);
  4870. if (*replica)
  4871. {
  4872. /* check that generation matches the one in replica object */
  4873. r = (Replica*)object_get_data (*replica);
  4874. repl_gen = replica_get_generation (r);
  4875. PR_ASSERT (repl_gen);
  4876. if (strcmp (file_gen, repl_gen) != 0)
  4877. {
  4878. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4879. "_cl5FileName2Replica "
  4880. "replica generation mismatch for replica at (%s), "
  4881. "file generation %s, new replica generation %s\n",
  4882. slapi_sdn_get_dn (replica_get_root (r)), file_gen, repl_gen);
  4883. object_release (*replica);
  4884. *replica = NULL;
  4885. }
  4886. slapi_ch_free ((void**)&repl_gen);
  4887. }
  4888. }
  4889. slapi_ch_free ((void**)&repl_name);
  4890. }
  4891. else
  4892. {
  4893. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5FileName2Replica "
  4894. "malformed file name - %s\n", file_name);
  4895. }
  4896. return PR_TRUE;
  4897. }
  4898. else
  4899. return PR_FALSE;
  4900. }
  4901. /* file name format : <replica name>_<replica generation>db{2,3} */
  4902. static char* _cl5Replica2FileName (Object *replica)
  4903. {
  4904. const char *replName;
  4905. char *replGen, *fileName;
  4906. Replica *r;
  4907. PR_ASSERT (replica);
  4908. r = (Replica*)object_get_data (replica);
  4909. PR_ASSERT (r);
  4910. replName = replica_get_name (r);
  4911. replGen = replica_get_generation (r);
  4912. fileName = _cl5MakeFileName (replName, replGen) ;
  4913. slapi_ch_free ((void**)&replGen);
  4914. return fileName;
  4915. }
  4916. static char* _cl5MakeFileName (const char *replName, const char *replGen)
  4917. {
  4918. char *fileName = slapi_ch_smprintf("%s/%s%s%s.%s",
  4919. s_cl5Desc.dbDir, replName,
  4920. FILE_SEP, replGen, DB_EXTENSION);
  4921. return fileName;
  4922. }
  4923. /* open file that corresponds to a particular database */
  4924. static int _cl5DBOpenFile (Object *replica, Object **obj, PRBool checkDups)
  4925. {
  4926. int rc;
  4927. const char *replName;
  4928. char *replGen;
  4929. Replica *r;
  4930. PR_ASSERT (replica);
  4931. r = (Replica*)object_get_data (replica);
  4932. replName = replica_get_name (r);
  4933. PR_ASSERT (replName);
  4934. replGen = replica_get_generation (r);
  4935. PR_ASSERT (replGen);
  4936. rc = _cl5DBOpenFileByReplicaName (replName, replGen, obj, checkDups);
  4937. slapi_ch_free ((void**)&replGen);
  4938. return rc;
  4939. }
  4940. static int _cl5DBOpenFileByReplicaName (const char *replName, const char *replGen,
  4941. Object **obj, PRBool checkDups)
  4942. {
  4943. int rc = CL5_SUCCESS;
  4944. Object *tmpObj;
  4945. CL5DBFile *file;
  4946. char *file_name;
  4947. PR_ASSERT (replName && replGen);
  4948. if (checkDups)
  4949. {
  4950. PR_Lock (s_cl5Desc.fileLock);
  4951. file_name = _cl5MakeFileName (replName, replGen);
  4952. tmpObj = objset_find (s_cl5Desc.dbFiles, _cl5CompareDBFile, file_name);
  4953. slapi_ch_free((void **)&file_name);
  4954. if (tmpObj) /* this file already exist */
  4955. {
  4956. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4957. "_cl5DBOpenFileByReplicaName: Found DB object %p for replica %s\n", tmpObj, replName);
  4958. /* if we were asked for file handle - keep the handle */
  4959. if (obj)
  4960. {
  4961. *obj = tmpObj;
  4962. }
  4963. else
  4964. {
  4965. object_release (tmpObj);
  4966. }
  4967. rc = CL5_SUCCESS;
  4968. goto done;
  4969. }
  4970. }
  4971. rc = _cl5NewDBFile (replName, replGen, &file);
  4972. if (rc == CL5_SUCCESS)
  4973. {
  4974. /* This creates the file but doesn't set the init flag
  4975. * The flag is set later when the purge and max ruvs are set.
  4976. * This is to prevent some thread to get file access before the
  4977. * structure is fully initialized */
  4978. rc = _cl5AddDBFile (file, &tmpObj);
  4979. if (rc == CL5_SUCCESS)
  4980. {
  4981. /* read purge RUV - done here because it needs file object rather than file pointer */
  4982. rc = _cl5ReadRUV (replGen, tmpObj, PR_TRUE);
  4983. if (rc != CL5_SUCCESS)
  4984. {
  4985. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4986. "_cl5DBOpenFileByReplicaName: failed to get purge RUV\n");
  4987. goto done;
  4988. }
  4989. /* read ruv that represents the upper bound of the changes stored in the file */
  4990. rc = _cl5ReadRUV (replGen, tmpObj, PR_FALSE);
  4991. if (rc != CL5_SUCCESS)
  4992. {
  4993. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  4994. "_cl5DBOpenFileByReplicaName: failed to get upper bound RUV\n");
  4995. goto done;
  4996. }
  4997. /* Mark the DB File initialize */
  4998. _cl5DBFileInitialized(tmpObj);
  4999. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  5000. "_cl5DBOpenFileByReplicaName: created new DB object %p\n", tmpObj);
  5001. if (obj)
  5002. {
  5003. *obj = tmpObj;
  5004. }
  5005. else
  5006. {
  5007. object_release (tmpObj);
  5008. }
  5009. }
  5010. }
  5011. done:;
  5012. if (rc != CL5_SUCCESS)
  5013. {
  5014. if (file)
  5015. _cl5DBCloseFile ((void**)&file);
  5016. }
  5017. if (checkDups)
  5018. {
  5019. PR_Unlock (s_cl5Desc.fileLock);
  5020. }
  5021. return rc;
  5022. }
  5023. /* adds file to the db file list */
  5024. static int _cl5AddDBFile (CL5DBFile *file, Object **obj)
  5025. {
  5026. int rc;
  5027. Object *tmpObj;
  5028. PR_ASSERT (file);
  5029. tmpObj = object_new (file, _cl5DBCloseFile);
  5030. rc = objset_add_obj(s_cl5Desc.dbFiles, tmpObj);
  5031. if (rc != OBJSET_SUCCESS)
  5032. {
  5033. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  5034. "_cl5AddDBFile: failed to add db file to the list; "
  5035. "repl_objset error - %d\n", rc);
  5036. object_release (tmpObj);
  5037. return CL5_OBJSET_ERROR;
  5038. }
  5039. else
  5040. {
  5041. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  5042. "_cl5AddDBFile: Added new DB object %p\n", tmpObj);
  5043. }
  5044. if (obj)
  5045. {
  5046. *obj = tmpObj;
  5047. }
  5048. else
  5049. object_release (tmpObj);
  5050. return CL5_SUCCESS;
  5051. }
  5052. static int _cl5NewDBFile (const char *replName, const char *replGen, CL5DBFile** dbFile)
  5053. {
  5054. int rc;
  5055. DB *db = NULL;
  5056. char *name;
  5057. char *semadir;
  5058. #ifdef HPUX
  5059. char cwd [PATH_MAX+1];
  5060. #endif
  5061. PR_ASSERT (replName && replGen && dbFile);
  5062. if (!dbFile) {
  5063. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5064. "_cl5NewDBFile: NULL dbFile\n");
  5065. return CL5_UNKNOWN_ERROR;
  5066. }
  5067. (*dbFile) = (CL5DBFile *)slapi_ch_calloc (1, sizeof (CL5DBFile));
  5068. if (*dbFile == NULL)
  5069. {
  5070. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5071. "_cl5NewDBFile: memory allocation failed\n");
  5072. return CL5_MEMORY_ERROR;
  5073. }
  5074. name = _cl5MakeFileName (replName, replGen);
  5075. {
  5076. /* The subname argument allows applications to have
  5077. * subdatabases, i.e., multiple databases inside of a single
  5078. * physical file. This is useful when the logical databases
  5079. * are both numerous and reasonably small, in order to
  5080. * avoid creating a large number of underlying files.
  5081. */
  5082. char *subname = NULL;
  5083. DB_ENV *dbEnv = s_cl5Desc.dbEnv;
  5084. rc = db_create(&db, dbEnv, 0);
  5085. if (0 != rc) {
  5086. goto out;
  5087. }
  5088. rc = db->set_pagesize(
  5089. db,
  5090. s_cl5Desc.dbConfig.pageSize);
  5091. if (0 != rc) {
  5092. goto out;
  5093. }
  5094. #if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 3300
  5095. rc = db->set_malloc(db, (void *)slapi_ch_malloc);
  5096. if (0 != rc) {
  5097. goto out;
  5098. }
  5099. #endif
  5100. DB_OPEN(s_cl5Desc.dbEnvOpenFlags,
  5101. db, NULL /* txnid */, name, subname, DB_BTREE,
  5102. DB_CREATE | DB_THREAD, s_cl5Desc.dbConfig.fileMode, rc);
  5103. }
  5104. out:
  5105. if (rc != 0)
  5106. {
  5107. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5108. "_cl5NewDBFile: db_open failed; db error - %d %s\n",
  5109. rc, db_strerror(rc));
  5110. rc = CL5_DB_ERROR;
  5111. goto done;
  5112. }
  5113. (*dbFile)->db = db;
  5114. (*dbFile)->name = name;
  5115. (*dbFile)->replName = slapi_ch_strdup (replName);
  5116. (*dbFile)->replGen = slapi_ch_strdup (replGen);
  5117. /*
  5118. * Considerations for setting up cl semaphore:
  5119. * (1) The NT version of SleepyCat uses test-and-set mutexes
  5120. * at the DB page level instead of blocking mutexes. That has
  5121. * proven to be a killer for the changelog DB, as this DB is
  5122. * accessed by multiple a reader threads (the repl thread) and
  5123. * writer threads (the server ops threads) usually at the last
  5124. * pages of the DB, due to the sequential nature of the changelog
  5125. * keys. To avoid the test-and-set mutexes, we could use semaphore
  5126. * to serialize the writers and avoid the high mutex contention
  5127. * that SleepyCat is unable to avoid.
  5128. * (2) DS 6.2 introduced the semaphore on all platforms (replaced
  5129. * the serial lock used on Windows and Linux described above).
  5130. * The number of the concurrent writes now is configurable by
  5131. * nsslapd-changelogmaxconcurrentwrites (the server needs to
  5132. * be restarted).
  5133. */
  5134. semadir = s_cl5Desc.dbDir;
  5135. #ifdef HPUX
  5136. /*
  5137. * HP sem_open() does not allow pathname component "./" or "../"
  5138. * in the semaphore name. For simplicity and to avoid doing
  5139. * chdir() in multi-thread environment, current working dir
  5140. * (log dir) is used to replace the original semaphore dir
  5141. * if it contains "./".
  5142. */
  5143. if ( strstr ( semadir, "./" ) != NULL && getcwd ( cwd, PATH_MAX+1 ) != NULL )
  5144. {
  5145. semadir = cwd;
  5146. }
  5147. #endif
  5148. if ( semadir != NULL )
  5149. {
  5150. (*dbFile)->semaName = slapi_ch_smprintf("%s/%s.sema", semadir, replName);
  5151. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  5152. "_cl5NewDBFile: semaphore %s\n", (*dbFile)->semaName);
  5153. (*dbFile)->sema = PR_OpenSemaphore((*dbFile)->semaName,
  5154. PR_SEM_CREATE | PR_SEM_EXCL, 0666,
  5155. s_cl5Desc.dbConfig.maxConcurrentWrites );
  5156. slapi_log_error (SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5NewDBFile: maxConcurrentWrites=%d\n", s_cl5Desc.dbConfig.maxConcurrentWrites );
  5157. }
  5158. if ((*dbFile)->sema == NULL )
  5159. {
  5160. /* If the semaphore was left around due
  5161. * to an unclean exit last time, remove
  5162. * and re-create it.
  5163. */
  5164. if (PR_GetError() == PR_FILE_EXISTS_ERROR) {
  5165. PR_DeleteSemaphore((*dbFile)->semaName);
  5166. (*dbFile)->sema = PR_OpenSemaphore((*dbFile)->semaName,
  5167. PR_SEM_CREATE | PR_SEM_EXCL, 0666,
  5168. s_cl5Desc.dbConfig.maxConcurrentWrites );
  5169. }
  5170. /* If we still failed to create the semaphore,
  5171. * we should just error out. */
  5172. if ((*dbFile)->sema == NULL )
  5173. {
  5174. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5175. "_cl5NewDBFile: failed to create semaphore %s; NSPR error - %d\n",
  5176. (*dbFile)->semaName ? (*dbFile)->semaName : "(nil)", PR_GetError());
  5177. rc = CL5_SYSTEM_ERROR;
  5178. goto done;
  5179. }
  5180. }
  5181. /* compute number of entries in the file */
  5182. /* ONREPL - to improve performance, we keep entry count in memory
  5183. and write it down during shutdown. Problem: this will not
  5184. work with multiple processes. Do we have to worry about that?
  5185. */
  5186. if (s_cl5Desc.dbOpenMode == CL5_OPEN_NORMAL)
  5187. {
  5188. rc = _cl5GetEntryCount (*dbFile);
  5189. if (rc != CL5_SUCCESS)
  5190. {
  5191. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  5192. "_cl5NewDBFile: failed to get entry count\n");
  5193. goto done;
  5194. }
  5195. }
  5196. done:
  5197. if (rc != CL5_SUCCESS)
  5198. {
  5199. _cl5DBCloseFile ((void**)dbFile);
  5200. /* slapi_ch_free accepts NULL pointer */
  5201. slapi_ch_free ((void**)&name);
  5202. slapi_ch_free ((void**)dbFile);
  5203. }
  5204. return rc;
  5205. }
  5206. static void _cl5DBCloseFile (void **data)
  5207. {
  5208. CL5DBFile *file;
  5209. int rc = 0;
  5210. PR_ASSERT (data);
  5211. file = *(CL5DBFile**)data;
  5212. PR_ASSERT (file);
  5213. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
  5214. "Closing database %s\n", file->name);
  5215. /* close the file */
  5216. /* if this is normal close or close after import, update entry count */
  5217. if ((s_cl5Desc.dbOpenMode == CL5_OPEN_NORMAL && s_cl5Desc.dbState == CL5_STATE_CLOSING) ||
  5218. s_cl5Desc.dbOpenMode == CL5_OPEN_LDIF2CL)
  5219. {
  5220. _cl5WriteEntryCount (file);
  5221. _cl5WriteRUV (file, PR_TRUE);
  5222. _cl5WriteRUV (file, PR_FALSE);
  5223. }
  5224. /* close the db */
  5225. if (file->db) {
  5226. rc = file->db->close(file->db, 0);
  5227. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  5228. "_cl5DBCloseFile: "
  5229. "Closed the changelog database handle for %s "
  5230. "(rc: %d)\n", file->name, rc);
  5231. file->db = NULL;
  5232. }
  5233. if (file->flags & DB_FILE_DELETED)
  5234. {
  5235. /* We need to use the libdb API to delete the files, otherwise we'll
  5236. * run into problems when we try to checkpoint transactions later. */
  5237. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
  5238. "removing the changelog %s (flag %d)\n",
  5239. file->name, DEFAULT_DB_ENV_OP_FLAGS);
  5240. rc = s_cl5Desc.dbEnv->dbremove(s_cl5Desc.dbEnv, 0, file->name, 0,
  5241. DEFAULT_DB_ENV_OP_FLAGS);
  5242. if (rc != 0)
  5243. {
  5244. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
  5245. "failed to remove (%s) file; libdb error - %d (%s)\n",
  5246. file->name, rc, db_strerror(rc));
  5247. } else {
  5248. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
  5249. "Deleted the changelog database file %s\n", file->name);
  5250. }
  5251. }
  5252. /* slapi_ch_free accepts NULL pointer */
  5253. slapi_ch_free ((void**)&file->name);
  5254. slapi_ch_free ((void**)&file->replName);
  5255. slapi_ch_free ((void**)&file->replGen);
  5256. ruv_destroy(&file->maxRUV);
  5257. ruv_destroy(&file->purgeRUV);
  5258. file->db = NULL;
  5259. if (file->sema) {
  5260. PR_CloseSemaphore (file->sema);
  5261. PR_DeleteSemaphore (file->semaName);
  5262. file->sema = NULL;
  5263. }
  5264. slapi_ch_free ((void**)&file->semaName);
  5265. slapi_ch_free (data);
  5266. }
  5267. static int _cl5GetDBFile (Object *replica, Object **obj)
  5268. {
  5269. char *fileName;
  5270. PR_ASSERT (replica && obj);
  5271. fileName = _cl5Replica2FileName (replica);
  5272. *obj = objset_find(s_cl5Desc.dbFiles, _cl5CompareDBFile, fileName);
  5273. if (*obj)
  5274. {
  5275. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFile: "
  5276. "found DB object %p for database %s\n", *obj, fileName);
  5277. slapi_ch_free_string(&fileName);
  5278. return CL5_SUCCESS;
  5279. }
  5280. else
  5281. {
  5282. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFile: "
  5283. "no DB object found for database %s\n", fileName);
  5284. slapi_ch_free_string(&fileName);
  5285. return CL5_NOTFOUND;
  5286. }
  5287. }
  5288. static int _cl5GetDBFileByReplicaName (const char *replName, const char *replGen,
  5289. Object **obj)
  5290. {
  5291. char *fileName;
  5292. PR_ASSERT (replName && replGen && obj);
  5293. fileName = _cl5MakeFileName (replName, replGen);
  5294. *obj = objset_find(s_cl5Desc.dbFiles, _cl5CompareDBFile, fileName);
  5295. if (*obj)
  5296. {
  5297. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFileByReplicaName: "
  5298. "found DB object %p for database %s\n", *obj, fileName);
  5299. slapi_ch_free_string(&fileName);
  5300. return CL5_SUCCESS;
  5301. }
  5302. else
  5303. {
  5304. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFileByReplicaName: "
  5305. "no DB object found for database %s\n", fileName);
  5306. slapi_ch_free_string(&fileName);
  5307. return CL5_NOTFOUND;
  5308. }
  5309. }
  5310. static void _cl5DBDeleteFile (Object *obj)
  5311. {
  5312. CL5DBFile *file;
  5313. int rc = 0;
  5314. PR_ASSERT (obj);
  5315. file = (CL5DBFile*)object_get_data (obj);
  5316. PR_ASSERT (file);
  5317. file->flags |= DB_FILE_DELETED;
  5318. rc = objset_remove_obj(s_cl5Desc.dbFiles, obj);
  5319. if (rc != OBJSET_SUCCESS) {
  5320. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBDeleteFile: "
  5321. "could not find DB object %p\n", obj);
  5322. } else {
  5323. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBDeleteFile: "
  5324. "removed DB object %p\n", obj);
  5325. }
  5326. object_release (obj);
  5327. }
  5328. static void _cl5DBFileInitialized (Object *obj)
  5329. {
  5330. CL5DBFile *file;
  5331. PR_ASSERT (obj);
  5332. file = (CL5DBFile*)object_get_data (obj);
  5333. PR_ASSERT (file);
  5334. file->flags |= DB_FILE_INIT;
  5335. }
  5336. static int _cl5CompareDBFile (Object *el1, const void *el2)
  5337. {
  5338. CL5DBFile *file;
  5339. const char *name;
  5340. PR_ASSERT (el1 && el2);
  5341. file = (CL5DBFile*) object_get_data (el1);
  5342. name = (const char*) el2;
  5343. return ((file->flags & DB_FILE_INIT) ? strcmp (file->name, name) : 1);
  5344. }
  5345. /*
  5346. * return 1: true (the "filename" ends with "ext")
  5347. * return 0: false
  5348. */
  5349. static int _cl5FileEndsWith(const char *filename, const char *ext)
  5350. {
  5351. char *p = NULL;
  5352. int flen = strlen(filename);
  5353. int elen = strlen(ext);
  5354. if (0 == flen || 0 == elen)
  5355. {
  5356. return 0;
  5357. }
  5358. p = strstr(filename, ext);
  5359. if (NULL == p)
  5360. {
  5361. return 0;
  5362. }
  5363. if (p - filename + elen == flen)
  5364. {
  5365. return 1;
  5366. }
  5367. return 0;
  5368. }
  5369. static int _cl5ExportFile (PRFileDesc *prFile, Object *obj)
  5370. {
  5371. int rc;
  5372. void *iterator = NULL;
  5373. slapi_operation_parameters op = {0};
  5374. char *buff;
  5375. PRInt32 len, wlen;
  5376. CL5Entry entry;
  5377. CL5DBFile *file;
  5378. PR_ASSERT (prFile && obj);
  5379. file = (CL5DBFile*)object_get_data (obj);
  5380. PR_ASSERT (file);
  5381. if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) {
  5382. ruv_dump (file->purgeRUV, "clpurgeruv", prFile);
  5383. ruv_dump (file->maxRUV, "clmaxruv", prFile);
  5384. }
  5385. slapi_write_buffer (prFile, "\n", strlen("\n"));
  5386. entry.op = &op;
  5387. rc = _cl5GetFirstEntry (obj, &entry, &iterator, NULL);
  5388. while (rc == CL5_SUCCESS)
  5389. {
  5390. rc = _cl5Operation2LDIF (&op, file->replGen, &buff, &len);
  5391. if (rc != CL5_SUCCESS)
  5392. {
  5393. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5394. "_cl5ExportFile: failed to convert operation to ldif\n");
  5395. operation_parameters_done (&op);
  5396. break;
  5397. }
  5398. wlen = slapi_write_buffer (prFile, buff, len);
  5399. slapi_ch_free((void **)&buff);
  5400. if (wlen < len)
  5401. {
  5402. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5403. "_cl5ExportFile: failed to write to ldif file\n");
  5404. rc = CL5_SYSTEM_ERROR;
  5405. operation_parameters_done (&op);
  5406. break;
  5407. }
  5408. cl5_operation_parameters_done (&op);
  5409. rc = _cl5GetNextEntry (&entry, iterator);
  5410. }
  5411. cl5_operation_parameters_done (&op);
  5412. if (iterator)
  5413. cl5DestroyIterator (iterator);
  5414. if (rc != CL5_NOTFOUND)
  5415. {
  5416. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5417. "_cl5ExportFile: failed to retrieve changelog entry\n");
  5418. }
  5419. else
  5420. {
  5421. rc = CL5_SUCCESS;
  5422. }
  5423. return rc;
  5424. }
  5425. static PRBool _cl5ReplicaInList (Object *replica, Object **replicas)
  5426. {
  5427. int i;
  5428. PR_ASSERT (replica && replicas);
  5429. /* ONREPL I think it should be sufficient to just compare replica pointers */
  5430. for (i=0; replicas[i]; i++)
  5431. {
  5432. if (replica == replicas[i])
  5433. return PR_TRUE;
  5434. }
  5435. return PR_FALSE;
  5436. }
  5437. static char* _cl5GetHelperEntryKey (int type, char *csnStr)
  5438. {
  5439. CSN *csn= csn_new();
  5440. char *rt;
  5441. csn_set_time(csn, (time_t)type);
  5442. csn_set_replicaid(csn, 0);
  5443. rt = csn_as_string(csn, PR_FALSE, csnStr);
  5444. csn_free(&csn);
  5445. return rt;
  5446. }
  5447. static Object* _cl5GetReplica (const slapi_operation_parameters *op, const char* replGen)
  5448. {
  5449. Slapi_DN *sdn;
  5450. Object *replObj;
  5451. Replica *replica;
  5452. char *newGen;
  5453. PR_ASSERT (op && replGen);
  5454. sdn = op->target_address.sdn;
  5455. replObj = replica_get_replica_from_dn (sdn);
  5456. if (replObj)
  5457. {
  5458. /* check to see if replica generation has not change */
  5459. replica = (Replica*)object_get_data (replObj);
  5460. PR_ASSERT (replica);
  5461. newGen = replica_get_generation (replica);
  5462. PR_ASSERT (newGen);
  5463. if (strcmp (replGen, newGen) != 0)
  5464. {
  5465. object_release (replObj);
  5466. replObj = NULL;
  5467. }
  5468. slapi_ch_free ((void**)&newGen);
  5469. }
  5470. return replObj;
  5471. }
  5472. int
  5473. cl5_is_diskfull()
  5474. {
  5475. int rc;
  5476. PR_Lock(cl5_diskfull_lock);
  5477. rc = cl5_diskfull_flag;
  5478. PR_Unlock(cl5_diskfull_lock);
  5479. return rc;
  5480. }
  5481. static void
  5482. cl5_set_diskfull()
  5483. {
  5484. PR_Lock(cl5_diskfull_lock);
  5485. cl5_diskfull_flag = 1;
  5486. PR_Unlock(cl5_diskfull_lock);
  5487. }
  5488. static void
  5489. cl5_set_no_diskfull()
  5490. {
  5491. PR_Lock(cl5_diskfull_lock);
  5492. cl5_diskfull_flag = 0;
  5493. PR_Unlock(cl5_diskfull_lock);
  5494. }
  5495. int
  5496. cl5_diskspace_is_available()
  5497. {
  5498. int rval = 1;
  5499. #if defined( OS_solaris ) || defined( hpux )
  5500. struct statvfs fsbuf;
  5501. if (statvfs(s_cl5Desc.dbDir, &fsbuf) < 0)
  5502. {
  5503. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5504. "cl5_diskspace_is_available: Cannot get file system info\n");
  5505. rval = 0;
  5506. }
  5507. else
  5508. {
  5509. unsigned long fsiz = fsbuf.f_bavail * fsbuf.f_frsize;
  5510. if (fsiz < NO_DISK_SPACE)
  5511. {
  5512. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5513. "cl5_diskspace_is_available: No enough diskspace for changelog: (%u bytes free)\n", fsiz);
  5514. rval = 0;
  5515. }
  5516. else if (fsiz > MIN_DISK_SPACE)
  5517. {
  5518. /* assume recovered */
  5519. cl5_set_no_diskfull();
  5520. }
  5521. }
  5522. #endif
  5523. #if defined( linux )
  5524. struct statfs fsbuf;
  5525. if (statfs(s_cl5Desc.dbDir, &fsbuf) < 0)
  5526. {
  5527. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5528. "cl5_diskspace_is_available: Cannot get file system info\n");
  5529. rval = 0;
  5530. }
  5531. else
  5532. {
  5533. unsigned long fsiz = fsbuf.f_bavail * fsbuf.f_bsize;
  5534. if (fsiz < NO_DISK_SPACE)
  5535. {
  5536. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5537. "cl5_diskspace_is_available: No enough diskspace for changelog: (%lu bytes free)\n", fsiz);
  5538. rval = 0;
  5539. }
  5540. else if (fsiz > MIN_DISK_SPACE)
  5541. {
  5542. /* assume recovered */
  5543. cl5_set_no_diskfull();
  5544. }
  5545. }
  5546. #endif
  5547. return rval;
  5548. }
  5549. int
  5550. cl5DbDirIsEmpty(const char *dir)
  5551. {
  5552. PRDir *prDir;
  5553. PRDirEntry *prDirEntry;
  5554. int isempty = 1;
  5555. if (!dir || !*dir) {
  5556. return isempty;
  5557. }
  5558. /* assume failure means it does not exist - other failure
  5559. cases will be handled by code which attempts to create the
  5560. db in this directory */
  5561. if (PR_Access(dir, PR_ACCESS_EXISTS)) {
  5562. return isempty;
  5563. }
  5564. prDir = PR_OpenDir(dir);
  5565. if (prDir == NULL) {
  5566. return isempty; /* assume failure means does not exist */
  5567. }
  5568. while (NULL != (prDirEntry = PR_ReadDir(prDir, PR_SKIP_DOT | PR_SKIP_DOT_DOT))) {
  5569. if (NULL == prDirEntry->name) { /* NSPR doesn't behave like the docs say it should */
  5570. break;
  5571. }
  5572. isempty = 0; /* found at least one "real" file */
  5573. break;
  5574. }
  5575. PR_CloseDir(prDir);
  5576. return isempty;
  5577. }
  5578. /*
  5579. * Write RUVs into the changelog;
  5580. * implemented for backup to make sure the backed up changelog contains RUVs
  5581. * Return values: 0 -- success
  5582. * 1 -- failure
  5583. */
  5584. int
  5585. cl5WriteRUV()
  5586. {
  5587. int rc = 0;
  5588. Object *file_obj = NULL;
  5589. CL5DBFile *dbfile = NULL;
  5590. int closeit = 0;
  5591. int slapd_pid = 0;
  5592. changelog5Config config;
  5593. /* read changelog configuration */
  5594. changelog5_read_config (&config);
  5595. if (config.dir == NULL) {
  5596. /* Changelog is not configured; Replication is not enabled.
  5597. * we don't have to update RUVs.
  5598. * bail out - return success */
  5599. goto bail;
  5600. }
  5601. slapd_pid = is_slapd_running();
  5602. if (slapd_pid <= 0) {
  5603. /* I'm not a server, rather a utility.
  5604. * And the server is NOT running.
  5605. * RUVs should be in the changelog.
  5606. * we don't have to update RUVs.
  5607. * bail out - return success */
  5608. goto bail;
  5609. }
  5610. if (getpid() != slapd_pid) {
  5611. /* I'm not a server, rather a utility.
  5612. * And the server IS running.
  5613. * RUVs are not in the changelog and no easy way to retrieve them.
  5614. * bail out - return failure */
  5615. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5616. "cl5WriteRUV: server (pid %d) is already running; bail.\n",
  5617. slapd_pid);
  5618. rc = 1;
  5619. goto bail;
  5620. }
  5621. /* file is stored in the changelog directory and is named
  5622. * <replica name>.ldif */
  5623. if (CL5_STATE_OPEN != s_cl5Desc.dbState) {
  5624. rc = _cl5Open(config.dir, &config.dbconfig, CL5_OPEN_NORMAL);
  5625. if (rc != CL5_SUCCESS) {
  5626. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5627. "cl5WriteRUV: failed to open changelog\n");
  5628. goto bail;
  5629. }
  5630. s_cl5Desc.dbState = CL5_STATE_OPEN; /* force to change the state */
  5631. closeit = 1; /* It had not been opened; close it */
  5632. }
  5633. file_obj = objset_first_obj(s_cl5Desc.dbFiles);
  5634. while (file_obj) {
  5635. dbfile = (CL5DBFile *)object_get_data(file_obj);
  5636. if (dbfile) {
  5637. _cl5WriteEntryCount(dbfile);
  5638. _cl5WriteRUV(dbfile, PR_TRUE);
  5639. _cl5WriteRUV(dbfile, PR_FALSE);
  5640. }
  5641. file_obj = objset_next_obj(s_cl5Desc.dbFiles, file_obj);
  5642. }
  5643. bail:
  5644. if (closeit && (CL5_STATE_OPEN == s_cl5Desc.dbState)) {
  5645. _cl5Close ();
  5646. s_cl5Desc.dbState = CL5_STATE_CLOSED; /* force to change the state */
  5647. }
  5648. changelog5_config_done(&config);
  5649. return rc;
  5650. }
  5651. /*
  5652. * Delete RUVs from the changelog;
  5653. * implemented for backup to clean up RUVs
  5654. * Return values: 0 -- success
  5655. * 1 -- failure
  5656. */
  5657. int
  5658. cl5DeleteRUV()
  5659. {
  5660. int rc = 0;
  5661. Object *file_obj = NULL;
  5662. CL5DBFile *dbfile = NULL;
  5663. int slapd_pid = 0;
  5664. int closeit = 0;
  5665. changelog5Config config;
  5666. /* read changelog configuration */
  5667. changelog5_read_config (&config);
  5668. if (config.dir == NULL) {
  5669. /* Changelog is not configured; Replication is not enabled.
  5670. * we don't have to update RUVs.
  5671. * bail out - return success */
  5672. goto bail;
  5673. }
  5674. slapd_pid = is_slapd_running();
  5675. if (slapd_pid <= 0) {
  5676. /* I'm not a server, rather a utility.
  5677. * And the server is NOT running.
  5678. * RUVs should be in the changelog.
  5679. * we don't have to update RUVs.
  5680. * bail out - return success */
  5681. goto bail;
  5682. }
  5683. if (getpid() != slapd_pid) {
  5684. /* I'm not a server, rather a utility.
  5685. * And the server IS running.
  5686. * RUVs are not in the changelog.
  5687. * bail out - return success */
  5688. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5689. "cl5DeleteRUV: server (pid %d) is already running; bail.\n",
  5690. slapd_pid);
  5691. goto bail;
  5692. }
  5693. /* file is stored in the changelog directory and is named
  5694. * <replica name>.ldif */
  5695. if (CL5_STATE_OPEN != s_cl5Desc.dbState) {
  5696. rc = _cl5Open(config.dir, &config.dbconfig, CL5_OPEN_NORMAL);
  5697. if (rc != CL5_SUCCESS) {
  5698. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5699. "cl5DeleteRUV: failed to open changelog\n");
  5700. goto bail;
  5701. }
  5702. s_cl5Desc.dbState = CL5_STATE_OPEN; /* force to change the state */
  5703. closeit = 1; /* It had been opened; no need to close */
  5704. }
  5705. file_obj = objset_first_obj(s_cl5Desc.dbFiles);
  5706. while (file_obj) {
  5707. dbfile = (CL5DBFile *)object_get_data(file_obj);
  5708. /* _cl5GetEntryCount deletes entry count after reading it */
  5709. rc = _cl5GetEntryCount(dbfile);
  5710. if (rc != CL5_SUCCESS)
  5711. {
  5712. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
  5713. "cl5DeleteRUV: failed to get/delete entry count\n");
  5714. goto bail;
  5715. }
  5716. /* _cl5ReadRUV deletes RUV after reading it */
  5717. rc = _cl5ReadRUV (dbfile->replGen, file_obj, PR_TRUE);
  5718. if (rc != CL5_SUCCESS) {
  5719. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5720. "cl5DeleteRUV: failed to read/delete purge RUV\n");
  5721. goto bail;
  5722. }
  5723. rc = _cl5ReadRUV (dbfile->replGen, file_obj, PR_FALSE);
  5724. if (rc != CL5_SUCCESS) {
  5725. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5726. "cl5DeleteRUV: failed to read/delete upper bound RUV\n");
  5727. goto bail;
  5728. }
  5729. file_obj = objset_next_obj(s_cl5Desc.dbFiles, file_obj);
  5730. }
  5731. bail:
  5732. if (file_obj) {
  5733. object_release (file_obj);
  5734. }
  5735. if (closeit && (CL5_STATE_OPEN == s_cl5Desc.dbState)) {
  5736. _cl5Close ();
  5737. s_cl5Desc.dbState = CL5_STATE_CLOSED; /* force to change the state */
  5738. }
  5739. changelog5_config_done(&config);
  5740. return rc;
  5741. }
  5742. /*
  5743. * Clean the in memory RUV, at shutdown we will write the update to the db
  5744. */
  5745. void
  5746. cl5CleanRUV(ReplicaId rid){
  5747. CL5DBFile *file;
  5748. Object *obj = NULL;
  5749. slapi_rwlock_wrlock (s_cl5Desc.stLock);
  5750. obj = objset_first_obj(s_cl5Desc.dbFiles);
  5751. while (obj){
  5752. file = (CL5DBFile *)object_get_data(obj);
  5753. ruv_delete_replica(file->purgeRUV, rid);
  5754. ruv_delete_replica(file->maxRUV, rid);
  5755. obj = objset_next_obj(s_cl5Desc.dbFiles, obj);
  5756. }
  5757. slapi_rwlock_unlock (s_cl5Desc.stLock);
  5758. }
  5759. void trigger_cl_trimming(ReplicaId rid){
  5760. PRThread *trim_tid = NULL;
  5761. slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "trigger_cl_trimming: rid (%d)\n",(int)rid);
  5762. trim_tid = PR_CreateThread(PR_USER_THREAD, (VFP)(void*)trigger_cl_trimming_thread,
  5763. (void *)&rid, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
  5764. PR_UNJOINABLE_THREAD, DEFAULT_THREAD_STACKSIZE);
  5765. if (NULL == trim_tid){
  5766. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5767. "trigger_cl_trimming: failed to create trimming "
  5768. "thread; NSPR error - %d\n", PR_GetError ());
  5769. } else {
  5770. /* need a little time for the thread to get started */
  5771. DS_Sleep(PR_SecondsToInterval(1));
  5772. }
  5773. }
  5774. void
  5775. trigger_cl_trimming_thread(void *arg){
  5776. ReplicaId rid = *(ReplicaId *)arg;
  5777. /* make sure we have a change log, and we aren't closing it */
  5778. if(s_cl5Desc.dbState == CL5_STATE_CLOSED || s_cl5Desc.dbState == CL5_STATE_CLOSING){
  5779. return;
  5780. }
  5781. if (CL5_SUCCESS != _cl5AddThread()) {
  5782. slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
  5783. "trigger_cl_trimming: failed to increment thread count "
  5784. "NSPR error - %d\n", PR_GetError ());
  5785. }
  5786. _cl5DoTrimming(rid);
  5787. _cl5RemoveThread();
  5788. }