cl5_api.c 191 KB

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