daemon_client.go 1.99 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

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

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

45 46 47 48
// SendCommand attempts to run the command over a currently-running daemon.
// If there is no running daemon, returns ErrDaemonNotRunning. This is done
// over network RPC API. The address of the daemon is retrieved from the config
// directory, where live daemons write their addresses to special files.
49
func SendCommand(command *Command, confdir string) error {
50 51 52 53 54 55 56
	//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
	}
57
	lk, err := daemonLock(confdir)
58 59
	if err == nil {
		lk.Close()
60
		return ErrDaemonNotRunning
61 62
	}

63
	log.Info("Daemon is running! [reason = %s]", err)
64

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

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

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

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
}