active.go 1.79 KB
Newer Older
1 2 3 4 5 6
package commands

import (
	"bytes"
	"fmt"
	"io"
7
	"sort"
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
	"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
24 25 26
	Options: []cmds.Option{
		cmds.BoolOption("v", "verbose", "print more verbose output"),
	},
27 28 29 30 31 32 33 34 35
	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
36 37
			verbose, _, _ := res.Request().Option("v").Bool()

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

48
			for _, req := range *out {
49 50 51
				if verbose {
					fmt.Fprintf(w, "%d\t", req.ID)
				}
Jeromy's avatar
Jeromy committed
52 53 54
				fmt.Fprintf(w, "%s\t", req.Command)
				if verbose {
					fmt.Fprintf(w, "%v\t[", req.Args)
55 56 57 58 59 60 61 62
					var keys []string
					for k, _ := range req.Options {
						keys = append(keys, k)
					}
					sort.Strings(keys)

					for _, k := range keys {
						fmt.Fprintf(w, "%s=%v,", k, req.Options[k])
Jeromy's avatar
Jeromy committed
63 64 65 66 67
					}
					fmt.Fprintf(w, "]\t")
				}

				var live time.Duration
68
				if req.Active {
Jeromy's avatar
Jeromy committed
69
					live = time.Now().Sub(req.StartTime)
70
				} else {
Jeromy's avatar
Jeromy committed
71
					live = req.EndTime.Sub(req.StartTime)
72
				}
Jeromy's avatar
Jeromy committed
73 74
				t := req.StartTime.Format(time.Stamp)
				fmt.Fprintf(w, "%t\t%s\t%s\n", req.Active, t, live)
75 76 77 78 79 80 81 82
			}
			w.Flush()

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