forked from vmware/vic
/
container_proxy.go
1469 lines (1225 loc) · 48.9 KB
/
container_proxy.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
package proxy
//****
// container_proxy.go
//
// Contains all code that touches the portlayer for container operations and all
// code that converts swagger based returns to docker personality backend structs.
// The goal is to make the backend code that implements the docker engine-api
// interfaces be as simple as possible and contain no swagger or portlayer code.
//
// Rule for code to be in here:
// 1. touches VIC portlayer
// 2. converts swagger to docker engine-api structs
// 3. errors MUST be docker engine-api compatible errors. DO NOT return arbitrary errors!
// - Do NOT return portlayer errors
// - Do NOT return fmt.Errorf()
// - Do NOT return errors.New()
// - Please USE the aliased docker error package 'derr'
import (
"context"
"fmt"
"net"
"strconv"
"strings"
"syscall"
"time"
log "github.com/Sirupsen/logrus"
derr "github.com/docker/docker/api/errors"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
dnetwork "github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/go-connections/nat"
"github.com/vmware/vic/lib/apiservers/engine/backends/cache"
viccontainer "github.com/vmware/vic/lib/apiservers/engine/backends/container"
"github.com/vmware/vic/lib/apiservers/engine/backends/convert"
epoint "github.com/vmware/vic/lib/apiservers/engine/backends/endpoint"
"github.com/vmware/vic/lib/apiservers/engine/backends/filter"
engconstants "github.com/vmware/vic/lib/apiservers/engine/constants"
"github.com/vmware/vic/lib/apiservers/engine/errors"
"github.com/vmware/vic/lib/apiservers/engine/network"
"github.com/vmware/vic/lib/apiservers/portlayer/client"
"github.com/vmware/vic/lib/apiservers/portlayer/client/containers"
"github.com/vmware/vic/lib/apiservers/portlayer/client/interaction"
"github.com/vmware/vic/lib/apiservers/portlayer/client/logging"
"github.com/vmware/vic/lib/apiservers/portlayer/client/scopes"
"github.com/vmware/vic/lib/apiservers/portlayer/client/tasks"
"github.com/vmware/vic/lib/apiservers/portlayer/models"
"github.com/vmware/vic/lib/constants"
"github.com/vmware/vic/lib/metadata"
"github.com/vmware/vic/pkg/trace"
"github.com/vmware/vic/pkg/vsphere/sys"
)
// VicContainerProxy interface
type VicContainerProxy interface {
CreateContainerHandle(ctx context.Context, vc *viccontainer.VicContainer, config types.ContainerCreateConfig) (string, string, error)
CreateContainerTask(ctx context.Context, handle string, id string, config types.ContainerCreateConfig) (string, error)
CreateExecTask(ctx context.Context, handle string, config *types.ExecConfig) (string, string, error)
AddContainerToScope(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error)
AddLoggingToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error)
AddInteractionToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error)
BindInteraction(ctx context.Context, handle string, name string, id string) (string, error)
UnbindInteraction(ctx context.Context, handle string, name string, id string) (string, error)
UnbindContainerFromNetwork(ctx context.Context, vc *viccontainer.VicContainer, handle string) (string, error)
CommitContainerHandle(ctx context.Context, handle, containerID string, waitTime int32) error
// TODO: we should not be returning a swagger model here, however we do not have a solid architected return for this yet.
InspectTask(op trace.Operation, handle string, eid string, cid string) (*models.TaskInspectResponse, error)
BindTask(op trace.Operation, handle string, eid string) (string, error)
WaitTask(op trace.Operation, handle string, cid string, eid string) error
Handle(ctx context.Context, id, name string) (string, error)
Stop(ctx context.Context, vc *viccontainer.VicContainer, name string, seconds *int, unbound bool) error
State(ctx context.Context, vc *viccontainer.VicContainer) (*types.ContainerState, error)
GetStateFromHandle(op trace.Operation, handle string) (string, string, error)
Wait(ctx context.Context, vc *viccontainer.VicContainer, timeout time.Duration) (*types.ContainerState, error)
Signal(ctx context.Context, vc *viccontainer.VicContainer, sig uint64) error
Resize(ctx context.Context, id string, height, width int32) error
Rename(ctx context.Context, vc *viccontainer.VicContainer, newName string) error
Remove(ctx context.Context, vc *viccontainer.VicContainer, config *types.ContainerRmConfig) error
ExitCode(ctx context.Context, vc *viccontainer.VicContainer) (string, error)
}
// ContainerProxy struct
type ContainerProxy struct {
client *client.PortLayer
portlayerAddr string
portlayerName string
}
const (
forceLogType = "json-file" //Use in inspect to allow docker logs to work
ShortIDLen = 12
ContainerRunning = "running"
ContainerError = "error"
ContainerStopped = "stopped"
ContainerExited = "exited"
ContainerCreated = "created"
)
// NewContainerProxy will create a new proxy
func NewContainerProxy(plClient *client.PortLayer, portlayerAddr string, portlayerName string) *ContainerProxy {
return &ContainerProxy{client: plClient, portlayerAddr: portlayerAddr, portlayerName: portlayerName}
}
// Handle retrieves a handle to a VIC container. Handles should be treated as opaque strings.
//
// returns:
// (handle string, error)
func (c *ContainerProxy) Handle(ctx context.Context, id, name string) (string, error) {
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
resp, err := c.client.Containers.Get(containers.NewGetParamsWithContext(ctx).WithID(id))
if err != nil {
switch err := err.(type) {
case *containers.GetNotFound:
cache.ContainerCache().DeleteContainer(id)
return "", errors.NotFoundError(name)
case *containers.GetDefault:
return "", errors.InternalServerError(err.Payload.Message)
default:
return "", errors.InternalServerError(err.Error())
}
}
return resp.Payload, nil
}
// CreateContainerHandle creates a new VIC container by calling the portlayer
//
// returns:
// (containerID, containerHandle, error)
func (c *ContainerProxy) CreateContainerHandle(ctx context.Context, vc *viccontainer.VicContainer, config types.ContainerCreateConfig) (string, string, error) {
defer trace.End(trace.Begin(vc.ImageID))
if c.client == nil {
return "", "", errors.NillPortlayerClientError("ContainerProxy")
}
if vc.ImageID == "" {
return "", "", errors.NotFoundError("No image specified")
}
if vc.LayerID == "" {
return "", "", errors.NotFoundError("No layer specified")
}
// Call the Exec port layer to create the container
host, err := sys.UUID()
if err != nil {
return "", "", errors.InternalServerError("ContainerProxy.CreateContainerHandle got unexpected error getting VCH UUID")
}
plCreateParams := dockerContainerCreateParamsToPortlayer(ctx, config, vc, host)
createResults, err := c.client.Containers.Create(plCreateParams)
if err != nil {
if _, ok := err.(*containers.CreateNotFound); ok {
cerr := fmt.Errorf("No such image: %s", vc.ImageID)
log.Errorf("%s (%s)", cerr, err)
return "", "", errors.NotFoundError(cerr.Error())
}
// If we get here, most likely something went wrong with the port layer API server
return "", "", errors.InternalServerError(err.Error())
}
id := createResults.Payload.ID
h := createResults.Payload.Handle
return id, h, nil
}
// CreateContainerTask sets the primary command to run in the container
//
// returns:
// (containerHandle, error)
func (c *ContainerProxy) CreateContainerTask(ctx context.Context, handle, id string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(""))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
plTaskParams := dockerContainerCreateParamsToTask(ctx, id, config)
plTaskParams.Config.Handle = handle
responseJoin, err := c.client.Tasks.Join(plTaskParams)
if err != nil {
log.Errorf("Unable to join primary task to container: %+v", err)
return "", errors.InternalServerError(err.Error())
}
handle, ok := responseJoin.Payload.Handle.(string)
if !ok {
return "", errors.InternalServerError(fmt.Sprintf("Type assertion failed on handle from task join: %#+v", handle))
}
plBindParams := tasks.NewBindParamsWithContext(ctx).WithConfig(&models.TaskBindConfig{Handle: handle, ID: id})
responseBind, err := c.client.Tasks.Bind(plBindParams)
if err != nil {
log.Errorf("Unable to bind primary task to container: %+v", err)
return "", errors.InternalServerError(err.Error())
}
handle, ok = responseBind.Payload.Handle.(string)
if !ok {
return "", errors.InternalServerError(fmt.Sprintf("Type assertion failed on handle from task bind %#+v", handle))
}
return handle, nil
}
func (c *ContainerProxy) CreateExecTask(ctx context.Context, handle string, config *types.ExecConfig) (string, string, error) {
defer trace.End(trace.Begin(""))
if c.client == nil {
return "", "", errors.NillPortlayerClientError("ContainerProxy")
}
joinconfig := &models.TaskJoinConfig{
Handle: handle,
Path: config.Cmd[0],
Args: config.Cmd[1:],
Env: config.Env,
User: config.User,
Attach: config.AttachStdin || config.AttachStdout || config.AttachStderr,
OpenStdin: config.AttachStdin,
Tty: config.Tty,
}
// call Join with JoinParams
joinparams := tasks.NewJoinParamsWithContext(ctx).WithConfig(joinconfig)
resp, err := c.client.Tasks.Join(joinparams)
if err != nil {
return "", "", errors.InternalServerError(err.Error())
}
eid := resp.Payload.ID
handleprime, ok := resp.Payload.Handle.(string)
if !ok {
return "", "", errors.InternalServerError(fmt.Sprintf("Type assertion failed on handle from task bind %#+v", handleprime))
}
return handleprime, eid, nil
}
// AddContainerToScope adds a container, referenced by handle, to a scope.
// If an error is return, the returned handle should not be used.
//
// returns:
// modified handle
func (c *ContainerProxy) AddContainerToScope(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
log.Debugf("Network Configuration Section - Container Create")
// configure network
netConf := toModelsNetworkConfig(config)
if netConf != nil {
addContRes, err := c.client.Scopes.AddContainer(scopes.NewAddContainerParamsWithContext(ctx).
WithScope(netConf.NetworkName).
WithConfig(&models.ScopesAddContainerConfig{
Handle: handle,
NetworkConfig: netConf,
}))
if err != nil {
log.Errorf("ContainerProxy.AddContainerToScope: Scopes error: %s", err.Error())
return handle, errors.InternalServerError(err.Error())
}
defer func() {
if err == nil {
return
}
// roll back the AddContainer call
if _, err2 := c.client.Scopes.RemoveContainer(scopes.NewRemoveContainerParamsWithContext(ctx).WithHandle(handle).WithScope(netConf.NetworkName)); err2 != nil {
log.Warnf("could not roll back container add: %s", err2)
}
}()
handle = addContRes.Payload
}
return handle, nil
}
// AddLoggingToContainer adds logging capability to a container, referenced by handle.
// If an error is return, the returned handle should not be used.
//
// returns:
// modified handle
func (c *ContainerProxy) AddLoggingToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
response, err := c.client.Logging.LoggingJoin(logging.NewLoggingJoinParamsWithContext(ctx).
WithConfig(&models.LoggingJoinConfig{
Handle: handle,
}))
if err != nil {
return "", errors.InternalServerError(err.Error())
}
handle, ok := response.Payload.Handle.(string)
if !ok {
return "", errors.InternalServerError(fmt.Sprintf("Type assertion failed for %#+v", handle))
}
return handle, nil
}
// AddInteractionToContainer adds interaction capabilities to a container, referenced by handle.
// If an error is return, the returned handle should not be used.
//
// returns:
// modified handle
func (c *ContainerProxy) AddInteractionToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
response, err := c.client.Interaction.InteractionJoin(interaction.NewInteractionJoinParamsWithContext(ctx).
WithConfig(&models.InteractionJoinConfig{
Handle: handle,
}))
if err != nil {
return "", errors.InternalServerError(err.Error())
}
handle, ok := response.Payload.Handle.(string)
if !ok {
return "", errors.InternalServerError(fmt.Sprintf("Type assertion failed for %#+v", handle))
}
return handle, nil
}
// BindInteraction enables interaction capabilities
func (c *ContainerProxy) BindInteraction(ctx context.Context, handle string, name string, id string) (string, error) {
defer trace.End(trace.Begin(handle))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
bind, err := c.client.Interaction.InteractionBind(
interaction.NewInteractionBindParamsWithContext(ctx).
WithConfig(&models.InteractionBindConfig{
Handle: handle,
ID: id,
}))
if err != nil {
switch err := err.(type) {
case *interaction.InteractionBindInternalServerError:
return "", errors.InternalServerError(err.Payload.Message)
default:
return "", errors.InternalServerError(err.Error())
}
}
handle, ok := bind.Payload.Handle.(string)
if !ok {
return "", errors.InternalServerError(fmt.Sprintf("Type assertion failed for %#+v", handle))
}
return handle, nil
}
// UnbindInteraction disables interaction capabilities
func (c *ContainerProxy) UnbindInteraction(ctx context.Context, handle string, name string, id string) (string, error) {
defer trace.End(trace.Begin(handle))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
unbind, err := c.client.Interaction.InteractionUnbind(
interaction.NewInteractionUnbindParamsWithContext(ctx).
WithConfig(&models.InteractionUnbindConfig{
Handle: handle,
ID: id,
}))
if err != nil {
return "", errors.InternalServerError(err.Error())
}
handle, ok := unbind.Payload.Handle.(string)
if !ok {
return "", errors.InternalServerError("type assertion failed")
}
return handle, nil
}
// CommitContainerHandle commits any changes to container handle.
//
// Args:
// waitTime <= 0 means no wait time
func (c *ContainerProxy) CommitContainerHandle(ctx context.Context, handle, containerID string, waitTime int32) error {
defer trace.End(trace.Begin(handle))
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
var commitParams *containers.CommitParams
if waitTime > 0 {
commitParams = containers.NewCommitParamsWithContext(ctx).WithHandle(handle).WithWaitTime(&waitTime)
} else {
commitParams = containers.NewCommitParamsWithContext(ctx).WithHandle(handle)
}
_, err := c.client.Containers.Commit(commitParams)
if err != nil {
switch err := err.(type) {
case *containers.CommitNotFound:
return errors.NotFoundError(containerID)
case *containers.CommitConflict:
return errors.ConflictError(err.Error())
case *containers.CommitDefault:
return errors.InternalServerError(err.Payload.Message)
default:
return errors.InternalServerError(err.Error())
}
}
return nil
}
func (c *ContainerProxy) InspectTask(op trace.Operation, handle string, eid string, cid string) (*models.TaskInspectResponse, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s), eid(%s), cid(%s)", handle, eid, cid)))
if c.client == nil {
return nil, errors.NillPortlayerClientError("ContainerProxy")
}
// inspect the Task to obtain ProcessConfig
config := &models.TaskInspectConfig{
Handle: handle,
ID: eid,
}
// FIXME: right now we are only using this path for exec targets. But later the error messages may need to be changed
// to be more accurate.
params := tasks.NewInspectParamsWithContext(op).WithConfig(config)
resp, err := c.client.Tasks.Inspect(params)
if err != nil {
switch err := err.(type) {
case *tasks.InspectNotFound:
// These error types may need to be expanded. NotFoundError does not fit here.
op.Errorf("received a TaskNotFound error during task inspect: %s", err.Payload.Message)
return nil, errors.TaskPoweredOffError(cid)
case *tasks.InspectInternalServerError:
op.Errorf("received an internal server error during task inspect: %s", err.Payload.Message)
return nil, errors.InternalServerError(err.Payload.Message)
default:
// right now Task inspection in the portlayer does not return a conflict error
return nil, errors.InternalServerError(err.Error())
}
}
return resp.Payload, nil
}
func (c *ContainerProxy) BindTask(op trace.Operation, handle string, eid string) (string, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s), eid(%s)", handle, eid)))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
bindconfig := &models.TaskBindConfig{
Handle: handle,
ID: eid,
}
bindparams := tasks.NewBindParamsWithContext(op).WithConfig(bindconfig)
// call Bind with bindparams
resp, err := c.client.Tasks.Bind(bindparams)
if err != nil {
switch err := err.(type) {
case *tasks.BindNotFound:
op.Errorf("received TaskNotFound error during task bind: %s", err.Payload.Message)
return "", errors.TaskBindPowerError()
case *tasks.BindInternalServerError:
op.Errorf("received unexpected error attempting to bind task(%s) for handle(%s): %s", eid, handle, err.Payload.Message)
return "", errors.InternalServerError(err.Payload.Message)
default:
op.Errorf("received unexpected error attempting to bind task(%s) for handle(%s): %s", eid, handle, err.Error())
return "", errors.InternalServerError(err.Error())
}
}
respHandle, ok := resp.Payload.Handle.(string)
if !ok {
op.Errorf("Unable to marshal string object from BindTask response for handle(%s) on eid(%s)", handle, eid)
// TODO: perhaps a better error message here?
return "", errors.InternalServerError("An unknown error occurred during the handling of this request")
}
return respHandle, nil
}
func (c *ContainerProxy) WaitTask(op trace.Operation, handle string, cid string, eid string) error {
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
// wait for the Task to change in state
config := &models.TaskWaitConfig{
Handle: handle,
ID: eid,
}
params := tasks.NewWaitParamsWithContext(op).WithConfig(config)
_, err := c.client.Tasks.Wait(params)
if err != nil {
switch err := err.(type) {
case *tasks.WaitNotFound:
return errors.InternalServerError(fmt.Sprintf("the container(%s) has been shutdown during execution of the exec operation", cid))
case *tasks.WaitPreconditionRequired:
return errors.InternalServerError(fmt.Sprintf("container(%s) must be powered on in order to perform the desired exec operation", cid))
case *tasks.WaitInternalServerError:
return errors.InternalServerError(err.Payload.Message)
default:
return errors.InternalServerError(err.Error())
}
}
return nil
}
// Stop will stop (shutdown) a VIC container.
//
// returns
// error
func (c *ContainerProxy) Stop(ctx context.Context, vc *viccontainer.VicContainer, name string, seconds *int, unbound bool) error {
defer trace.End(trace.Begin(vc.ContainerID))
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
//retrieve client to portlayer
handle, err := c.Handle(context.TODO(), vc.ContainerID, name)
if err != nil {
return err
}
// we have a container on the PL side lets check the state before proceeding
// ignore the error since others will be checking below..this is an attempt to short circuit the op
// TODO: can be replaced with simple cache check once power events are propagated to persona
state, err := c.State(ctx, vc)
if err != nil && errors.IsNotFoundError(err) {
cache.ContainerCache().DeleteContainer(vc.ContainerID)
return err
}
// attempt to stop container only if container state is not stopped, exited or created.
// we should allow user to stop and remove the container that is in unexpected status, e.g. starting, because of serial port connection issue
if state.Status == ContainerStopped || state.Status == ContainerExited || state.Status == ContainerCreated {
return nil
}
if unbound {
handle, err = c.UnbindContainerFromNetwork(ctx, vc, handle)
if err != nil {
return err
}
// unmap ports
if err = network.UnmapPorts(vc.ContainerID, vc); err != nil {
return err
}
}
// change the state of the container
changeParams := containers.NewStateChangeParamsWithContext(ctx).WithHandle(handle).WithState("STOPPED")
stateChangeResponse, err := c.client.Containers.StateChange(changeParams)
if err != nil {
switch err := err.(type) {
case *containers.StateChangeNotFound:
cache.ContainerCache().DeleteContainer(vc.ContainerID)
return errors.NotFoundError(name)
case *containers.StateChangeDefault:
return errors.InternalServerError(err.Payload.Message)
default:
return errors.InternalServerError(err.Error())
}
}
handle = stateChangeResponse.Payload
// if no timeout in seconds provided then set to default of 10
if seconds == nil {
s := 10
seconds = &s
}
err = c.CommitContainerHandle(ctx, handle, vc.ContainerID, int32(*seconds))
if err != nil {
if errors.IsNotFoundError(err) {
cache.ContainerCache().DeleteContainer(vc.ContainerID)
}
return err
}
return nil
}
// UnbindContainerFromNetwork unbinds a container from the networks that it connects to
func (c *ContainerProxy) UnbindContainerFromNetwork(ctx context.Context, vc *viccontainer.VicContainer, handle string) (string, error) {
defer trace.End(trace.Begin(vc.ContainerID))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
unbindParams := scopes.NewUnbindContainerParamsWithContext(ctx).WithHandle(handle)
ub, err := c.client.Scopes.UnbindContainer(unbindParams)
if err != nil {
switch err := err.(type) {
case *scopes.UnbindContainerNotFound:
// ignore error
log.Warnf("Container %s not found by network unbind", vc.ContainerID)
case *scopes.UnbindContainerInternalServerError:
return "", errors.InternalServerError(err.Payload.Message)
default:
return "", errors.InternalServerError(err.Error())
}
}
return ub.Payload.Handle, nil
}
// State returns container state
func (c *ContainerProxy) State(ctx context.Context, vc *viccontainer.VicContainer) (*types.ContainerState, error) {
defer trace.End(trace.Begin(""))
if c.client == nil {
return nil, errors.NillPortlayerClientError("ContainerProxy")
}
results, err := c.client.Containers.GetContainerInfo(containers.NewGetContainerInfoParamsWithContext(ctx).WithID(vc.ContainerID))
if err != nil {
switch err := err.(type) {
case *containers.GetContainerInfoNotFound:
return nil, errors.NotFoundError(vc.Name)
case *containers.GetContainerInfoInternalServerError:
return nil, errors.InternalServerError(err.Payload.Message)
default:
return nil, errors.InternalServerError(fmt.Sprintf("Unknown error from the interaction port layer: %s", err))
}
}
inspectJSON, err := ContainerInfoToDockerContainerInspect(vc, results.Payload, c.portlayerName)
if err != nil {
return nil, err
}
return inspectJSON.State, nil
}
// GetStateFromHandle takes a handle and returns the state of the container based on that handle. Also returns handle that comes back with the response.
func (c *ContainerProxy) GetStateFromHandle(op trace.Operation, handle string) (string, string, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s)", handle), op))
if c.client == nil {
return "", "", errors.NillPortlayerClientError("ContainerProxy")
}
params := containers.NewGetStateParams().WithHandle(handle)
resp, err := c.client.Containers.GetState(params)
if err != nil {
switch err := err.(type) {
case *containers.GetStateNotFound:
return handle, "", errors.NotFoundError(err.Payload.Message)
default:
return handle, "", errors.InternalServerError(err.Error())
}
}
return resp.Payload.Handle, resp.Payload.State, nil
}
// ExitCode returns container exitCode
func (c *ContainerProxy) ExitCode(ctx context.Context, vc *viccontainer.VicContainer) (string, error) {
defer trace.End(trace.Begin(""))
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
results, err := c.client.Containers.GetContainerInfo(containers.NewGetContainerInfoParamsWithContext(ctx).WithID(vc.ContainerID))
if err != nil {
switch err := err.(type) {
case *containers.GetContainerInfoNotFound:
return "", errors.NotFoundError(vc.Name)
case *containers.GetContainerInfoInternalServerError:
return "", errors.InternalServerError(err.Payload.Message)
default:
return "", errors.InternalServerError(fmt.Sprintf("Unknown error from the interaction port layer: %s", err))
}
}
// get the container state
dockerState := convert.State(results.Payload)
if dockerState == nil {
return "", errors.InternalServerError("Unable to determine container state")
}
return strconv.Itoa(dockerState.ExitCode), nil
}
func (c *ContainerProxy) Wait(ctx context.Context, vc *viccontainer.VicContainer, timeout time.Duration) (
*types.ContainerState, error) {
defer trace.End(trace.Begin(vc.ContainerID))
if vc == nil {
return nil, errors.InternalServerError("Wait bad arguments")
}
// Get an API client to the portlayer
if c.client == nil {
return nil, errors.NillPortlayerClientError("ContainerProxy")
}
params := containers.NewContainerWaitParamsWithContext(ctx).
WithTimeout(int64(timeout.Seconds())).
WithID(vc.ContainerID)
results, err := c.client.Containers.ContainerWait(params)
if err != nil {
switch err := err.(type) {
case *containers.ContainerWaitNotFound:
// since the container wasn't found on the PL lets remove from the local
// cache
cache.ContainerCache().DeleteContainer(vc.ContainerID)
return nil, errors.NotFoundError(vc.ContainerID)
case *containers.ContainerWaitInternalServerError:
return nil, errors.InternalServerError(err.Payload.Message)
default:
return nil, errors.InternalServerError(err.Error())
}
}
if results == nil || results.Payload == nil {
return nil, errors.InternalServerError("Unexpected swagger error")
}
dockerState := convert.State(results.Payload)
if dockerState == nil {
return nil, errors.InternalServerError("Unable to determine container state")
}
return dockerState, nil
}
func (c *ContainerProxy) Signal(ctx context.Context, vc *viccontainer.VicContainer, sig uint64) error {
defer trace.End(trace.Begin(vc.ContainerID))
if vc == nil {
return errors.InternalServerError("Signal bad arguments")
}
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
if state, err := c.State(ctx, vc); !state.Running && err == nil {
return fmt.Errorf("%s is not running", vc.ContainerID)
}
// If Docker CLI sends sig == 0, we use sigkill
if sig == 0 {
sig = uint64(syscall.SIGKILL)
}
params := containers.NewContainerSignalParamsWithContext(ctx).WithID(vc.ContainerID).WithSignal(int64(sig))
if _, err := c.client.Containers.ContainerSignal(params); err != nil {
switch err := err.(type) {
case *containers.ContainerSignalNotFound:
return errors.NotFoundError(vc.ContainerID)
case *containers.ContainerSignalInternalServerError:
return errors.InternalServerError(err.Payload.Message)
default:
return errors.InternalServerError(err.Error())
}
}
if state, err := c.State(ctx, vc); !state.Running && err == nil {
// unmap ports
if err = network.UnmapPorts(vc.ContainerID, vc); err != nil {
return err
}
}
return nil
}
func (c *ContainerProxy) Resize(ctx context.Context, id string, height, width int32) error {
defer trace.End(trace.Begin(id))
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
plResizeParam := interaction.NewContainerResizeParamsWithContext(ctx).
WithID(id).
WithHeight(height).
WithWidth(width)
_, err := c.client.Interaction.ContainerResize(plResizeParam)
if err != nil {
if _, isa := err.(*interaction.ContainerResizeNotFound); isa {
return errors.ContainerResourceNotFoundError(id, "interaction connection")
}
// If we get here, most likely something went wrong with the port layer API server
return errors.InternalServerError(err.Error())
}
return nil
}
// Rename calls the portlayer's RenameContainerHandler to update the container name in the handle,
// and then commit the new name to vSphere
func (c *ContainerProxy) Rename(ctx context.Context, vc *viccontainer.VicContainer, newName string) error {
defer trace.End(trace.Begin(vc.ContainerID))
//retrieve client to portlayer
handle, err := c.Handle(context.TODO(), vc.ContainerID, vc.Name)
if err != nil {
return err
}
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
// Call the rename functionality in the portlayer.
renameParams := containers.NewContainerRenameParamsWithContext(ctx).WithName(newName).WithHandle(handle)
result, err := c.client.Containers.ContainerRename(renameParams)
if err != nil {
switch err := err.(type) {
// Here we don't check the portlayer error type for *containers.ContainerRenameConflict since
// (1) we already check that in persona cache for ConflictError and
// (2) the container name in portlayer cache will be updated when committing the handle in the next step
case *containers.ContainerRenameNotFound:
return errors.NotFoundError(vc.Name)
default:
return errors.InternalServerError(err.Error())
}
}
h := result.Payload
// commit handle
_, err = c.client.Containers.Commit(containers.NewCommitParamsWithContext(ctx).WithHandle(h))
if err != nil {
switch err := err.(type) {
case *containers.CommitNotFound:
return errors.NotFoundError(err.Payload.Message)
case *containers.CommitConflict:
return errors.ConflictError(err.Payload.Message)
default:
return errors.InternalServerError(err.Error())
}
}
return nil
}
// Remove calls the portlayer's ContainerRemove handler to remove the container and its
// anonymous volumes if the remove flag is set.
func (c *ContainerProxy) Remove(ctx context.Context, vc *viccontainer.VicContainer, config *types.ContainerRmConfig) error {
defer trace.End(trace.Begin(vc.ContainerID))
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
id := vc.ContainerID
_, err := c.client.Containers.ContainerRemove(containers.NewContainerRemoveParamsWithContext(ctx).WithID(id))
if err != nil {
switch err := err.(type) {
case *containers.ContainerRemoveNotFound:
// Remove container from persona cache, but don't return error to the user.
cache.ContainerCache().DeleteContainer(id)
return nil
case *containers.ContainerRemoveDefault:
return errors.InternalServerError(err.Payload.Message)
case *containers.ContainerRemoveConflict:
return derr.NewRequestConflictError(fmt.Errorf("You cannot remove a running container. Stop the container before attempting removal or use -f"))
case *containers.ContainerRemoveInternalServerError:
if err.Payload == nil || err.Payload.Message == "" {
return errors.InternalServerError(err.Error())
}
return errors.InternalServerError(err.Payload.Message)
default:
return errors.InternalServerError(err.Error())
}
}
// Once the container is removed, remove anonymous volumes (vc.Config.Volumes) if
// the remove flag is set.
if config.RemoveVolume && len(vc.Config.Volumes) > 0 {
RemoveAnonContainerVols(ctx, c.client, id, vc)
}
return nil
}
//----------
// Utility Functions
//----------
func dockerContainerCreateParamsToTask(ctx context.Context, id string, cc types.ContainerCreateConfig) *tasks.JoinParams {
config := &models.TaskJoinConfig{}
var path string
var args []string
// we explicitly specify the ID for the primary task so that it's the same as the containerID
config.ID = id
// Expand cmd into entrypoint and args
cmd := strslice.StrSlice(cc.Config.Cmd)
if len(cc.Config.Entrypoint) != 0 {
path, args = cc.Config.Entrypoint[0], append(cc.Config.Entrypoint[1:], cmd...)
} else {
path, args = cmd[0], cmd[1:]
}
// copy the path
config.Path = path
// copy the args
config.Args = make([]string, len(args))
copy(config.Args, args)
// copy the env array
config.Env = make([]string, len(cc.Config.Env))
copy(config.Env, cc.Config.Env)
// working dir
config.WorkingDir = cc.Config.WorkingDir
// user
config.User = cc.Config.User
// attach. Always set to true otherwise we cannot attach later.
// this tells portlayer container is attachable.
config.Attach = true
// openstdin
config.OpenStdin = cc.Config.OpenStdin
// tty
config.Tty = cc.Config.Tty
// container stop signal
config.StopSignal = cc.Config.StopSignal
log.Debugf("dockerContainerCreateParamsToTask = %+v", config)
return tasks.NewJoinParamsWithContext(ctx).WithConfig(config)
}
func dockerContainerCreateParamsToPortlayer(ctx context.Context, cc types.ContainerCreateConfig, vc *viccontainer.VicContainer, imageStore string) *containers.CreateParams {
config := &models.ContainerCreateConfig{}
config.NumCpus = cc.HostConfig.CPUCount
config.MemoryMB = cc.HostConfig.Memory