daemon.go 1.69 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
	configPath, err := getConfigRoot(req)
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
	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()

Matt Bell's avatar
Matt Bell committed
46
	config, err := getConfig(configPath)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}

	addr, err := ma.NewMultiaddr(config.Addresses.API)
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}

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

64 65
	handler := cmdsHttp.Handler{}
	http.Handle(cmdsHttp.ApiPath+"/", handler)
66
	err = http.ListenAndServe(host, nil)
67 68 69 70 71
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}
	// TODO: log to indicate that we are now listening
72

73
}