active.go 1.56 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package commands

import (
	"bytes"
	"fmt"
	"io"
	"text/tabwriter"
	"time"

	cmds "github.com/ipfs/go-ipfs/commands"
)

var ActiveReqsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List commands run on this ipfs node",
		ShortDescription: `
Lists running and recently run commands.
`,
	},
	Run: func(req cmds.Request, res cmds.Response) {
		res.SetOutput(req.InvocContext().ReqLog.Report())
	},
Jeromy's avatar
Jeromy committed
23 24 25
	Options: []cmds.Option{
		cmds.BoolOption("v", "verbose", "print more verbose output"),
	},
26 27 28 29 30 31 32 33 34
	Marshalers: map[cmds.EncodingType]cmds.Marshaler{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			out, ok := res.Output().(*[]*cmds.ReqLogEntry)
			if !ok {
				log.Errorf("%#v", res.Output())
				return nil, cmds.ErrIncorrectType
			}
			buf := new(bytes.Buffer)

Jeromy's avatar
Jeromy committed
35 36
			verbose, _, _ := res.Request().Option("v").Bool()

37
			w := tabwriter.NewWriter(buf, 4, 4, 2, ' ', 0)
Jeromy's avatar
Jeromy committed
38 39 40 41 42 43
			fmt.Fprint(w, "Command\t")
			if verbose {
				fmt.Fprint(w, "Arguments\tOptions\t")
			}
			fmt.Fprintln(w, "Active\tStartTime\tRunTime")

44
			for _, req := range *out {
Jeromy's avatar
Jeromy committed
45 46 47 48 49 50 51 52 53 54
				fmt.Fprintf(w, "%s\t", req.Command)
				if verbose {
					fmt.Fprintf(w, "%v\t[", req.Args)
					for k, v := range req.Options {
						fmt.Fprintf(w, "%s=%v,", k, v)
					}
					fmt.Fprintf(w, "]\t")
				}

				var live time.Duration
55
				if req.Active {
Jeromy's avatar
Jeromy committed
56
					live = time.Now().Sub(req.StartTime)
57
				} else {
Jeromy's avatar
Jeromy committed
58
					live = req.EndTime.Sub(req.StartTime)
59
				}
Jeromy's avatar
Jeromy committed
60 61
				t := req.StartTime.Format(time.Stamp)
				fmt.Fprintf(w, "%t\t%s\t%s\n", req.Active, t, live)
62 63 64 65 66 67 68 69
			}
			w.Flush()

			return buf, nil
		},
	},
	Type: []*cmds.ReqLogEntry{},
}