-
Notifications
You must be signed in to change notification settings - Fork 90
/
output.go
121 lines (106 loc) · 2.28 KB
/
output.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
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/util"
)
type statusMessage struct {
Status string `json:"status,omitempty"`
DisplayMessage string `json:"display_message,omitempty"`
ExitCode *int `json:"exit_code,omitempty"`
Data string `json:"data,omitempty"`
}
type StatusClient struct {
Chan chan interface{}
}
func connectToStatusServer(socket string) (*StatusClient, error) {
client, err := net.Dial("unix", socket)
if err != nil {
return nil, errors.Wrap(err, "failed to connect to server")
}
ch := make(chan interface{}, 0)
go func() {
for {
msg, ok := <-ch
if !ok {
client.Close()
return
}
switch msg := msg.(type) {
case statusMessage, *statusMessage:
b, err := json.Marshal(msg)
if err != nil {
// silent fail
continue
}
buff := bytes.NewBuffer(b)
if _, err := buff.Write([]byte("\n")); err != nil {
// silent fail
continue
}
if _, err := buff.WriteTo(client); err != nil {
fmt.Printf("failed to send status %s: %v\n", msg, err)
continue
}
default:
// silent fail
}
}
}()
return &StatusClient{Chan: ch}, nil
}
func (c *StatusClient) getOutputWriter() io.WriteCloser {
pipeReader, pipeWriter := io.Pipe()
go func() {
scanner := bufio.NewScanner(pipeReader)
for scanner.Scan() {
c.Chan <- statusMessage{
Status: "running",
DisplayMessage: scanner.Text(),
}
}
pipeReader.CloseWithError(scanner.Err())
}()
return pipeWriter
}
func (c *StatusClient) end(result *FFIResult) {
message := ""
if result.Err != nil {
message = result.Err.Error()
}
c.Chan <- statusMessage{
Status: "terminated",
ExitCode: &result.ExitCode,
DisplayMessage: message,
Data: result.Data,
}
close(c.Chan)
}
type FFIResult struct {
Err error
ExitCode int
Data string
}
func NewFFIResult(exitCode int) *FFIResult {
return &FFIResult{
ExitCode: exitCode,
}
}
func (f *FFIResult) WithError(err error) *FFIResult {
cause := errors.Cause(err)
if _, ok := cause.(util.ActionableError); ok {
f.Err = cause
} else {
f.Err = err
}
return f
}
func (f *FFIResult) WithData(data string) *FFIResult {
f.Data = data
return f
}