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)
163 vpp.connection = conn
165 // ... wait for Connected event
167 if e.State != core.Connected {
168 fmt.Println("connecting to VPP failed: ", e.Error)
171 // ... check compatibility of used messages
172 ch, err := conn.NewAPIChannel()
174 fmt.Println("creating channel failed: ", err)
176 if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
177 fmt.Println("compatibility error: ", err)
179 if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
180 fmt.Println("compatibility error: ", err)
187 func (vpp *VppInstance) vppctl(command string, arguments ...any) string {
188 vppCliCommand := fmt.Sprintf(command, arguments...)
189 containerExecCommand := fmt.Sprintf("docker exec --detach=false %[1]s vppctl -s %[2]s %[3]s",
190 vpp.container.name, vpp.getCliSocket(), vppCliCommand)
191 vpp.getSuite().log(containerExecCommand)
192 output, err := exechelper.CombinedOutput(containerExecCommand)
193 vpp.getSuite().assertNil(err)
195 return string(output)
198 func (vpp *VppInstance) GetSessionStat(stat string) int {
199 o := vpp.vppctl("show session stats")
200 vpp.getSuite().log(o)
201 for _, line := range strings.Split(o, "\n") {
202 if strings.Contains(line, stat) {
203 tokens := strings.Split(strings.TrimSpace(line), " ")
204 val, err := strconv.Atoi(tokens[0])
206 vpp.getSuite().FailNow("failed to parse stat value %s", err)
215 func (vpp *VppInstance) waitForApp(appName string, timeout int) {
216 for i := 0; i < timeout; i++ {
217 o := vpp.vppctl("show app")
218 if strings.Contains(o, appName) {
221 time.Sleep(1 * time.Second)
223 vpp.getSuite().assertNil(1, "Timeout while waiting for app '%s'", appName)
226 func (vpp *VppInstance) createAfPacket(
228 ) (interface_types.InterfaceIndex, error) {
229 createReq := &af_packet.AfPacketCreateV2{
230 UseRandomHwAddr: true,
231 HostIfName: veth.Name(),
233 if veth.hwAddress != (MacAddress{}) {
234 createReq.UseRandomHwAddr = false
235 createReq.HwAddr = veth.hwAddress
237 createReply := &af_packet.AfPacketCreateV2Reply{}
239 if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
242 veth.index = createReply.SwIfIndex
245 upReq := &interfaces.SwInterfaceSetFlags{
246 SwIfIndex: veth.index,
247 Flags: interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
249 upReply := &interfaces.SwInterfaceSetFlagsReply{}
251 if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
256 if veth.addressWithPrefix() == (AddressWithPrefix{}) {
258 var ip4Address string
259 if ip4Address, err = veth.ip4AddrAllocator.NewIp4InterfaceAddress(veth.peer.networkNumber); err == nil {
260 veth.ip4Address = ip4Address
265 addressReq := &interfaces.SwInterfaceAddDelAddress{
267 SwIfIndex: veth.index,
268 Prefix: veth.addressWithPrefix(),
270 addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
272 if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
276 return veth.index, nil
279 func (vpp *VppInstance) addAppNamespace(
281 ifx interface_types.InterfaceIndex,
284 req := &session.AppNamespaceAddDelV2{
287 NamespaceID: namespaceId,
289 reply := &session.AppNamespaceAddDelV2Reply{}
291 if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
295 sessionReq := &session.SessionEnableDisable{
298 sessionReply := &session.SessionEnableDisableReply{}
300 if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
307 func (vpp *VppInstance) createTap(
315 createTapReq := &tapv2.TapCreateV2{
318 HostIfName: tap.Name(),
319 HostIP4PrefixSet: true,
320 HostIP4Prefix: tap.ip4AddressWithPrefix(),
322 createTapReply := &tapv2.TapCreateV2Reply{}
324 // Create tap interface
325 if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
330 addAddressReq := &interfaces.SwInterfaceAddDelAddress{
332 SwIfIndex: createTapReply.SwIfIndex,
333 Prefix: tap.peer.addressWithPrefix(),
335 addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
337 if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
341 // Set interface to up
342 upReq := &interfaces.SwInterfaceSetFlags{
343 SwIfIndex: createTapReply.SwIfIndex,
344 Flags: interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
346 upReply := &interfaces.SwInterfaceSetFlagsReply{}
348 if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
355 func (vpp *VppInstance) saveLogs() {
356 logTarget := vpp.container.getLogDirPath() + "vppinstance-" + vpp.container.name + ".log"
357 logSource := vpp.container.getHostWorkDir() + defaultLogFilePath
358 cmd := exec.Command("cp", logSource, logTarget)
359 vpp.getSuite().T().Helper()
360 vpp.getSuite().log(cmd.String())
364 func (vpp *VppInstance) disconnect() {
365 vpp.connection.Disconnect()
366 vpp.apiChannel.Close()
369 func (vpp *VppInstance) generateCpuConfig() string {
372 if len(vpp.cpus) < 1 {
376 append(fmt.Sprintf("main-core %d", vpp.cpus[0]))
377 workers := vpp.cpus[1:]
379 if len(workers) > 0 {
380 for i := 0; i < len(workers); i++ {
384 s = s + fmt.Sprintf("%d", workers[i])
386 c.append(fmt.Sprintf("corelist-workers %s", s))
388 return c.close().toString()