-
Notifications
You must be signed in to change notification settings - Fork 174
/
toolbox.go
472 lines (382 loc) · 12.1 KB
/
toolbox.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// Copyright 2016-2018 VMware, Inc. All Rights Reserved.
//
// 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.
// +build !windows,!darwin
package tether
import (
"archive/tar"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"strconv"
"sync"
"syscall"
"time"
log "github.com/Sirupsen/logrus"
dar "github.com/docker/docker/pkg/archive"
"golang.org/x/crypto/ssh"
"github.com/vmware/govmomi/toolbox"
"github.com/vmware/govmomi/toolbox/hgfs"
"github.com/vmware/govmomi/toolbox/vix"
"github.com/vmware/vic/lib/archive"
"github.com/vmware/vic/lib/tether/msgs"
"github.com/vmware/vic/lib/tether/shared"
"github.com/vmware/vic/pkg/trace"
)
// Toolbox is a tether extension that wraps toolbox.Service
type Toolbox struct {
*toolbox.Service
sess struct {
sync.Mutex
session *SessionConfig
}
// IDs that can be used to authenticate
authIDs map[string]struct{}
stop chan struct{}
// System interface for basic operations
baseOp System
}
var (
defaultArchiveHandler = hgfs.NewArchiveHandler().(*hgfs.ArchiveHandler)
baseOp = &BaseOperations{}
)
// NewToolbox returns a tether.Extension that wraps the vsphere/toolbox service
func NewToolbox() *Toolbox {
in := toolbox.NewBackdoorChannelIn()
out := toolbox.NewBackdoorChannelOut()
service := toolbox.NewService(in, out)
service.PrimaryIP = toolbox.DefaultIP
return &Toolbox{
Service: service,
authIDs: make(map[string]struct{}),
}
}
// Start implementation of the tether.Extension interface
func (t *Toolbox) Start(system System) error {
t.stop = make(chan struct{})
on := make(chan struct{})
t.Service.Power.PowerOn.Handler = func() error {
log.Info("toolbox: service is ready (power on event received)")
close(on)
return nil
}
t.baseOp = system
err := t.Service.Start()
if err != nil {
return err
}
// Wait for the vmx to send the OS_PowerOn message,
// at which point it will be ready to service vix command requests.
log.Info("toolbox: waiting for initialization")
select {
case <-on:
case <-time.After(time.Second):
log.Warn("toolbox: timeout waiting for power on event")
}
return nil
}
// Stop implementation of the tether.Extension interface
func (t *Toolbox) Stop() error {
t.Service.Stop()
t.Service.Wait()
close(t.stop)
return nil
}
// Reload implementation of the tether.Extension interface
func (t *Toolbox) Reload(config *ExecutorConfig) error {
if config != nil && config.Sessions != nil {
t.sess.Lock()
defer t.sess.Unlock()
t.sess.session = config.Sessions[config.ID]
}
// we allow the primary session
t.authIDs[config.ID] = struct{}{}
// we also allow any device IDs that are attached
for _, mspec := range config.Mounts {
// mounstpect.source.path is the disk label for vmdks
// TODO: this is not the case for other volumes, eg nfs vols.
if mspec.Source.Scheme == "label" {
t.authIDs[mspec.Source.Path] = struct{}{}
}
}
return nil
}
// InContainer configures the toolbox to run within a container VM
func (t *Toolbox) InContainer() *Toolbox {
t.Power.Halt.Handler = t.halt
cmd := t.Service.Command
cmd.Authenticate = t.containerAuthenticate
cmd.ProcessStartCommand = t.containerStartCommand
ar := func(u *url.URL, r *tar.Reader) error {
return toolboxOverrideArchiveRead(t.baseOp, u, r)
}
aw := func(u *url.URL, w *tar.Writer) error {
return toolboxOverrideArchiveWrite(t.baseOp, u, w)
}
cmd.FileServer.RegisterFileHandler(hgfs.ArchiveScheme, &hgfs.ArchiveHandler{
Read: ar,
Write: aw,
})
return t
}
func (t *Toolbox) session() *SessionConfig {
t.sess.Lock()
defer t.sess.Unlock()
return t.sess.session
}
func (t *Toolbox) kill(_ context.Context, name string) error {
session := t.session()
if session == nil {
return fmt.Errorf("failed to kill container: process not found")
}
session.Lock()
defer session.Unlock()
return t.killHelper(session, name, false)
}
func (t *Toolbox) groupKill(_ context.Context, name string) error {
session := t.session()
if session == nil {
return fmt.Errorf("failed to kill container: process not found")
}
session.Lock()
defer session.Unlock()
return t.killHelper(session, name, true)
}
func (t *Toolbox) killHelper(session *SessionConfig, name string, groupKill bool) error {
if name == "" {
name = string(ssh.SIGTERM)
}
if session.Cmd.Process == nil {
return fmt.Errorf("the session %s hasn't launched yet", session.ID)
}
sig := new(msgs.SignalMsg)
err := sig.FromString(name)
if err != nil {
return err
}
num := syscall.Signal(sig.Signum())
var pid int
if groupKill == false {
// Send signal to a single process
pid = session.Cmd.Process.Pid
log.Infof("sending signal %s (%d) to process %d for %s", sig.Signal, num, session.Cmd.Process.Pid, session.ID)
} else {
// Send signal to the whole process group
pid = -session.Cmd.Process.Pid
log.Infof("sending signal %s (%d) to process group %d for %s", sig.Signal, num, session.Cmd.Process.Pid, session.ID)
}
if err := syscall.Kill(pid, num); err != nil {
return fmt.Errorf("failed to signal %s: %s", session.ID, err)
}
return nil
}
func (t *Toolbox) containerAuthenticate(_ vix.CommandRequestHeader, data []byte) error {
var c vix.UserCredentialNamePassword
if err := c.UnmarshalBinary(data); err != nil {
return err
}
session := t.session()
if session == nil {
return errors.New("not yet initialized")
}
log.Debugf("containerAuthenticate, acquiring session lock: %s ..", session.ID)
session.Lock()
log.Debugf("containerAuthenticate, acquired session lock: %s", session.ID)
defer session.Unlock()
// no authentication yet, just using container ID and device IDs as a sanity check for now
if _, ok := t.authIDs[c.Name]; !ok {
return errors.New("failed to verify authentication ID")
}
return nil
}
func (t *Toolbox) containerStartCommand(m *toolbox.ProcessManager, r *vix.StartProgramRequest) (int64, error) {
var p *toolbox.Process
switch r.ProgramPath {
case shared.GuestActionKill:
p = toolbox.NewProcessFunc(t.kill)
case shared.GuestActionGroupKill:
p = toolbox.NewProcessFunc(t.groupKill)
case shared.GuestActionReload:
p = toolbox.NewProcessFunc(func(_ context.Context, _ string) error {
return ReloadConfig()
})
default:
return -1, fmt.Errorf("unknown command %q", r.ProgramPath)
}
return m.Start(r, p)
}
func (t *Toolbox) halt() error {
session := t.session()
if session == nil {
return fmt.Errorf("failed to halt container: not initialized yet")
}
session.Lock()
defer session.Unlock()
if session.Cmd.Process == nil {
return fmt.Errorf("the session %s hasn't launched yet", session.ID)
}
log.Infof("stopping %s", session.ID)
if err := t.killHelper(session, session.StopSignal, false); err != nil {
return err
}
// Killing the executor session in the container VM will stop the tether and its extensions.
// If that doesn't happen within the timeout, send a SIGKILL.
select {
case <-t.stop:
log.Infof("%s has stopped", session.ID)
return nil
case <-time.After(time.Second * 10):
}
log.Warnf("killing %s", session.ID)
return session.Cmd.Process.Kill()
}
// toolboxOverrideArchiveRead is the online DataSink Override Handler
func toolboxOverrideArchiveRead(system System, u *url.URL, tr *tar.Reader) error {
// special behavior when using disk-labels and filterspec
diskLabel := u.Query().Get(shared.DiskLabelQueryName)
filterSpec := u.Query().Get(shared.FilterSpecQueryName)
if diskLabel != "" && filterSpec != "" {
op := trace.NewOperation(context.Background(), "ToolboxOnlineDataSink: %s", u.String())
op.Debugf("Reading from tar archive to path %s: %s", u.Path, u.String())
spec, err := archive.DecodeFilterSpec(op, &filterSpec)
if err != nil {
op.Errorf(err.Error())
return err
}
diskPath, err := mountDiskLabel(op, system, diskLabel)
if err != nil {
op.Errorf(err.Error())
return err
}
defer unmount(op, diskPath)
// no need to join on u.Path here. u.Path == spec.Rebase, but
// Unpack will rebase tar headers for us. :thumbsup:
op.Debugf("Unpacking tar archive to %s", diskPath)
waitChan, err := system.LaunchUtility(func() (*os.Process, error) {
cmd, err := archive.OnlineUnpack(op, tr, spec, diskPath)
return cmd.Process, err
})
if err != nil {
return err
}
if rc := <-waitChan; rc != 0 {
return fmt.Errorf("Got nonzero exit code from unpack binary: %d", rc)
}
op.Debugf("Finished reading from tar archive to path %s: %s", u.Path, u.String())
return err
}
return defaultArchiveHandler.Read(u, tr)
}
// toolboxOverrideArchiveWrite is the Online DataSource Override Handler
func toolboxOverrideArchiveWrite(system System, u *url.URL, tw *tar.Writer) error {
// special behavior when using disk-labels and filterspec
diskLabel := u.Query().Get(shared.DiskLabelQueryName)
filterSpec := u.Query().Get(shared.FilterSpecQueryName)
skiprecurse, _ := strconv.ParseBool(u.Query().Get(shared.SkipRecurseQueryName))
skipdata, _ := strconv.ParseBool(u.Query().Get(shared.SkipDataQueryName))
if diskLabel != "" && filterSpec != "" {
op := trace.NewOperation(context.Background(), "ToolboxOnlineDataSource: %s", u.String())
op.Debugf("Writing to archive from %s: %s", u.Path, u.String())
spec, err := archive.DecodeFilterSpec(op, &filterSpec)
if err != nil {
op.Errorf(err.Error())
return err
}
// get the container fs mount
diskPath, err := mountDiskLabel(op, system, diskLabel)
if err != nil {
op.Errorf(err.Error())
return err
}
defer unmount(op, diskPath)
var rc io.ReadCloser
if skiprecurse {
// we only want a single file - this is a hack while we're abusing Diff, but
// accomplish this by generating a single entry ChangeSet
changes := []dar.Change{
{
Kind: dar.ChangeModify,
Path: u.Path,
},
}
rc, err = archive.Tar(op, diskPath, changes, spec, !skipdata, false)
} else {
rc, err = archive.Diff(op, diskPath, "", spec, !skipdata, false)
}
if err != nil {
op.Errorf(err.Error())
return err
}
tr := tar.NewReader(rc)
defer rc.Close()
for {
hdr, err := tr.Next()
if err == io.EOF {
op.Debugf("Finished writing to archive from %s: %s with error %#v", u.Path, u.String(), err)
break
}
if err != nil {
op.Errorf("error writing tar: %s", err.Error())
return err
}
op.Debugf("Writing header: %#s", *hdr)
err = tw.WriteHeader(hdr)
if err != nil {
op.Errorf("error writing tar header: %s", err.Error())
return err
}
_, err = io.Copy(tw, tr)
if err != nil {
op.Errorf("error writing tar contents: %s", err.Error())
return err
}
}
return nil
}
return defaultArchiveHandler.Write(u, tw)
}
func mountDiskLabel(op trace.Operation, system System, label string) (string, error) {
// We know the vmdk will always be attached at '/'
if label == shared.ScratchDiskLabel {
return "/", nil
}
// otherwise, label represents a volume that needs to be mounted
tmpDir, err := ioutil.TempDir("", fmt.Sprintf("toolbox-%s", label))
if err != nil {
op.Errorf("failed to create mountpoint %s: %s", tmpDir, err)
return "", fmt.Errorf("failed to create mountpoint %s: %s", tmpDir, err)
}
err = system.MountLabel(op, label, tmpDir)
if err != nil {
os.Remove(tmpDir)
op.Errorf("failed to mount label %s at %s: %s", label, tmpDir, err)
return "", fmt.Errorf("failed to mount label %s at %s: %s", label, tmpDir, err)
}
return tmpDir, nil
}
func unmount(op trace.Operation, unmountPath string) {
// don't unmount the root vmdk
if unmountPath == "/" {
return
}
// unmount the disk from the temporary directory
if err := Sys.Syscall.Unmount(unmountPath, syscall.MNT_DETACH); err != nil {
op.Errorf("failed to unmount %s: %s", unmountPath, err.Error())
}
// finally, remove the temporary directory
os.Remove(unmountPath)
}