1 // Copyright (c) 2018 Cisco and/or its affiliates.
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:
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
24 "git.fd.io/govpp.git/adapter"
25 "git.fd.io/govpp.git/adapter/vppapiclient"
28 // ------------------------------------------------------------------
29 // Example - Stats API
30 // ------------------------------------------------------------------
31 // The example stats_api demonstrates how to retrieve stats
32 // from the VPP using the new stats API.
33 // ------------------------------------------------------------------
36 statsSocket = flag.String("socket", vppapiclient.DefaultStatSocket, "VPP stats segment socket")
37 dumpAll = flag.Bool("all", false, "Dump all stats including ones with zero values")
42 fmt.Fprintf(os.Stderr, "%s: usage [ls|dump] <patterns>...\n", os.Args[0])
54 case "", "ls", "dump":
61 patterns = flag.Args()[1:]
64 client := vppapiclient.NewStatClient(*statsSocket)
66 fmt.Printf("Connecting to stats socket: %s\n", *statsSocket)
68 if err := client.Connect(); err != nil {
69 log.Fatalln("Connecting failed:", err)
71 defer client.Disconnect()
75 dumpStats(client, patterns, !*dumpAll)
77 listStats(client, patterns)
81 func listStats(client adapter.StatsAPI, patterns []string) {
82 fmt.Printf("Listing stats.. %s\n", strings.Join(patterns, " "))
84 list, err := client.ListStats(patterns...)
86 log.Fatalln("listing stats failed:", err)
89 for _, stat := range list {
90 fmt.Printf(" - %v\n", stat)
93 fmt.Printf("Listed %d stats\n", len(list))
96 func dumpStats(client adapter.StatsAPI, patterns []string, skipZeros bool) {
97 fmt.Printf("Dumping stats.. %s\n", strings.Join(patterns, " "))
99 stats, err := client.DumpStats(patterns...)
101 log.Fatalln("dumping stats failed:", err)
105 for _, stat := range stats {
106 if isZero(stat.Data) && skipZeros {
109 fmt.Printf(" - %-25s %25v %+v\n", stat.Name, stat.Type, stat.Data)
113 fmt.Printf("Dumped %d (%d) stats\n", n, len(stats))
116 func isZero(stat adapter.Stat) bool {
117 switch s := stat.(type) {
118 case adapter.ScalarStat:
120 case adapter.ErrorStat:
122 case adapter.SimpleCounterStat:
123 for _, ss := range s {
124 for _, sss := range ss {
130 case adapter.CombinedCounterStat:
131 for _, ss := range s {
132 for _, sss := range ss {
133 if sss.Bytes != 0 || sss.Packets != 0 {