Introduce higer-level API for retrieving statistics
[govpp.git] / examples / stats-api / stats_api.go
1 // Copyright (c) 2018 Cisco and/or its affiliates.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package main
16
17 import (
18         "flag"
19         "fmt"
20         "log"
21         "os"
22         "strings"
23
24         "git.fd.io/govpp.git/adapter"
25         "git.fd.io/govpp.git/adapter/vppapiclient"
26         "git.fd.io/govpp.git/core"
27 )
28
29 // ------------------------------------------------------------------
30 // Example - Stats API
31 // ------------------------------------------------------------------
32 // The example stats_api demonstrates how to retrieve stats
33 // from the VPP using the new stats API.
34 // ------------------------------------------------------------------
35
36 var (
37         statsSocket = flag.String("socket", vppapiclient.DefaultStatSocket, "VPP stats segment socket")
38         dumpAll     = flag.Bool("all", false, "Dump all stats including ones with zero values")
39 )
40
41 func init() {
42         flag.Usage = func() {
43                 fmt.Fprintf(os.Stderr, "%s: usage [ls|dump|errors|interfaces|nodes|system] <patterns>...\n", os.Args[0])
44                 flag.PrintDefaults()
45                 os.Exit(1)
46         }
47 }
48
49 func main() {
50         flag.Parse()
51         skipZeros := !*dumpAll
52
53         cmd := flag.Arg(0)
54         switch cmd {
55         case "", "ls", "dump", "errors", "interfaces", "nodes", "system":
56         default:
57                 flag.Usage()
58         }
59
60         var patterns []string
61         if flag.NArg() > 0 {
62                 patterns = flag.Args()[1:]
63         }
64
65         client := vppapiclient.NewStatClient(*statsSocket)
66
67         fmt.Printf("Connecting to stats socket: %s\n", *statsSocket)
68
69         c, err := core.ConnectStats(client)
70         if err != nil {
71                 log.Fatalln("Connecting failed:", err)
72         }
73         defer c.Disconnect()
74
75         switch cmd {
76         case "system":
77                 stats, err := c.GetSystemStats()
78                 if err != nil {
79                         log.Fatalln("getting system stats failed:", err)
80                 }
81                 fmt.Printf("System stats: %+v\n", stats)
82         case "nodes":
83                 fmt.Println("Listing node stats..")
84                 stats, err := c.GetNodeStats()
85                 if err != nil {
86                         log.Fatalln("getting node stats failed:", err)
87                 }
88                 for _, iface := range stats.Nodes {
89                         fmt.Printf(" - %+v\n", iface)
90                 }
91                 fmt.Printf("Listed %d node counters\n", len(stats.Nodes))
92         case "interfaces":
93                 fmt.Println("Listing interface stats..")
94                 stats, err := c.GetInterfaceStats()
95                 if err != nil {
96                         log.Fatalln("getting interface stats failed:", err)
97                 }
98                 for _, iface := range stats.Interfaces {
99                         fmt.Printf(" - %+v\n", iface)
100                 }
101                 fmt.Printf("Listed %d interface counters\n", len(stats.Interfaces))
102         case "errors":
103                 fmt.Printf("Listing error stats.. %s\n", strings.Join(patterns, " "))
104                 stats, err := c.GetErrorStats(patterns...)
105                 if err != nil {
106                         log.Fatalln("getting error stats failed:", err)
107                 }
108                 n := 0
109                 for _, counter := range stats.Errors {
110                         if counter.Value == 0 && skipZeros {
111                                 continue
112                         }
113                         fmt.Printf(" - %v\n", counter)
114                         n++
115                 }
116                 fmt.Printf("Listed %d (%d) error counters\n", n, len(stats.Errors))
117         case "dump":
118                 dumpStats(client, patterns, skipZeros)
119         default:
120                 listStats(client, patterns)
121         }
122 }
123
124 func listStats(client adapter.StatsAPI, patterns []string) {
125         fmt.Printf("Listing stats.. %s\n", strings.Join(patterns, " "))
126
127         list, err := client.ListStats(patterns...)
128         if err != nil {
129                 log.Fatalln("listing stats failed:", err)
130         }
131
132         for _, stat := range list {
133                 fmt.Printf(" - %v\n", stat)
134         }
135
136         fmt.Printf("Listed %d stats\n", len(list))
137 }
138
139 func dumpStats(client adapter.StatsAPI, patterns []string, skipZeros bool) {
140         fmt.Printf("Dumping stats.. %s\n", strings.Join(patterns, " "))
141
142         stats, err := client.DumpStats(patterns...)
143         if err != nil {
144                 log.Fatalln("dumping stats failed:", err)
145         }
146
147         n := 0
148         for _, stat := range stats {
149                 if isZero(stat.Data) && skipZeros {
150                         continue
151                 }
152                 fmt.Printf(" - %-25s %25v %+v\n", stat.Name, stat.Type, stat.Data)
153                 n++
154         }
155
156         fmt.Printf("Dumped %d (%d) stats\n", n, len(stats))
157 }
158
159 func isZero(stat adapter.Stat) bool {
160         switch s := stat.(type) {
161         case adapter.ScalarStat:
162                 return s == 0
163         case adapter.ErrorStat:
164                 return s == 0
165         case adapter.SimpleCounterStat:
166                 for _, ss := range s {
167                         for _, sss := range ss {
168                                 if sss != 0 {
169                                         return false
170                                 }
171                         }
172                 }
173         case adapter.CombinedCounterStat:
174                 for _, ss := range s {
175                         for _, sss := range ss {
176                                 if sss.Bytes != 0 || sss.Packets != 0 {
177                                         return false
178                                 }
179                         }
180                 }
181         }
182         return true
183 }