From e011d950bb71c4b0e32248058c31af43e32338a9 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Mon, 27 Oct 2014 16:20:48 -0700 Subject: [PATCH] cmd/ipfs: Obtain lock when starting daemon --- cmd/ipfs/daemon.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/cmd/ipfs/daemon.go b/cmd/ipfs/daemon.go index b294cdf98..1ece04048 100644 --- a/cmd/ipfs/daemon.go +++ b/cmd/ipfs/daemon.go @@ -1,12 +1,19 @@ package main import ( + "fmt" "net/http" + "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/camlistore/lock" + cmds "github.com/jbenet/go-ipfs/commands" cmdsHttp "github.com/jbenet/go-ipfs/commands/http" + "github.com/jbenet/go-ipfs/config" ) +// DaemonLockFile is the filename of the daemon lock, relative to config dir +const DaemonLockFile = "daemon.lock" + var Daemon = &cmds.Command{ Options: []cmds.Option{}, Help: "TODO", @@ -15,13 +22,33 @@ var Daemon = &cmds.Command{ } func daemonFunc(req cmds.Request, res cmds.Response) { + configPath, err := getConfigPath(req) + if err != nil { + res.SetError(err, cmds.ErrNormal) + return + } + + lockPath, err := config.Path(configPath, DaemonLockFile) + if err != nil { + res.SetError(err, cmds.ErrNormal) + return + } + + lk, err := lock.Lock(lockPath) + if err != nil { + res.SetError(fmt.Errorf("Couldn't obtain lock. Is another daemon already running?"), cmds.ErrNormal) + return + } + defer lk.Close() + handler := cmdsHttp.Handler{} http.Handle(cmdsHttp.ApiPath+"/", handler) // TODO: load listen address/port from config/options - err := http.ListenAndServe(":8080", nil) + err = http.ListenAndServe(":8080", nil) if err != nil { res.SetError(err, cmds.ErrNormal) return } // TODO: log to indicate that we are now listening + }