/
cli.go
223 lines (195 loc) · 4.88 KB
/
cli.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
package cli
import (
"bytes"
"context"
"errors"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
log "github.com/sirupsen/logrus"
linter "github.com/tyhal/crie/pkg/crie/linter"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"time"
)
// Lint defines a predefined command to run against a file
type Lint struct {
Bin string
FrontPar Par
EndPar Par
Docker DockerCmd
useDocker bool
}
// Par represents cli parameters
type Par []string
// DockerCmd an image to launch
type DockerCmd struct {
Image string
client *client.Client
id string
}
// Name returns the command name
func (e *Lint) Name() string {
return e.Bin
}
// WillRun does preflight checks for the 'Run'
func (e *Lint) WillRun() error {
e.useDocker = exec.Command("which", e.Bin).Run() != nil
if e.useDocker {
if e.Docker.Image == "" {
return errors.New("could not find " + e.Bin + ", possibly not installed")
}
if err := e.startDocker(); err != nil {
return err
}
log.Warn("it's more efficient to have " + e.Bin + " installed locally")
}
return nil
}
// working solution posted to https://stackoverflow.com/questions/52145231/cannot-get-logs-from-docker-container-using-golang-docker-sdk
func (e *Lint) execDocker(params []string, stdout io.Writer) error {
ctx := context.Background()
cmd := append([]string{"/bin/" + e.Bin}, params...)
log.Trace(cmd)
config := types.ExecConfig{
Cmd: cmd,
Env: os.Environ(),
AttachStderr: true,
AttachStdout: true,
Tty: false,
}
execResp, err := e.Docker.client.ContainerExecCreate(ctx, e.Docker.id, config)
if err != nil {
return err
}
attach, err := e.Docker.client.ContainerExecAttach(ctx, execResp.ID, config)
if err != nil {
return err
}
defer attach.Close()
go io.Copy(stdout, attach.Reader)
timeout := time.After(5 * time.Second)
check := time.Tick(100 * time.Millisecond)
for {
select {
case <-timeout:
return errors.New("exec timed out")
case <-check:
inspect, err := e.Docker.client.ContainerExecInspect(ctx, execResp.ID)
if err != nil {
return err
}
if inspect.Running == false {
if inspect.ExitCode != 0 {
return errors.New("exit code " + strconv.Itoa(inspect.ExitCode))
}
return nil
}
}
}
}
func (e *Lint) pullDocker(ctx context.Context) error {
// Ensure we have the image downloaded
pullstat, err := e.Docker.client.ImagePull(ctx, e.Docker.Image, types.ImagePullOptions{})
if err != nil {
log.WithFields(log.Fields{
"stage": "docker pull",
"image": e.Docker.Image,
}).Fatal(err)
return err
}
var pullOut bytes.Buffer
_, err = io.Copy(&pullOut, pullstat)
log.Debug(pullOut.String())
return err
}
func (e *Lint) startDocker() error {
ctx := context.Background()
// Add our client
{
c, err := client.NewEnvClient()
if err != nil {
return err
}
e.Docker.client = c
}
_, err := e.Docker.client.ImageHistory(ctx, e.Docker.Image)
if err != nil {
if err := e.pullDocker(ctx); err != nil {
return err
}
}
// Ensure we can mount our filesystem to the same path inside the container
wd, err := os.Getwd()
if err != nil {
return err
}
dir, err := filepath.Abs(wd)
if err != nil {
return err
}
resp, err := e.Docker.client.ContainerCreate(ctx,
&container.Config{
Entrypoint: []string{"/bin/sleep"},
Cmd: []string{"3600"},
Image: e.Docker.Image,
WorkingDir: dir,
},
&container.HostConfig{
Mounts: []mount.Mount{
{
Type: mount.TypeBind,
Source: dir,
Target: dir,
},
},
}, nil,
"crie-"+e.Name())
if err != nil {
return err
}
if err := e.Docker.client.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
return err
}
e.Docker.id = resp.ID
return nil
}
// DidRun should be called after all other Runs to clean up
func (e *Lint) DidRun() {
if e.useDocker {
ctx := context.Background()
var timeout time.Duration
timeout = time.Second * 3
d := log.WithFields(log.Fields{"dockerId": e.Docker.id})
d.Debug("stopping container")
if err := e.Docker.client.ContainerStop(ctx, e.Docker.id, &timeout); err != nil {
log.Error(err)
}
d.Debug("removing container")
if err := e.Docker.client.ContainerRemove(ctx, e.Docker.id, types.ContainerRemoveOptions{}); err != nil {
log.Fatal(err)
}
}
}
// Run does the work required to lint the given filepath
func (e *Lint) Run(filepath string, rep chan linter.Report) {
params := append(e.FrontPar, filepath)
params = append(params, e.EndPar...)
// Format any file received as input.
var outB, errB bytes.Buffer
var err error
if e.useDocker {
err = e.execDocker(params, &outB)
} else {
// Local binary
c := exec.Command(e.Bin, params...)
c.Stdout = &outB
c.Stderr = &errB
err = c.Run()
}
rep <- linter.Report{File: filepath, Err: err, StdOut: &outB, StdErr: &errB}
}