-
Notifications
You must be signed in to change notification settings - Fork 77
/
receptorcontrol.go
519 lines (438 loc) · 11.9 KB
/
receptorcontrol.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package mesh
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"regexp"
"strings"
"time"
"github.com/ansible/receptor/pkg/netceptor"
"github.com/ansible/receptor/pkg/workceptor"
"github.com/ansible/receptor/tests/utils"
)
// ReceptorControl Connects to a control socket and provides basic commands.
type ReceptorControl struct {
socketConn *net.UnixConn
SocketFilename string
}
// New Returns an empty ReceptorControl.
func NewReceptorControl() *ReceptorControl {
return &ReceptorControl{
socketConn: nil,
SocketFilename: "",
}
}
// Connect connects to the socket at the specified filename and checks the
// handshake with the control service.
func (r *ReceptorControl) Connect(filename string) error {
if r.socketConn != nil {
return errors.New("tried to connect to a socket after already being connected to a socket")
}
addr, err := net.ResolveUnixAddr("unix", filename)
if err != nil {
return err
}
r.socketConn, err = net.DialUnix("unix", nil, addr)
if err != nil {
return err
}
err = r.handshake()
if err != nil {
return err
}
r.SocketFilename = filename
return nil
}
func (r *ReceptorControl) Reload() error {
if _, err := r.WriteStr("reload \n"); err != nil {
return err
}
jsonData, err := r.ReadAndParseJSON()
if err != nil {
return err
}
success := jsonData["Success"].(bool)
if !success {
return errors.New("Error")
}
return nil
}
// Reconnect to unix socket.
func (r *ReceptorControl) Reconnect() error {
if r.SocketFilename != "" {
err := r.Connect(r.SocketFilename)
if err != nil {
return err
}
} else {
return fmt.Errorf("could not reconnect, no SocketFilename")
}
return nil
}
// Read reads a line from the socket.
func (r *ReceptorControl) Read() ([]byte, error) {
dataBytes := make([]byte, 0)
buf := make([]byte, 1)
for {
n, err := r.socketConn.Read(buf)
if err != nil {
return dataBytes, err
}
if n == 1 {
if buf[0] == '\n' {
break
}
dataBytes = append(dataBytes, buf[0])
}
}
return dataBytes, nil
}
// Write writes some data to the socket.
func (r *ReceptorControl) Write(data []byte) (int, error) {
return r.socketConn.Write(data)
}
// ReadStr reads some data from the socket and converts it to a string.
func (r *ReceptorControl) ReadStr() (string, error) {
data, err := r.Read()
if err != nil {
return "", err
}
return string(data), nil
}
// WriteStr writes string data to the socket.
func (r *ReceptorControl) WriteStr(data string) (int, error) {
return r.Write([]byte(data))
}
func (r *ReceptorControl) handshake() error {
data, err := r.Read()
if err != nil {
return err
}
matched, err := regexp.Match("^Receptor Control, node (.+)$", data)
if err != nil {
return err
}
if !matched {
return fmt.Errorf("failed control socket handshake, got: %s", data)
}
return nil
}
// Close closes the connection to the socket.
func (r *ReceptorControl) Close() error {
err := r.socketConn.Close()
r.socketConn = nil
return err
}
// CloseWrite closes the write side of the socket.
func (r *ReceptorControl) CloseWrite() error {
err := r.socketConn.CloseWrite()
return err
}
// ReadAndParseJSON reads data from the socket and parses it as json.
func (r *ReceptorControl) ReadAndParseJSON() (map[string]interface{}, error) {
data, err := r.Read()
if err != nil {
return nil, err
}
if str := string(data); strings.HasPrefix(str, "ERROR") {
return nil, fmt.Errorf(str)
}
jsonData := make(map[string]interface{})
err = json.Unmarshal(data, &jsonData)
if err != nil {
return nil, err
}
return jsonData, nil
}
// Ping pings the specified node.
func (r *ReceptorControl) Ping(node string) (string, error) {
_, err := r.WriteStr(fmt.Sprintf("ping %s\n", node))
if err != nil {
return "", err
}
jsonData, err := r.ReadAndParseJSON()
if err != nil {
return "", err
}
success := jsonData["Success"].(bool)
if !success {
return "", errors.New(jsonData["Error"].(string))
}
return fmt.Sprintf("Reply from %s in %s", jsonData["From"].(string), jsonData["TimeStr"].(string)), nil
}
// Status retrieves the status of the current node.
func (r *ReceptorControl) Status() (*netceptor.Status, error) {
_, err := r.WriteStr("status\n")
if err != nil {
return nil, err
}
data, err := r.Read()
if err != nil {
return nil, err
}
status := netceptor.Status{}
err = json.Unmarshal(data, &status)
if err != nil {
return nil, err
}
return &status, nil
}
func (r *ReceptorControl) getWorkSubmitResponse() (string, error) {
msg, err := r.ReadStr() // flush getWorkSubmitResponse
if !strings.Contains(msg, "Send stdin data and EOF.") {
return "", fmt.Errorf(msg)
}
if err != nil {
return "", err
}
err = r.CloseWrite() // close write half to signal EOF
if err != nil {
return "", err
}
defer func() {
err = r.Close() // since write is closed, we should close the whole socket
if err != nil {
panic(err)
}
err = r.Reconnect()
if err != nil {
panic(err)
}
}()
response, err := r.ReadAndParseJSON()
if err != nil {
return "", err
}
unitID := fmt.Sprintf("%v", response["unitid"])
return unitID, nil
}
// WorkSubmitJSON begins work on remote node via JSON command.
func (r *ReceptorControl) WorkSubmitJSON(command string) (string, error) {
_, err := r.WriteStr(fmt.Sprintf("%s\n", command))
if err != nil {
return "", err
}
unitID, err := r.getWorkSubmitResponse()
if err != nil {
return "", err
}
return unitID, nil
}
// WorkSubmit begins work on remote node.
func (r *ReceptorControl) WorkSubmit(node, workType string) (string, error) {
_, err := r.WriteStr(fmt.Sprintf("work submit %s %s\n", node, workType))
if err != nil {
return "", err
}
unitID, err := r.getWorkSubmitResponse()
if err != nil {
return "", err
}
return unitID, nil
}
// WorkStart begins work on local node.
func (r *ReceptorControl) WorkStart(workType string) (string, error) {
return r.WorkSubmit("localhost", workType)
}
// WorkCancel cancels work.
func (r *ReceptorControl) WorkCancel(unitID string) (map[string]interface{}, error) {
_, err := r.WriteStr(fmt.Sprintf("work cancel %s\n", unitID))
if err != nil {
return nil, err
}
return r.ReadAndParseJSON()
}
// WorkRelease cancels and deletes work.
func (r *ReceptorControl) WorkRelease(unitID string) (map[string]interface{}, error) {
_, err := r.WriteStr(fmt.Sprintf("work release %s\n", unitID))
if err != nil {
return nil, err
}
return r.ReadAndParseJSON()
}
// GetWorkStatus returns JSON of status file for a given unitID.
func (r *ReceptorControl) GetWorkStatus(unitID string) (*workceptor.StatusFileData, error) {
status := &workceptor.StatusFileData{}
_, err := r.WriteStr(fmt.Sprintf("work status %s\n", unitID))
if err != nil {
return status, err
}
jsonData, err := r.Read()
if err != nil {
return status, err
}
err = json.Unmarshal(jsonData, status)
if err != nil {
return status, err
}
return status, nil
}
func (r *ReceptorControl) getWorkList() (map[string]interface{}, error) {
_, err := r.WriteStr("work list\n")
if err != nil {
return nil, err
}
workList, err := r.ReadAndParseJSON()
if err != nil {
return nil, err
}
return workList, nil
}
func assertWithTimeout(ctx context.Context, check func() bool) bool {
return utils.CheckUntilTimeout(ctx, 500*time.Millisecond, check)
}
func (r *ReceptorControl) assertWorkState(ctx context.Context, unitID string, state int) bool {
check := func() bool {
workStatus, _ := r.GetWorkStatus(unitID)
return workStatus.State == state
}
return assertWithTimeout(ctx, check)
}
func (r *ReceptorControl) assertWorkSize(ctx context.Context, unitID string, size int64) bool {
check := func() bool {
workStatus, _ := r.GetWorkStatus(unitID)
return workStatus.StdoutSize > size
}
return assertWithTimeout(ctx, check)
}
// assert if the work size is increasing.
func (r *ReceptorControl) AssertWorkSizeIncreasing(ctx context.Context, unitID string, size int64) error {
if !r.assertWorkSize(ctx, unitID, size) {
return fmt.Errorf("failed to assert %s is increasing or ctx timed out", unitID)
}
return nil
}
// AssertWorkRunning waits until work status is running.
func (r *ReceptorControl) AssertWorkRunning(ctx context.Context, unitID string) error {
if !r.assertWorkState(ctx, unitID, workceptor.WorkStateRunning) {
return fmt.Errorf("failed to assert %s is running or ctx timed out", unitID)
}
return nil
}
// AssertWorkPending waits until status is pending.
func (r *ReceptorControl) AssertWorkPending(ctx context.Context, unitID string) error {
if !r.assertWorkState(ctx, unitID, workceptor.WorkStatePending) {
return fmt.Errorf("failed to assert %s is pending or ctx timed out", unitID)
}
return nil
}
// AssertWorkSucceeded waits until status is successful.
func (r *ReceptorControl) AssertWorkSucceeded(ctx context.Context, unitID string) error {
if !r.assertWorkState(ctx, unitID, workceptor.WorkStateSucceeded) {
return fmt.Errorf("failed to assert %s succeeded or ctx timed out", unitID)
}
return nil
}
// AssertWorkFailed waits until status is failed.
func (r *ReceptorControl) AssertWorkFailed(ctx context.Context, unitID string) error {
if !r.assertWorkState(ctx, unitID, workceptor.WorkStateFailed) {
return fmt.Errorf("failed to assert %s failed or ctx timed out", unitID)
}
return nil
}
// AssertWorkCancelled waits until work status is cancelled.
func (r *ReceptorControl) AssertWorkCancelled(ctx context.Context, unitID string) error {
check := func() bool {
workStatus, err := r.GetWorkStatus(unitID)
if err != nil {
return false
}
if workStatus.State != workceptor.WorkStateCanceled {
return false
}
detail := workStatus.Detail
detailLc := strings.ToLower(detail)
keywords := []string{
"cancel",
"kill",
"terminate",
"stop",
}
for kwIdx := range keywords {
if strings.Contains(detailLc, keywords[kwIdx]) {
return true
}
}
return false
}
if !assertWithTimeout(ctx, check) {
return fmt.Errorf("failed to assert %s is cancelled or ctx timed out", unitID)
}
return nil
}
// AssertWorkTimedOut asserts that work failed.
func (r *ReceptorControl) AssertWorkTimedOut(ctx context.Context, unitID string) error {
check := func() bool {
workStatus, err := r.GetWorkStatus(unitID)
if err != nil {
return false
}
if workStatus.State != workceptor.WorkStateFailed {
return false
}
detail := workStatus.Detail
return strings.HasPrefix(detail, "Work unit expired on")
}
if !assertWithTimeout(ctx, check) {
return fmt.Errorf("failed to assert work timed out or ctx timed out")
}
return nil
}
// AssertWorkReleased asserts that work is not in work list.
func (r *ReceptorControl) AssertWorkReleased(ctx context.Context, unitID string) error {
check := func() bool {
workList, err := r.getWorkList()
if err != nil {
return false
}
_, ok := workList[unitID] // unitID should not be in list
return !ok
}
if !assertWithTimeout(ctx, check) {
return fmt.Errorf("failed to assert %s is released or ctx timed out", unitID)
}
return nil
}
func (r *ReceptorControl) getWorkResults(unitID string, readSize int) ([]byte, error) {
_, err := r.WriteStr(fmt.Sprintf("work results %s\n", unitID))
if err != nil {
return nil, err
}
str, err := r.ReadStr()
if err != nil {
return nil, err
}
if str[:5] == "ERROR" {
return nil, fmt.Errorf("remote error: %s", str)
}
buf := make([]byte, readSize)
n, err := r.socketConn.Read(buf)
if err != nil {
return nil, err
}
if n != readSize {
return nil, fmt.Errorf("did not read correct size")
}
err = r.Close()
if err != nil {
return nil, err
}
err = r.Reconnect()
if err != nil {
return nil, err
}
return buf, nil
}
// AssertWorkResults makes sure results match expected byte array.
func (r *ReceptorControl) AssertWorkResults(unitID string, expectedResults []byte) error {
workResults, err := r.getWorkResults(unitID, len(expectedResults))
if err != nil {
return err
}
if string(expectedResults) != string(workResults) {
return fmt.Errorf("work results did not match expected results")
}
return nil
}