pubsub.go 8.62 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4
package commands

import (
	"bytes"
5
	"context"
Jeromy's avatar
Jeromy committed
6
	"encoding/binary"
Jeromy's avatar
Jeromy committed
7
	"fmt"
Jeromy's avatar
Jeromy committed
8
	"io"
9
	"strings"
10 11
	"sync"
	"time"
Jeromy's avatar
Jeromy committed
12 13

	cmds "github.com/ipfs/go-ipfs/commands"
14
	core "github.com/ipfs/go-ipfs/core"
15
	blocks "gx/ipfs/QmSn9Td7xgxm9EV7iEjTckpUWmWApggzPxu7eFGWkkpwin/go-block-format"
Jeromy's avatar
Jeromy committed
16

17
	cid "gx/ipfs/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ/go-cid"
18 19
	pstore "gx/ipfs/QmPgDWmTmuzvP7QE5zwo1TmjbJme9pmZHNujB2453jkCTr/go-libp2p-peerstore"
	u "gx/ipfs/QmSU6eubNdhXjFBJBSksTp8kv8YRub8mGAPv8tVJHmL2EU/go-ipfs-util"
20
	floodsub "gx/ipfs/QmUUSLfvihARhCxxgnjW4hmycJpPvzNu12Aaz6JWVdfnLg/go-libp2p-floodsub"
Jeromy's avatar
Jeromy committed
21 22 23 24 25 26 27 28 29 30 31
)

var PubsubCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "An experimental publish-subscribe system on ipfs.",
		ShortDescription: `
ipfs pubsub allows you to publish messages to a given topic, and also to
subscribe to new messages on a given topic.

This is an experimental feature. It is not intended in its current state
to be used in a production environment.
Jeromy's avatar
Jeromy committed
32 33

To use, the daemon must be run with '--enable-pubsub-experiment'.
Jeromy's avatar
Jeromy committed
34 35 36
`,
	},
	Subcommands: map[string]*cmds.Command{
Jeromy's avatar
Jeromy committed
37 38 39 40
		"pub":   PubsubPubCmd,
		"sub":   PubsubSubCmd,
		"ls":    PubsubLsCmd,
		"peers": PubsubPeersCmd,
Jeromy's avatar
Jeromy committed
41 42 43 44 45 46 47 48 49 50 51
	},
}

var PubsubSubCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Subscribe to messages on a given topic.",
		ShortDescription: `
ipfs pubsub sub subscribes to messages on a given topic.

This is an experimental feature. It is not intended in its current state
to be used in a production environment.
Jeromy's avatar
Jeromy committed
52 53

To use, the daemon must be run with '--enable-pubsub-experiment'.
54 55 56 57 58 59 60 61 62 63 64 65
`,
		LongDescription: `
ipfs pubsub sub subscribes to messages on a given topic.

This is an experimental feature. It is not intended in its current state
to be used in a production environment.

To use, the daemon must be run with '--enable-pubsub-experiment'.

This command outputs data in the following encodings:
  * "json"
(Specified by the "--encoding" or "--enc" flag)
Jeromy's avatar
Jeromy committed
66 67 68 69 70
`,
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("topic", true, false, "String name of topic to subscribe to."),
	},
71 72 73
	Options: []cmds.Option{
		cmds.BoolOption("discover", "try to discover other peers subscribed to the same topic"),
	},
Jeromy's avatar
Jeromy committed
74 75 76 77 78 79 80 81 82 83 84 85 86
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		// Must be online!
		if !n.OnlineMode() {
			res.SetError(errNotOnline, cmds.ErrClient)
			return
		}

Jeromy's avatar
Jeromy committed
87 88 89 90 91
		if n.Floodsub == nil {
			res.SetError(fmt.Errorf("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use."), cmds.ErrNormal)
			return
		}

Jeromy's avatar
Jeromy committed
92
		topic := req.Arguments()[0]
Jan Winkelmann's avatar
Jan Winkelmann committed
93
		sub, err := n.Floodsub.Subscribe(topic)
Jeromy's avatar
Jeromy committed
94 95 96 97 98 99 100 101 102
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		out := make(chan interface{})
		res.SetOutput((<-chan interface{})(out))

		go func() {
Jan Winkelmann's avatar
Jan Winkelmann committed
103
			defer sub.Cancel()
Jeromy's avatar
Jeromy committed
104
			defer close(out)
105 106 107

			out <- floodsub.Message{}

Jeromy's avatar
Jeromy committed
108
			for {
Jan Winkelmann's avatar
Jan Winkelmann committed
109 110
				msg, err := sub.Next(req.Context())
				if err == io.EOF || err == context.Canceled {
111
					return
Jan Winkelmann's avatar
Jan Winkelmann committed
112 113 114
				} else if err != nil {
					res.SetError(err, cmds.ErrNormal)
					return
Jeromy's avatar
Jeromy committed
115
				}
Jan Winkelmann's avatar
Jan Winkelmann committed
116 117

				out <- msg
Jeromy's avatar
Jeromy committed
118 119
			}
		}()
120 121 122

		discover, _, _ := req.Option("discover").Bool()
		if discover {
123 124
			go func() {
				blk := blocks.NewBlock([]byte("floodsub:" + topic))
125
				cid, err := n.Blocks.AddBlock(blk)
126 127 128 129
				if err != nil {
					log.Error("pubsub discovery: ", err)
					return
				}
130

131 132
				connectToPubSubPeers(req.Context(), n, cid)
			}()
133
		}
Jeromy's avatar
Jeromy committed
134 135 136 137 138 139 140 141 142 143 144
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: getPsMsgMarshaler(func(m *floodsub.Message) (io.Reader, error) {
			return bytes.NewReader(m.Data), nil
		}),
		"ndpayload": getPsMsgMarshaler(func(m *floodsub.Message) (io.Reader, error) {
			m.Data = append(m.Data, '\n')
			return bytes.NewReader(m.Data), nil
		}),
		"lenpayload": getPsMsgMarshaler(func(m *floodsub.Message) (io.Reader, error) {
			buf := make([]byte, 8)
145

Jan Winkelmann's avatar
Jan Winkelmann committed
146 147
			n := binary.PutUvarint(buf, uint64(len(m.Data)))
			return io.MultiReader(bytes.NewReader(buf[:n]), bytes.NewReader(m.Data)), nil
Jeromy's avatar
Jeromy committed
148 149 150 151 152
		}),
	},
	Type: floodsub.Message{},
}

153 154 155 156
func connectToPubSubPeers(ctx context.Context, n *core.IpfsNode, cid *cid.Cid) {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

157
	provs := n.Routing.FindProvidersAsync(ctx, cid, 10)
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
	wg := &sync.WaitGroup{}
	for p := range provs {
		wg.Add(1)
		go func(pi pstore.PeerInfo) {
			defer wg.Done()
			ctx, cancel := context.WithTimeout(ctx, time.Second*10)
			defer cancel()
			err := n.PeerHost.Connect(ctx, pi)
			if err != nil {
				log.Info("pubsub discover: ", err)
				return
			}
			log.Info("connected to pubsub peer:", pi.ID)
		}(p)
	}

	wg.Wait()
}

Jeromy's avatar
Jeromy committed
177 178 179 180 181 182 183 184 185 186 187 188
func getPsMsgMarshaler(f func(m *floodsub.Message) (io.Reader, error)) func(cmds.Response) (io.Reader, error) {
	return func(res cmds.Response) (io.Reader, error) {
		outChan, ok := res.Output().(<-chan interface{})
		if !ok {
			return nil, u.ErrCast()
		}

		marshal := func(v interface{}) (io.Reader, error) {
			obj, ok := v.(*floodsub.Message)
			if !ok {
				return nil, u.ErrCast()
			}
Jan Winkelmann's avatar
Jan Winkelmann committed
189 190 191
			if obj.Message == nil {
				return strings.NewReader(""), nil
			}
Jeromy's avatar
Jeromy committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

			return f(obj)
		}

		return &cmds.ChannelMarshaler{
			Channel:   outChan,
			Marshaler: marshal,
			Res:       res,
		}, nil
	}
}

var PubsubPubCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Publish a message to a given pubsub topic.",
		ShortDescription: `
ipfs pubsub pub publishes a message to a specified topic.

This is an experimental feature. It is not intended in its current state
to be used in a production environment.
Jeromy's avatar
Jeromy committed
212 213

To use, the daemon must be run with '--enable-pubsub-experiment'.
Jeromy's avatar
Jeromy committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
`,
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("topic", true, false, "Topic to publish to."),
		cmds.StringArg("data", true, true, "Payload of message to publish.").EnableStdin(),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		// Must be online!
		if !n.OnlineMode() {
			res.SetError(errNotOnline, cmds.ErrClient)
			return
		}

Jeromy's avatar
Jeromy committed
233 234 235 236 237
		if n.Floodsub == nil {
			res.SetError(fmt.Errorf("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use."), cmds.ErrNormal)
			return
		}

Jeromy's avatar
Jeromy committed
238 239 240 241 242 243 244 245 246 247
		topic := req.Arguments()[0]

		for _, data := range req.Arguments()[1:] {
			if err := n.Floodsub.Publish(topic, []byte(data)); err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
		}
	},
}
Jeromy's avatar
Jeromy committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

var PubsubLsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List subscribed topics by name.",
		ShortDescription: `
ipfs pubsub ls lists out the names of topics you are currently subscribed to.

This is an experimental feature. It is not intended in its current state
to be used in a production environment.

To use, the daemon must be run with '--enable-pubsub-experiment'.
`,
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		// Must be online!
		if !n.OnlineMode() {
			res.SetError(errNotOnline, cmds.ErrClient)
			return
		}

		if n.Floodsub == nil {
			res.SetError(fmt.Errorf("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use."), cmds.ErrNormal)
			return
		}

		res.SetOutput(&stringList{n.Floodsub.GetTopics()})
	},
	Type: stringList{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
}
Jeromy's avatar
Jeromy committed
286 287 288

var PubsubPeersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
289
		Tagline: "List peers we are currently pubsubbing with.",
Jeromy's avatar
Jeromy committed
290
		ShortDescription: `
291 292 293
ipfs pubsub peers with no arguments lists out the pubsub peers you are
currently connected to. If given a topic, it will list connected
peers who are subscribed to the named topic.
Jeromy's avatar
Jeromy committed
294 295 296 297 298 299 300

This is an experimental feature. It is not intended in its current state
to be used in a production environment.

To use, the daemon must be run with '--enable-pubsub-experiment'.
`,
	},
301 302 303
	Arguments: []cmds.Argument{
		cmds.StringArg("topic", false, false, "topic to list connected peers of"),
	},
Jeromy's avatar
Jeromy committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		// Must be online!
		if !n.OnlineMode() {
			res.SetError(errNotOnline, cmds.ErrClient)
			return
		}

		if n.Floodsub == nil {
			res.SetError(fmt.Errorf("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use."), cmds.ErrNormal)
			return
		}

322 323 324 325 326
		var topic string
		if len(req.Arguments()) == 1 {
			topic = req.Arguments()[0]
		}

Jeromy's avatar
Jeromy committed
327
		var out []string
328
		for _, p := range n.Floodsub.ListPeers(topic) {
Jeromy's avatar
Jeromy committed
329 330 331 332 333 334 335 336 337
			out = append(out, p.Pretty())
		}
		res.SetOutput(&stringList{out})
	},
	Type: stringList{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
}