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

import (
	"encoding/json"
5
	"errors"
Jeromy's avatar
Jeromy committed
6
	"fmt"
Jeromy's avatar
Jeromy committed
7 8 9 10
	"io"
	"time"

	"github.com/jbenet/go-ipfs/core"
11
	diagn "github.com/jbenet/go-ipfs/diagnostics"
Jeromy's avatar
Jeromy committed
12 13
)

14 15 16 17 18 19 20 21 22 23 24 25 26
func PrintDiagnostics(info []*diagn.DiagInfo, out io.Writer) {
	for _, i := range info {
		fmt.Fprintf(out, "Peer: %s\n", i.ID)
		fmt.Fprintf(out, "\tUp for: %s\n", i.LifeSpan.String())
		fmt.Fprintf(out, "\tConnected To:\n")
		for _, c := range i.Connections {
			fmt.Fprintf(out, "\t%s\n\t\tLatency = %s\n", c.ID, c.Latency.String())
		}
		fmt.Fprintln(out)
	}

}

Jeromy's avatar
Jeromy committed
27
func Diag(n *core.IpfsNode, args []string, opts map[string]interface{}, out io.Writer) error {
28 29 30
	if n.Diagnostics == nil {
		return errors.New("Cannot run diagnostic in offline mode!")
	}
Jeromy's avatar
Jeromy committed
31 32 33 34
	info, err := n.Diagnostics.GetDiagnostic(time.Second * 20)
	if err != nil {
		return err
	}
35 36 37 38
	raw, ok := opts["raw"].(bool)
	if !ok {
		return errors.New("incorrect value to parameter 'raw'")
	}
Jeromy's avatar
Jeromy committed
39 40 41 42 43 44 45
	if raw {
		enc := json.NewEncoder(out)
		err = enc.Encode(info)
		if err != nil {
			return err
		}
	} else {
46
		PrintDiagnostics(info, out)
Jeromy's avatar
Jeromy committed
47 48 49
	}
	return nil
}