1919package tasks
2020
2121import (
22+ "encoding/json"
2223 "errors"
2324 "fmt"
24-
2525 "os"
2626 "text/tabwriter"
2727
@@ -37,11 +37,24 @@ func init() {
3737 Command .Subcommands = append (Command .Subcommands , metricsCommand )
3838}
3939
40+ const (
41+ formatFlag = "format"
42+ formatTable = "table"
43+ formatJSON = "json"
44+ )
45+
4046var metricsCommand = cli.Command {
4147 Name : "metrics" ,
4248 Usage : "get a single data point of metrics for a task with the built-in Linux runtime" ,
4349 ArgsUsage : "CONTAINER" ,
4450 Aliases : []string {"metric" },
51+ Flags : []cli.Flag {
52+ cli.StringFlag {
53+ Name : formatFlag ,
54+ Usage : `"table" or "json"` ,
55+ Value : formatTable ,
56+ },
57+ },
4558 Action : func (context * cli.Context ) error {
4659 client , ctx , cancel , err := commands .NewClient (context )
4760 if err != nil {
@@ -60,10 +73,6 @@ var metricsCommand = cli.Command{
6073 if err != nil {
6174 return nil
6275 }
63- w := tabwriter .NewWriter (os .Stdout , 1 , 8 , 4 , ' ' , 0 )
64- fmt .Fprintf (w , "ID\t TIMESTAMP\t \n " )
65- fmt .Fprintf (w , "%s\t %s\t \n \n " , metric .ID , metric .Timestamp )
66-
6776 anydata , err := typeurl .UnmarshalAny (metric .Data )
6877 if err != nil {
6978 return err
@@ -72,12 +81,28 @@ var metricsCommand = cli.Command{
7281 if ! ok {
7382 return errors .New ("cannot convert metric data to cgroups.Metrics" )
7483 }
75- fmt .Fprintf (w , "METRIC\t VALUE\t \n " )
76- fmt .Fprintf (w , "memory.usage_in_bytes\t %d\t \n " , data .Memory .Usage .Usage )
77- fmt .Fprintf (w , "memory.stat.cache\t %d\t \n " , data .Memory .TotalCache )
78- fmt .Fprintf (w , "cpuacct.usage\t %d\t \n " , data .CPU .Usage .Total )
79- fmt .Fprintf (w , "cpuacct.usage_percpu\t %v\t \n " , data .CPU .Usage .PerCPU )
8084
81- return w .Flush ()
85+ switch context .String (formatFlag ) {
86+ case formatTable :
87+ w := tabwriter .NewWriter (os .Stdout , 1 , 8 , 4 , ' ' , 0 )
88+ fmt .Fprintf (w , "ID\t TIMESTAMP\t \n " )
89+ fmt .Fprintf (w , "%s\t %s\t \n \n " , metric .ID , metric .Timestamp )
90+
91+ fmt .Fprintf (w , "METRIC\t VALUE\t \n " )
92+ fmt .Fprintf (w , "memory.usage_in_bytes\t %d\t \n " , data .Memory .Usage .Usage )
93+ fmt .Fprintf (w , "memory.stat.cache\t %d\t \n " , data .Memory .TotalCache )
94+ fmt .Fprintf (w , "cpuacct.usage\t %d\t \n " , data .CPU .Usage .Total )
95+ fmt .Fprintf (w , "cpuacct.usage_percpu\t %v\t \n " , data .CPU .Usage .PerCPU )
96+ return w .Flush ()
97+ case formatJSON :
98+ marshaledJSON , err := json .MarshalIndent (data , "" , " " )
99+ if err != nil {
100+ return err
101+ }
102+ fmt .Println (string (marshaledJSON ))
103+ return nil
104+ default :
105+ return errors .New ("format must be table or json" )
106+ }
82107 },
83108}
0 commit comments