From 0a64b592d54515abd68803de95fa95a105831409 Mon Sep 17 00:00:00 2001 From: siddontang Date: Wed, 24 Sep 2014 15:51:09 +0800 Subject: [PATCH] add file lock to promise one instance for a path --- bootstrap.sh | 1 + ledis/ledis.go | 26 +++++++++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/bootstrap.sh b/bootstrap.sh index 4a12258..e6d4071 100755 --- a/bootstrap.sh +++ b/bootstrap.sh @@ -16,3 +16,4 @@ go get github.com/siddontang/go/bson go get github.com/siddontang/go/log go get github.com/siddontang/go/snappy go get github.com/siddontang/go/num +go get github.com/siddontang/go/filelock diff --git a/ledis/ledis.go b/ledis/ledis.go index 2669c3a..27f2ad3 100644 --- a/ledis/ledis.go +++ b/ledis/ledis.go @@ -2,10 +2,14 @@ package ledis import ( "fmt" + "github.com/siddontang/go/filelock" "github.com/siddontang/go/log" "github.com/siddontang/ledisdb/config" "github.com/siddontang/ledisdb/rpl" "github.com/siddontang/ledisdb/store" + "io" + "os" + "path" "sync" "time" ) @@ -31,6 +35,8 @@ type Ledis struct { // for readonly mode, only replication can write readOnly bool + + lock io.Closer } func Open(cfg *config.Config) (*Ledis, error) { @@ -42,18 +48,23 @@ func Open2(cfg *config.Config, flags int) (*Ledis, error) { cfg.DataDir = config.DefaultDataDir } - ldb, err := store.Open(cfg) - if err != nil { - return nil, err - } + os.MkdirAll(cfg.DataDir, 0755) + + var err error l := new(Ledis) + if l.lock, err = filelock.Lock(path.Join(cfg.DataDir, "LOCK")); err != nil { + return nil, err + } + l.readOnly = (flags&ROnlyMode > 0) l.quit = make(chan struct{}) - l.ldb = ldb + if l.ldb, err = store.Open(cfg); err != nil { + return nil, err + } if cfg.UseReplication { if l.r, err = rpl.NewReplication(cfg); err != nil { @@ -91,6 +102,11 @@ func (l *Ledis) Close() { l.r.Close() l.r = nil } + + if l.lock != nil { + l.lock.Close() + l.lock = nil + } } func (l *Ledis) Select(index int) (*DB, error) {