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 }
61 plugin tlsopenssl_plugin.so { enable }
65 default-log-level debug
66 default-syslog-log-level debug
72 defaultCliSocketFilePath = "/var/run/vpp/cli.sock"
73 defaultApiSocketFilePath = "/var/run/vpp/api.sock"
74 defaultLogFilePath = "/var/log/vpp/vpp.log"
77 type VppInstance struct {
79 additionalConfig []Stanza
80 connection *core.Connection
81 apiChannel api.Channel
85 func (vpp *VppInstance) getSuite() *HstSuite {
86 return vpp.container.suite
89 func (vpp *VppInstance) getCliSocket() string {
90 return fmt.Sprintf("%s%s", vpp.container.getContainerWorkDir(), defaultCliSocketFilePath)
93 func (vpp *VppInstance) getRunDir() string {
94 return vpp.container.getContainerWorkDir() + "/var/run/vpp"
97 func (vpp *VppInstance) getLogDir() string {
98 return vpp.container.getContainerWorkDir() + "/var/log/vpp"
101 func (vpp *VppInstance) getEtcDir() string {
102 return vpp.container.getContainerWorkDir() + "/etc/vpp"
105 func (vpp *VppInstance) start() error {
107 containerWorkDir := vpp.container.getContainerWorkDir()
109 vpp.container.exec("mkdir --mode=0700 -p " + vpp.getRunDir())
110 vpp.container.exec("mkdir --mode=0700 -p " + vpp.getLogDir())
111 vpp.container.exec("mkdir --mode=0700 -p " + vpp.getEtcDir())
113 // Create startup.conf inside the container
114 configContent := fmt.Sprintf(
117 defaultCliSocketFilePath,
118 defaultApiSocketFilePath,
121 configContent += vpp.generateCpuConfig()
122 for _, c := range vpp.additionalConfig {
123 configContent += c.toString()
125 startupFileName := vpp.getEtcDir() + "/startup.conf"
126 vpp.container.createFile(startupFileName, configContent)
128 // create wrapper script for vppctl with proper CLI socket path
129 cliContent := "#!/usr/bin/bash\nvppctl -s " + vpp.getRunDir() + "/cli.sock"
130 vppcliFileName := "/usr/bin/vppcli"
131 vpp.container.createFile(vppcliFileName, cliContent)
132 vpp.container.exec("chmod 0755 " + vppcliFileName)
135 sig := make(chan os.Signal, 1)
136 signal.Notify(sig, syscall.SIGINT)
137 cont := make(chan bool, 1)
143 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
144 fmt.Println("run following command in different terminal:")
145 fmt.Println("docker exec -it " + vpp.container.name + " gdb -ex \"attach $(docker exec " + vpp.container.name + " pidof vpp)\"")
146 fmt.Println("Afterwards press CTRL+C to continue")
148 fmt.Println("continuing...")
151 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
154 // Connect to VPP and store the connection
155 sockAddress := vpp.container.getHostWorkDir() + defaultApiSocketFilePath
156 conn, connEv, err := govpp.AsyncConnect(
158 core.DefaultMaxReconnectAttempts,
159 core.DefaultReconnectInterval)
161 fmt.Println("async connect error: ", err)
164 vpp.connection = conn
166 // ... wait for Connected event
168 if e.State != core.Connected {
169 fmt.Println("connecting to VPP failed: ", e.Error)
172 // ... check compatibility of used messages
173 ch, err := conn.NewAPIChannel()
175 fmt.Println("creating channel failed: ", err)
178 if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
179 fmt.Println("compatibility error: ", err)
182 if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
183 fmt.Println("compatibility error: ", err)
191 func (vpp *VppInstance) vppctl(command string, arguments ...any) string {
192 vppCliCommand := fmt.Sprintf(command, arguments...)
193 containerExecCommand := fmt.Sprintf("docker exec --detach=false %[1]s vppctl -s %[2]s %[3]s",
194 vpp.container.name, vpp.getCliSocket(), vppCliCommand)
195 vpp.getSuite().log(containerExecCommand)
196 output, err := exechelper.CombinedOutput(containerExecCommand)
197 vpp.getSuite().assertNil(err)
199 return string(output)
202 func (vpp *VppInstance) GetSessionStat(stat string) int {
203 o := vpp.vppctl("show session stats")
204 vpp.getSuite().log(o)
205 for _, line := range strings.Split(o, "\n") {
206 if strings.Contains(line, stat) {
207 tokens := strings.Split(strings.TrimSpace(line), " ")
208 val, err := strconv.Atoi(tokens[0])
210 vpp.getSuite().FailNow("failed to parse stat value %s", err)
219 func (vpp *VppInstance) waitForApp(appName string, timeout int) {
220 for i := 0; i < timeout; i++ {
221 o := vpp.vppctl("show app")
222 if strings.Contains(o, appName) {
225 time.Sleep(1 * time.Second)
227 vpp.getSuite().assertNil(1, "Timeout while waiting for app '%s'", appName)
230 func (vpp *VppInstance) createAfPacket(
232 ) (interface_types.InterfaceIndex, error) {
233 createReq := &af_packet.AfPacketCreateV2{
234 UseRandomHwAddr: true,
235 HostIfName: veth.Name(),
237 if veth.hwAddress != (MacAddress{}) {
238 createReq.UseRandomHwAddr = false
239 createReq.HwAddr = veth.hwAddress
241 createReply := &af_packet.AfPacketCreateV2Reply{}
243 if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
246 veth.index = createReply.SwIfIndex
249 upReq := &interfaces.SwInterfaceSetFlags{
250 SwIfIndex: veth.index,
251 Flags: interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
253 upReply := &interfaces.SwInterfaceSetFlagsReply{}
255 if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
260 if veth.addressWithPrefix() == (AddressWithPrefix{}) {
262 var ip4Address string
263 if ip4Address, err = veth.ip4AddrAllocator.NewIp4InterfaceAddress(veth.peer.networkNumber); err == nil {
264 veth.ip4Address = ip4Address
269 addressReq := &interfaces.SwInterfaceAddDelAddress{
271 SwIfIndex: veth.index,
272 Prefix: veth.addressWithPrefix(),
274 addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
276 if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
280 return veth.index, nil
283 func (vpp *VppInstance) addAppNamespace(
285 ifx interface_types.InterfaceIndex,
288 req := &session.AppNamespaceAddDelV2{
291 NamespaceID: namespaceId,
293 reply := &session.AppNamespaceAddDelV2Reply{}
295 if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
299 sessionReq := &session.SessionEnableDisable{
302 sessionReply := &session.SessionEnableDisableReply{}
304 if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
311 func (vpp *VppInstance) createTap(
319 createTapReq := &tapv2.TapCreateV2{
322 HostIfName: tap.Name(),
323 HostIP4PrefixSet: true,
324 HostIP4Prefix: tap.ip4AddressWithPrefix(),
326 createTapReply := &tapv2.TapCreateV2Reply{}
328 // Create tap interface
329 if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
334 addAddressReq := &interfaces.SwInterfaceAddDelAddress{
336 SwIfIndex: createTapReply.SwIfIndex,
337 Prefix: tap.peer.addressWithPrefix(),
339 addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
341 if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
345 // Set interface to up
346 upReq := &interfaces.SwInterfaceSetFlags{
347 SwIfIndex: createTapReply.SwIfIndex,
348 Flags: interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
350 upReply := &interfaces.SwInterfaceSetFlagsReply{}
352 if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
359 func (vpp *VppInstance) saveLogs() {
360 logTarget := vpp.container.getLogDirPath() + "vppinstance-" + vpp.container.name + ".log"
361 logSource := vpp.container.getHostWorkDir() + defaultLogFilePath
362 cmd := exec.Command("cp", logSource, logTarget)
363 vpp.getSuite().T().Helper()
364 vpp.getSuite().log(cmd.String())
368 func (vpp *VppInstance) disconnect() {
369 vpp.connection.Disconnect()
370 vpp.apiChannel.Close()
373 func (vpp *VppInstance) generateCpuConfig() string {
376 if len(vpp.cpus) < 1 {
380 append(fmt.Sprintf("main-core %d", vpp.cpus[0]))
381 workers := vpp.cpus[1:]
383 if len(workers) > 0 {
384 for i := 0; i < len(workers); i++ {
388 s = s + fmt.Sprintf("%d", workers[i])
390 c.append(fmt.Sprintf("corelist-workers %s", s))
392 return c.close().toString()