hs-test: add more asserts
[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   plugin http_static_plugin.so { enable }
60   plugin prom_plugin.so { enable }
61   plugin tlsopenssl_plugin.so { enable }
62 }
63
64 logging {
65   default-log-level debug
66   default-syslog-log-level debug
67 }
68
69 `
70
71 const (
72         defaultCliSocketFilePath = "/var/run/vpp/cli.sock"
73         defaultApiSocketFilePath = "/var/run/vpp/api.sock"
74         defaultLogFilePath       = "/var/log/vpp/vpp.log"
75 )
76
77 type VppInstance struct {
78         container        *Container
79         additionalConfig []Stanza
80         connection       *core.Connection
81         apiChannel       api.Channel
82         cpus             []int
83 }
84
85 func (vpp *VppInstance) getSuite() *HstSuite {
86         return vpp.container.suite
87 }
88
89 func (vpp *VppInstance) getCliSocket() string {
90         return fmt.Sprintf("%s%s", vpp.container.getContainerWorkDir(), defaultCliSocketFilePath)
91 }
92
93 func (vpp *VppInstance) getRunDir() string {
94         return vpp.container.getContainerWorkDir() + "/var/run/vpp"
95 }
96
97 func (vpp *VppInstance) getLogDir() string {
98         return vpp.container.getContainerWorkDir() + "/var/log/vpp"
99 }
100
101 func (vpp *VppInstance) getEtcDir() string {
102         return vpp.container.getContainerWorkDir() + "/etc/vpp"
103 }
104
105 func (vpp *VppInstance) start() error {
106         // Create folders
107         containerWorkDir := vpp.container.getContainerWorkDir()
108
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())
112
113         // Create startup.conf inside the container
114         configContent := fmt.Sprintf(
115                 vppConfigTemplate,
116                 containerWorkDir,
117                 defaultCliSocketFilePath,
118                 defaultApiSocketFilePath,
119                 defaultLogFilePath,
120         )
121         configContent += vpp.generateCpuConfig()
122         for _, c := range vpp.additionalConfig {
123                 configContent += c.toString()
124         }
125         startupFileName := vpp.getEtcDir() + "/startup.conf"
126         vpp.container.createFile(startupFileName, configContent)
127
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)
133
134         if *isVppDebug {
135                 sig := make(chan os.Signal, 1)
136                 signal.Notify(sig, syscall.SIGINT)
137                 cont := make(chan bool, 1)
138                 go func() {
139                         <-sig
140                         cont <- true
141                 }()
142
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")
147                 <-cont
148                 fmt.Println("continuing...")
149         } else {
150                 // Start VPP
151                 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
152         }
153
154         // Connect to VPP and store the connection
155         sockAddress := vpp.container.getHostWorkDir() + defaultApiSocketFilePath
156         conn, connEv, err := govpp.AsyncConnect(
157                 sockAddress,
158                 core.DefaultMaxReconnectAttempts,
159                 core.DefaultReconnectInterval)
160         if err != nil {
161                 fmt.Println("async connect error: ", err)
162                 return err
163         }
164         vpp.connection = conn
165
166         // ... wait for Connected event
167         e := <-connEv
168         if e.State != core.Connected {
169                 fmt.Println("connecting to VPP failed: ", e.Error)
170         }
171
172         // ... check compatibility of used messages
173         ch, err := conn.NewAPIChannel()
174         if err != nil {
175                 fmt.Println("creating channel failed: ", err)
176                 return err
177         }
178         if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
179                 fmt.Println("compatibility error: ", err)
180                 return err
181         }
182         if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
183                 fmt.Println("compatibility error: ", err)
184                 return err
185         }
186         vpp.apiChannel = ch
187
188         return nil
189 }
190
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)
198
199         return string(output)
200 }
201
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])
209                         if err != nil {
210                                 vpp.getSuite().FailNow("failed to parse stat value %s", err)
211                                 return 0
212                         }
213                         return val
214                 }
215         }
216         return 0
217 }
218
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) {
223                         return
224                 }
225                 time.Sleep(1 * time.Second)
226         }
227         vpp.getSuite().assertNil(1, "Timeout while waiting for app '%s'", appName)
228 }
229
230 func (vpp *VppInstance) createAfPacket(
231         veth *NetInterface,
232 ) (interface_types.InterfaceIndex, error) {
233         createReq := &af_packet.AfPacketCreateV2{
234                 UseRandomHwAddr: true,
235                 HostIfName:      veth.Name(),
236         }
237         if veth.hwAddress != (MacAddress{}) {
238                 createReq.UseRandomHwAddr = false
239                 createReq.HwAddr = veth.hwAddress
240         }
241         createReply := &af_packet.AfPacketCreateV2Reply{}
242
243         if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
244                 return 0, err
245         }
246         veth.index = createReply.SwIfIndex
247
248         // Set to up
249         upReq := &interfaces.SwInterfaceSetFlags{
250                 SwIfIndex: veth.index,
251                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
252         }
253         upReply := &interfaces.SwInterfaceSetFlagsReply{}
254
255         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
256                 return 0, err
257         }
258
259         // Add address
260         if veth.addressWithPrefix() == (AddressWithPrefix{}) {
261                 var err error
262                 var ip4Address string
263                 if ip4Address, err = veth.ip4AddrAllocator.NewIp4InterfaceAddress(veth.peer.networkNumber); err == nil {
264                         veth.ip4Address = ip4Address
265                 } else {
266                         return 0, err
267                 }
268         }
269         addressReq := &interfaces.SwInterfaceAddDelAddress{
270                 IsAdd:     true,
271                 SwIfIndex: veth.index,
272                 Prefix:    veth.addressWithPrefix(),
273         }
274         addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
275
276         if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
277                 return 0, err
278         }
279
280         return veth.index, nil
281 }
282
283 func (vpp *VppInstance) addAppNamespace(
284         secret uint64,
285         ifx interface_types.InterfaceIndex,
286         namespaceId string,
287 ) error {
288         req := &session.AppNamespaceAddDelV2{
289                 Secret:      secret,
290                 SwIfIndex:   ifx,
291                 NamespaceID: namespaceId,
292         }
293         reply := &session.AppNamespaceAddDelV2Reply{}
294
295         if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
296                 return err
297         }
298
299         sessionReq := &session.SessionEnableDisable{
300                 IsEnable: true,
301         }
302         sessionReply := &session.SessionEnableDisableReply{}
303
304         if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
305                 return err
306         }
307
308         return nil
309 }
310
311 func (vpp *VppInstance) createTap(
312         tap *NetInterface,
313         tapId ...uint32,
314 ) error {
315         var id uint32 = 1
316         if len(tapId) > 0 {
317                 id = tapId[0]
318         }
319         createTapReq := &tapv2.TapCreateV2{
320                 ID:               id,
321                 HostIfNameSet:    true,
322                 HostIfName:       tap.Name(),
323                 HostIP4PrefixSet: true,
324                 HostIP4Prefix:    tap.ip4AddressWithPrefix(),
325         }
326         createTapReply := &tapv2.TapCreateV2Reply{}
327
328         // Create tap interface
329         if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
330                 return err
331         }
332
333         // Add address
334         addAddressReq := &interfaces.SwInterfaceAddDelAddress{
335                 IsAdd:     true,
336                 SwIfIndex: createTapReply.SwIfIndex,
337                 Prefix:    tap.peer.addressWithPrefix(),
338         }
339         addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
340
341         if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
342                 return err
343         }
344
345         // Set interface to up
346         upReq := &interfaces.SwInterfaceSetFlags{
347                 SwIfIndex: createTapReply.SwIfIndex,
348                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
349         }
350         upReply := &interfaces.SwInterfaceSetFlagsReply{}
351
352         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
353                 return err
354         }
355
356         return nil
357 }
358
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())
365         cmd.Run()
366 }
367
368 func (vpp *VppInstance) disconnect() {
369         vpp.connection.Disconnect()
370         vpp.apiChannel.Close()
371 }
372
373 func (vpp *VppInstance) generateCpuConfig() string {
374         var c Stanza
375         var s string
376         if len(vpp.cpus) < 1 {
377                 return ""
378         }
379         c.newStanza("cpu").
380                 append(fmt.Sprintf("main-core %d", vpp.cpus[0]))
381         workers := vpp.cpus[1:]
382
383         if len(workers) > 0 {
384                 for i := 0; i < len(workers); i++ {
385                         if i != 0 {
386                                 s = s + ", "
387                         }
388                         s = s + fmt.Sprintf("%d", workers[i])
389                 }
390                 c.append(fmt.Sprintf("corelist-workers %s", s))
391         }
392         return c.close().toString()
393 }