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

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

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

15 16 17
// 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
18

19 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
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 {
	server, err := getDaemonAddr(confdir)
50 51 52 53
	if err != nil {
		return err
	}

54
	maddr, err := ma.NewMultiaddr(server)
55 56 57
	if err != nil {
		return err
	}
Siraj Ravel's avatar
Siraj Ravel committed
58

59 60
	network, host, err := maddr.DialArgs()

61
	conn, err := net.Dial(network, host)
62
	if err != nil {
63
		return err
64 65
	}

Siraj Ravel's avatar
Siraj Ravel committed
66 67
	enc := json.NewEncoder(conn)
	err = enc.Encode(command)
68
	if err != nil {
69
		return err
70 71
	}

Siraj Ravel's avatar
Siraj Ravel committed
72
	io.Copy(os.Stdout, conn)
73

74
	return nil
75
}