hs-test: fix gdb attach
[vpp.git] / extras / hs-test / vppinstance.go
1 package main
2
3 import (
4         "fmt"
5         "os"
6         "os/exec"
7         "os/signal"
8         "strconv"
9         "strings"
10         "syscall"
11         "time"
12
13         "github.com/edwarnicke/exechelper"
14
15         "go.fd.io/govpp"
16         "go.fd.io/govpp/api"
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"
23         "go.fd.io/govpp/core"
24 )
25
26 const vppConfigTemplate = `unix {
27   nodaemon
28   log %[1]s%[4]s
29   full-coredump
30   cli-listen %[1]s%[2]s
31   runtime-dir %[1]s/var/run
32   gid vpp
33 }
34
35 api-trace {
36   on
37 }
38
39 api-segment {
40   gid vpp
41 }
42
43 socksvr {
44   socket-name %[1]s%[3]s
45 }
46
47 statseg {
48   socket-name %[1]s/var/run/vpp/stats.sock
49 }
50
51 plugins {
52   plugin default { disable }
53
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 }
60
61 logging {
62   default-log-level debug
63   default-syslog-log-level debug
64 }
65
66 `
67
68 const (
69         defaultCliSocketFilePath = "/var/run/vpp/cli.sock"
70         defaultApiSocketFilePath = "/var/run/vpp/api.sock"
71         defaultLogFilePath       = "/var/log/vpp/vpp.log"
72 )
73
74 type VppInstance struct {
75         container        *Container
76         additionalConfig []Stanza
77         connection       *core.Connection
78         apiChannel       api.Channel
79         cpus             []int
80 }
81
82 func (vpp *VppInstance) getSuite() *HstSuite {
83         return vpp.container.suite
84 }
85
86 func (vpp *VppInstance) getCliSocket() string {
87         return fmt.Sprintf("%s%s", vpp.container.getContainerWorkDir(), defaultCliSocketFilePath)
88 }
89
90 func (vpp *VppInstance) getRunDir() string {
91         return vpp.container.getContainerWorkDir() + "/var/run/vpp"
92 }
93
94 func (vpp *VppInstance) getLogDir() string {
95         return vpp.container.getContainerWorkDir() + "/var/log/vpp"
96 }
97
98 func (vpp *VppInstance) getEtcDir() string {
99         return vpp.container.getContainerWorkDir() + "/etc/vpp"
100 }
101
102 func (vpp *VppInstance) start() error {
103         // Create folders
104         containerWorkDir := vpp.container.getContainerWorkDir()
105
106         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getRunDir())
107         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getLogDir())
108         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getEtcDir())
109
110         // Create startup.conf inside the container
111         configContent := fmt.Sprintf(
112                 vppConfigTemplate,
113                 containerWorkDir,
114                 defaultCliSocketFilePath,
115                 defaultApiSocketFilePath,
116                 defaultLogFilePath,
117         )
118         configContent += vpp.generateCpuConfig()
119         for _, c := range vpp.additionalConfig {
120                 configContent += c.toString()
121         }
122         startupFileName := vpp.getEtcDir() + "/startup.conf"
123         vpp.container.createFile(startupFileName, configContent)
124
125         // create wrapper script for vppctl with proper CLI socket path
126         cliContent := "#!/usr/bin/bash\nvppctl -s " + vpp.getRunDir() + "/cli.sock"
127         vppcliFileName := "/usr/bin/vppcli"
128         vpp.container.createFile(vppcliFileName, cliContent)
129         vpp.container.exec("chmod 0755 " + vppcliFileName)
130
131         if *isVppDebug {
132                 sig := make(chan os.Signal, 1)
133                 signal.Notify(sig, syscall.SIGINT)
134                 cont := make(chan bool, 1)
135                 go func() {
136                         <-sig
137                         cont <- true
138                 }()
139
140                 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
141                 fmt.Println("run following command in different terminal:")
142                 fmt.Println("docker exec -it " + vpp.container.name + " gdb -ex \"attach $(docker exec " + vpp.container.name + " pidof vpp)\"")
143                 fmt.Println("Afterwards press CTRL+C to continue")
144                 <-cont
145                 fmt.Println("continuing...")
146         } else {
147                 // Start VPP
148                 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
149         }
150
151         // Connect to VPP and store the connection
152         sockAddress := vpp.container.getHostWorkDir() + defaultApiSocketFilePath
153         conn, connEv, err := govpp.AsyncConnect(
154                 sockAddress,
155                 core.DefaultMaxReconnectAttempts,
156                 core.DefaultReconnectInterval)
157         if err != nil {
158                 fmt.Println("async connect error: ", err)
159         }
160         vpp.connection = conn
161
162         // ... wait for Connected event
163         e := <-connEv
164         if e.State != core.Connected {
165                 fmt.Println("connecting to VPP failed: ", e.Error)
166         }
167
168         // ... check compatibility of used messages
169         ch, err := conn.NewAPIChannel()
170         if err != nil {
171                 fmt.Println("creating channel failed: ", err)
172         }
173         if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
174                 fmt.Println("compatibility error: ", err)
175         }
176         if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
177                 fmt.Println("compatibility error: ", err)
178         }
179         vpp.apiChannel = ch
180
181         return nil
182 }
183
184 func (vpp *VppInstance) vppctl(command string, arguments ...any) string {
185         vppCliCommand := fmt.Sprintf(command, arguments...)
186         containerExecCommand := fmt.Sprintf("docker exec --detach=false %[1]s vppctl -s %[2]s %[3]s",
187                 vpp.container.name, vpp.getCliSocket(), vppCliCommand)
188         vpp.getSuite().log(containerExecCommand)
189         output, err := exechelper.CombinedOutput(containerExecCommand)
190         vpp.getSuite().assertNil(err)
191
192         return string(output)
193 }
194
195 func (vpp *VppInstance) GetSessionStat(stat string) int {
196         o := vpp.vppctl("show session stats")
197         vpp.getSuite().log(o)
198         for _, line := range strings.Split(o, "\n") {
199                 if strings.Contains(line, stat) {
200                         tokens := strings.Split(strings.TrimSpace(line), " ")
201                         val, err := strconv.Atoi(tokens[0])
202                         if err != nil {
203                                 vpp.getSuite().FailNow("failed to parse stat value %s", err)
204                                 return 0
205                         }
206                         return val
207                 }
208         }
209         return 0
210 }
211
212 func (vpp *VppInstance) waitForApp(appName string, timeout int) {
213         for i := 0; i < timeout; i++ {
214                 o := vpp.vppctl("show app")
215                 if strings.Contains(o, appName) {
216                         return
217                 }
218                 time.Sleep(1 * time.Second)
219         }
220         vpp.getSuite().assertNil(1, "Timeout while waiting for app '%s'", appName)
221 }
222
223 func (vpp *VppInstance) createAfPacket(
224         veth *NetInterface,
225 ) (interface_types.InterfaceIndex, error) {
226         createReq := &af_packet.AfPacketCreateV2{
227                 UseRandomHwAddr: true,
228                 HostIfName:      veth.Name(),
229         }
230         if veth.hwAddress != (MacAddress{}) {
231                 createReq.UseRandomHwAddr = false
232                 createReq.HwAddr = veth.hwAddress
233         }
234         createReply := &af_packet.AfPacketCreateV2Reply{}
235
236         if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
237                 return 0, err
238         }
239         veth.index = createReply.SwIfIndex
240
241         // Set to up
242         upReq := &interfaces.SwInterfaceSetFlags{
243                 SwIfIndex: veth.index,
244                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
245         }
246         upReply := &interfaces.SwInterfaceSetFlagsReply{}
247
248         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
249                 return 0, err
250         }
251
252         // Add address
253         if veth.addressWithPrefix() == (AddressWithPrefix{}) {
254                 var err error
255                 var ip4Address string
256                 if ip4Address, err = veth.ip4AddrAllocator.NewIp4InterfaceAddress(veth.peer.networkNumber); err == nil {
257                         veth.ip4Address = ip4Address
258                 } else {
259                         return 0, err
260                 }
261         }
262         addressReq := &interfaces.SwInterfaceAddDelAddress{
263                 IsAdd:     true,
264                 SwIfIndex: veth.index,
265                 Prefix:    veth.addressWithPrefix(),
266         }
267         addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
268
269         if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
270                 return 0, err
271         }
272
273         return veth.index, nil
274 }
275
276 func (vpp *VppInstance) addAppNamespace(
277         secret uint64,
278         ifx interface_types.InterfaceIndex,
279         namespaceId string,
280 ) error {
281         req := &session.AppNamespaceAddDelV2{
282                 Secret:      secret,
283                 SwIfIndex:   ifx,
284                 NamespaceID: namespaceId,
285         }
286         reply := &session.AppNamespaceAddDelV2Reply{}
287
288         if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
289                 return err
290         }
291
292         sessionReq := &session.SessionEnableDisable{
293                 IsEnable: true,
294         }
295         sessionReply := &session.SessionEnableDisableReply{}
296
297         if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
298                 return err
299         }
300
301         return nil
302 }
303
304 func (vpp *VppInstance) createTap(
305         tap *NetInterface,
306         tapId ...uint32,
307 ) error {
308         var id uint32 = 1
309         if len(tapId) > 0 {
310                 id = tapId[0]
311         }
312         createTapReq := &tapv2.TapCreateV2{
313                 ID:               id,
314                 HostIfNameSet:    true,
315                 HostIfName:       tap.Name(),
316                 HostIP4PrefixSet: true,
317                 HostIP4Prefix:    tap.ip4AddressWithPrefix(),
318         }
319         createTapReply := &tapv2.TapCreateV2Reply{}
320
321         // Create tap interface
322         if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
323                 return err
324         }
325
326         // Add address
327         addAddressReq := &interfaces.SwInterfaceAddDelAddress{
328                 IsAdd:     true,
329                 SwIfIndex: createTapReply.SwIfIndex,
330                 Prefix:    tap.peer.addressWithPrefix(),
331         }
332         addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
333
334         if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
335                 return err
336         }
337
338         // Set interface to up
339         upReq := &interfaces.SwInterfaceSetFlags{
340                 SwIfIndex: createTapReply.SwIfIndex,
341                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
342         }
343         upReply := &interfaces.SwInterfaceSetFlagsReply{}
344
345         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
346                 return err
347         }
348
349         return nil
350 }
351
352 func (vpp *VppInstance) saveLogs() {
353         logTarget := vpp.container.getLogDirPath() + "vppinstance-" + vpp.container.name + ".log"
354         logSource := vpp.container.getHostWorkDir() + defaultLogFilePath
355         cmd := exec.Command("cp", logSource, logTarget)
356         vpp.getSuite().T().Helper()
357         vpp.getSuite().log(cmd.String())
358         cmd.Run()
359 }
360
361 func (vpp *VppInstance) disconnect() {
362         vpp.connection.Disconnect()
363         vpp.apiChannel.Close()
364 }
365
366 func (vpp *VppInstance) generateCpuConfig() string {
367         var c Stanza
368         var s string
369         if len(vpp.cpus) < 1 {
370                 return ""
371         }
372         c.newStanza("cpu").
373                 append(fmt.Sprintf("main-core %d", vpp.cpus[0]))
374         workers := vpp.cpus[1:]
375
376         if len(workers) > 0 {
377                 for i := 0; i < len(workers); i++ {
378                         if i != 0 {
379                                 s = s + ", "
380                         }
381                         s = s + fmt.Sprintf("%d", workers[i])
382                 }
383                 c.append(fmt.Sprintf("corelist-workers %s", s))
384         }
385         return c.close().toString()
386 }