hs-test: add tls proxy test
[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         }
163         vpp.connection = conn
164
165         // ... wait for Connected event
166         e := <-connEv
167         if e.State != core.Connected {
168                 fmt.Println("connecting to VPP failed: ", e.Error)
169         }
170
171         // ... check compatibility of used messages
172         ch, err := conn.NewAPIChannel()
173         if err != nil {
174                 fmt.Println("creating channel failed: ", err)
175         }
176         if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
177                 fmt.Println("compatibility error: ", err)
178         }
179         if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
180                 fmt.Println("compatibility error: ", err)
181         }
182         vpp.apiChannel = ch
183
184         return nil
185 }
186
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)
194
195         return string(output)
196 }
197
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])
205                         if err != nil {
206                                 vpp.getSuite().FailNow("failed to parse stat value %s", err)
207                                 return 0
208                         }
209                         return val
210                 }
211         }
212         return 0
213 }
214
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) {
219                         return
220                 }
221                 time.Sleep(1 * time.Second)
222         }
223         vpp.getSuite().assertNil(1, "Timeout while waiting for app '%s'", appName)
224 }
225
226 func (vpp *VppInstance) createAfPacket(
227         veth *NetInterface,
228 ) (interface_types.InterfaceIndex, error) {
229         createReq := &af_packet.AfPacketCreateV2{
230                 UseRandomHwAddr: true,
231                 HostIfName:      veth.Name(),
232         }
233         if veth.hwAddress != (MacAddress{}) {
234                 createReq.UseRandomHwAddr = false
235                 createReq.HwAddr = veth.hwAddress
236         }
237         createReply := &af_packet.AfPacketCreateV2Reply{}
238
239         if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
240                 return 0, err
241         }
242         veth.index = createReply.SwIfIndex
243
244         // Set to up
245         upReq := &interfaces.SwInterfaceSetFlags{
246                 SwIfIndex: veth.index,
247                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
248         }
249         upReply := &interfaces.SwInterfaceSetFlagsReply{}
250
251         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
252                 return 0, err
253         }
254
255         // Add address
256         if veth.addressWithPrefix() == (AddressWithPrefix{}) {
257                 var err error
258                 var ip4Address string
259                 if ip4Address, err = veth.ip4AddrAllocator.NewIp4InterfaceAddress(veth.peer.networkNumber); err == nil {
260                         veth.ip4Address = ip4Address
261                 } else {
262                         return 0, err
263                 }
264         }
265         addressReq := &interfaces.SwInterfaceAddDelAddress{
266                 IsAdd:     true,
267                 SwIfIndex: veth.index,
268                 Prefix:    veth.addressWithPrefix(),
269         }
270         addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
271
272         if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
273                 return 0, err
274         }
275
276         return veth.index, nil
277 }
278
279 func (vpp *VppInstance) addAppNamespace(
280         secret uint64,
281         ifx interface_types.InterfaceIndex,
282         namespaceId string,
283 ) error {
284         req := &session.AppNamespaceAddDelV2{
285                 Secret:      secret,
286                 SwIfIndex:   ifx,
287                 NamespaceID: namespaceId,
288         }
289         reply := &session.AppNamespaceAddDelV2Reply{}
290
291         if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
292                 return err
293         }
294
295         sessionReq := &session.SessionEnableDisable{
296                 IsEnable: true,
297         }
298         sessionReply := &session.SessionEnableDisableReply{}
299
300         if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
301                 return err
302         }
303
304         return nil
305 }
306
307 func (vpp *VppInstance) createTap(
308         tap *NetInterface,
309         tapId ...uint32,
310 ) error {
311         var id uint32 = 1
312         if len(tapId) > 0 {
313                 id = tapId[0]
314         }
315         createTapReq := &tapv2.TapCreateV2{
316                 ID:               id,
317                 HostIfNameSet:    true,
318                 HostIfName:       tap.Name(),
319                 HostIP4PrefixSet: true,
320                 HostIP4Prefix:    tap.ip4AddressWithPrefix(),
321         }
322         createTapReply := &tapv2.TapCreateV2Reply{}
323
324         // Create tap interface
325         if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
326                 return err
327         }
328
329         // Add address
330         addAddressReq := &interfaces.SwInterfaceAddDelAddress{
331                 IsAdd:     true,
332                 SwIfIndex: createTapReply.SwIfIndex,
333                 Prefix:    tap.peer.addressWithPrefix(),
334         }
335         addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
336
337         if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
338                 return err
339         }
340
341         // Set interface to up
342         upReq := &interfaces.SwInterfaceSetFlags{
343                 SwIfIndex: createTapReply.SwIfIndex,
344                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
345         }
346         upReply := &interfaces.SwInterfaceSetFlagsReply{}
347
348         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
349                 return err
350         }
351
352         return nil
353 }
354
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())
361         cmd.Run()
362 }
363
364 func (vpp *VppInstance) disconnect() {
365         vpp.connection.Disconnect()
366         vpp.apiChannel.Close()
367 }
368
369 func (vpp *VppInstance) generateCpuConfig() string {
370         var c Stanza
371         var s string
372         if len(vpp.cpus) < 1 {
373                 return ""
374         }
375         c.newStanza("cpu").
376                 append(fmt.Sprintf("main-core %d", vpp.cpus[0]))
377         workers := vpp.cpus[1:]
378
379         if len(workers) > 0 {
380                 for i := 0; i < len(workers); i++ {
381                         if i != 0 {
382                                 s = s + ", "
383                         }
384                         s = s + fmt.Sprintf("%d", workers[i])
385                 }
386                 c.append(fmt.Sprintf("corelist-workers %s", s))
387         }
388         return c.close().toString()
389 }