-
Notifications
You must be signed in to change notification settings - Fork 12
/
io.go
94 lines (79 loc) · 1.67 KB
/
io.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
package util
import (
"bytes"
"context"
"io"
"io/ioutil"
"os"
"github.com/projecteru2/yavirt/errors"
"github.com/projecteru2/yavirt/log"
)
// ReadAll .
func ReadAll(fpth string) ([]byte, error) {
f, err := os.Open(fpth)
if err != nil {
return nil, errors.Trace(err)
}
buf, err := ioutil.ReadAll(f)
if err != nil {
return nil, errors.Trace(err)
}
return buf, nil
}
// WriteTempFile .
func WriteTempFile(buf []byte) (string, error) {
f, err := ioutil.TempFile(os.TempDir(), "temp-guest-*.xml")
if err != nil {
return "", errors.Trace(err)
}
if _, err := f.Write(buf); err != nil {
return "", errors.Trace(err)
}
return f.Name(), nil
}
// Scan is tested to guarantee no goroutine leaking
func Scan(_ context.Context, reader io.Reader) <-chan []byte {
ch := make(chan []byte)
go func() {
defer close(ch)
for {
p := make([]byte, 65536) //nolint // max(uint16) + 1
n, err := reader.Read(p)
if n > 0 {
if bytes.Contains(p[:n], []byte("^]")) {
log.Warnf("[io.Scan] reader exited: %v", reader)
return
}
ch <- p[:n]
}
if err != nil {
if err != io.EOF {
log.Warnf("[io.Scan] error in reading %s: %s", reader, errors.Trace(err))
}
return
}
}
}()
return ch
}
// CopyIO is parallel to io.Copy execpt accepting context
func CopyIO(ctx context.Context, dst io.WriteCloser, src io.Reader) (written int, err error) {
defer dst.Close()
var n int
ch := Scan(ctx, src)
for {
select {
case <-ctx.Done():
return
case bytes, ok := <-ch:
if !ok {
return
}
if n, err = dst.Write(bytes); err != nil {
log.Warnf("error in copy io: %s", errors.Trace(err))
return
}
written += n
}
}
}