daemon.go 1.51 KB
Newer Older
1 2 3
package main

import (
4
	"fmt"
5 6
	"net/http"

7
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/camlistore/lock"
8 9
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net"
10

11 12
	cmds "github.com/jbenet/go-ipfs/commands"
	cmdsHttp "github.com/jbenet/go-ipfs/commands/http"
13
	"github.com/jbenet/go-ipfs/config"
14 15
)

16 17 18
// DaemonLockFile is the filename of the daemon lock, relative to config dir
const DaemonLockFile = "daemon.lock"

19 20 21 22 23 24 25 26
var Daemon = &cmds.Command{
	Options:     []cmds.Option{},
	Help:        "TODO",
	Subcommands: map[string]*cmds.Command{},
	Run:         daemonFunc,
}

func daemonFunc(req cmds.Request, res cmds.Response) {
27
	ctx := req.Context()
28

29
	lockPath, err := config.Path(ctx.ConfigRoot, DaemonLockFile)
30 31 32 33 34 35 36 37 38 39 40 41
	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()

42
	addr, err := ma.NewMultiaddr(ctx.Config.Addresses.API)
43 44 45 46 47 48 49 50 51 52 53
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}

	_, host, err := manet.DialArgs(addr)
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}

54 55
	handler := cmdsHttp.Handler{}
	http.Handle(cmdsHttp.ApiPath+"/", handler)
56
	err = http.ListenAndServe(host, nil)
57 58 59 60 61
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}
	// TODO: log to indicate that we are now listening
62

63
}