forked from docker-archive/compose-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.go
254 lines (227 loc) · 6.32 KB
/
exec.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
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package mobycli
import (
"context"
"debug/buildinfo"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/google/shlex"
"github.com/spf13/cobra"
apicontext "github.com/docker/compose-cli/api/context"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/cli/metrics"
"github.com/docker/compose-cli/cli/mobycli/resolvepath"
)
var delegatedContextTypes = []string{store.DefaultContextType}
// ComDockerCli name of the classic cli binary
var ComDockerCli = "com.docker.cli"
func init() {
if runtime.GOOS == "windows" {
ComDockerCli += ".exe"
}
}
// ExecIfDefaultCtxType delegates to com.docker.cli if on moby context
func ExecIfDefaultCtxType(ctx context.Context, root *cobra.Command) {
currentContext := apicontext.Current()
s := store.Instance()
currentCtx, err := s.Get(currentContext)
// Only run original docker command if the current context is not ours.
if err != nil || mustDelegateToMoby(currentCtx.Type()) {
Exec(root)
}
}
func mustDelegateToMoby(ctxType string) bool {
for _, ctype := range delegatedContextTypes {
if ctxType == ctype {
return true
}
}
return false
}
// Exec delegates to com.docker.cli if on moby context
func Exec(_ *cobra.Command) {
metricsClient := metrics.NewDefaultClient()
metricsClient.WithCliVersionFunc(func() string {
return CliVersion()
})
start := time.Now().UTC()
childExit := make(chan bool)
err := RunDocker(childExit, os.Args[1:]...)
childExit <- true
duration := time.Since(start)
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
exitCode := exiterr.ExitCode()
metricsClient.Track(
metrics.CmdResult{
ContextType: store.DefaultContextType,
Args: os.Args[1:],
Status: metrics.FailureCategoryFromExitCode(exitCode).MetricsStatus,
ExitCode: exitCode,
Start: start,
Duration: duration,
},
)
os.Exit(exitCode)
}
metricsClient.Track(
metrics.CmdResult{
ContextType: store.DefaultContextType,
Args: os.Args[1:],
Status: metrics.FailureStatus,
Start: start,
Duration: duration,
},
)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
commandArgs := os.Args[1:]
command := metrics.GetCommand(commandArgs)
if !metrics.HasQuietFlag(commandArgs) {
switch command {
case "build": // only on regular build, not on buildx build
displayScoutQuickViewSuggestMsgOnBuild(commandArgs)
case "pull":
displayScoutQuickViewSuggestMsgOnPull(commandArgs)
case "login":
displayPATSuggestMsg(commandArgs)
default:
}
}
metricsClient.Track(
metrics.CmdResult{
ContextType: store.DefaultContextType,
Args: os.Args[1:],
Status: metrics.SuccessStatus,
ExitCode: 0,
Start: start,
Duration: duration,
},
)
os.Exit(0)
}
// RunDocker runs a docker command, and forward signals to the shellout command (stops listening to signals when an event is sent to childExit)
func RunDocker(childExit chan bool, args ...string) error {
cmd := exec.Command(comDockerCli(), args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
signals := make(chan os.Signal, 1)
signal.Notify(signals) // catch all signals
go func() {
for {
select {
case sig := <-signals:
if cmd.Process == nil {
continue // can happen if receiving signal before the process is actually started
}
// In go1.14+, the go runtime issues SIGURG as an interrupt to
// support preemptable system calls on Linux. Since we can't
// forward that along we'll check that here.
if isRuntimeSig(sig) {
continue
}
_ = cmd.Process.Signal(sig)
case <-childExit:
return
}
}
}()
return cmd.Run()
}
func comDockerCli() string {
if v := os.Getenv("DOCKER_COM_DOCKER_CLI"); v != "" {
return v
}
execBinary := findBinary(ComDockerCli)
if execBinary == "" {
var err error
execBinary, err = resolvepath.LookPath(ComDockerCli)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, "Current PATH : "+os.Getenv("PATH"))
os.Exit(1)
}
}
return execBinary
}
func findBinary(filename string) string {
currentBinaryPath, err := os.Executable()
if err != nil {
return ""
}
currentBinaryPath, err = filepath.EvalSymlinks(currentBinaryPath)
if err != nil {
return ""
}
binaryPath := filepath.Join(filepath.Dir(currentBinaryPath), filename)
if _, err := os.Stat(binaryPath); err != nil {
return ""
}
return binaryPath
}
// IsDefaultContextCommand checks if the command exists in the classic cli (issues a shellout --help)
func IsDefaultContextCommand(dockerCommand string) bool {
cmd := exec.Command(comDockerCli(), dockerCommand, "--help")
b, e := cmd.CombinedOutput()
if e != nil {
fmt.Println(e)
}
return regexp.MustCompile("Usage:\\s*docker\\s*" + dockerCommand).Match(b)
}
// CliVersion returns the docker cli version
func CliVersion() string {
info, err := buildinfo.ReadFile(ComDockerCli)
if err != nil {
return ""
}
for _, s := range info.Settings {
if s.Key != "-ldflags" {
continue
}
args, err := shlex.Split(s.Value)
if err != nil {
return ""
}
for _, a := range args {
// https://github.com/docker/cli/blob/f1615facb1ca44e4336ab20e621315fc2cfb845a/scripts/build/.variables#L77
if !strings.HasPrefix(a, "github.com/docker/cli/cli/version.Version") {
continue
}
parts := strings.Split(a, "=")
if len(parts) != 2 {
return ""
}
return parts[1]
}
}
return ""
}
// ExecSilent executes a command and do redirect output to stdOut, return output
func ExecSilent(ctx context.Context, args ...string) ([]byte, error) {
if len(args) == 0 {
args = os.Args[1:]
}
cmd := exec.CommandContext(ctx, comDockerCli(), args...)
cmd.Stderr = os.Stderr
return cmd.Output()
}