forked from puppetlabs-toy-chest/wash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutputStream.go
89 lines (78 loc) · 1.93 KB
/
outputStream.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
package plugin
import (
"context"
"sync"
"time"
)
// OutputStream represents stdout/stderr.
type OutputStream struct {
ctx context.Context
sentCtxErr bool
id ExecPacketType
ch chan ExecOutputChunk
closer *multiCloser
mux sync.RWMutex
closed bool
}
func (s *OutputStream) sendData(timestamp time.Time, data string) {
s.ch <- ExecOutputChunk{StreamID: s.id, Timestamp: timestamp, Data: data}
}
func (s *OutputStream) sendError(timestamp time.Time, err error) {
s.ch <- ExecOutputChunk{StreamID: s.id, Timestamp: timestamp, Err: err}
}
// WriteWithTimestamp writes the given data with the specified timestamp
func (s *OutputStream) WriteWithTimestamp(timestamp time.Time, data []byte) error {
s.mux.RLock()
defer s.mux.RUnlock()
if s.closed {
return nil
}
select {
case <-s.ctx.Done():
s.sendError(timestamp, s.ctx.Err())
s.sentCtxErr = true
return s.ctx.Err()
default:
s.sendData(timestamp, string(data))
return nil
}
}
func (s *OutputStream) Write(data []byte) (int, error) {
err := s.WriteWithTimestamp(time.Now(), data)
return len(data), err
}
// CloseWithError sends the given error before closing the OutputStream.
// It will noop if the OutputStream's already closed.
func (s *OutputStream) CloseWithError(err error) {
// The lock's necessary because this can be called by multiple threads
// (e.g. the goroutine in NewExecCommand + ExecCommandImpl#CloseStreamsWithError)
s.mux.Lock()
defer s.mux.Unlock()
if s.closed {
return
}
defer func() {
s.closed = true
}()
if err != nil {
// Avoid re-sending ctx.Err() if it was already sent
// by OutputStream#Write
if err != s.ctx.Err() || !s.sentCtxErr {
s.sendError(time.Now(), err)
}
}
s.closer.Close()
}
type multiCloser struct {
mux sync.Mutex
ch chan ExecOutputChunk
countdown int
}
func (c *multiCloser) Close() {
c.mux.Lock()
c.countdown--
if c.countdown == 0 {
close(c.ch)
}
c.mux.Unlock()
}