Stream API options
[govpp.git] / examples / simple-client / simple_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 // simple-client is an example VPP management application that exercises the
16 // govpp API on real-world use-cases.
17 package main
18
19 import (
20         "encoding/json"
21         "flag"
22         "fmt"
23         "log"
24         "os"
25
26         "git.fd.io/govpp.git"
27         "git.fd.io/govpp.git/adapter/socketclient"
28         "git.fd.io/govpp.git/api"
29         interfaces "git.fd.io/govpp.git/binapi/interface"
30         "git.fd.io/govpp.git/binapi/interface_types"
31         "git.fd.io/govpp.git/binapi/ip"
32         "git.fd.io/govpp.git/binapi/ip_types"
33         "git.fd.io/govpp.git/binapi/vpe"
34         "git.fd.io/govpp.git/core"
35 )
36
37 var (
38         sockAddr = flag.String("sock", socketclient.DefaultSocketName, "Path to VPP binary API socket file")
39 )
40
41 func main() {
42         flag.Parse()
43
44         fmt.Println("Starting simple client example")
45         fmt.Println()
46
47         // connect to VPP asynchronously
48         conn, connEv, err := govpp.AsyncConnect(*sockAddr, core.DefaultMaxReconnectAttempts, core.DefaultReconnectInterval)
49         if err != nil {
50                 log.Fatalln("ERROR:", err)
51         }
52         defer conn.Disconnect()
53
54         // wait for Connected event
55         select {
56         case e := <-connEv:
57                 if e.State != core.Connected {
58                         log.Fatalln("ERROR: connecting to VPP failed:", e.Error)
59                 }
60         }
61
62         // check compatibility of used messages
63         ch, err := conn.NewAPIChannel()
64         if err != nil {
65                 log.Fatalln("ERROR: creating channel failed:", err)
66         }
67         defer ch.Close()
68         if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
69                 log.Fatal(err)
70         }
71         if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
72                 log.Fatal(err)
73         }
74
75         // process errors encountered during the example
76         defer func() {
77                 if len(Errors) > 0 {
78                         fmt.Printf("finished with %d errors\n", len(Errors))
79                         os.Exit(1)
80                 } else {
81                         fmt.Println("finished successfully")
82                 }
83         }()
84
85         // use request/reply (channel API)
86         getVppVersion(ch)
87         idx := createLoopback(ch)
88         interfaceDump(ch)
89         addIPAddress(ch, idx)
90         ipAddressDump(ch, idx)
91         interfaceNotifications(ch, idx)
92 }
93
94 func getVppVersion(ch api.Channel) {
95         fmt.Println("Retrieving version..")
96
97         req := &vpe.ShowVersion{}
98         reply := &vpe.ShowVersionReply{}
99
100         if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
101                 logError(err, "retrieving version")
102                 return
103         }
104
105         fmt.Printf("VPP version: %q\n", reply.Version)
106         fmt.Println("OK")
107         fmt.Println()
108 }
109
110 func createLoopback(ch api.Channel) interface_types.InterfaceIndex {
111         fmt.Println("Creating loopback interface..")
112
113         req := &interfaces.CreateLoopback{}
114         reply := &interfaces.CreateLoopbackReply{}
115
116         if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
117                 logError(err, "creating loopback interface")
118                 return 0
119         }
120
121         fmt.Printf("interface index: %v\n", reply.SwIfIndex)
122         fmt.Println("OK")
123         fmt.Println()
124
125         return reply.SwIfIndex
126 }
127
128 func interfaceDump(ch api.Channel) {
129         fmt.Println("Dumping interfaces..")
130
131         n := 0
132         reqCtx := ch.SendMultiRequest(&interfaces.SwInterfaceDump{
133                 SwIfIndex: ^interface_types.InterfaceIndex(0),
134         })
135         for {
136                 msg := &interfaces.SwInterfaceDetails{}
137                 stop, err := reqCtx.ReceiveReply(msg)
138                 if stop {
139                         break
140                 }
141                 if err != nil {
142                         logError(err, "dumping interfaces")
143                         return
144                 }
145                 n++
146                 fmt.Printf(" - interface #%d: %+v\n", n, msg)
147                 marshal(msg)
148         }
149
150         fmt.Println("OK")
151         fmt.Println()
152 }
153
154 func addIPAddress(ch api.Channel, index interface_types.InterfaceIndex) {
155         fmt.Printf("Adding IP address to interface index %d\n", index)
156
157         req := &interfaces.SwInterfaceAddDelAddress{
158                 SwIfIndex: index,
159                 IsAdd:     true,
160                 Prefix: ip_types.AddressWithPrefix{
161                         Address: ip_types.Address{
162                                 Af: ip_types.ADDRESS_IP4,
163                                 Un: ip_types.AddressUnionIP4(ip_types.IP4Address{10, 10, 0, uint8(index)}),
164                         },
165                         Len: 32,
166                 },
167         }
168         marshal(req)
169         reply := &interfaces.SwInterfaceAddDelAddressReply{}
170
171         if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
172                 logError(err, "adding IP address to interface")
173                 return
174         }
175
176         fmt.Println("OK")
177         fmt.Println()
178 }
179
180 func ipAddressDump(ch api.Channel, index interface_types.InterfaceIndex) {
181         fmt.Printf("Dumping IP addresses for interface index %d..\n", index)
182
183         req := &ip.IPAddressDump{
184                 SwIfIndex: index,
185         }
186         reqCtx := ch.SendMultiRequest(req)
187
188         for {
189                 msg := &ip.IPAddressDetails{}
190                 stop, err := reqCtx.ReceiveReply(msg)
191                 if err != nil {
192                         logError(err, "dumping IP addresses")
193                         return
194                 }
195                 if stop {
196                         break
197                 }
198                 fmt.Printf(" - ip address: %+v\n", msg)
199                 marshal(msg)
200         }
201
202         fmt.Println("OK")
203         fmt.Println()
204 }
205
206 // interfaceNotifications shows the usage of notification API. Note that for notifications,
207 // you are supposed to create your own Go channel with your preferred buffer size. If the channel's
208 // buffer is full, the notifications will not be delivered into it.
209 func interfaceNotifications(ch api.Channel, index interface_types.InterfaceIndex) {
210         fmt.Printf("Subscribing to notificaiton events for interface index %d\n", index)
211
212         notifChan := make(chan api.Message, 100)
213
214         // subscribe for specific notification message
215         sub, err := ch.SubscribeNotification(notifChan, &interfaces.SwInterfaceEvent{})
216         if err != nil {
217                 logError(err, "subscribing to interface events")
218                 return
219         }
220
221         // enable interface events in VPP
222         err = ch.SendRequest(&interfaces.WantInterfaceEvents{
223                 PID:           uint32(os.Getpid()),
224                 EnableDisable: 1,
225         }).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
226         if err != nil {
227                 logError(err, "enabling interface events")
228                 return
229         }
230
231         // receive notifications
232         go func() {
233                 for notif := range notifChan {
234                         e := notif.(*interfaces.SwInterfaceEvent)
235                         fmt.Printf("incoming event: %+v\n", e)
236                         marshal(e)
237                 }
238         }()
239
240         // generate some events in VPP
241         err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
242                 SwIfIndex: index,
243                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
244         }).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
245         if err != nil {
246                 logError(err, "setting interface flags")
247                 return
248         }
249         err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
250                 SwIfIndex: index,
251                 Flags:     0,
252         }).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
253         if err != nil {
254                 logError(err, "setting interface flags")
255                 return
256         }
257
258         // disable interface events in VPP
259         err = ch.SendRequest(&interfaces.WantInterfaceEvents{
260                 PID:           uint32(os.Getpid()),
261                 EnableDisable: 0,
262         }).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
263         if err != nil {
264                 logError(err, "setting interface flags")
265                 return
266         }
267
268         // unsubscribe from delivery of the notifications
269         err = sub.Unsubscribe()
270         if err != nil {
271                 logError(err, "unsubscribing from interface events")
272                 return
273         }
274
275         fmt.Println("OK")
276         fmt.Println()
277 }
278
279 func marshal(v interface{}) {
280         fmt.Printf("GO: %#v\n", v)
281         b, err := json.MarshalIndent(v, "", "  ")
282         if err != nil {
283                 panic(err)
284         }
285         fmt.Printf("JSON: %s\n", b)
286 }
287
288 var Errors []error
289
290 func logError(err error, msg string) {
291         fmt.Printf("ERROR: %s: %v\n", msg, err)
292         Errors = append(Errors, err)
293 }