-
Notifications
You must be signed in to change notification settings - Fork 4
/
streamer.go
324 lines (285 loc) · 7.76 KB
/
streamer.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
/*
Package streamer describes interface for interaction on network level.
*/
package streamer
import (
"context"
"errors"
"fmt"
"net"
"os"
"time"
"go.uber.org/zap"
"golang.org/x/exp/slices"
"go.uber.org/multierr"
"github.com/annetutil/gnetcli/pkg/cmd"
"github.com/annetutil/gnetcli/pkg/credentials"
"github.com/annetutil/gnetcli/pkg/expr"
"github.com/annetutil/gnetcli/pkg/trace"
)
var ErrNotSupported = errors.New("not supported")
type Connector interface {
Init(context.Context) error
GetCredentials() credentials.Credentials
SetCredentialsInterceptor(func(credentials.Credentials) credentials.Credentials)
SetTrace(trace.CB)
SetReadTimeout(time.Duration) time.Duration
Close()
ReadTo(context.Context, expr.Expr) (ReadRes, error)
Read(ctx context.Context, n int) ([]byte, error)
Cmd(ctx context.Context, cmd string) (cmd.CmdRes, error)
Write([]byte) error
HasFeature(Const) bool
Download(paths []string, recurse bool) (map[string]File, error)
Upload(map[string]File) error
InitAgentForward() error
}
type ReadRes interface {
GetBefore() []byte
GetAfter() []byte
GetMatchedGroups() map[string][]byte
GetMatched() []byte
GetPatternNo() int
GetUnderlyingRes() ReadRes // may be nil
}
const readBufferSize = 1024
type File struct {
Data []byte
Mode *os.FileMode
Chmod *Chmod
Err error
}
func NewFileData(data []byte) File {
return NewFile(data, nil, nil)
}
type Chmod struct {
UID int
GID int
}
func NewFile(data []byte, fileMode *os.FileMode, chmod *Chmod) File {
return File{
Data: data,
Mode: fileMode,
Chmod: chmod,
Err: nil,
}
}
func NewFileError(err error) File {
var f File
f.Err = err
return f
}
type Const int
const (
AutoLogin Const = iota
Cmd
)
type ReadResImpl struct {
before []byte
after []byte
matchedGroups map[string][]byte
matched []byte
patternNo int
underlyingRes ReadRes
}
func (m ReadResImpl) GetBefore() []byte {
return m.before
}
func (m ReadResImpl) GetAfter() []byte {
return m.after
}
func (m ReadResImpl) GetMatchedGroups() map[string][]byte {
return m.matchedGroups
}
func (m ReadResImpl) GetMatched() []byte {
return m.matched
}
func (m ReadResImpl) GetPatternNo() int {
return m.patternNo
}
func (m ReadResImpl) GetUnderlyingRes() ReadRes {
return m.underlyingRes
}
func NewReadResImplWithUnder(before, after []byte, matchedGroups map[string][]byte, matched []byte, patternNo int, underlying ReadRes) ReadResImpl {
return ReadResImpl{
before: before,
after: after,
matchedGroups: matchedGroups,
matched: matched,
patternNo: patternNo,
underlyingRes: underlying,
}
}
func NewReadResImpl(before, after []byte, matchedGroups map[string][]byte, matched []byte, patternNo int) ReadResImpl {
return ReadResImpl{before: before, after: after, matchedGroups: matchedGroups, matched: matched, patternNo: patternNo}
}
// TCPDialCtx net.Dial version with context arg
func TCPDialCtx(ctx context.Context, network, addr string) (net.Conn, error) {
d := net.Dialer{}
conn, err := d.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
return conn, nil
}
// CloserCTX calls fn if ctx is cancelled. Returns cancel function.
func CloserCTX(ctx context.Context, fn func()) context.CancelFunc {
innerCtx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-ctx.Done():
fn()
return
case <-innerCtx.Done():
return
}
}()
return cancel
}
func splitBytes(data []byte, index int) ([]byte, []byte) {
if len(data) <= index {
return data, []byte{}
}
first := data[:index]
second := data[index:]
return first, second
}
func GetLastBytes(data []byte, last int) []byte {
if len(data) > last {
return data[len(data)-last:]
}
return data
}
type ReadXRes struct {
RetType ReadXType
ExprRes ReadRes
BytesRes []byte
ExprAfter []byte
}
type ReadXType int64
const (
Size ReadXType = iota
Expr
Timeout
EOF
)
func (m ReadXType) String() string {
switch m {
case Size:
return "size"
case Expr:
return "expr"
case Timeout:
return "timeout"
case EOF:
return "EOF"
}
return "unknown"
}
func NewReadXRes(retType ReadXType, bytesRes []byte, exprRes ReadRes, after []byte) *ReadXRes {
return &ReadXRes{
RetType: retType,
BytesRes: bytesRes,
ExprRes: exprRes,
ExprAfter: after,
}
}
func NewTimerWithDefault(duration time.Duration) *time.Timer {
newMaxDuration := time.Duration(1<<63 - 1)
if duration > 0 {
newMaxDuration = duration
}
return time.NewTimer(newMaxDuration)
}
func StopTimer(timer *time.Timer) {
if !timer.Stop() {
<-timer.C
}
}
// GenericReadX reads from readCh till expr matched, exceeded time or read more than size.
// Returns error if nothing was read during readTimeout or ctx was Done
// readSize - maximum read size
// maxDuration - maximum time for reading
// regExpr - read till regex match
// Returns read res, left bytes, read bytes, error
func GenericReadX(ctx context.Context, inBuffer []byte, readCh chan []byte, readSize int, readTimeout time.Duration,
regExpr expr.Expr, maxReadSize int, maxDuration time.Duration) (*ReadXRes, []byte, []byte, error) {
if maxDuration == 0 && maxReadSize == 0 && regExpr == nil {
return nil, nil, nil, fmt.Errorf("specify maxDuration, maxReadSize or regExpr")
}
buffer := slices.Clone(inBuffer)
maxDurationTimeout := NewTimerWithDefault(maxDuration)
for {
readIterTimeout := NewTimerWithDefault(readTimeout)
// check size
if maxReadSize > 0 && len(buffer) >= maxReadSize {
data, extra := splitBytes(buffer, maxReadSize)
StopTimer(readIterTimeout)
StopTimer(maxDurationTimeout)
return NewReadXRes(Size, data, nil, []byte{}), extra, buffer[len(inBuffer):], nil
}
if regExpr != nil {
// check expr
mRes, ok := regExpr.Match(buffer)
if ok {
var underlyingRes ReadRes
if mRes.Underlying != nil {
underlyingRes = NewReadResImpl(buffer[:mRes.Underlying.Start], buffer[mRes.Underlying.End:], mRes.Underlying.GroupDict, buffer[mRes.Underlying.Start:mRes.End], mRes.Underlying.PatternNo)
}
res := NewReadResImplWithUnder(buffer[:mRes.Start], buffer[mRes.End:], mRes.GroupDict, buffer[mRes.Start:mRes.End], mRes.PatternNo, underlyingRes)
after := buffer[mRes.End:]
StopTimer(readIterTimeout)
StopTimer(maxDurationTimeout)
return NewReadXRes(Expr, buffer, res, after), after, buffer[len(inBuffer):], nil
}
}
select {
case <-ctx.Done():
StopTimer(readIterTimeout)
StopTimer(maxDurationTimeout)
return nil, buffer, buffer[len(inBuffer):], multierr.Combine(ctx.Err(), ThrowReadTimeoutException(GetLastBytes(buffer, readSize)))
case readData, ok := <-readCh:
StopTimer(readIterTimeout)
buffer = append(buffer, readData...)
if !ok {
return NewReadXRes(EOF, buffer, nil, []byte{}), buffer, buffer[len(inBuffer):], nil
}
case <-maxDurationTimeout.C:
// check maxDuration
StopTimer(readIterTimeout)
return NewReadXRes(Timeout, buffer, nil, []byte{}), buffer, buffer[len(inBuffer):], nil
case <-readIterTimeout.C:
StopTimer(maxDurationTimeout)
return nil, buffer, buffer[len(inBuffer):], ThrowReadTimeoutException(GetLastBytes(buffer, readSize))
}
}
}
// NetReader reads data from connection and put it into channel
func NetReader(ctx context.Context, buff chan []byte, conn net.Conn, logger *zap.Logger) error {
defer func() {
_ = conn.SetReadDeadline(time.Time{})
}()
for {
select {
case <-ctx.Done():
return nil
default:
for {
err := conn.SetReadDeadline(time.Now().Add(2 * time.Second))
if err != nil {
return err
}
readBuffer := make([]byte, readBufferSize)
readLen, err := conn.Read(readBuffer)
if err, ok := err.(net.Error); ok && err.Timeout() {
break
}
if err != nil {
return err
}
logger.Debug("read", zap.ByteString("data", readBuffer[:readLen]))
buff <- readBuffer[:readLen]
}
}
}
}