hs-test: refactor netconfig
[vpp.git] / extras / hs-test / vppinstance.go
1 package main
2
3 import (
4         "fmt"
5         "github.com/edwarnicke/exechelper"
6         "os/exec"
7         "strings"
8         "time"
9
10         "go.fd.io/govpp"
11         "go.fd.io/govpp/api"
12         "go.fd.io/govpp/binapi/af_packet"
13         interfaces "go.fd.io/govpp/binapi/interface"
14         "go.fd.io/govpp/binapi/interface_types"
15         "go.fd.io/govpp/binapi/session"
16         "go.fd.io/govpp/binapi/tapv2"
17         "go.fd.io/govpp/binapi/vpe"
18         "go.fd.io/govpp/core"
19 )
20
21 const vppConfigTemplate = `unix {
22   nodaemon
23   log %[1]s%[4]s
24   full-coredump
25   cli-listen %[1]s%[2]s
26   runtime-dir %[1]s/var/run
27   gid vpp
28 }
29
30 api-trace {
31   on
32 }
33
34 api-segment {
35   gid vpp
36 }
37
38 socksvr {
39   socket-name %[1]s%[3]s
40 }
41
42 statseg {
43   socket-name %[1]s/var/run/vpp/stats.sock
44 }
45
46 plugins {
47   plugin default { disable }
48
49   plugin unittest_plugin.so { enable }
50   plugin quic_plugin.so { enable }
51   plugin af_packet_plugin.so { enable }
52   plugin hs_apps_plugin.so { enable }
53   plugin http_plugin.so { enable }
54 }
55
56 logging {
57   default-log-level debug
58   default-syslog-log-level debug
59 }
60
61 `
62
63 const (
64         defaultCliSocketFilePath = "/var/run/vpp/cli.sock"
65         defaultApiSocketFilePath = "/var/run/vpp/api.sock"
66         defaultLogFilePath       = "/var/log/vpp/vpp.log"
67 )
68
69 type VppInstance struct {
70         container        *Container
71         additionalConfig Stanza
72         connection       *core.Connection
73         apiChannel       api.Channel
74 }
75
76 func (vpp *VppInstance) Suite() *HstSuite {
77         return vpp.container.suite
78 }
79
80 func (vpp *VppInstance) getCliSocket() string {
81         return fmt.Sprintf("%s%s", vpp.container.GetContainerWorkDir(), defaultCliSocketFilePath)
82 }
83
84 func (vpp *VppInstance) getRunDir() string {
85         return vpp.container.GetContainerWorkDir() + "/var/run/vpp"
86 }
87
88 func (vpp *VppInstance) getLogDir() string {
89         return vpp.container.GetContainerWorkDir() + "/var/log/vpp"
90 }
91
92 func (vpp *VppInstance) getEtcDir() string {
93         return vpp.container.GetContainerWorkDir() + "/etc/vpp"
94 }
95
96 func (vpp *VppInstance) start() error {
97         // Create folders
98         containerWorkDir := vpp.container.GetContainerWorkDir()
99
100         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getRunDir())
101         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getLogDir())
102         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getEtcDir())
103
104         // Create startup.conf inside the container
105         configContent := fmt.Sprintf(
106                 vppConfigTemplate,
107                 containerWorkDir,
108                 defaultCliSocketFilePath,
109                 defaultApiSocketFilePath,
110                 defaultLogFilePath,
111         )
112         configContent += vpp.additionalConfig.ToString()
113         startupFileName := vpp.getEtcDir() + "/startup.conf"
114         vpp.container.createFile(startupFileName, configContent)
115
116         // Start VPP
117         vpp.container.execServer("su -c \"vpp -c " + startupFileName + " &> /proc/1/fd/1\"")
118
119         // Connect to VPP and store the connection
120         sockAddress := vpp.container.GetHostWorkDir() + defaultApiSocketFilePath
121         conn, connEv, err := govpp.AsyncConnect(
122                 sockAddress,
123                 core.DefaultMaxReconnectAttempts,
124                 core.DefaultReconnectInterval)
125         if err != nil {
126                 fmt.Println("async connect error: ", err)
127         }
128         vpp.connection = conn
129
130         // ... wait for Connected event
131         e := <-connEv
132         if e.State != core.Connected {
133                 fmt.Println("connecting to VPP failed: ", e.Error)
134         }
135
136         // ... check compatibility of used messages
137         ch, err := conn.NewAPIChannel()
138         if err != nil {
139                 fmt.Println("creating channel failed: ", err)
140         }
141         if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
142                 fmt.Println("compatibility error: ", err)
143         }
144         if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
145                 fmt.Println("compatibility error: ", err)
146         }
147         vpp.apiChannel = ch
148
149         return nil
150 }
151
152 func (vpp *VppInstance) vppctl(command string, arguments ...any) string {
153         vppCliCommand := fmt.Sprintf(command, arguments...)
154         containerExecCommand := fmt.Sprintf("docker exec --detach=false %[1]s vppctl -s %[2]s %[3]s",
155                 vpp.container.name, vpp.getCliSocket(), vppCliCommand)
156         vpp.Suite().log(containerExecCommand)
157         output, err := exechelper.CombinedOutput(containerExecCommand)
158         vpp.Suite().assertNil(err)
159
160         return string(output)
161 }
162
163 func (vpp *VppInstance) waitForApp(appName string, timeout int) error {
164         for i := 0; i < timeout; i++ {
165                 o := vpp.vppctl("show app")
166                 if strings.Contains(o, appName) {
167                         return nil
168                 }
169                 time.Sleep(1 * time.Second)
170         }
171         return fmt.Errorf("timeout while waiting for app '%s'", appName)
172 }
173
174 func (vpp *VppInstance) createAfPacket(
175         veth *NetInterface,
176 ) (interface_types.InterfaceIndex, error) {
177         createReq := &af_packet.AfPacketCreateV2{
178                 UseRandomHwAddr: true,
179                 HostIfName:      veth.Name(),
180         }
181         if veth.HwAddress() != (MacAddress{}) {
182                 createReq.UseRandomHwAddr = false
183                 createReq.HwAddr = veth.HwAddress()
184         }
185         createReply := &af_packet.AfPacketCreateV2Reply{}
186
187         if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
188                 return 0, err
189         }
190         veth.SetIndex(createReply.SwIfIndex)
191
192         // Set to up
193         upReq := &interfaces.SwInterfaceSetFlags{
194                 SwIfIndex: veth.Index(),
195                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
196         }
197         upReply := &interfaces.SwInterfaceSetFlagsReply{}
198
199         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
200                 return 0, err
201         }
202
203         // Add address
204         if veth.AddressWithPrefix() == (AddressWithPrefix{}) {
205                 var err error
206                 var ip4Address string
207                 if ip4Address, err = veth.addresser.NewIp4Address(veth.Peer().networkNumber); err == nil {
208                         veth.SetAddress(ip4Address)
209                 } else {
210                         return 0, err
211                 }
212         }
213         addressReq := &interfaces.SwInterfaceAddDelAddress{
214                 IsAdd:     true,
215                 SwIfIndex: veth.Index(),
216                 Prefix:    veth.AddressWithPrefix(),
217         }
218         addressReply := &interfaces.SwInterfaceAddDelAddressReply{}
219
220         if err := vpp.apiChannel.SendRequest(addressReq).ReceiveReply(addressReply); err != nil {
221                 return 0, err
222         }
223
224         return veth.Index(), nil
225 }
226
227 func (vpp *VppInstance) addAppNamespace(
228         secret uint64,
229         ifx interface_types.InterfaceIndex,
230         namespaceId string,
231 ) error {
232         req := &session.AppNamespaceAddDelV2{
233                 Secret:      secret,
234                 SwIfIndex:   ifx,
235                 NamespaceID: namespaceId,
236         }
237         reply := &session.AppNamespaceAddDelV2Reply{}
238
239         if err := vpp.apiChannel.SendRequest(req).ReceiveReply(reply); err != nil {
240                 return err
241         }
242
243         sessionReq := &session.SessionEnableDisable{
244                 IsEnable: true,
245         }
246         sessionReply := &session.SessionEnableDisableReply{}
247
248         if err := vpp.apiChannel.SendRequest(sessionReq).ReceiveReply(sessionReply); err != nil {
249                 return err
250         }
251
252         return nil
253 }
254
255 func (vpp *VppInstance) createTap(
256         id uint32,
257         tap *NetInterface,
258 ) error {
259         createTapReq := &tapv2.TapCreateV2{
260                 ID:               id,
261                 HostIfNameSet:    true,
262                 HostIfName:       tap.Name(),
263                 HostIP4PrefixSet: true,
264                 HostIP4Prefix:    tap.IP4AddressWithPrefix(),
265         }
266         createTapReply := &tapv2.TapCreateV2Reply{}
267
268         // Create tap interface
269         if err := vpp.apiChannel.SendRequest(createTapReq).ReceiveReply(createTapReply); err != nil {
270                 return err
271         }
272
273         // Add address
274         addAddressReq := &interfaces.SwInterfaceAddDelAddress{
275                 IsAdd:     true,
276                 SwIfIndex: createTapReply.SwIfIndex,
277                 Prefix:    tap.Peer().AddressWithPrefix(),
278         }
279         addAddressReply := &interfaces.SwInterfaceAddDelAddressReply{}
280
281         if err := vpp.apiChannel.SendRequest(addAddressReq).ReceiveReply(addAddressReply); err != nil {
282                 return err
283         }
284
285         // Set interface to up
286         upReq := &interfaces.SwInterfaceSetFlags{
287                 SwIfIndex: createTapReply.SwIfIndex,
288                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
289         }
290         upReply := &interfaces.SwInterfaceSetFlagsReply{}
291
292         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
293                 return err
294         }
295
296         return nil
297 }
298
299 func (vpp *VppInstance) saveLogs() {
300         logTarget := vpp.container.getLogDirPath() + "vppinstance-" + vpp.container.name + ".log"
301         logSource := vpp.container.GetHostWorkDir() + defaultLogFilePath
302         cmd := exec.Command("cp", logSource, logTarget)
303         vpp.Suite().T().Helper()
304         vpp.Suite().log(cmd.String())
305         cmd.Run()
306 }
307
308 func (vpp *VppInstance) disconnect() {
309         vpp.connection.Disconnect()
310         vpp.apiChannel.Close()
311 }