stat.go 5.41 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5 6
package commands

import (
	"errors"
	"fmt"
	"io"
Jan Winkelmann's avatar
Jan Winkelmann committed
7
	"os"
Jeromy's avatar
Jeromy committed
8 9
	"time"

10 11
	cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"

Jakub Sztandera's avatar
Jakub Sztandera committed
12
	humanize "gx/ipfs/QmPSBJL4momYnE7DcUyk2DVhD6rH488ZmHBGLbxNdhU44K/go-humanize"
13 14 15
	cmds "gx/ipfs/QmPTfgFTo9PFr1PvPKyKoeMgBvYPh6cX3aDP7DHKVbnCbi/go-ipfs-cmds"
	peer "gx/ipfs/QmQsErDt8Qgw1XrsXf2BpEzDgGWtB1YLsTAARBup5b6B9W/go-libp2p-peer"
	cmdkit "gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
16
	protocol "gx/ipfs/QmZNkThpqfVXs9GNbexPrfBbXSLNYeKrE7jwFM2oqHbyqN/go-libp2p-protocol"
17
	metrics "gx/ipfs/QmdhwKw53CTV8EJSAsR1bpmMT5kXiWBgeAyv1EXeeDiXqR/go-libp2p-metrics"
Jeromy's avatar
Jeromy committed
18 19 20
)

var StatsCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
21
	Helptext: cmdkit.HelpText{
22
		Tagline: "Query IPFS statistics.",
23
		ShortDescription: `'ipfs stats' is a set of commands to help look at statistics
24
for your IPFS node.
25
`,
Jeromy's avatar
Jeromy committed
26
		LongDescription: `'ipfs stats' is a set of commands to help look at statistics
27
for your IPFS node.`,
Jeromy's avatar
Jeromy committed
28 29 30
	},

	Subcommands: map[string]*cmds.Command{
31 32 33
		"bw":      statBwCmd,
		"repo":    repoStatCmd,
		"bitswap": bitswapStatCmd,
Jeromy's avatar
Jeromy committed
34 35 36 37
	},
}

var statBwCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
38
	Helptext: cmdkit.HelpText{
Jeromy's avatar
Jeromy committed
39
		Tagline: "Print ipfs bandwidth information.",
40 41 42 43 44 45
		ShortDescription: `'ipfs stats bw' prints bandwidth information for the ipfs daemon.
It displays: TotalIn, TotalOut, RateIn, RateOut.
		`,
		LongDescription: `'ipfs stats bw' prints bandwidth information for the ipfs daemon.
It displays: TotalIn, TotalOut, RateIn, RateOut.

46 47 48 49 50
By default, overall bandwidth and all protocols are shown. To limit bandwidth
to a particular peer, use the 'peer' option along with that peer's multihash
id. To specify a specific protocol, use the 'proto' option. The 'peer' and
'proto' options cannot be specified simultaneously. The protocols that are
queried using this method are outlined in the specification:
51
https://github.com/libp2p/specs/blob/master/7-properties.md#757-protocol-multicodecs
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

Example protocol options:
  - /ipfs/id/1.0.0
  - /ipfs/bitswap
  - /ipfs/dht

Example:

    > ipfs stats bw -t /ipfs/bitswap
    Bandwidth
    TotalIn: 5.0MB
    TotalOut: 0B
    RateIn: 343B/s
    RateOut: 0B/s
    > ipfs stats bw -p QmepgFW7BHEtU4pZJdxaNiv75mKLLRQnPi1KaaXmQN4V1a
    Bandwidth
    TotalIn: 4.9MB
    TotalOut: 12MB
    RateIn: 0B/s
    RateOut: 0B/s
`,
Jeromy's avatar
Jeromy committed
73
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
74 75 76
	Options: []cmdkit.Option{
		cmdkit.StringOption("peer", "p", "Specify a peer to print bandwidth for."),
		cmdkit.StringOption("proto", "t", "Specify a protocol to print bandwidth for."),
77
		cmdkit.BoolOption("poll", "Print bandwidth at an interval."),
Jan Winkelmann's avatar
Jan Winkelmann committed
78
		cmdkit.StringOption("interval", "i", `Time interval to wait between updating output, if 'poll' is true.
79 80

    This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are:
81
    "ns", "us" (or "µs"), "ms", "s", "m", "h".`).WithDefault("1s"),
Jeromy's avatar
Jeromy committed
82 83
	},

Jeromy's avatar
Jeromy committed
84
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
85
		nd, err := cmdenv.GetNode(env)
Jeromy's avatar
Jeromy committed
86
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
87
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
88 89 90 91 92
			return
		}

		// Must be online!
		if !nd.OnlineMode() {
93
			res.SetError(ErrNotOnline, cmdkit.ErrClient)
Jeromy's avatar
Jeromy committed
94 95 96
			return
		}

97
		if nd.Reporter == nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
98
			res.SetError(fmt.Errorf("bandwidth reporter disabled in config"), cmdkit.ErrNormal)
99 100 101
			return
		}

102 103
		pstr, pfound := req.Options["peer"].(string)
		tstr, tfound := req.Options["proto"].(string)
Jeromy's avatar
Jeromy committed
104
		if pfound && tfound {
Jan Winkelmann's avatar
Jan Winkelmann committed
105
			res.SetError(errors.New("please only specify peer OR protocol"), cmdkit.ErrClient)
Jeromy's avatar
Jeromy committed
106 107 108 109 110 111 112
			return
		}

		var pid peer.ID
		if pfound {
			checkpid, err := peer.IDB58Decode(pstr)
			if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
113
				res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
114 115 116 117 118
				return
			}
			pid = checkpid
		}

119
		timeS, _ := req.Options["interval"].(string)
120 121
		interval, err := time.ParseDuration(timeS)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
122
			res.SetError(err, cmdkit.ErrNormal)
123
			return
Jeromy's avatar
Jeromy committed
124 125
		}

126
		doPoll, _ := req.Options["poll"].(bool)
Jan Winkelmann's avatar
Jan Winkelmann committed
127 128 129 130 131 132 133 134 135 136 137
		for {
			if pfound {
				stats := nd.Reporter.GetBandwidthForPeer(pid)
				res.Emit(&stats)
			} else if tfound {
				protoId := protocol.ID(tstr)
				stats := nd.Reporter.GetBandwidthForProtocol(protoId)
				res.Emit(&stats)
			} else {
				totals := nd.Reporter.GetBandwidthTotals()
				res.Emit(&totals)
Jeromy's avatar
Jeromy committed
138
			}
Jan Winkelmann's avatar
Jan Winkelmann committed
139 140 141 142 143
			if !doPoll {
				return
			}
			select {
			case <-time.After(interval):
144
			case <-req.Context.Done():
Jan Winkelmann's avatar
Jan Winkelmann committed
145 146 147 148
				return
			}
		}

Jeromy's avatar
Jeromy committed
149 150
	},
	Type: metrics.Stats{},
Jan Winkelmann's avatar
Jan Winkelmann committed
151
	PostRun: cmds.PostRunMap{
152
		cmds.CLI: func(req *cmds.Request, re cmds.ResponseEmitter) cmds.ResponseEmitter {
Jan Winkelmann's avatar
Jan Winkelmann committed
153
			reNext, res := cmds.NewChanResponsePair(req)
Jeromy's avatar
Jeromy committed
154

Jan Winkelmann's avatar
Jan Winkelmann committed
155 156
			go func() {
				defer re.Close()
Jeromy's avatar
Jeromy committed
157

158
				polling, _ := res.Request().Options["poll"].(bool)
159 160 161
				if polling {
					fmt.Fprintln(os.Stdout, "Total Up    Total Down  Rate Up     Rate Down")
				}
Jan Winkelmann's avatar
Jan Winkelmann committed
162 163 164 165
				for {
					v, err := res.Next()
					if !cmds.HandleError(err, res, re) {
						break
Jeromy's avatar
Jeromy committed
166 167
					}

Jan Winkelmann's avatar
Jan Winkelmann committed
168 169 170 171 172 173 174 175 176 177
					bs := v.(*metrics.Stats)

					if !polling {
						printStats(os.Stdout, bs)
						return
					}

					fmt.Fprintf(os.Stdout, "%8s    ", humanize.Bytes(uint64(bs.TotalOut)))
					fmt.Fprintf(os.Stdout, "%8s    ", humanize.Bytes(uint64(bs.TotalIn)))
					fmt.Fprintf(os.Stdout, "%8s/s  ", humanize.Bytes(uint64(bs.RateOut)))
Jeromy's avatar
Jeromy committed
178
					fmt.Fprintf(os.Stdout, "%8s/s      \r", humanize.Bytes(uint64(bs.RateIn)))
Jan Winkelmann's avatar
Jan Winkelmann committed
179 180
				}
			}()
Jeromy's avatar
Jeromy committed
181

Jan Winkelmann's avatar
Jan Winkelmann committed
182
			return reNext
Jeromy's avatar
Jeromy committed
183 184 185 186 187 188 189 190 191 192 193
		},
	},
}

func printStats(out io.Writer, bs *metrics.Stats) {
	fmt.Fprintln(out, "Bandwidth")
	fmt.Fprintf(out, "TotalIn: %s\n", humanize.Bytes(uint64(bs.TotalIn)))
	fmt.Fprintf(out, "TotalOut: %s\n", humanize.Bytes(uint64(bs.TotalOut)))
	fmt.Fprintf(out, "RateIn: %s/s\n", humanize.Bytes(uint64(bs.RateIn)))
	fmt.Fprintf(out, "RateOut: %s/s\n", humanize.Bytes(uint64(bs.RateOut)))
}