13 "github.com/edwarnicke/exechelper"
17 "go.fd.io/govpp/binapi/af_packet"
18 interfaces "go.fd.io/govpp/binapi/interface"
19 "go.fd.io/govpp/binapi/interface_types"
20 "go.fd.io/govpp/binapi/session"
21 "go.fd.io/govpp/binapi/tapv2"
22 "go.fd.io/govpp/binapi/vpe"
26 const vppConfigTemplate = `unix {
31 runtime-dir %[1]s/var/run
44 socket-name %[1]s%[3]s
48 socket-name %[1]s/var/run/vpp/stats.sock
52 plugin default { disable }
54 plugin unittest_plugin.so { enable }
55 plugin quic_plugin.so { enable }
56 plugin af_packet_plugin.so { enable }
57 plugin hs_apps_plugin.so { enable }
58 plugin http_plugin.so { enable }
59 plugin http_static_plugin.so { enable }
60 plugin prom_plugin.so { enable }
64 default-log-level debug
65 default-syslog-log-level debug
71 defaultCliSocketFilePath = "/var/run/vpp/cli.sock"
72 defaultApiSocketFilePath = "/var/run/vpp/api.sock"
73 defaultLogFilePath = "/var/log/vpp/vpp.log"
76 type VppInstance struct {
78 additionalConfig []Stanza
79 connection *core.Connection
80 apiChannel api.Channel
84 func (vpp *VppInstance) getSuite() *HstSuite {
85 return vpp.container.suite
88 func (vpp *VppInstance) getCliSocket() string {
89 return fmt.Sprintf("%s%s", vpp.container.getContainerWorkDir(), defaultCliSocketFilePath)
92 func (vpp *VppInstance) getRunDir() string {
93 return vpp.container.getContainerWorkDir() + "/var/run/vpp"
96 func (vpp *VppInstance) getLogDir() string {
97 return vpp.container.getContainerWorkDir() + "/var/log/vpp"
100 func (vpp *VppInstance) getEtcDir() string {
101 return vpp.container.getContainerWorkDir() + "/etc/vpp"
104 func (vpp *VppInstance) start() error {
106 containerWorkDir := vpp.container.getContainerWorkDir()
108 vpp.container.exec("mkdir --mode=0700 -p " + vpp.getRunDir())
109 vpp.container.exec("mkdir --mode=0700 -p " + vpp.getLogDir())
110 vpp.container.exec("mkdir --mode=0700 -p " + vpp.getEtcDir())
112 // Create startup.conf inside the container
113 configContent := fmt.Sprintf(
116 defaultCliSocketFilePath,
117 defaultApiSocketFilePath,
120 configContent += vpp.generateCpuConfig()
121 for _, c := range vpp.additionalConfig {
122 configContent += c.toString()
124 startupFileName := vpp.getEtcDir() + "/startup.conf"
125 vpp.container.createFile(startupFileName, configContent)
127 // create wrapper script for vppctl with proper CLI socket path
128 cliContent := "#!/usr/bin/bash\nvppctl -s " + vpp.getRunDir() + "/cli.sock"
129 vppcliFileName := "/usr/bin/vppcli"
130 vpp.container.createFile(vppcliFileName, cliContent)
131 vpp.container.exec("chmod 0755 " + vppcliFileName)
134 sig := make(chan os.Signal, 1)
135 signal.Notify(sig, syscall.SIGINT)
136 cont := make(chan bool, 1)
142 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
143 fmt.Println("run following command in different terminal:")
144 fmt.Println("docker exec -it " + vpp.container.name + " gdb -ex \"attach $(docker exec " + vpp.container.name + " pidof vpp)\"")
145 fmt.Println("Afterwards press CTRL+C to continue")
147 fmt.Println("continuing...")
150 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
153 // Connect to VPP and store the connection
154 sockAddress := vpp.container.getHostWorkDir() + defaultApiSocketFilePath
155 conn, connEv, err := govpp.AsyncConnect(
157 core.DefaultMaxReconnectAttempts,
158 core.DefaultReconnectInterval)
160 fmt.Println("async connect error: ", err)
162 vpp.connection = conn
164 // ... wait for Connected event
166 if e.State != core.Connected {
167 fmt.Println("connecting to VPP failed: ", e.Error)
170 // ... check compatibility of used messages
171 ch, err := conn.NewAPIChannel()
173 fmt.Println("creating channel failed: ", err)
175 if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
176 fmt.Println("compatibility error: ", err)
178 if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
179 fmt.Println("compatibility error: ", err)
186 func (vpp *VppInstance) vppctl(command string, arguments ...any) string {
187 vppCliCommand := fmt.Sprintf(command, arguments...)
188 containerExecCommand := fmt.Sprintf("docker exec --detach=false %[1]s vppctl -s %[2]s %[3]s",
189 vpp.container.name, vpp.getCliSocket(), vppCliCommand)
190 vpp.getSuite().log(containerExecCommand)
191 output, err := exechelper.CombinedOutput(containerExecCommand)
192 vpp.getSuite().assertNil(err)
194 return string(output)
197 func (vpp *VppInstance) GetSessionStat(stat string) int {
198 o := vpp.vppctl("show session stats")
199 vpp.getSuite().log(o)
200 for _, line := range strings.Split(o, "\n") {
201 if strings.Contains(line, stat) {
202 tokens := strings.Split(strings.TrimSpace(line), " ")
203 val, err := strconv.Atoi(tokens[0])
205 vpp.getSuite().FailNow("failed to parse stat value %s", err)
214 func (vpp *VppInstance) waitForApp(appName string, timeout int) {
215 for i := 0; i < timeout; i++ {
216 o := vpp.vppctl("show app")
217 if strings.Contains(o, appName) {
220 time.Sleep(1 * time.Second)
222 vpp.getSuite().assertNil(1, "Timeout while waiting for app '%s'", appName)
225 func (vpp *VppInstance) createAfPacket(
227 ) (interface_types.InterfaceIndex, error) {
228 createReq := &af_packet.AfPacketCreateV2{
229 UseRandomHwAddr: true,
230 HostIfName: veth.Name(),
232 if veth.hwAddress != (MacAddress{}) {
233 createReq.UseRandomHwAddr = false
234 createReq.HwAddr = veth.hwAddress
236 createReply := &af_packet.AfPacketCreateV2Reply{}
238 if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
241 veth.index = createReply.SwIfIndex
244 upReq := &interfaces.SwInterfaceSetFlags{
245 SwIfIndex: veth.index,
246 Flags: interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
248 upReply := &interfaces.SwInterfaceSetFlagsReply{}
250 if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
255 if veth.addressWithPrefix() == (AddressWithPrefix{}) {
257 var ip4Address string
258 if ip4Address, err = veth.ip4AddrAllocator.NewIp4InterfaceAddress(veth.peer.networkNumber); err == nil {
259 veth.ip4Address = ip4Address
264 addressReq := &interfaces.SwInterfaceAddDelAddress{
266 SwIfIndex: veth.index,
267 Prefix: veth.addressWithPrefix(),
269 addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
271 if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
275 return veth.index, nil
278 func (vpp *VppInstance) addAppNamespace(
280 ifx interface_types.InterfaceIndex,
283 req := &session.AppNamespaceAddDelV2{
286 NamespaceID: namespaceId,
288 reply := &session.AppNamespaceAddDelV2Reply{}
290 if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
294 sessionReq := &session.SessionEnableDisable{
297 sessionReply := &session.SessionEnableDisableReply{}
299 if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
306 func (vpp *VppInstance) createTap(
314 createTapReq := &tapv2.TapCreateV2{
317 HostIfName: tap.Name(),
318 HostIP4PrefixSet: true,
319 HostIP4Prefix: tap.ip4AddressWithPrefix(),
321 createTapReply := &tapv2.TapCreateV2Reply{}
323 // Create tap interface
324 if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
329 addAddressReq := &interfaces.SwInterfaceAddDelAddress{
331 SwIfIndex: createTapReply.SwIfIndex,
332 Prefix: tap.peer.addressWithPrefix(),
334 addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
336 if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
340 // Set interface to up
341 upReq := &interfaces.SwInterfaceSetFlags{
342 SwIfIndex: createTapReply.SwIfIndex,
343 Flags: interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
345 upReply := &interfaces.SwInterfaceSetFlagsReply{}
347 if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
354 func (vpp *VppInstance) saveLogs() {
355 logTarget := vpp.container.getLogDirPath() + "vppinstance-" + vpp.container.name + ".log"
356 logSource := vpp.container.getHostWorkDir() + defaultLogFilePath
357 cmd := exec.Command("cp", logSource, logTarget)
358 vpp.getSuite().T().Helper()
359 vpp.getSuite().log(cmd.String())
363 func (vpp *VppInstance) disconnect() {
364 vpp.connection.Disconnect()
365 vpp.apiChannel.Close()
368 func (vpp *VppInstance) generateCpuConfig() string {
371 if len(vpp.cpus) < 1 {
375 append(fmt.Sprintf("main-core %d", vpp.cpus[0]))
376 workers := vpp.cpus[1:]
378 if len(workers) > 0 {
379 for i := 0; i < len(workers); i++ {
383 s = s + fmt.Sprintf("%d", workers[i])
385 c.append(fmt.Sprintf("corelist-workers %s", s))
387 return c.close().toString()