This repository has been archived by the owner on Jul 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webctl_test.go
380 lines (322 loc) · 8.32 KB
/
webctl_test.go
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Copyright 2019 The go-daq Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tdaq_test // import "github.com/go-daq/tdaq"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/go-daq/tdaq"
"github.com/go-daq/tdaq/config"
"github.com/go-daq/tdaq/fsm"
"github.com/go-daq/tdaq/internal/iomux"
"github.com/go-daq/tdaq/internal/tcputil"
"github.com/go-daq/tdaq/log"
"github.com/go-daq/tdaq/xdaq"
"golang.org/x/net/websocket"
"golang.org/x/sync/errgroup"
)
func TestRunControlWebAPI(t *testing.T) {
t.Parallel()
const (
rclvl = log.LvlDebug
proclvl = log.LvlDebug
)
port, err := tcputil.GetTCPPort()
if err != nil {
t.Fatalf("could not find a tcp port for run-ctl: %+v", err)
}
rcAddr := ":" + port
port, err = tcputil.GetTCPPort()
if err != nil {
t.Fatalf("could not find a tcp port for run-ctl web server: %+v", err)
}
webAddr := ":" + port
stdout := iomux.NewWriter(new(bytes.Buffer))
fname, err := os.CreateTemp("", "tdaq-")
if err != nil {
t.Fatalf("could not create a temporary log file for run-ctl log server: %+v", err)
}
fname.Close()
defer func() {
if err != nil {
raw, err := os.ReadFile(fname.Name())
if err == nil {
t.Logf("log-file:\n%v\n", string(raw))
}
}
os.Remove(fname.Name())
}()
cfg := config.RunCtl{
Name: "run-ctl",
Level: rclvl,
Trans: "tcp",
RunCtl: rcAddr,
Web: webAddr,
LogFile: fname.Name(),
HBeatFreq: 50 * time.Millisecond,
}
rc, err := tdaq.NewRunControl(cfg, stdout)
if err != nil {
t.Fatalf("could not create run-ctl: %+v", err)
}
tsrv := httptest.NewUnstartedServer(rc.Web().(*http.Server).Handler)
tsrv.Config.ReadTimeout = 5 * time.Second
tsrv.Config.WriteTimeout = 5 * time.Second
tsrv.Start()
defer tsrv.Close()
cli := tsrv.Client()
rc.SetWebSrv(newWebSrvTest(tsrv))
tcli := &testCli{tsrv}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
grp, ctx := errgroup.WithContext(ctx)
errc := make(chan error)
go func() {
errc <- rc.Run(ctx)
}()
grp.Go(func() error {
dev := xdaq.I64Gen{}
cfg := config.Process{
Name: "data-src",
Level: proclvl,
Trans: "tcp",
RunCtl: rcAddr,
}
srv := tdaq.New(cfg, stdout)
srv.CmdHandle("/config", dev.OnConfig)
srv.CmdHandle("/init", dev.OnInit)
srv.CmdHandle("/reset", dev.OnReset)
srv.CmdHandle("/start", dev.OnStart)
srv.CmdHandle("/stop", dev.OnStop)
srv.CmdHandle("/quit", dev.OnQuit)
srv.OutputHandle("/i64", dev.Output)
srv.RunHandle(dev.Loop)
err := srv.Run(ctx)
return err
})
for _, i := range []int{1, 2, 3} {
name := fmt.Sprintf("data-sink-%d", i)
grp.Go(func() error {
dev := xdaq.I64Dumper{}
cfg := config.Process{
Name: name,
Level: proclvl,
Trans: "tcp",
RunCtl: rcAddr,
}
srv := tdaq.New(cfg, stdout)
srv.CmdHandle("/init", dev.OnInit)
srv.CmdHandle("/reset", dev.OnReset)
srv.CmdHandle("/stop", dev.OnStop)
srv.InputHandle("/i64", dev.Input)
err := srv.Run(context.Background())
return err
})
}
timeout := time.NewTimer(5 * time.Second)
defer timeout.Stop()
loop:
for {
select {
case <-timeout.C:
t.Fatalf("devices did not connect")
default:
n := rc.NumClients()
if n == 4 {
break loop
}
}
}
func() {
req, err := http.NewRequest(http.MethodGet, tsrv.URL+"/", nil)
if err != nil {
t.Fatalf("could not create http request for %q: %+v", "/", err)
}
resp, err := cli.Do(req)
if err != nil {
t.Fatalf("could not get /: %+v", err)
}
defer resp.Body.Close()
}()
ws, err := newTestWS(tsrv)
if err != nil {
t.Fatalf("could not create test websocket: %+v", err)
}
defer ws.Close()
status, err := ws.readStatus()
if err != nil {
t.Fatalf("could not get /status: %+v", err)
}
if got, want := status, fsm.UnConf.String(); got != want {
t.Fatalf("invalid status: got=%q, want=%q", got, want)
}
func() {
// test invalid command
cmd := "invalid-command"
req, err := tcli.cmd(cmd)
if err != nil {
t.Fatalf("could not prepare invalid command /%s: %+v", cmd, err)
}
resp, err := cli.Do(req)
if err != nil {
t.Fatalf("could not send invalid command /%s: %+v", cmd, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("invalid status code for invalid command: %v", resp.StatusCode)
}
}()
for _, tt := range []struct {
name string
want string
}{
{name: "config", want: fsm.Conf.String()},
{name: "init", want: fsm.Init.String()},
{name: "reset", want: fsm.UnConf.String()},
{name: "config", want: fsm.Conf.String()},
{name: "init", want: fsm.Init.String()},
{name: "start", want: fsm.Running.String()},
{name: "stop", want: fsm.Stopped.String()},
{name: "status", want: fsm.Stopped.String()},
{name: "start", want: fsm.Running.String()},
{name: "stop", want: fsm.Stopped.String()},
{name: "quit", want: fsm.Exiting.String()},
} {
req, err := tcli.cmd(tt.name)
if err != nil {
t.Fatalf("could not prepare cmd /%s: %+v", tt.name, err)
}
func() {
var resp *http.Response
resp, err = cli.Do(req)
if err != nil {
t.Fatalf("could not send command /%s: %+v", tt.name, err)
}
defer resp.Body.Close()
if tt.name == "quit" {
return
}
status, err := ws.readStatus()
if err != nil {
t.Fatalf("could not get /status after /%s: %+v", tt.name, err)
}
if got, want := status, tt.want; got != want {
t.Fatalf("invalid status after /%s: got=%q, want=%q", tt.name, got, want)
}
}()
}
err = grp.Wait()
if err != nil {
t.Fatalf("could not run device run-group: %+v", err)
}
err = <-errc
if err != nil && !errors.Is(err, context.Canceled) {
t.Fatalf("error shutting down run-ctl: %+v", err)
}
}
type websrvTest struct {
srv *httptest.Server
quit chan error
}
func newWebSrvTest(srv *httptest.Server) *websrvTest {
return &websrvTest{
srv: srv,
quit: make(chan error),
}
}
func (srv *websrvTest) Close() {
srv.srv.Close()
}
func (srv *websrvTest) ListenAndServe() error {
<-srv.quit
return nil
}
func (srv *websrvTest) Shutdown(ctx context.Context) error {
close(srv.quit)
return nil
}
type testCli struct {
srv *httptest.Server
}
func (cli *testCli) cmd(name string) (*http.Request, error) {
buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)
err := w.WriteField("cmd", "/"+name)
if err != nil {
return nil, fmt.Errorf("could not create mime/multipart field: %w", err)
}
err = w.Close()
if err != nil {
return nil, fmt.Errorf("could not create mime/multipart form: %w", err)
}
req, err := http.NewRequest(http.MethodPost, cli.srv.URL+"/cmd", buf)
if err != nil {
return nil, fmt.Errorf("could not create http request for %q: %w", name, err)
}
req.Header.Set("Content-Type", w.FormDataContentType())
return req, nil
}
type testWS struct {
status *websocket.Conn
msg *websocket.Conn
buf *bytes.Buffer
}
func newTestWS(tsrv *httptest.Server) (*testWS, error) {
origin := tsrv.URL + "/"
urlStatus := "ws://" + strings.Replace(tsrv.URL, "http://", "", 1) + "/status"
status, err := websocket.Dial(urlStatus, "", origin)
if err != nil {
return nil, fmt.Errorf("could not dial /status websocket: %w", err)
}
urlMsg := "ws://" + strings.Replace(tsrv.URL, "http://", "", 1) + "/msg"
msg, err := websocket.Dial(urlMsg, "", origin)
if err != nil {
return nil, fmt.Errorf("could not dial /status websocket: %w", err)
}
buf := new(bytes.Buffer)
go func() {
_, _ = io.Copy(buf, msg)
}()
return &testWS{
status: status,
msg: msg,
buf: buf,
}, nil
}
func (ws *testWS) Close() error {
err1 := ws.status.Close()
err2 := ws.msg.Close()
if err1 != nil {
return fmt.Errorf("could not close /status websocket: %w", err1)
}
if err2 != nil {
return fmt.Errorf("could not close /msg websocket: %w", err2)
}
return nil
}
func (ws *testWS) readStatus() (string, error) {
buf := make([]byte, 1024)
n, err := ws.status.Read(buf)
if err != nil {
return "", fmt.Errorf("could not read /status response: %w", err)
}
var data struct {
Status string `json:"status"`
}
err = json.NewDecoder(bytes.NewReader(buf[:n])).Decode(&data)
if err != nil {
return "", fmt.Errorf("could not decode /status JSON response: %w", err)
}
return data.Status, nil
}