Introduce StatsAPI and it's initial implementation
[govpp.git] / examples / cmd / 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         "fmt"
19         "log"
20
21         "git.fd.io/govpp.git/adapter"
22         "git.fd.io/govpp.git/adapter/vppapiclient"
23 )
24
25 // This example shows how to work with VPP's new stats API.
26
27 func main() {
28         fmt.Println("Starting VPP stats API example..")
29
30         client := vppapiclient.NewStatClient(vppapiclient.DefaultStatSocket)
31
32         // connect to stats API
33         if err := client.Connect(); err != nil {
34                 log.Fatalln("connecting client failed:", err)
35         }
36         defer client.Disconnect()
37
38         // list stats by patterns
39         // you can omit parameters to list all stats
40         list, err := client.ListStats("/if", "/sys")
41         if err != nil {
42                 log.Fatalln("listing stats failed:", err)
43         }
44
45         for _, stat := range list {
46                 fmt.Printf(" - %v\n", stat)
47         }
48         fmt.Printf("listed %d stats\n", len(list))
49
50         // dump stats by patterns to retrieve stats with the stats data
51         stats, err := client.DumpStats()
52         if err != nil {
53                 log.Fatalln("dumping stats failed:", err)
54         }
55
56         for _, stat := range stats {
57                 switch data := stat.Data.(type) {
58                 case adapter.ErrorStat:
59                         if data == 0 {
60                                 // skip printing errors with 0 value
61                                 continue
62                         }
63                 }
64                 fmt.Printf(" - %-25s %25v %+v\n", stat.Name, stat.Type, stat.Data)
65         }
66 }