-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathapps.go
405 lines (364 loc) · 11.4 KB
/
apps.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright 2020 ETH Zurich
//
// Licensed 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 integration
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"regexp"
"strings"
"time"
"github.com/scionproto/scion/go/lib/common"
sintegration "github.com/scionproto/scion/go/lib/integration"
"github.com/scionproto/scion/go/lib/log"
"github.com/scionproto/scion/go/lib/serrors"
"github.com/scionproto/scion/go/lib/snet"
)
var _ sintegration.Integration = (*ScionAppsIntegration)(nil)
type ScionAppsIntegration struct {
name string
clientCmd string
serverCmd string
clientArgs []string
serverArgs []string
logDir string
serverOutMatchFun func(previous bool, stdout string) bool
serverErrMatchFun func(previous bool, stderrr string) bool
clientOutMatchFun func(previous bool, stdout string) bool
clientErrMatchFun func(previous bool, stderrr string) bool
}
// NewAppsIntegration returns an implementation of the Integration interface.
// Start{Client|Server} will run the binary program with name and use the given arguments for the client/server.
// Use SrcIAReplace and DstIAReplace in arguments as placeholder for the source and destination IAs.
// When starting a client/server the placeholders will be replaced with the actual values.
// The server should output the ReadySignal to Stdout once it is ready to accept clients.
// If keepLog is true, also store client and server error logs.
func NewAppsIntegration(name string, test string, clientCmd string, serverCmd string, clientArgs, serverArgs []string, keepLogs bool) *ScionAppsIntegration {
log.Info(fmt.Sprintf("Run %s-%s-tests:", name, test))
sai := &ScionAppsIntegration{
name: test,
clientCmd: clientCmd,
serverCmd: serverCmd,
clientArgs: clientArgs,
serverArgs: serverArgs,
logDir: "",
}
if keepLogs {
_ = sai.initLogDir(name)
}
return sai
}
func (sai *ScionAppsIntegration) Name() string {
return sai.name
}
// StartServer starts a server and blocks until the ReadySignal is received on Stdout.
func (sai *ScionAppsIntegration) StartServer(ctx context.Context,
dst *snet.UDPAddr) (sintegration.Waiter, error) {
sciondAddr, err := getSCIONDAddress(dst.IA)
if err != nil {
return nil, serrors.WrapStr("unable to determine SCIOND address", err)
}
args := replacePattern(SCIOND, sciondAddr, sai.serverArgs)
args = replacePattern(DstIAReplace, dst.IA.String(), args)
args = replacePattern(DstHostReplace, dst.Host.IP.String(), args)
log.Debug(fmt.Sprintf("Running server command: %v %v\n", sai.serverCmd, strings.Join(args, " ")))
r := &appsWaiter{
exec.CommandContext(ctx, sai.serverCmd, args...),
make(chan bool, 1),
make(chan bool, 1),
}
r.Env = os.Environ()
r.Env = append(r.Env, fmt.Sprintf("%s=1", GoIntegrationEnv))
r.Env = append(r.Env, fmt.Sprintf("SCION_DAEMON_ADDRESS=%s", sciondAddr))
sp, err := r.StdoutPipe()
if err != nil {
return nil, err
}
ep, err := r.StderrPipe()
if err != nil {
return nil, err
}
logfile := fmt.Sprintf("server_%s", dst.IA.FileFmt(false))
startInfo := dst.IA.FileFmt(false)
ready := make(chan struct{})
signal := ReadySignal
init := true
// parse stdout until we have the ready signal
// and check the output with serverOutMatchFun.
sp = sai.pipeLog(logfile+".log", startInfo, sp)
go func() {
defer log.HandlePanic()
var stdoutMatch bool
scanner := bufio.NewScanner(sp)
for scanner.Scan() {
if scanner.Err() != nil {
log.Error("Error during reading of stdout", "err", scanner.Err())
return
}
line := scanner.Text()
if init && strings.Contains(line, signal) {
close(ready)
init = false
}
if sai.serverOutMatchFun != nil {
stdoutMatch = sai.serverOutMatchFun(stdoutMatch, line)
}
}
if sai.serverOutMatchFun != nil {
r.stdoutMatch <- stdoutMatch
} else {
r.stdoutMatch <- true
}
}()
// Check the stderr with serverErrMatchFun.
ep = sai.pipeLog(logfile+".err", startInfo, ep)
go func() {
defer log.HandlePanic()
var stderrMatch bool
scanner := bufio.NewScanner(ep)
for scanner.Scan() {
if scanner.Err() != nil {
log.Error("Error during reading of stderr", "err", scanner.Err())
return
}
line := scanner.Text()
if init && strings.Contains(line, signal) {
close(ready)
init = false
}
if sai.serverErrMatchFun != nil {
stderrMatch = sai.serverErrMatchFun(stderrMatch, line)
}
}
if sai.serverErrMatchFun != nil {
r.stderrMatch <- stderrMatch
} else {
r.stderrMatch <- true
}
}()
if err = r.Start(); err != nil {
return nil, common.NewBasicError("Failed to start server", err, "dst", dst.IA)
}
select {
case <-ready:
return r, err
case <-time.After(sintegration.StartServerTimeout):
return nil, common.NewBasicError("Start server timed out", nil, "dst", dst.IA)
}
}
func (sai *ScionAppsIntegration) StartClient(ctx context.Context,
src, dst *snet.UDPAddr) (sintegration.Waiter, error) {
sciondAddr, err := getSCIONDAddress(src.IA)
if err != nil {
return nil, serrors.WrapStr("unable to determine SCIOND address", err)
}
args := replacePattern(SCIOND, sciondAddr, sai.clientArgs)
args = replacePattern(SrcIAReplace, src.IA.String(), args)
args = replacePattern(SrcHostReplace, src.Host.IP.String(), args)
args = replacePattern(DstIAReplace, dst.IA.String(), args)
args = replacePattern(DstHostReplace, dst.Host.IP.String(), args)
log.Debug(fmt.Sprintf("Running client command: %v %v\n", sai.clientCmd, strings.Join(args, " ")))
r := &appsWaiter{
exec.CommandContext(ctx, sai.clientCmd, args...),
make(chan bool, 1),
make(chan bool, 1),
}
r.Env = os.Environ()
r.Env = append(r.Env, fmt.Sprintf("%s=1", GoIntegrationEnv))
r.Env = append(r.Env, fmt.Sprintf("SCION_DAEMON_ADDRESS=%s", sciondAddr))
sp, err := r.StdoutPipe()
if err != nil {
return nil, err
}
ep, err := r.StderrPipe()
if err != nil {
return nil, err
}
logfile := fmt.Sprintf("client_%s", clientID(src, dst))
startInfo := fmt.Sprintf("%s -> %s", src.IA, dst.IA)
sp = sai.pipeLog(logfile+".log", startInfo, sp)
// check the output with clientOutMatchFun
go func() {
var stdoutMatch bool
scanner := bufio.NewScanner(sp)
for scanner.Scan() {
if scanner.Err() != nil {
log.Error("Error during reading of stdout", "err", scanner.Err())
}
line := scanner.Text()
if sai.clientOutMatchFun != nil {
stdoutMatch = sai.clientOutMatchFun(stdoutMatch, line)
}
}
if sai.clientOutMatchFun != nil {
r.stdoutMatch <- stdoutMatch
} else {
r.stdoutMatch <- true
}
}()
// Check the stderr with clientErrMatchFun
ep = sai.pipeLog(logfile+".err", startInfo, ep)
go func() {
var stderrMatch bool
scanner := bufio.NewScanner(ep)
for scanner.Scan() {
if scanner.Err() != nil {
log.Error("Error during reading of stderr", "err", scanner.Err())
}
line := scanner.Text()
if sai.clientErrMatchFun != nil {
stderrMatch = sai.clientErrMatchFun(stderrMatch, line)
}
}
if sai.clientErrMatchFun != nil {
r.stderrMatch <- stderrMatch
} else {
r.stderrMatch <- true
}
}()
return r, r.Start()
}
func (sai *ScionAppsIntegration) ServerStdout(outMatch func(bool, string) bool) {
sai.serverOutMatchFun = outMatch
}
func (sai *ScionAppsIntegration) ServerStderr(errMatch func(bool, string) bool) {
sai.serverErrMatchFun = errMatch
}
func (sai *ScionAppsIntegration) ClientStdout(outMatch func(bool, string) bool) {
sai.clientOutMatchFun = outMatch
}
func (sai *ScionAppsIntegration) ClientStderr(errMatch func(bool, string) bool) {
sai.clientErrMatchFun = errMatch
}
func (sai *ScionAppsIntegration) initLogDir(name string) error {
tmpDir := path.Join(os.TempDir(), "scion-apps-integration")
err := os.MkdirAll(tmpDir, 0777)
if err != nil {
log.Error("Failed to create log folder for testrun", "dir", tmpDir, "err", err)
}
logDir, err := ioutil.TempDir(tmpDir, name)
if err != nil {
log.Error("Failed to create log folder for testrun", "dir", name, "err", err)
return err
}
sai.logDir = logDir
log.Info("Log directory:", "path", sai.logDir)
return nil
}
func (sai *ScionAppsIntegration) pipeLog(name, startInfo string, r io.ReadCloser) io.ReadCloser {
if sai.logDir != "" {
// tee to log
pipeR, pipeW := io.Pipe()
tee := io.TeeReader(r, pipeW)
go func() {
sai.writeLog(name, startInfo, tee)
pipeW.Close()
}()
return pipeR
}
return r
}
func (sai *ScionAppsIntegration) writeLog(name, startInfo string, pipe io.Reader) {
file := path.Join(sai.logDir, name)
f, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.FileMode(0644))
if err != nil {
log.Error("Failed to create log file for test run (create)",
"file", file, "err", err)
return
}
defer f.Close()
_, _ = f.WriteString(sintegration.WithTimestamp(fmt.Sprintf("Starting %s %s\n", name, startInfo)))
defer func() {
_, _ = f.WriteString(sintegration.WithTimestamp(fmt.Sprintf("Finished %s %s\n", name, startInfo)))
}()
_, _ = io.Copy(f, pipe)
}
func clientID(src, dst *snet.UDPAddr) string {
return fmt.Sprintf("%s_%s", src.IA.FileFmt(false), dst.IA.FileFmt(false))
}
var _ sintegration.Waiter = (*appsWaiter)(nil)
type appsWaiter struct {
*exec.Cmd
stdoutMatch chan bool
stderrMatch chan bool
}
func (aw *appsWaiter) Wait() error {
state, err := aw.Process.Wait()
if err != nil {
return err
}
if state.ExitCode() > 0 { // Ignore servers killed by the framework
return fmt.Errorf("the program under test returned non-zero exit code:\n%s [exit code=%d]",
aw.Cmd.String(), state.ExitCode())
}
err = checkOutputMatches(aw.stdoutMatch, aw.stderrMatch)
if err != nil {
return err
}
_ = aw.Cmd.Wait()
return nil
}
func checkOutputMatches(stdoutRes chan bool, stderrRes chan bool) error {
result, ok := <-stdoutRes
if ok {
if !result {
return errors.New("the program under test did not produce the expected standard output")
}
}
result, ok = <-stderrRes
if ok {
if !result {
return errors.New("the program under test did not produce the expected error output")
}
}
return nil
}
// Sample match functions
func Contains(expected string) func(prev bool, line string) bool {
return func(prev bool, line string) bool {
res := strings.Contains(line, expected)
return prev || res // return true if any output line contains the string
}
}
func RegExp(regularExpression string) func(prev bool, line string) bool {
return func(prev bool, line string) bool {
matched, err := regexp.MatchString(regularExpression, line)
if err != nil {
// invalid regexp, don't count as a match
matched = false
}
return prev || matched // return true if any output line matches the expression
}
}
func NoPanic() func(prev bool, line string) bool {
return func(prev bool, line string) bool {
matched, err := regexp.MatchString("^.*panic: .*$", line)
if err != nil {
// invalid regexp, don't count as a match
return prev
}
if init, err := regexp.MatchString("^.*Registered with dispatcher.*$", line); err == nil {
if init {
return init
}
}
return prev && !matched
}
}