/
binary.go
285 lines (263 loc) · 8.95 KB
/
binary.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
// Copyright 2018 Anapaya Systems
//
// 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"
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/scionproto/scion/go/lib/addr"
"github.com/scionproto/scion/go/lib/log"
"github.com/scionproto/scion/go/lib/serrors"
"github.com/scionproto/scion/go/lib/snet"
)
const (
// SCIOND is a placeholder for the SCIOND server in the arguments.
SCIOND = "<SCIOND>"
// ServerPortReplace is a placeholder for the server port in the arguments.
ServerPortReplace = "<ServerPort>"
// SrcIAReplace is a placeholder for the source IA in the arguments.
SrcIAReplace = "<SRCIA>"
// SrcHostReplace is a placeholder for the source host in the arguments.
SrcHostReplace = "<SRCHost>"
// SrcAddrPattern is a placeholder for the source address in the arguments.
SrcAddrPattern = SrcIAReplace + ",[" + SrcHostReplace + "]"
// DstIAReplace is a placeholder for the destination IA in the arguments.
DstIAReplace = "<DSTIA>"
// DstHostReplace is a placeholder for the destination host in the arguments.
DstHostReplace = "<DSTHost>"
// DstAddrPattern is a placeholder for the destination address in the arguments.
DstAddrPattern = DstIAReplace + ",[" + DstHostReplace + "]"
// ReadySignal should be written to Stdout by the server once it is read to accept clients.
// The message should always be `Listening ia=<IA>`
// where <IA> is the IA the server is listening on.
ReadySignal = "Listening ia="
// GoIntegrationEnv is an environment variable that is set for the binary under test.
// It can be used to guard certain statements, like printing the ReadySignal,
// in a program under test.
GoIntegrationEnv = "SCION_GO_INTEGRATION"
// portString is the string a server prints to specify the port it's listening on.
portString = "Port="
// WrapperCmd is the command used to run non-test binaries
WrapperCmd = "./integration/bin_wrapper.sh"
)
var (
// FIXME(roosd): The caller to StartServer and StartClient
// should take care of aggregating the data. I would prefer not to use a
// global here.
serverPortsMtx sync.Mutex
serverPorts = make(map[addr.IA]string)
)
var _ Integration = (*binaryIntegration)(nil)
type binaryIntegration struct {
name string
cmd string
clientArgs []string
serverArgs []string
logDir string
}
// NewBinaryIntegration returns an implementation of the Integration interface.
// Start* will run the binary programm 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.
func NewBinaryIntegration(name string, cmd string, clientArgs, serverArgs []string) Integration {
logDir := filepath.Join(LogDir(), name)
err := os.Mkdir(logDir, os.ModePerm)
if err != nil && !os.IsExist(err) {
log.Error("Failed to create log folder for testrun", "dir", name, "err", err)
return nil
}
bi := &binaryIntegration{
name: name,
cmd: cmd,
clientArgs: clientArgs,
serverArgs: serverArgs,
logDir: logDir,
}
return dockerize(bi)
}
func (bi *binaryIntegration) Name() string {
return bi.name
}
// StartServer starts a server and blocks until the ReadySignal is received on Stdout.
func (bi *binaryIntegration) StartServer(ctx context.Context, dst *snet.UDPAddr) (Waiter, error) {
args := replacePattern(DstIAReplace, dst.IA.String(), bi.serverArgs)
args = replacePattern(DstHostReplace, dst.Host.IP.String(), args)
if needSCIOND(args) {
sciond, err := GetSCIONDAddress(GenFile(SCIONDAddressesFile), dst.IA)
if err != nil {
return nil, serrors.WrapStr("unable to determine SCION Daemon address", err)
}
args = replacePattern(SCIOND, sciond, args)
}
r := exec.CommandContext(ctx, bi.cmd, args...)
log.Info(fmt.Sprintf("%v %v\n", bi.cmd, strings.Join(args, " ")))
r.Env = os.Environ()
r.Env = append(r.Env, fmt.Sprintf("%s=1", GoIntegrationEnv))
ep, err := r.StderrPipe()
if err != nil {
return nil, err
}
sp, err := r.StdoutPipe()
if err != nil {
return nil, err
}
ready := make(chan struct{})
// parse until we have the ready signal.
// and then discard the output until the end (required by StdoutPipe).
go func() {
defer log.HandlePanic()
defer sp.Close()
signal := fmt.Sprintf("%s%s", ReadySignal, dst.IA)
init := true
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 strings.HasPrefix(line, portString) {
serverPortsMtx.Lock()
serverPorts[dst.IA] = strings.TrimPrefix(line, portString)
serverPortsMtx.Unlock()
}
if init && signal == line {
close(ready)
init = false
}
}
}()
go func() {
defer log.HandlePanic()
bi.writeLog("server", dst.IA.FileFmt(false), dst.IA.FileFmt(false), ep)
}()
if err = r.Start(); err != nil {
return nil, serrors.WrapStr("Failed to start server", err, "dst", dst.IA)
}
select {
case <-ready:
return r, err
case <-time.After(StartServerTimeout):
return nil, serrors.New("Start server timed out", "dst", dst.IA)
}
}
func (bi *binaryIntegration) StartClient(ctx context.Context,
src, dst *snet.UDPAddr) (*BinaryWaiter, error) {
args := replacePattern(SrcIAReplace, src.IA.String(), bi.clientArgs)
args = replacePattern(SrcHostReplace, src.Host.IP.String(), args)
args = replacePattern(DstIAReplace, dst.IA.String(), args)
args = replacePattern(DstHostReplace, dst.Host.IP.String(), args)
args = replacePattern(ServerPortReplace, serverPorts[dst.IA], args)
if needSCIOND(args) {
sciond, err := GetSCIONDAddress(GenFile(SCIONDAddressesFile), src.IA)
if err != nil {
return nil, serrors.WrapStr("unable to determine SCION Daemon address", err)
}
args = replacePattern(SCIOND, sciond, args)
}
r := &BinaryWaiter{
cmd: exec.CommandContext(ctx, bi.cmd, args...),
logsWritten: make(chan struct{}),
}
log.Info(fmt.Sprintf("%v %v\n", bi.cmd, strings.Join(args, " ")))
r.cmd.Env = os.Environ()
r.cmd.Env = append(r.cmd.Env, fmt.Sprintf("%s=1", GoIntegrationEnv))
pr, pw, err := os.Pipe()
if err != nil {
return nil, serrors.WrapStr("creating pipe", err)
}
r.cmd.Stderr = pw
r.cmd.Stdout = pw
defer pw.Close()
tpr := io.TeeReader(pr, &r.output)
go func() {
defer log.HandlePanic()
defer close(r.logsWritten)
defer pr.Close()
bi.writeLog("client", clientID(src, dst), fmt.Sprintf("%s -> %s", src.IA, dst.IA), tpr)
}()
return r, r.cmd.Start()
}
func replacePattern(pattern string, replacement string, args []string) []string {
// first copy
argsCopy := append([]string(nil), args...)
for i, arg := range argsCopy {
if strings.Contains(arg, pattern) {
argsCopy[i] = strings.Replace(arg, pattern, replacement, -1)
}
}
return argsCopy
}
func (bi *binaryIntegration) writeLog(name, id, startInfo string, ep io.Reader) {
f, err := os.OpenFile(fmt.Sprintf("%s/%s_%s.log", bi.logDir, name, id),
os.O_CREATE|os.O_WRONLY, os.FileMode(0644))
if err != nil {
log.Error("Failed to create log file for test run (create)",
"name", name, "id", id, "err", err)
return
}
defer f.Close()
// seek to end of file.
if _, err := f.Seek(0, 2); err != nil {
log.Error("Failed to create log file for test run (seek)",
"name", name, "id", id, "err", err)
return
}
w := bufio.NewWriter(f)
defer w.Flush()
w.WriteString(WithTimestamp(fmt.Sprintf("Starting %s %s\n", name, startInfo)))
defer func() {
w.WriteString(WithTimestamp(fmt.Sprintf("Finished %s %s\n", name, startInfo)))
}()
scanner := bufio.NewScanner(ep)
for scanner.Scan() {
w.WriteString(fmt.Sprintf("%s\n", scanner.Text()))
}
}
func needSCIOND(args []string) bool {
for _, arg := range args {
if strings.Contains(arg, SCIOND) {
return true
}
}
return false
}
func clientID(src, dst *snet.UDPAddr) string {
return fmt.Sprintf("%s_%s", src.IA.FileFmt(false), dst.IA.FileFmt(false))
}
// BinaryWaiter can be used to wait on completion of the process.
type BinaryWaiter struct {
cmd *exec.Cmd
logsWritten chan struct{}
output bytes.Buffer
}
// Wait waits for completion of the process.
func (bw *BinaryWaiter) Wait() error {
err := bw.cmd.Wait()
<-bw.logsWritten
return err
}
// Output is the output of the process, only available after Wait is returnred.
func (bw *BinaryWaiter) Output() []byte {
return bw.output.Bytes()
}