-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi7_framework.go
More file actions
287 lines (230 loc) · 8.16 KB
/
api7_framework.go
File metadata and controls
287 lines (230 loc) · 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package framework
import (
"bytes"
"encoding/json"
"fmt"
"os"
"time"
"github.com/api7/gopkg/pkg/log"
"github.com/gruntwork-io/terratest/modules/k8s"
. "github.com/onsi/ginkgo/v2" //nolint:staticcheck
. "github.com/onsi/gomega" //nolint:staticcheck
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/kube"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
)
const defaultDashboardVersion = "dev"
var (
API7EELicense string
dashboardVersion string
)
// initSuiteEnv reads required environment variables and panics early with a clear
// message if any mandatory variable is missing.
func initSuiteEnv() {
API7EELicense = os.Getenv("API7_EE_LICENSE")
if API7EELicense == "" {
panic("env {API7_EE_LICENSE} is required")
}
dashboardVersion = os.Getenv("DASHBOARD_VERSION")
if dashboardVersion == "" {
dashboardVersion = defaultDashboardVersion
}
}
func (f *Framework) BeforeSuite() {
initSuiteEnv()
_ = k8s.DeleteNamespaceE(GinkgoT(), f.kubectlOpts, _namespace)
Eventually(func() error {
_, err := k8s.GetNamespaceE(GinkgoT(), f.kubectlOpts, _namespace)
if k8serrors.IsNotFound(err) {
return nil
}
return fmt.Errorf("namespace %s still exists", _namespace)
}, "1m", "2s").Should(Succeed())
k8s.CreateNamespace(GinkgoT(), f.kubectlOpts, _namespace)
f.DeployComponents()
time.Sleep(1 * time.Minute)
err := f.newDashboardTunnel()
f.Logf("Dashboard HTTP Tunnel:" + _dashboardHTTPTunnel.Endpoint())
Expect(err).ShouldNot(HaveOccurred(), "creating dashboard tunnel")
f.UploadLicense()
f.setDpManagerEndpoints()
}
func (f *Framework) AfterSuite() {
f.shutdownDashboardTunnel()
}
// DeployAPI7EE deploys the API7EE control plane once (runs on ginkgo node 1 only).
// It returns a ready signal consumed by InitNodeConnections on all nodes.
func (f *Framework) DeployAPI7EE() []byte {
initSuiteEnv()
_ = k8s.DeleteNamespaceE(GinkgoT(), f.kubectlOpts, _namespace)
Eventually(func() error {
_, err := k8s.GetNamespaceE(GinkgoT(), f.kubectlOpts, _namespace)
if k8serrors.IsNotFound(err) {
return nil
}
return fmt.Errorf("namespace %s still exists", _namespace)
}, "1m", "2s").Should(Succeed())
k8s.CreateNamespace(GinkgoT(), f.kubectlOpts, _namespace)
f.DeployComponents()
time.Sleep(1 * time.Minute)
// Create a temporary tunnel for one-time setup operations.
// Each node will create its own persistent tunnel in InitNodeConnections.
err := f.newDashboardTunnel()
Expect(err).ShouldNot(HaveOccurred(), "creating temporary dashboard tunnel")
f.Logf("Temporary dashboard tunnel: %s", _dashboardHTTPTunnel.Endpoint())
f.UploadLicense()
f.setDpManagerEndpoints()
// Close the temporary tunnel; each node creates its own in InitNodeConnections.
f.shutdownDashboardTunnel()
return []byte("ready")
}
// InitNodeConnections initializes per-node connections to the shared API7EE control plane.
// It runs on every ginkgo parallel node after DeployAPI7EE completes.
func (f *Framework) InitNodeConnections(_ []byte) {
initSuiteEnv()
err := f.newDashboardTunnel()
Expect(err).ShouldNot(HaveOccurred(), "creating dashboard tunnel for node")
f.Logf("Dashboard HTTP Tunnel: %s", _dashboardHTTPTunnel.Endpoint())
}
// CloseNodeConnections closes per-node connections. Runs on every ginkgo parallel node.
func (f *Framework) CloseNodeConnections() {
f.shutdownDashboardTunnel()
}
// TeardownInfrastructure cleans up suite-level resources. Runs on ginkgo node 1 only.
// The Kind cluster is deleted by CI after the job, so this is a no-op.
func (f *Framework) TeardownInfrastructure() {}
// DeployComponents deploy necessary components
func (f *Framework) DeployComponents() {
f.deploy()
f.initDashboard()
}
func (f *Framework) UploadLicense() {
payload := map[string]any{"data": API7EELicense}
payloadBytes, err := json.Marshal(payload)
assert.Nil(f.GinkgoT, err)
respExpect := f.DashboardHTTPClient().PUT("/api/license").
WithBasicAuth("admin", "admin").
WithHeader("Content-Type", "application/json").
WithBytes(payloadBytes).
Expect()
body := respExpect.Body().Raw()
f.Logf("request /api/license, response body: %s", body)
respExpect.Status(200)
}
func (f *Framework) deploy() {
debug := func(format string, v ...any) {
log.Infof(format, v...)
}
kubeConfigPath := os.Getenv("KUBECONFIG")
actionConfig := new(action.Configuration)
err := actionConfig.Init(
kube.GetConfig(kubeConfigPath, "", f.kubectlOpts.Namespace),
f.kubectlOpts.Namespace,
"memory",
debug,
)
f.GomegaT.Expect(err).ShouldNot(HaveOccurred(), "init helm action config")
install := action.NewInstall(actionConfig)
install.Namespace = f.kubectlOpts.Namespace
install.ReleaseName = "api7ee3"
chartPath, err := install.LocateChart("api7/api7ee3", cli.New())
f.GomegaT.Expect(err).ShouldNot(HaveOccurred(), "locate helm chart")
chart, err := loader.Load(chartPath)
f.GomegaT.Expect(err).ShouldNot(HaveOccurred(), "load helm chart")
buf := bytes.NewBuffer(nil)
_ = valuesTemplate.Execute(buf, map[string]any{
"DB": _db,
"DSN": getDSN(),
"Tag": dashboardVersion,
})
f.Logf("values: %s", buf.String())
var v map[string]any
err = yaml.Unmarshal(buf.Bytes(), &v)
f.GomegaT.Expect(err).ShouldNot(HaveOccurred(), "unmarshal values")
_, err = install.Run(chart, v)
if err != nil {
f.Logf("install dashboard failed, err: %v", err)
}
f.GomegaT.Expect(err).ShouldNot(HaveOccurred(), "install dashboard")
err = f.ensureService("api7ee3-dashboard", _namespace, 1)
f.GomegaT.Expect(err).ShouldNot(HaveOccurred(), "ensuring dashboard service")
err = f.ensureService("api7-postgresql", _namespace, 1)
f.GomegaT.Expect(err).ShouldNot(HaveOccurred(), "ensuring postgres service")
}
func (f *Framework) initDashboard() {
f.deletePods("app.kubernetes.io/name=api7ee3")
time.Sleep(5 * time.Second)
}
var (
_dashboardHTTPTunnel *k8s.Tunnel
_dashboardHTTPSTunnel *k8s.Tunnel
)
// dashboardLocalPorts returns the local port pair to use for the dashboard HTTP
// and HTTPS tunnels. Each ginkgo parallel process gets a unique, non-overlapping
// range based on its 1-indexed process number, eliminating port conflicts without
// any TOCTOU race.
//
// Formula: base = 18000 + node*100
//
// node=1 → 18100 (HTTP) / 18101 (HTTPS)
// node=2 → 18200 (HTTP) / 18201 (HTTPS)
func dashboardLocalPorts() (httpLocal, httpsLocal int) {
node := GinkgoParallelProcess() // 1-indexed
base := 18000 + node*100
return base, base + 1
}
func (f *Framework) newDashboardTunnel() error {
var (
httpPort int
httpsPort int
)
service := k8s.GetService(f.GinkgoT, f.kubectlOpts, "api7ee3-dashboard")
for _, port := range service.Spec.Ports {
switch port.Name {
case "http":
httpPort = int(port.Port)
case "https":
httpsPort = int(port.Port)
}
}
httpLocal, httpsLocal := dashboardLocalPorts()
_dashboardHTTPTunnel = k8s.NewTunnel(f.kubectlOpts, k8s.ResourceTypeService, "api7ee3-dashboard",
httpLocal, httpPort)
_dashboardHTTPSTunnel = k8s.NewTunnel(f.kubectlOpts, k8s.ResourceTypeService, "api7ee3-dashboard",
httpsLocal, httpsPort)
if err := _dashboardHTTPTunnel.ForwardPortE(f.GinkgoT); err != nil {
return err
}
if err := _dashboardHTTPSTunnel.ForwardPortE(f.GinkgoT); err != nil {
return err
}
return nil
}
func (f *Framework) shutdownDashboardTunnel() {
if _dashboardHTTPTunnel != nil {
_dashboardHTTPTunnel.Close()
}
if _dashboardHTTPSTunnel != nil {
_dashboardHTTPSTunnel.Close()
}
}