Introduce StatsAPI and it's initial implementation
[govpp.git] / examples / cmd / stats-client / stats_client.go
1 // Copyright (c) 2017 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 // Binary stats-client is an example VPP management application that exercises the
16 // govpp API for interface counters together with asynchronous connection to VPP.
17 package main
18
19 import (
20         "fmt"
21         "log"
22         "os"
23         "os/signal"
24
25         "git.fd.io/govpp.git"
26         "git.fd.io/govpp.git/api"
27         "git.fd.io/govpp.git/core"
28         "git.fd.io/govpp.git/examples/bin_api/stats"
29 )
30
31 /*
32
33         IMPORTANT NOTICE!
34
35         The binary API module stats used in this example will be deprecated in VPP 19.01.
36         VPP's new stats API should be used, you can find basic usage of new stats API in example stats-api.
37
38 */
39
40 func main() {
41         fmt.Println("Starting stats VPP client..")
42
43         // async connect to VPP
44         conn, statCh, err := govpp.AsyncConnect("")
45         if err != nil {
46                 log.Fatalln("Error:", err)
47         }
48         defer conn.Disconnect()
49
50         // create an API channel that will be used in the examples
51         ch, err := conn.NewAPIChannel()
52         if err != nil {
53                 log.Fatalln("Error:", err)
54         }
55         defer ch.Close()
56
57         // create channel for Interrupt signal
58         sigChan := make(chan os.Signal, 1)
59         signal.Notify(sigChan, os.Interrupt)
60
61         var notifChan chan api.Message
62         var simpleSub api.SubscriptionCtx
63         var combinedSub api.SubscriptionCtx
64
65         // loop until Interrupt signal is received
66 loop:
67         for {
68                 select {
69                 case connEvent := <-statCh:
70                         // VPP connection state change
71                         switch connEvent.State {
72                         case core.Connected:
73                                 fmt.Println("VPP connected.")
74                                 if notifChan == nil {
75                                         simpleSub, combinedSub, notifChan = subscribeNotifications(ch)
76                                 }
77                                 requestStatistics(ch)
78
79                         case core.Disconnected:
80                                 fmt.Println("VPP disconnected.")
81                         }
82
83                 case msg := <-notifChan:
84                         switch notif := msg.(type) {
85                         case *stats.VnetInterfaceSimpleCounters:
86                                 // simple counter notification received
87                                 processSimpleCounters(notif)
88                         case *stats.VnetInterfaceCombinedCounters:
89                                 // combined counter notification received
90                                 processCombinedCounters(notif)
91                         default:
92                                 fmt.Println("Ignoring unknown VPP notification")
93                         }
94
95                 case <-sigChan:
96                         // interrupt received
97                         fmt.Println("Interrupt received, exiting.")
98                         break loop
99                 }
100         }
101
102         simpleSub.Unsubscribe()
103         combinedSub.Unsubscribe()
104 }
105
106 // subscribeNotifications subscribes for interface counters notifications.
107 func subscribeNotifications(ch api.Channel) (api.SubscriptionCtx, api.SubscriptionCtx, chan api.Message) {
108         notifChan := make(chan api.Message, 100)
109
110         simpleSub, err := ch.SubscribeNotification(notifChan, &stats.VnetInterfaceSimpleCounters{})
111         if err != nil {
112                 panic(err)
113         }
114         combinedSub, err := ch.SubscribeNotification(notifChan, &stats.VnetInterfaceCombinedCounters{})
115         if err != nil {
116                 panic(err)
117         }
118
119         return simpleSub, combinedSub, notifChan
120 }
121
122 // requestStatistics requests interface counters notifications from VPP.
123 func requestStatistics(ch api.Channel) {
124         if err := ch.SendRequest(&stats.WantStats{
125                 PID:           uint32(os.Getpid()),
126                 EnableDisable: 1,
127         }).ReceiveReply(&stats.WantStatsReply{}); err != nil {
128                 panic(err)
129         }
130 }
131
132 // processSimpleCounters processes simple counters received from VPP.
133 func processSimpleCounters(counters *stats.VnetInterfaceSimpleCounters) {
134         fmt.Printf("SimpleCounters: %+v\n", counters)
135
136         counterNames := []string{
137                 "Drop", "Punt",
138                 "IPv4", "IPv6",
139                 "RxNoBuf", "RxMiss",
140                 "RxError", "TxError",
141                 "MPLS",
142         }
143
144         for i := uint32(0); i < counters.Count; i++ {
145                 fmt.Printf("Interface '%d': %s = %d\n",
146                         counters.FirstSwIfIndex+i, counterNames[counters.VnetCounterType], counters.Data[i])
147         }
148 }
149
150 // processCombinedCounters processes combined counters received from VPP.
151 func processCombinedCounters(counters *stats.VnetInterfaceCombinedCounters) {
152         fmt.Printf("CombinedCounters: %+v\n", counters)
153
154         counterNames := []string{"Rx", "Tx"}
155
156         for i := uint32(0); i < counters.Count; i++ {
157                 if len(counterNames) <= int(counters.VnetCounterType) {
158                         continue
159                 }
160                 fmt.Printf("Interface '%d': %s packets = %d, %s bytes = %d\n",
161                         counters.FirstSwIfIndex+i,
162                         counterNames[counters.VnetCounterType], counters.Data[i].Packets,
163                         counterNames[counters.VnetCounterType], counters.Data[i].Bytes)
164         }
165 }