forked from vmware-archive/fly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hijack.go
301 lines (246 loc) · 7.48 KB
/
hijack.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package commands
import (
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"github.com/concourse/atc"
"github.com/concourse/fly/commands/internal/displayhelpers"
"github.com/concourse/fly/commands/internal/flaghelpers"
"github.com/concourse/fly/commands/internal/hijacker"
"github.com/concourse/fly/commands/internal/hijackhelpers"
"github.com/concourse/fly/pty"
"github.com/concourse/fly/rc"
"github.com/concourse/go-concourse/concourse"
"github.com/tedsuo/rata"
"github.com/vito/go-interact/interact"
)
type HijackCommand struct {
Job flaghelpers.JobFlag `short:"j" long:"job" value-name:"PIPELINE/JOB" description:"Name of a job to hijack"`
Check flaghelpers.ResourceFlag `short:"c" long:"check" value-name:"PIPELINE/CHECK" description:"Name of a resource's checking container to hijack"`
Build string `short:"b" long:"build" description:"Build number within the job, or global build ID"`
StepName string `short:"s" long:"step" description:"Name of step to hijack (e.g. build, unit, resource name)"`
Attempt []int `short:"a" long:"attempt" description:"Attempt number of step to hijack. Can be specified multiple times for nested retries"`
PositionalArgs struct {
Command []string `positional-arg-name:"command" description:"The command to run in the container (default: bash)"`
} `positional-args:"yes"`
}
func (command *HijackCommand) Execute([]string) error {
target, err := rc.LoadTarget(Fly.Target)
if err != nil {
return err
}
err = target.Validate()
if err != nil {
return err
}
containers, err := command.getContainerIDs(target.Client())
if err != nil {
return err
}
var chosenContainer atc.Container
if len(containers) == 0 {
displayhelpers.Failf("no containers matched your search parameters!\n\nthey may have expired if your build hasn't recently finished.")
} else if len(containers) > 1 {
var choices []interact.Choice
for _, container := range containers {
var infos []string
if container.BuildID != 0 {
if container.JobName != "" {
infos = append(infos, fmt.Sprintf("build #%s", container.BuildName))
} else {
infos = append(infos, fmt.Sprintf("build id: %d", container.BuildID))
}
}
if container.StepType != "" {
infos = append(infos, fmt.Sprintf("step: %s", container.StepName))
infos = append(infos, fmt.Sprintf("type: %s", container.StepType))
} else if container.ResourceName != "" {
infos = append(infos, fmt.Sprintf("resource: %s", container.ResourceName))
infos = append(infos, "type: check")
} else {
infos = append(infos, fmt.Sprintf("step: %s", container.StepName))
infos = append(infos, "type: check")
}
if len(container.Attempts) != 0 {
attempt := SliceItoa(container.Attempts)
infos = append(infos, fmt.Sprintf("attempt: %s", attempt))
}
choices = append(choices, interact.Choice{
Display: strings.Join(infos, ", "),
Value: container,
})
}
err = interact.NewInteraction("choose a container", choices...).Resolve(&chosenContainer)
if err == io.EOF {
return nil
}
if err != nil {
return err
}
} else {
chosenContainer = containers[0]
}
privileged := true
reqGenerator := rata.NewRequestGenerator(target.URL(), atc.Routes)
var ttySpec *atc.HijackTTYSpec
rows, cols, err := pty.Getsize(os.Stdin)
if err == nil {
ttySpec = &atc.HijackTTYSpec{
WindowSize: atc.HijackWindowSize{
Columns: cols,
Rows: rows,
},
}
}
envVariables := append(chosenContainer.EnvironmentVariables, "TERM="+os.Getenv("TERM"))
path, args := remoteCommand(command.PositionalArgs.Command)
spec := atc.HijackProcessSpec{
Path: path,
Args: args,
Env: envVariables,
User: chosenContainer.User,
Dir: chosenContainer.WorkingDirectory,
Privileged: privileged,
TTY: ttySpec,
}
result, err := func() (int, error) { // so the term.Restore() can run before the os.Exit()
var in io.Reader
if pty.IsTerminal() {
term, err := pty.OpenRawTerm()
if err != nil {
return -1, err
}
defer term.Restore()
in = term
} else {
in = os.Stdin
}
io := hijacker.ProcessIO{
In: in,
Out: os.Stdout,
Err: os.Stderr,
}
h := hijacker.New(target.TLSConfig(), reqGenerator, target.Token())
return h.Hijack(chosenContainer.ID, spec, io)
}()
if err != nil {
return err
}
os.Exit(result)
return nil
}
func (command *HijackCommand) getContainerIDs(client concourse.Client) ([]atc.Container, error) {
var pipelineName string
if command.Job.PipelineName != "" {
pipelineName = command.Job.PipelineName
} else {
pipelineName = command.Check.PipelineName
}
buildNameOrID := command.Build
stepName := command.StepName
jobName := command.Job.JobName
check := command.Check.ResourceName
attempt := command.Attempt
fingerprint := containerFingerprint{
pipelineName: pipelineName,
jobName: jobName,
buildNameOrID: buildNameOrID,
stepName: stepName,
checkName: check,
attempt: attempt,
}
reqValues, err := locateContainer(client, fingerprint)
if err != nil {
return nil, err
}
containers, err := client.ListContainers(reqValues)
if err != nil {
return nil, err
}
sort.Sort(hijackhelpers.ContainerSorter(containers))
return containers, nil
}
func remoteCommand(argv []string) (string, []string) {
var path string
var args []string
switch len(argv) {
case 0:
path = "bash"
case 1:
path = argv[0]
default:
path = argv[0]
args = argv[1:]
}
return path, args
}
type containerLocator interface {
locate(containerFingerprint) (map[string]string, error)
}
type stepContainerLocator struct {
client concourse.Client
}
func (locator stepContainerLocator) locate(fingerprint containerFingerprint) (map[string]string, error) {
reqValues := map[string]string{}
if fingerprint.jobName != "" {
reqValues["pipeline_name"] = fingerprint.pipelineName
reqValues["job_name"] = fingerprint.jobName
if fingerprint.buildNameOrID != "" {
reqValues["build_name"] = fingerprint.buildNameOrID
}
} else if fingerprint.buildNameOrID != "" {
reqValues["build-id"] = fingerprint.buildNameOrID
} else {
build, err := GetBuild(locator.client, nil, "", "", "")
if err != nil {
return reqValues, err
}
reqValues["build-id"] = strconv.Itoa(build.ID)
}
if fingerprint.stepName != "" {
reqValues["step_name"] = fingerprint.stepName
}
if len(fingerprint.attempt) > 0 {
attemptBlob, err := json.Marshal(fingerprint.attempt)
if err != nil {
return nil, err
}
reqValues["attempt"] = string(attemptBlob)
}
return reqValues, nil
}
type checkContainerLocator struct{}
func (locator checkContainerLocator) locate(fingerprint containerFingerprint) (map[string]string, error) {
reqValues := map[string]string{}
reqValues["type"] = "check"
if fingerprint.checkName != "" {
reqValues["resource_name"] = fingerprint.checkName
}
if fingerprint.pipelineName != "" {
reqValues["pipeline_name"] = fingerprint.pipelineName
}
return reqValues, nil
}
type containerFingerprint struct {
pipelineName string
jobName string
buildNameOrID string
stepName string
checkName string
attempt []int
}
func locateContainer(client concourse.Client, fingerprint containerFingerprint) (map[string]string, error) {
var locator containerLocator
if fingerprint.checkName == "" {
locator = stepContainerLocator{
client: client,
}
} else {
locator = checkContainerLocator{}
}
return locator.locate(fingerprint)
}