123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396(* The MIT License
Copyright (c) 2019 Craig Ferguson <craig@tarides.com>
Thomas Gazagnaire <thomas@tarides.com>
Ioana Cristescu <ioana@tarides.com>
Clément Pascutto <clement@tarides.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. *)open!Importletsrc=Logs.Src.create"index_unix"~doc:"Index_unix"moduleLog=(valLogs.src_logsrc:Logs.LOG)exceptionRO_not_allowedletcurrent_version="00000001"moduleStats=Index.StatsmoduleIO:Index.Platform.IO=structlet(++)=Int63.addlet(--)=Int63.subtypet={mutablefile:string;mutableheader:int63;mutableraw:Raw.t;mutableoffset:int63;mutableflushed:int63;mutablefan_size:int63;readonly:bool;buf:Buffer.t;flush_callback:unit->unit;}letflush?no_callback?(with_fsync=false)t=ift.readonlythenraiseRO_not_allowed;ifnot(Buffer.is_emptyt.buf)then(letbuf_len=Buffer.lengtht.bufinletoffset=t.offsetin(matchno_callbackwithSome()->()|None->t.flush_callback());Log.debug(funl->l"[%s] flushing %d bytes"t.filebuf_len);Buffer.write_with(Raw.unsafe_writet.raw~off:t.flushed)t.buf;Buffer.cleart.buf;Raw.Offset.sett.rawoffset;assert(t.flushed++Int63.of_intbuf_len=t.header++offset);t.flushed<-offset++t.header);ifwith_fsyncthenRaw.fsynct.rawletrename~src~dst=flush~with_fsync:truesrc;Raw.closedst.raw;Unix.renamesrc.filedst.file;Buffer.cleardst.buf;src.file<-dst.file;dst.header<-src.header;dst.fan_size<-src.fan_size;dst.offset<-src.offset;dst.flushed<-src.flushed;dst.raw<-src.rawletcloset=ifnott.readonlythenBuffer.cleart.buf;Raw.closet.rawletauto_flush_limit=Int63.of_int1_000_000letappend_substringtbuf~off~len=ift.readonlythenraiseRO_not_allowed;Buffer.add_substringt.bufbuf~off~len;letlen=Int63.of_intlenint.offset<-t.offset++len;ift.offset--t.flushed>auto_flush_limitthenflushtletappendtbuf=append_substringtbuf~off:0~len:(String.lengthbuf)letreadt~off~lenbuf=ifnott.readonlythenassert(t.header++off<=t.flushed);Raw.unsafe_readt.raw~off:(t.header++off)~lenbufletoffsett=t.offsetletget_generationt=leti=Raw.Generation.gett.rawinLog.debug(funm->m"get_generation: %a"Int63.ppi);iletget_fanoutt=Raw.Fan.gett.rawletget_fanout_sizet=Raw.Fan.get_sizet.rawletset_fanouttbuf=assert(Int63.(equal(of_int(String.lengthbuf))t.fan_size));Raw.Fan.sett.rawbufmoduleHeader=structtypeheader={offset:int63;generation:int63}letppppf{offset;generation}=Format.fprintfppf"{ offset = %a; generation = %a }"Int63.ppoffsetInt63.ppgenerationletgett=letRaw.Header.{offset;generation;_}=Raw.Header.gett.rawint.offset<-offset;letheaders={offset;generation}inLog.debug(funm->m"[%s] get_headers: %a"t.fileppheaders);headersletsett{offset;generation}=letversion=current_versioninLog.debug(funm->m"[%s] set_header %a"t.filepp{offset;generation});Raw.Header.(sett.raw{offset;version;generation})endletprotect_unix_exn=function|Unix.Unix_error_ase->failwith(Printexc.to_stringe)|e->raiseeletignore_enoent=function|Unix.Unix_error(Unix.ENOENT,_,_)->()|e->raiseeletprotectfx=tryfxwithe->protect_unix_exneletsafefx=tryfxwithe->ignore_enoenteletmkdirdirname=letrecauxdirk=ifSys.file_existsdir&&Sys.is_directorydirthenk()else(ifSys.file_existsdirthensafeUnix.unlinkdir;(aux[@tailcall])(Filename.dirnamedir)(fun()->protect(Unix.mkdirdir)0o755;k()))in(aux[@tailcall])dirname(fun()->())letraw_file~flags~version~offset~generationfile=letx=Unix.openfilefileflags0o644inletraw=Raw.vxinletheader={Raw.Header.offset;version;generation}inLog.debug(funm->m"[%s] raw set_header %a"fileHeader.pp{offset;generation});Raw.Header.setrawheader;Raw.Fan.setraw"";Raw.fsyncraw;rawletclear~generation?(hook=fun()->())~reopent=t.offset<-Int63.zero;t.flushed<-t.header;Buffer.cleart.buf;letold=t.rawinifreopenthen((* Open a fresh file and rename it to ensure atomicity:
concurrent readers should never see the file disapearing. *)lettmp_file=t.file^"_tmp"int.raw<-raw_file~version:current_version~generation~offset:Int63.zero~flags:Unix.[O_CREAT;O_RDWR;O_CLOEXEC]tmp_file;Unix.renametmp_filet.file)else(* Remove the file current file. This allows a fresh file to be
created, before writing the new generation in the old file. *)Unix.unlinkt.file;hook();(* Set new generation in the old file. *)Raw.Header.setold{Raw.Header.offset=Int63.zero;generation;version=current_version};Raw.closeoldlet()=assert(String.lengthcurrent_version=8)letv_instance?(flush_callback=fun()->())~readonly~fan_size~offsetfileraw=leteight=Int63.of_int8inletheader=eight++eight++eight++eight++fan_sizein{header;file;offset;raw;readonly;fan_size;buf=Buffer.create(4*1024);flushed=header++offset;flush_callback;}letv?flush_callback~fresh~generation~fan_sizefile=letv=v_instance?flush_callback~readonly:falsefileinmkdir(Filename.dirnamefile);letheader={Raw.Header.offset=Int63.zero;version=current_version;generation}inmatchSys.file_existsfilewith|false->letx=Unix.openfilefileUnix.[O_CREAT;O_CLOEXEC;O_RDWR]0o644inletraw=Raw.vxinRaw.Header.setrawheader;Raw.Fan.set_sizerawfan_size;v~fan_size~offset:Int63.zeroraw|true->letx=Unix.openfilefileUnix.[O_EXCL;O_CLOEXEC;O_RDWR]0o644inletraw=Raw.vxiniffreshthen(Raw.Header.setrawheader;Raw.Fan.set_sizerawfan_size;Raw.fsyncraw;v~fan_size~offset:Int63.zeroraw)elseletversion=Raw.Version.getrawinifversion<>current_versionthenFmt.failwith"Io.v: unsupported version %s (current version is %s)"versioncurrent_version;letoffset=Raw.Offset.getrawinletfan_size=Raw.Fan.get_sizerawinv~fan_size~offsetrawletv_readonlyfile=letv=v_instance~readonly:truefileinmkdir(Filename.dirnamefile);tryletx=Unix.openfilefileUnix.[O_EXCL;O_CLOEXEC;O_RDONLY]0o644inletraw=Raw.vxintryletversion=Raw.Version.getrawinifversion<>current_versionthenFmt.failwith"Io.v: unsupported version %s (current version is %s)"versioncurrent_version;letoffset=Raw.Offset.getrawinletfan_size=Raw.Fan.get_sizerawinOk(v~fan_size~offsetraw)withRaw.Not_written->(* The readonly instance cannot read a file that does not have a
header.*)Raw.closeraw;Error`No_file_on_diskwith|Unix.Unix_error(Unix.ENOENT,_,_)->(* The readonly instance cannot open a non existing file. *)Error`No_file_on_disk|e->raiseeletexists=Sys.file_existsletsize{raw;_}=(Raw.fstatraw).st_sizeletsize_headert=t.header|>Int63.to_intmoduleLock=structtypet={path:string;fd:Unix.file_descr}exceptionLockedofstringletunsafe_lockopf=mkdir(Filename.dirnamef);letfd=Unix.openfilef[Unix.O_CREAT;Unix.O_RDWR]0o600andpid=string_of_int(Unix.getpid())inletpid_len=String.lengthpidintryUnix.lockffdop0;ifUnix.single_write_substringfdpid0pid_len<>pid_lenthen(Unix.closefd;failwith"Unable to write PID to lock file")elseSomefdwith|Unix.Unix_error(Unix.EAGAIN,_,_)->Unix.closefd;None|e->Unix.closefd;raiseeletwith_icpathf=letic=open_inpathinleta=ficinclose_inic;aleterr_rw_lockpath=letline=with_icpathinput_lineinletpid=int_of_stringlineinLog.err(funl->l"Cannot lock %s: index is already opened in write mode by PID %d. \
Current PID is %d."pathpid(Unix.getpid()));raise(Lockedpath)letlockpath=Log.debug(funl->l"Locking %s"path);matchunsafe_lockUnix.F_TLOCKpathwith|Somefd->{path;fd}|None->err_rw_lockpathletunlock{path;fd}=Log.debug(funl->l"Unlocking %s"path);Unix.closefdletpp_dumppath=matchSys.file_existspathwith|false->None|true->letcontents=with_icpath(funic->really_input_stringic(in_channel_lengthic))inSome(funppf->Fmt.stringppfcontents)endendmoduleSemaphore=structmoduleS=Semaphore_compat.Semaphore.Binaryletis_heldt=letacquired=S.try_acquiretinifacquiredthenS.releaset;notacquiredincludeSletacquirent=letx=Mtime_clock.counter()inS.acquiret;lety=Mtime_clock.countxinifMtime.Span.to_sy>1.thenLog.warn(funl->l"Semaphore %s was blocked for %a"nMtime.Span.ppy)letwith_acquirentf=acquirent;Fun.protect~finally:(fun()->S.releaset)fendmoduleThread=structtype'at=|Asyncof{thread:Thread.t;result:('a,exn)resultoptionref}|Valueof'aletasyncf=letresult=refNoneinletprotected_fx=tryresult:=Some(Ok(fx))withexn->result:=Some(Errorexn);raiseexninletthread=Thread.createprotected_f()inAsync{thread;result}letyield=Thread.yieldletreturna=Valuealetawaitt=matchtwith|Valuev->Okv|Async{thread;result}->(let()=Thread.jointhreadinmatch!resultwith|Some(Ok_aso)->o|Some(Errorexn)->Error(`Async_exnexn)|None->assertfalse)endmodulePlatform=structmoduleIO=IOmoduleSemaphore=SemaphoremoduleThread=ThreadmoduleClock=Mtime_clockendmoduleMake(K:Index.Key.S)(V:Index.Value.S)=Index.Make(K)(V)(Platform)moduleSyscalls=SyscallsmodulePrivate=structmoduleIO=IOmoduleRaw=RawmoduleMake(K:Index.Key.S)(V:Index.Value.S)=Index.Private.Make(K)(V)(Platform)end