aboutsummaryrefslogtreecommitdiffstats
path: root/examples/multi-vpp/multi_vpp.go
blob: c42f8026478ddcabbd4700e10966713632fc9af5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright (c) 2020 Cisco and/or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// multi-vpp is an example of managing multiple VPPs in single application.
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"strings"

	"git.fd.io/govpp.git"
	"git.fd.io/govpp.git/adapter/socketclient"
	"git.fd.io/govpp.git/adapter/statsclient"
	"git.fd.io/govpp.git/api"
	interfaces "git.fd.io/govpp.git/binapi/interface"
	"git.fd.io/govpp.git/binapi/interface_types"
	"git.fd.io/govpp.git/binapi/ip"
	"git.fd.io/govpp.git/binapi/ip_types"
	"git.fd.io/govpp.git/binapi/vpe"
	"git.fd.io/govpp.git/core"
)

var (
	binapiSockAddrVpp1 = flag.String("api-sock-1", socketclient.DefaultSocketName, "Path to binary API socket file of the VPP1")
	statsSockAddrVpp1  = flag.String("stats-sock-1", statsclient.DefaultSocketName, "Path to stats socket file of the VPP1")
	binapiSockAddrVpp2 = flag.String("api-sock-2", socketclient.DefaultSocketName, "Path to binary API socket file of the VPP2")
	statsSockAddrVpp2  = flag.String("stats-sock-2", statsclient.DefaultSocketName, "Path to stats socket file of the VPP2")
)

var Errors []error

func main() {
	flag.Parse()
	fmt.Println("Starting multi-vpp example")

	defer func() {
		if len(Errors) > 0 {
			logInfo("Finished with %d errors\n", len(Errors))
			os.Exit(1)
		} else {
			logInfo("Finished successfully\n")
		}
	}()

	// since sockets default to the same value
	if *binapiSockAddrVpp1 == *binapiSockAddrVpp2 {
		log.Fatalln("ERROR: identical VPP binapi sockets defined, set at least one of them to a non-default path")
	}
	if *statsSockAddrVpp1 == *statsSockAddrVpp2 {
		log.Fatalln("ERROR: identical VPP stats sockets defined, set at least one of them to a non-default path")
	}
	var name1, name2 = "vpp1", "vpp2"
	ch1, statsConn1, disconnect1 := connectVPP(name1, *binapiSockAddrVpp1, *statsSockAddrVpp1)
	defer disconnect1()

	ch2, statsConn2, disconnect2 := connectVPP(name2, *binapiSockAddrVpp2, *statsSockAddrVpp2)
	defer disconnect2()

	fmt.Println()

	// retrieve VPP1 version
	logHeader("Retrieving %s version", name1)
	getVppVersion(ch1, name1)

	// retrieve VPP2 version
	logHeader("Retrieving %s version", name2)
	getVppVersion(ch1, name2)

	// configure VPP1
	logHeader("Configuring %s", name1)
	ifIdx1 := createLoopback(ch1, name1)
	addIPsToInterface(ch1, ifIdx1, []string{"10.10.0.1/24", "15.10.0.1/24"})

	// configure VPP2
	logHeader("Configuring %s", name2)
	ifIdx2 := createLoopback(ch2, name2)
	addIPsToInterface(ch2, ifIdx2, []string{"20.10.0.1/24", "25.10.0.1/24"})

	// retrieve configuration from VPPs
	retrieveIPAddresses(ch1, name1, ifIdx1)
	retrieveIPAddresses(ch2, name2, ifIdx2)

	// retrieve stats from VPPs
	retrieveStats(statsConn1, name1)
	retrieveStats(statsConn2, name2)

	// cleanup
	logHeader("Cleaning up %s", name1)
	deleteIPsToInterface(ch1, ifIdx1, []string{"10.10.0.1/24", "15.10.0.1/24"})
	deleteLoopback(ch1, ifIdx1)
	logHeader("Cleaning up %s", name2)
	deleteIPsToInterface(ch2, ifIdx2, []string{"20.10.0.1/24", "25.10.0.1/24"})
	deleteLoopback(ch2, ifIdx2)
}

func connectVPP(name, binapiSocket, statsSocket string) (api.Channel, api.StatsProvider, func()) {
	fmt.Println()
	logHeader("Connecting to %s", name)

	// connect VPP1 to the binapi socket
	ch, disconnectBinapi, err := connectBinapi(binapiSocket, 1)
	if err != nil {
		log.Fatalf("ERROR: connecting VPP binapi failed (socket %s): %v\n", binapiSocket, err)
	}

	// connect VPP1 to the stats socket
	statsConn, disconnectStats, err := connectStats(name, statsSocket)
	if err != nil {
		disconnectBinapi()
		log.Fatalf("ERROR: connecting VPP stats failed (socket %s): %v\n", statsSocket, err)
	}

	logInfo("OK\n")

	return ch, statsConn, func() {
		disconnectStats()
		disconnectBinapi()
		logInfo("VPP %s disconnected\n", name)
	}
}

// connectBinapi connects to the binary API socket and returns a communication channel
func connectBinapi(socket string, attempts int) (api.Channel, func(), error) {
	logInfo("Attaching to the binapi socket %s\n", socket)
	conn, event, err := govpp.AsyncConnect(socket, attempts, core.DefaultReconnectInterval)
	if err != nil {
		return nil, nil, err
	}
	select {
	case e := <-event:
		if e.State != core.Connected {
			return nil, nil, err
		}
	}
	ch, err := getAPIChannel(conn)
	if err != nil {
		return nil, nil, err
	}
	disconnect := func() {
		if ch != nil {
			ch.Close()
		}
		if conn != nil {
			conn.Disconnect()
		}
	}
	return ch, disconnect, nil
}

// connectStats connects to the stats socket and returns a stats provider
func connectStats(name, socket string) (api.StatsProvider, func(), error) {
	logInfo("Attaching to the stats socket %s\n", socket)
	sc := statsclient.NewStatsClient(socket)
	conn, err := core.ConnectStats(sc)
	if err != nil {
		return nil, nil, err
	}
	disconnect := func() {
		if err := sc.Disconnect(); err != nil {
			logError(err, "failed to disconnect "+name+" stats socket")
		}
	}
	return conn, disconnect, nil
}

// getAPIChannel creates new API channel and verifies its compatibility
func getAPIChannel(c api.ChannelProvider) (api.Channel, error) {
	ch, err := c.NewAPIChannel()
	if err != nil {
		return nil, err
	}
	if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
		return nil, err
	}
	if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
		return nil, err
	}
	return ch, nil
}

// getVppVersion returns VPP version (simple API usage)
func getVppVersion(ch api.Channel, name string) {
	logInfo("Retrieving version of %s ..\n", name)

	req := &vpe.ShowVersion{}
	reply := &vpe.ShowVersionReply{}

	if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
		logError(err, "retrieving version")
		return
	}
	logInfo("Retrieved version is %q\n", reply.Version)
	fmt.Println()
}

// createLoopback sends request to create a loopback interface
func createLoopback(ch api.Channel, name string) interface_types.InterfaceIndex {
	logInfo("Adding loopback interface ..\n")

	req := &interfaces.CreateLoopback{}
	reply := &interfaces.CreateLoopbackReply{}

	if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
		logError(err, "adding loopback interface")
		return 0
	}
	logInfo("Interface index %d added to %s\n", reply.SwIfIndex, name)

	return reply.SwIfIndex
}

// deleteLoopback removes created loopback interface
func deleteLoopback(ch api.Channel, ifIdx interface_types.InterfaceIndex) {
	logInfo("Removing loopback interface ..\n")
	req := &interfaces.DeleteLoopback{
		SwIfIndex: ifIdx,
	}
	reply := &interfaces.DeleteLoopbackReply{}

	if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
		logError(err, "removing loopback interface")
	}
	logInfo("OK\n")
	fmt.Println()
}

// addIPsToInterface sends request to add IP addresses to an interface.
func addIPsToInterface(ch api.Channel, index interface_types.InterfaceIndex, ips []string) {
	for _, ipAddr := range ips {
		logInfo("Adding IP address %s\n", ipAddr)
		prefix, err := ip_types.ParsePrefix(ipAddr)
		if err != nil {
			logError(err, "attempt to add invalid IP address")
			return
		}

		req := &interfaces.SwInterfaceAddDelAddress{
			SwIfIndex: index,
			IsAdd:     true,
			Prefix:    ip_types.AddressWithPrefix(prefix),
		}
		reply := &interfaces.SwInterfaceAddDelAddressReply{}

		if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
			logError(err, "adding IP address to interface")
			return
		}
	}

	logInfo("OK\n")
	fmt.Println()
}

// deleteIPsToInterface sends request to remove IP addresses from an interface.
func deleteIPsToInterface(ch api.Channel, index interface_types.InterfaceIndex, ips []string) {
	for _, ipAddr := range ips {
		logInfo("Removing IP address %s\n", ipAddr)
		prefix, err := ip_types.ParsePrefix(ipAddr)
		if err != nil {
			logError(err, "attempt to remove invalid IP address")
			return
		}

		req := &interfaces.SwInterfaceAddDelAddress{
			SwIfIndex: index,
			Prefix:    ip_types.AddressWithPrefix(prefix),
		}
		reply := &interfaces.SwInterfaceAddDelAddressReply{}

		if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
			logError(err, "removing IP address to interface")
			return
		}
	}
}

// retrieveIPAddresses reads IP address from the interface
func retrieveIPAddresses(ch api.Channel, name string, index interface_types.InterfaceIndex) {
	logHeader("Retrieving interface data from %s", name)
	req := &ip.IPAddressDump{
		SwIfIndex: index,
	}
	reqCtx := ch.SendMultiRequest(req)

	logInfo("Dump IP addresses for interface index %d ..\n", index)
	for {
		msg := &ip.IPAddressDetails{}
		stop, err := reqCtx.ReceiveReply(msg)
		if err != nil {
			logError(err, "dumping IP addresses")
			return
		}
		if stop {
			break
		}
		prefix := ip_types.Prefix(msg.Prefix)
		logInfo(" - ip address: %v\n", prefix)
	}

	logInfo("OK\n")
	fmt.Println()
}

// retrieveStats reads interface stats
func retrieveStats(s api.StatsProvider, name string) {
	logHeader("Retrieving interface stats from %s", name)
	ifStats := &api.InterfaceStats{}
	err := s.GetInterfaceStats(ifStats)
	if err != nil {
		logError(err, "dumping interface stats")
		return
	}
	logInfo("Dump interface stats ..\n")
	for _, ifStats := range ifStats.Interfaces {
		logInfo(" - %+v\n", ifStats)
	}

	logInfo("OK\n")
	fmt.Println()
}

// logHeader prints underlined message (for better output segmentation)
func logHeader(format string, a ...interface{}) {
	n, _ := fmt.Printf(format+"\n", a...)
	fmt.Println(strings.Repeat("-", n-1))
}

// logInfo prints info message
func logInfo(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}

// logError prints error message
func logError(err error, msg string) {
	fmt.Printf("[ERROR]: %s: %v\n", msg, err)
	Errors = append(Errors, err)
}