daemon_client.go 1.97 KB
Newer Older
1 2 3
package daemon

import (
4
	"bufio"
5
	"encoding/json"
6
	"errors"
7
	"io"
8
	"net"
9
	"os"
10

11
	lock "github.com/camlistore/lock"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
13

14
	u "github.com/jbenet/go-ipfs/util"
15 16
)

17 18 19
// ErrDaemonNotRunning is returned when attempting to retrieve the daemon's
// address and the daemon is not actually running.
var ErrDaemonNotRunning = errors.New("daemon not running")
Siraj Ravel's avatar
Siraj Ravel committed
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
func getDaemonAddr(confdir string) (string, error) {
	var err error
	confdir, err = u.TildeExpansion(confdir)
	if err != nil {
		return "", err
	}
	fi, err := os.Open(confdir + "/rpcaddress")
	if err != nil {
		log.Debug("getDaemonAddr failed: %s", err)
		if err == os.ErrNotExist {
			return "", ErrDaemonNotRunning
		}
		return "", err
	}

	read := bufio.NewReader(fi)

	// TODO: operating system agostic line delim
	line, err := read.ReadBytes('\n')
	if err != nil && err != io.EOF {
		return "", err
	}
	return string(line), nil
}

// SendCommand issues a command (of type daemon.Command) to the daemon, if it
// is running (if not, errors out). This is done over network RPC API. The
// address of the daemon is retrieved from the configuration directory, where
// live daemons write their addresses to special files.
func SendCommand(command *Command, confdir string) error {
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	//check if daemon is running
	log.Info("Checking if daemon is running...")
	var err error
	confdir, err = u.TildeExpansion(confdir)
	if err != nil {
		return err
	}
	lk, err := lock.Lock(confdir + "/daemon.lock")
	if err == nil {
		return ErrDaemonNotRunning
		lk.Close()
	}

	log.Info("Daemon is running! %s", err)

66
	server, err := getDaemonAddr(confdir)
67 68 69 70
	if err != nil {
		return err
	}

71
	maddr, err := ma.NewMultiaddr(server)
72 73 74
	if err != nil {
		return err
	}
Siraj Ravel's avatar
Siraj Ravel committed
75

76 77
	network, host, err := maddr.DialArgs()

78
	conn, err := net.Dial(network, host)
79
	if err != nil {
80
		return err
81 82
	}

Siraj Ravel's avatar
Siraj Ravel committed
83 84
	enc := json.NewEncoder(conn)
	err = enc.Encode(command)
85
	if err != nil {
86
		return err
87 88
	}

Siraj Ravel's avatar
Siraj Ravel committed
89
	io.Copy(os.Stdout, conn)
90

91
	return nil
92
}