hs-test: refactor test cases from ns suite
[vpp.git] / extras / hs-test / vppinstance.go
1 package main
2
3 import (
4         "encoding/json"
5         "fmt"
6         "github.com/edwarnicke/exechelper"
7
8         "go.fd.io/govpp"
9         "go.fd.io/govpp/api"
10         "go.fd.io/govpp/binapi/af_packet"
11         interfaces "go.fd.io/govpp/binapi/interface"
12         "go.fd.io/govpp/binapi/interface_types"
13         "go.fd.io/govpp/binapi/session"
14         "go.fd.io/govpp/binapi/vpe"
15         "go.fd.io/govpp/core"
16 )
17
18 const vppConfigTemplate = `unix {
19   nodaemon
20   log %[1]s/var/log/vpp/vpp.log
21   full-coredump
22   cli-listen %[1]s%[2]s
23   runtime-dir %[1]s/var/run
24   gid vpp
25 }
26
27 api-trace {
28   on
29 }
30
31 api-segment {
32   gid vpp
33 }
34
35 socksvr {
36   socket-name %[1]s/var/run/vpp/api.sock
37 }
38
39 statseg {
40   socket-name %[1]s/var/run/vpp/stats.sock
41 }
42
43 plugins {
44   plugin default { disable }
45
46   plugin unittest_plugin.so { enable }
47   plugin quic_plugin.so { enable }
48   plugin af_packet_plugin.so { enable }
49   plugin hs_apps_plugin.so { enable }
50   plugin http_plugin.so { enable }
51 }
52
53 `
54
55 const (
56         defaultCliSocketFilePath = "/var/run/vpp/cli.sock"
57         defaultApiSocketFilePath = "/var/run/vpp/api.sock"
58 )
59
60 type VppInstance struct {
61         container      *Container
62         config         *VppConfig
63         actionFuncName string
64         connection     *core.Connection
65         apiChannel     api.Channel
66 }
67
68 type VppConfig struct {
69         Variant           string
70         CliSocketFilePath string
71         additionalConfig  Stanza
72 }
73
74 func (vc *VppConfig) getTemplate() string {
75         return fmt.Sprintf(vppConfigTemplate, "%[1]s", vc.CliSocketFilePath)
76 }
77
78 func (vpp *VppInstance) Suite() *HstSuite {
79         return vpp.container.suite
80 }
81
82 func (vpp *VppInstance) setVppProxy() {
83         vpp.actionFuncName = "ConfigureVppProxy"
84 }
85
86 func (vpp *VppInstance) setEnvoyProxy() {
87         vpp.actionFuncName = "ConfigureEnvoyProxy"
88 }
89
90 func (vpp *VppInstance) setCliSocket(filePath string) {
91         vpp.config.CliSocketFilePath = filePath
92 }
93
94 func (vpp *VppInstance) getCliSocket() string {
95         return fmt.Sprintf("%s%s", vpp.container.GetContainerWorkDir(), vpp.config.CliSocketFilePath)
96 }
97
98 func (vpp *VppInstance) getRunDir() string {
99         return vpp.container.GetContainerWorkDir() + "/var/run/vpp"
100 }
101
102 func (vpp *VppInstance) getLogDir() string {
103         return vpp.container.GetContainerWorkDir() + "/var/log/vpp"
104 }
105
106 func (vpp *VppInstance) getEtcDir() string {
107         return vpp.container.GetContainerWorkDir() + "/etc/vpp"
108 }
109
110 func (vpp *VppInstance) legacyStart() error {
111         serializedConfig, err := serializeVppConfig(vpp.config)
112         if err != nil {
113                 return fmt.Errorf("serialize vpp config: %v", err)
114         }
115         args := fmt.Sprintf("%s '%s'", vpp.actionFuncName, serializedConfig)
116         _, err = vpp.container.execAction(args)
117         if err != nil {
118                 return fmt.Errorf("vpp start failed: %s", err)
119         }
120         return nil
121 }
122
123 func (vpp *VppInstance) start() error {
124         if vpp.actionFuncName != "" {
125                 return vpp.legacyStart()
126         }
127
128         // Create folders
129         containerWorkDir := vpp.container.GetContainerWorkDir()
130
131         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getRunDir())
132         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getLogDir())
133         vpp.container.exec("mkdir --mode=0700 -p " + vpp.getEtcDir())
134
135         // Create startup.conf inside the container
136         configContent := fmt.Sprintf(vppConfigTemplate, containerWorkDir, vpp.config.CliSocketFilePath)
137         configContent += vpp.config.additionalConfig.ToString()
138         startupFileName := vpp.getEtcDir() + "/startup.conf"
139         vpp.container.createFile(startupFileName, configContent)
140
141         // Start VPP
142         vpp.container.execServer("vpp -c " + startupFileName)
143
144         // Connect to VPP and store the connection
145         sockAddress := vpp.container.GetHostWorkDir() + defaultApiSocketFilePath
146         conn, connEv, err := govpp.AsyncConnect(
147                 sockAddress,
148                 core.DefaultMaxReconnectAttempts,
149                 core.DefaultReconnectInterval)
150         if err != nil {
151                 fmt.Println("async connect error: ", err)
152         }
153         vpp.connection = conn
154
155         // ... wait for Connected event
156         e := <-connEv
157         if e.State != core.Connected {
158                 fmt.Println("connecting to VPP failed: ", e.Error)
159         }
160
161         // ... check compatibility of used messages
162         ch, err := conn.NewAPIChannel()
163         if err != nil {
164                 fmt.Println("creating channel failed: ", err)
165         }
166         if err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {
167                 fmt.Println("compatibility error: ", err)
168         }
169         if err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {
170                 fmt.Println("compatibility error: ", err)
171         }
172         vpp.apiChannel = ch
173
174         return nil
175 }
176
177 func (vpp *VppInstance) vppctl(command string, arguments ...any) string {
178         vppCliCommand := fmt.Sprintf(command, arguments...)
179         containerExecCommand := fmt.Sprintf("docker exec --detach=false %[1]s vppctl -s %[2]s %[3]s",
180                 vpp.container.name, vpp.getCliSocket(), vppCliCommand)
181         vpp.Suite().log(containerExecCommand)
182         output, err := exechelper.CombinedOutput(containerExecCommand)
183         vpp.Suite().assertNil(err)
184
185         return string(output)
186 }
187
188 func NewVppInstance(c *Container) *VppInstance {
189         vppConfig := new(VppConfig)
190         vppConfig.CliSocketFilePath = defaultCliSocketFilePath
191         vpp := new(VppInstance)
192         vpp.container = c
193         vpp.config = vppConfig
194         return vpp
195 }
196
197 func serializeVppConfig(vppConfig *VppConfig) (string, error) {
198         serializedConfig, err := json.Marshal(vppConfig)
199         if err != nil {
200                 return "", fmt.Errorf("vpp start failed: serializing configuration failed: %s", err)
201         }
202         return string(serializedConfig), nil
203 }
204
205 func deserializeVppConfig(input string) (VppConfig, error) {
206         var vppConfig VppConfig
207         err := json.Unmarshal([]byte(input), &vppConfig)
208         if err != nil {
209                 // Since input is not a  valid JSON it is going be used as a variant value
210                 // for compatibility reasons
211                 vppConfig.Variant = input
212                 vppConfig.CliSocketFilePath = defaultCliSocketFilePath
213         }
214         return vppConfig, nil
215 }
216
217 func (vpp *VppInstance) createAfPacket(
218         netInterface NetInterface,
219 ) (interface_types.InterfaceIndex, error) {
220         var veth *NetworkInterfaceVeth
221         veth = netInterface.(*NetworkInterfaceVeth)
222
223         createReq := &af_packet.AfPacketCreateV2{
224                 UseRandomHwAddr: true,
225                 HostIfName:      veth.Name(),
226         }
227         if veth.HwAddress() != (MacAddress{}) {
228                 createReq.UseRandomHwAddr = false
229                 createReq.HwAddr = veth.HwAddress()
230         }
231         createReply := &af_packet.AfPacketCreateV2Reply{}
232
233         if err := vpp.apiChannel.SendRequest(createReq).ReceiveReply(createReply); err != nil {
234                 return 0, err
235         }
236         veth.SetIndex(createReply.SwIfIndex)
237
238         // Set to up
239         upReq := &interfaces.SwInterfaceSetFlags{
240                 SwIfIndex: veth.Index(),
241                 Flags:     interface_types.IF_STATUS_API_FLAG_ADMIN_UP,
242         }
243         upReply := &interfaces.SwInterfaceSetFlagsReply{}
244
245         if err := vpp.apiChannel.SendRequest(upReq).ReceiveReply(upReply); err != nil {
246                 return 0, err
247         }
248
249         // Add address
250         if veth.Ip4AddressWithPrefix() == (AddressWithPrefix{}) {
251                 if veth.peerNetworkNamespace != "" {
252                         ip4Address, err := veth.addresser.
253                                 NewIp4AddressWithNamespace(veth.peerNetworkNamespace)
254                         if err == nil {
255                                 veth.SetAddress(ip4Address)
256                         } else {
257                                 return 0, err
258                         }
259                 } else {
260                         ip4Address, err := veth.addresser.
261                                 NewIp4Address()
262                         if err == nil {
263                                 veth.SetAddress(ip4Address)
264                         } else {
265                                 return 0, err
266                         }
267                 }
268         }
269         addressReq := &interfaces.SwInterfaceAddDelAddress{
270                 IsAdd:     true,
271                 SwIfIndex: veth.Index(),
272                 Prefix:    veth.Ip4AddressWithPrefix(),
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) disconnect() {
312         vpp.connection.Disconnect()
313         vpp.apiChannel.Close()
314 }