/
capture.go
104 lines (85 loc) · 1.65 KB
/
capture.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
package reporters
import (
"bufio"
"io"
"os"
"syscall"
"github.com/microsoft/ApplicationInsights-Go/appinsights"
"github.com/microsoft/ApplicationInsights-Go/appinsights/contracts"
)
type Capture struct {
done chan struct{}
fd int
oldfile *os.File
io.Reader
}
func (c *Capture) Close() error {
// fd -> closefd
closefd, err := syscall.Dup(c.fd)
if err != nil {
return err
}
// oldfile.fd -> fd
err = syscall.Dup2(int(c.oldfile.Fd()), c.fd)
if err != nil {
return err
}
err = syscall.Close(closefd)
if err != nil {
return err
}
<-c.done
return nil
}
func NewCapture(fd int) (*Capture, error) {
c := &Capture{
done: make(chan struct{}),
fd: fd,
}
// fd -> oldfd
oldfd, err := syscall.Dup(c.fd)
if err != nil {
return nil, err
}
c.oldfile = os.NewFile(uintptr(oldfd), "")
ospr, ospw, err := os.Pipe()
if err != nil {
c.oldfile.Close()
return nil, err
}
defer ospw.Close()
// ospw -> fd
err = syscall.Dup2(int(ospw.Fd()), c.fd)
if err != nil {
c.oldfile.Close()
ospr.Close()
return nil, err
}
iopr, iopw := io.Pipe()
go func() {
// copy from ospr -> c.oldfile and iopw (read by c.Reader)
_, err = io.Copy(io.MultiWriter(c.oldfile, iopw), ospr)
iopw.CloseWithError(err)
close(c.done)
}()
c.Reader = iopr
return c, nil
}
func StartCapture(fd int, c appinsights.TelemetryClient, done chan struct{}) (*Capture, error) {
capture, err := NewCapture(fd)
if err != nil {
return nil, err
}
go func() {
br := bufio.NewReader(capture)
for {
s, err := br.ReadString('\n')
if err != nil {
break
}
c.TrackTrace(s, contracts.Information)
}
close(done)
}()
return capture, nil
}