swarm.go 1.76 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
package commands

import (
	"bytes"
	"fmt"

	cmds "github.com/jbenet/go-ipfs/commands"
	errors "github.com/jbenet/go-ipfs/util/debugerror"
)

type stringList struct {
	Strings []string
}

var swarmCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "swarm inspection tool",
		Synopsis: `
ipfs swarm peers             - List peers with open connections
ipfs swarm connect <address> - Open connection to a given peer
`,
		ShortDescription: `
ipfs swarm is a tool to manipulate the network swarm. The swarm is the
component that opens, listens for, and maintains connections to other
ipfs peers in the internet.
`,
	},
	Subcommands: map[string]*cmds.Command{
		"peers": swarmPeersCmd,
		// "connect": swarmConnectCmd,
	},
}

var swarmPeersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List peers with open connections",
		ShortDescription: `
ipfs swarm peers lists the set of peers this node is connected to.
`,
	},
	Run: func(req cmds.Request) (interface{}, error) {

		log.Debug("ipfs swarm peers")
		n, err := req.Context().GetNode()
		if err != nil {
			return nil, err
		}

		if n.Network == nil {
			return nil, errNotOnline
		}

		conns := n.Network.GetConnections()
		addrs := make([]string, len(conns))
		for i, c := range conns {
			pid := c.RemotePeer().ID()
			addr := c.RemoteMultiaddr()
			addrs[i] = fmt.Sprintf("%s/%s", addr, pid)
		}

		return &stringList{addrs}, nil
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
	Type: &stringList{},
}

func stringListMarshaler(res cmds.Response) ([]byte, error) {
	list, ok := res.Output().(*stringList)
	if !ok {
		return nil, errors.New("failed to cast []string")
	}

	var buf bytes.Buffer
	for _, s := range list.Strings {
		buf.Write([]byte(s))
		buf.Write([]byte("\n"))
	}
	return buf.Bytes(), nil
}