bed084c42edac1b16aa5546d0c8a0958ea135bcd
[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                 // Start VPP in GDB and wait for user to attach it
141                 vpp.container.execServer("su -c \"gdb -ex run --args vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
142                 fmt.Println("run following command in different terminal:")
143                 fmt.Println("docker exec -it " + vpp.container.name + " gdb -ex \"attach $(docker exec " + vpp.container.name + " pidof gdb)\"")
144                 fmt.Println("Afterwards press CTRL+C to continue")
145                 <-cont
146                 fmt.Println("continuing...")
147         } else {
148                 // Start VPP
149                 vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
150         }
151
152         // Connect to VPP and store the connection
153         sockAddress := vpp.container.getHostWorkDir() + defaultApiSocketFilePath
154         conn, connEv, err := govpp.AsyncConnect(
155                 sockAddress,
156                 core.DefaultMaxReconnectAttempts,
157                 core.DefaultReconnectInterval)
158         if err != nil {
159                 fmt.Println("async connect error: ", err)
160         }
161         vpp.connection = conn
162
163         // ... wait for Connected event
164         e := <-connEv
165         if e.State != core.Connected {
166                 fmt.Println("connecting to VPP failed: ", e.Error)
167         }
168
169         // ... check compatibility of used messages
170         ch, err := conn.NewAPIChannel()
171         if err != nil {
172                 fmt.Println("creating channel failed: ", err)
173         }
174         if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
175                 fmt.Println("compatibility error: ", err)
176         }
177         if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
178                 fmt.Println("compatibility error: ", err)
179         }
180         vpp.apiChannel = ch
181
182         return nil
183 }
184
185 func (vpp *VppInstance) vppctl(command string, arguments ...any) string {
186         vppCliCommand := fmt.Sprintf(command, arguments...)
187         containerExecCommand := fmt.Sprintf("docker exec --detach=false %[1]s vppctl -s %[2]s %[3]s",
188                 vpp.container.name, vpp.getCliSocket(), vppCliCommand)
189         vpp.getSuite().log(containerExecCommand)
190         output, err := exechelper.CombinedOutput(containerExecCommand)
191         vpp.getSuite().assertNil(err)
192
193         return string(output)
194 }
195
196 func (vpp *VppInstance) GetSessionStat(stat string) int {
197         o := vpp.vppctl("show session stats")
198         vpp.getSuite().log(o)
199         for _, line := range strings.Split(o, "\n") {
200                 if strings.Contains(line, stat) {
201                         tokens := strings.Split(strings.TrimSpace(line), " ")
202                         val, err := strconv.Atoi(tokens[0])
203                         if err != nil {
204                                 vpp.getSuite().FailNow("failed to parse stat value %s", err)
205                                 return 0
206                         }
207                         return val
208                 }
209         }
210         return 0
211 }
212
213 func (vpp *VppInstance) waitForApp(appName string, timeout int) {
214         for i := 0; i < timeout; i++ {
215                 o := vpp.vppctl("show app")
216                 if strings.Contains(o, appName) {
217                         return
218                 }
219                 time.Sleep(1 * time.Second)
220         }
221         vpp.getSuite().assertNil(1, "Timeout while waiting for app '%s'", appName)
222 }
223
224 func (vpp *VppInstance) createAfPacket(
225         veth *NetInterface,
226 ) (interface_types.InterfaceIndex, error) {
227         createReq := &af_packet.AfPacketCreateV2{
228                 UseRandomHwAddr: true,
229                 HostIfName:      veth.Name(),
230         }
231         if veth.hwAddress != (MacAddress{}) {
232                 createReq.UseRandomHwAddr = false
233                 createReq.HwAddr = veth.hwAddress
234         }
235         createReply := &af_packet.AfPacketCreateV2Reply{}
236
237         if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
238                 return 0, err
239         }
240         veth.index = createReply.SwIfIndex
241
242         // Set to up
243         upReq := &interfaces.SwInterfaceSetFlags{
244                 SwIfIndex: veth.index,
245                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
246         }
247         upReply := &interfaces.SwInterfaceSetFlagsReply{}
248
249         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
250                 return 0, err
251         }
252
253         // Add address
254         if veth.addressWithPrefix() == (AddressWithPrefix{}) {
255                 var err error
256                 var ip4Address string
257                 if ip4Address, err = veth.ip4AddrAllocator.NewIp4InterfaceAddress(veth.peer.networkNumber); err == nil {
258                         veth.ip4Address = ip4Address
259                 } else {
260                         return 0, err
261                 }
262         }
263         addressReq := &interfaces.SwInterfaceAddDelAddress{
264                 IsAdd:     true,
265                 SwIfIndex: veth.index,
266                 Prefix:    veth.addressWithPrefix(),
267         }
268         addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
269
270         if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
271                 return 0, err
272         }
273
274         return veth.index, nil
275 }
276
277 func (vpp *VppInstance) addAppNamespace(
278         secret uint64,
279         ifx interface_types.InterfaceIndex,
280         namespaceId string,
281 ) error {
282         req := &session.AppNamespaceAddDelV2{
283                 Secret:      secret,
284                 SwIfIndex:   ifx,
285                 NamespaceID: namespaceId,
286         }
287         reply := &session.AppNamespaceAddDelV2Reply{}
288
289         if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
290                 return err
291         }
292
293         sessionReq := &session.SessionEnableDisable{
294                 IsEnable: true,
295         }
296         sessionReply := &session.SessionEnableDisableReply{}
297
298         if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
299                 return err
300         }
301
302         return nil
303 }
304
305 func (vpp *VppInstance) createTap(
306         tap *NetInterface,
307         tapId ...uint32,
308 ) error {
309         var id uint32 = 1
310         if len(tapId) > 0 {
311                 id = tapId[0]
312         }
313         createTapReq := &tapv2.TapCreateV2{
314                 ID:               id,
315                 HostIfNameSet:    true,
316                 HostIfName:       tap.Name(),
317                 HostIP4PrefixSet: true,
318                 HostIP4Prefix:    tap.ip4AddressWithPrefix(),
319         }
320         createTapReply := &tapv2.TapCreateV2Reply{}
321
322         // Create tap interface
323         if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
324                 return err
325         }
326
327         // Add address
328         addAddressReq := &interfaces.SwInterfaceAddDelAddress{
329                 IsAdd:     true,
330                 SwIfIndex: createTapReply.SwIfIndex,
331                 Prefix:    tap.peer.addressWithPrefix(),
332         }
333         addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
334
335         if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
336                 return err
337         }
338
339         // Set interface to up
340         upReq := &interfaces.SwInterfaceSetFlags{
341                 SwIfIndex: createTapReply.SwIfIndex,
342                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
343         }
344         upReply := &interfaces.SwInterfaceSetFlagsReply{}
345
346         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
347                 return err
348         }
349
350         return nil
351 }
352
353 func (vpp *VppInstance) saveLogs() {
354         logTarget := vpp.container.getLogDirPath() + "vppinstance-" + vpp.container.name + ".log"
355         logSource := vpp.container.getHostWorkDir() + defaultLogFilePath
356         cmd := exec.Command("cp", logSource, logTarget)
357         vpp.getSuite().T().Helper()
358         vpp.getSuite().log(cmd.String())
359         cmd.Run()
360 }
361
362 func (vpp *VppInstance) disconnect() {
363         vpp.connection.Disconnect()
364         vpp.apiChannel.Close()
365 }
366
367 func (vpp *VppInstance) generateCpuConfig() string {
368         var c Stanza
369         var s string
370         if len(vpp.cpus) < 1 {
371                 return ""
372         }
373         c.newStanza("cpu").
374                 append(fmt.Sprintf("main-core %d", vpp.cpus[0]))
375         workers := vpp.cpus[1:]
376
377         if len(workers) > 0 {
378                 for i := 0; i < len(workers); i++ {
379                         if i != 0 {
380                                 s = s + ", "
381                         }
382                         s = s + fmt.Sprintf("%d", workers[i])
383                 }
384                 c.append(fmt.Sprintf("corelist-workers %s", s))
385         }
386         return c.close().toString()
387 }