forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
volume.go
975 lines (882 loc) · 31.6 KB
/
volume.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
package set
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path"
"regexp"
"strconv"
"strings"
"github.com/golang/glog"
"github.com/spf13/cobra"
"k8s.io/api/core/v1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
kresource "k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/storage/names"
kapi "k8s.io/kubernetes/pkg/apis/core"
kcoreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
"k8s.io/kubernetes/pkg/kubectl/categories"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
"github.com/openshift/origin/pkg/oc/cli/util/clientcmd"
)
const (
volumePrefix = "volume-"
storageAnnClass = "volume.beta.kubernetes.io/storage-class"
)
var (
volumeLong = templates.LongDesc(`
Update volumes on a pod template
This command can add, update or remove volumes from containers for any object
that has a pod template (deployment configs, replication controllers, or pods).
You can list volumes in pod or any object that has a pod template. You can
specify a single object or multiple, and alter volumes on all containers or
just those that match a given name.
If you alter a volume setting on a deployment config, a deployment will be
triggered. Changing a replication controller will not affect running pods, and
you cannot change a pod's volumes once it has been created.
Volume types include:
* emptydir (empty directory) *default*: A directory allocated when the pod is
created on a local host, is removed when the pod is deleted and is not copied
across servers
* hostdir (host directory): A directory with specific path on any host
(requires elevated privileges)
* persistentvolumeclaim or pvc (persistent volume claim): Link the volume
directory in the container to a persistent volume claim you have allocated by
name - a persistent volume claim is a request to allocate storage. Note that
if your claim hasn't been bound, your pods will not start.
* secret (mounted secret): Secret volumes mount a named secret to the provided
directory.
For descriptions on other volume types, see https://docs.openshift.com`)
volumeExample = templates.Examples(`
# List volumes defined on all deployment configs in the current project
%[1]s volume dc --all
# Add a new empty dir volume to deployment config (dc) 'registry' mounted under
# /var/lib/registry
%[1]s volume dc/registry --add --mount-path=/var/lib/registry
# Use an existing persistent volume claim (pvc) to overwrite an existing volume 'v1'
%[1]s volume dc/registry --add --name=v1 -t pvc --claim-name=pvc1 --overwrite
# Remove volume 'v1' from deployment config 'registry'
%[1]s volume dc/registry --remove --name=v1
# Create a new persistent volume claim that overwrites an existing volume 'v1'
%[1]s volume dc/registry --add --name=v1 -t pvc --claim-size=1G --overwrite
# Change the mount point for volume 'v1' to /data
%[1]s volume dc/registry --add --name=v1 -m /data --overwrite
# Modify the deployment config by removing volume mount "v1" from container "c1"
# (and by removing the volume "v1" if no other containers have volume mounts that reference it)
%[1]s volume dc/registry --remove --name=v1 --containers=c1
# Add new volume based on a more complex volume source (Git repo, AWS EBS, GCE PD,
# Ceph, Gluster, NFS, ISCSI, ...)
%[1]s volume dc/registry --add -m /repo --source=<json-string>`)
)
type VolumeOptions struct {
DefaultNamespace string
ExplicitNamespace bool
Out io.Writer
Err io.Writer
Mapper meta.RESTMapper
Typer runtime.ObjectTyper
CategoryExpander categories.CategoryExpander
RESTClientFactory func(mapping *meta.RESTMapping) (resource.RESTClient, error)
UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error)
Client kcoreclient.PersistentVolumeClaimsGetter
Encoder runtime.Encoder
Cmd *cobra.Command
// Resource selection
Selector string
All bool
Filenames []string
// Operations
Add bool
Remove bool
List bool
// Common optional params
Name string
Containers string
Confirm bool
Local bool
Output string
PrintObject func([]*resource.Info) error
// Add op params
AddOpts *AddVolumeOptions
}
type AddVolumeOptions struct {
Type string
MountPath string
SubPath string
DefaultMode string
Overwrite bool
Path string
ConfigMapName string
SecretName string
Source string
CreateClaim bool
ClaimName string
ClaimSize string
ClaimMode string
ClaimClass string
TypeChanged bool
}
func NewCmdVolume(fullName string, f *clientcmd.Factory, out, errOut io.Writer) *cobra.Command {
addOpts := &AddVolumeOptions{}
opts := &VolumeOptions{
AddOpts: addOpts,
Out: out,
Err: errOut,
}
cmd := &cobra.Command{
Use: "volumes RESOURCE/NAME --add|--remove|--list",
Short: "Update volumes on a pod template",
Long: volumeLong,
Example: fmt.Sprintf(volumeExample, fullName),
Aliases: []string{"volume"},
Run: func(cmd *cobra.Command, args []string) {
addOpts.TypeChanged = cmd.Flag("type").Changed
kcmdutil.CheckErr(opts.Complete(f, cmd))
err := opts.Validate(cmd, args)
if err != nil {
kcmdutil.CheckErr(kcmdutil.UsageErrorf(cmd, err.Error()))
}
err = opts.RunVolume(args, f)
if err == kcmdutil.ErrExit {
os.Exit(1)
}
kcmdutil.CheckErr(err)
},
}
cmd.Flags().StringVarP(&opts.Selector, "selector", "l", "", "Selector (label query) to filter on")
cmd.Flags().BoolVar(&opts.All, "all", false, "If true, select all resources in the namespace of the specified resource types")
cmd.Flags().StringSliceVarP(&opts.Filenames, "filename", "f", opts.Filenames, "Filename, directory, or URL to file to use to edit the resource.")
cmd.Flags().BoolVar(&opts.Add, "add", false, "If true, add volume and/or volume mounts for containers")
cmd.Flags().BoolVar(&opts.Remove, "remove", false, "If true, remove volume and/or volume mounts for containers")
cmd.Flags().BoolVar(&opts.List, "list", false, "If true, list volumes and volume mounts for containers")
cmd.Flags().BoolVar(&opts.Local, "local", false, "If true, set image will NOT contact api-server but run locally.")
cmd.Flags().StringVar(&opts.Name, "name", "", "Name of the volume. If empty, auto generated for add operation")
cmd.Flags().StringVarP(&opts.Containers, "containers", "c", "*", "The names of containers in the selected pod templates to change - may use wildcards")
cmd.Flags().BoolVar(&opts.Confirm, "confirm", false, "If true, confirm that you really want to remove multiple volumes")
cmd.Flags().StringVarP(&addOpts.Type, "type", "t", "", "Type of the volume source for add operation. Supported options: emptyDir, hostPath, secret, configmap, persistentVolumeClaim")
cmd.Flags().StringVarP(&addOpts.MountPath, "mount-path", "m", "", "Mount path inside the container. Optional param for --add or --remove")
cmd.Flags().StringVar(&addOpts.SubPath, "sub-path", "", "Path within the local volume from which the container's volume should be mounted. Optional param for --add or --remove")
cmd.Flags().StringVarP(&addOpts.DefaultMode, "default-mode", "", "", "The default mode bits to create files with. Can be between 0000 and 0777. Defaults to 0644.")
cmd.Flags().BoolVar(&addOpts.Overwrite, "overwrite", false, "If true, replace existing volume source with the provided name and/or volume mount for the given resource")
cmd.Flags().StringVar(&addOpts.Path, "path", "", "Host path. Must be provided for hostPath volume type")
cmd.Flags().StringVar(&addOpts.ConfigMapName, "configmap-name", "", "Name of the persisted config map. Must be provided for configmap volume type")
cmd.Flags().StringVar(&addOpts.SecretName, "secret-name", "", "Name of the persisted secret. Must be provided for secret volume type")
cmd.Flags().StringVar(&addOpts.ClaimName, "claim-name", "", "Persistent volume claim name. Must be provided for persistentVolumeClaim volume type")
cmd.Flags().StringVar(&addOpts.ClaimClass, "claim-class", "", "StorageClass to use for the persistent volume claim")
cmd.Flags().StringVar(&addOpts.ClaimSize, "claim-size", "", "If specified along with a persistent volume type, create a new claim with the given size in bytes. Accepts SI notation: 10, 10G, 10Gi")
cmd.Flags().StringVar(&addOpts.ClaimMode, "claim-mode", "ReadWriteOnce", "Set the access mode of the claim to be created. Valid values are ReadWriteOnce (rwo), ReadWriteMany (rwm), or ReadOnlyMany (rom)")
cmd.Flags().StringVar(&addOpts.Source, "source", "", "Details of volume source as json string. This can be used if the required volume type is not supported by --type option. (e.g.: '{\"gitRepo\": {\"repository\": <git-url>, \"revision\": <commit-hash>}}')")
kcmdutil.AddDryRunFlag(cmd)
kcmdutil.AddPrinterFlags(cmd)
cmd.MarkFlagFilename("filename", "yaml", "yml", "json")
// deprecate --list option
cmd.Flags().MarkDeprecated("list", "Volumes and volume mounts can be listed by providing a resource with no additional options.")
return cmd
}
func (v *VolumeOptions) Validate(cmd *cobra.Command, args []string) error {
if len(v.Selector) > 0 {
if _, err := labels.Parse(v.Selector); err != nil {
return errors.New("--selector=<selector> must be a valid label selector")
}
if v.All {
return errors.New("you may specify either --selector or --all but not both")
}
}
if len(v.Filenames) == 0 && len(args) < 1 {
return errors.New("provide one or more resources to add, list, or delete volumes on as TYPE/NAME")
}
if v.List && len(v.Output) > 0 {
return errors.New("--list and --output may not be specified together")
}
if v.Add {
err := v.AddOpts.Validate()
if err != nil {
return err
}
} else if len(v.AddOpts.Source) > 0 || len(v.AddOpts.Path) > 0 || len(v.AddOpts.SecretName) > 0 ||
len(v.AddOpts.ConfigMapName) > 0 || len(v.AddOpts.ClaimName) > 0 || len(v.AddOpts.DefaultMode) > 0 ||
v.AddOpts.Overwrite {
return errors.New("--type|--path|--configmap-name|--secret-name|--claim-name|--source|--default-mode|--overwrite are only valid for --add operation")
}
// Removing all volumes for the resource type needs confirmation
if v.Remove && len(v.Name) == 0 && !v.Confirm {
return errors.New("must provide --confirm for removing more than one volume")
}
return nil
}
func (a *AddVolumeOptions) Validate() error {
if len(a.Type) == 0 && len(a.Source) == 0 {
return errors.New("must provide --type or --source for --add operation")
} else if a.TypeChanged && len(a.Source) > 0 {
return errors.New("either specify --type or --source but not both for --add operation")
}
if len(a.Type) > 0 {
switch strings.ToLower(a.Type) {
case "emptydir":
case "hostpath":
if len(a.Path) == 0 {
return errors.New("must provide --path for --type=hostPath")
}
case "secret":
if len(a.SecretName) == 0 {
return errors.New("must provide --secret-name for --type=secret")
}
if ok, _ := regexp.MatchString(`\b0?[0-7]{3}\b`, a.DefaultMode); !ok {
return errors.New("--default-mode must be between 0000 and 0777")
}
case "configmap":
if len(a.ConfigMapName) == 0 {
return errors.New("must provide --configmap-name for --type=configmap")
}
if ok, _ := regexp.MatchString(`\b0?[0-7]{3}\b`, a.DefaultMode); !ok {
return errors.New("--default-mode must be between 0000 and 0777")
}
case "persistentvolumeclaim", "pvc":
if len(a.ClaimName) == 0 && len(a.ClaimSize) == 0 {
return errors.New("must provide --claim-name or --claim-size (to create a new claim) for --type=pvc")
}
default:
return errors.New("invalid volume type. Supported types: emptyDir, hostPath, secret, persistentVolumeClaim")
}
} else if len(a.Path) > 0 || len(a.SecretName) > 0 || len(a.ClaimName) > 0 {
return errors.New("--path|--secret-name|--claim-name are only valid for --type option")
}
if len(a.Source) > 0 {
var source map[string]interface{}
err := json.Unmarshal([]byte(a.Source), &source)
if err != nil {
return err
}
if len(source) > 1 {
return errors.New("must provide only one volume for --source")
}
var vs kapi.VolumeSource
err = json.Unmarshal([]byte(a.Source), &vs)
if err != nil {
return err
}
}
if len(a.ClaimClass) > 0 {
selectedLowerType := strings.ToLower(a.Type)
if selectedLowerType != "persistentvolumeclaim" && selectedLowerType != "pvc" {
return errors.New("must provide --type as persistentVolumeClaim")
}
if len(a.ClaimSize) == 0 {
return errors.New("must provide --claim-size to create new pvc with claim-class")
}
}
return nil
}
func (v *VolumeOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command) error {
kc, err := f.ClientSet()
if err != nil {
return err
}
v.Client = kc.Core()
cmdNamespace, explicit, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object()
numOps := 0
if v.Add {
numOps++
}
if v.Remove {
numOps++
}
if v.List {
numOps++
}
switch {
case numOps == 0:
v.List = true
case numOps > 1:
return errors.New("you may only specify one operation at a time")
}
v.Output = kcmdutil.GetFlagString(cmd, "output")
v.PrintObject = func(infos []*resource.Info) error {
return f.PrintResourceInfos(cmd, v.Local, infos, v.Out)
}
v.Cmd = cmd
v.DefaultNamespace = cmdNamespace
v.ExplicitNamespace = explicit
v.Mapper = mapper
v.Typer = typer
v.CategoryExpander = f.CategoryExpander()
v.RESTClientFactory = f.ClientForMapping
v.UpdatePodSpecForObject = f.UpdatePodSpecForObject
v.Encoder = kcmdutil.InternalVersionJSONEncoder()
// Complete AddOpts
if v.Add {
err := v.AddOpts.Complete()
if err != nil {
return err
}
}
return nil
}
func (a *AddVolumeOptions) Complete() error {
if len(a.Type) == 0 {
switch {
case len(a.ClaimName) > 0 || len(a.ClaimSize) > 0:
a.Type = "persistentvolumeclaim"
a.TypeChanged = true
case len(a.SecretName) > 0:
a.Type = "secret"
a.TypeChanged = true
case len(a.ConfigMapName) > 0:
a.Type = "configmap"
a.TypeChanged = true
case len(a.Path) > 0:
a.Type = "hostpath"
a.TypeChanged = true
default:
a.Type = "emptydir"
}
}
if a.Type == "configmap" || a.Type == "secret" {
if len(a.DefaultMode) == 0 {
a.DefaultMode = "644"
}
} else {
if len(a.DefaultMode) != 0 {
return errors.New("--default-mode is only available for secrets and configmaps")
}
}
// In case of volume source ignore the default volume type
if len(a.Source) > 0 {
a.Type = ""
}
if len(a.ClaimSize) > 0 {
a.CreateClaim = true
if len(a.ClaimName) == 0 {
a.ClaimName = names.SimpleNameGenerator.GenerateName("pvc-")
}
q, err := kresource.ParseQuantity(a.ClaimSize)
if err != nil {
return fmt.Errorf("--claim-size is not valid: %v", err)
}
a.ClaimSize = q.String()
}
switch strings.ToLower(a.ClaimMode) {
case strings.ToLower(string(kapi.ReadOnlyMany)), "rom":
a.ClaimMode = string(kapi.ReadOnlyMany)
case strings.ToLower(string(kapi.ReadWriteOnce)), "rwo":
a.ClaimMode = string(kapi.ReadWriteOnce)
case strings.ToLower(string(kapi.ReadWriteMany)), "rwm":
a.ClaimMode = string(kapi.ReadWriteMany)
case "":
default:
return errors.New("--claim-mode must be one of ReadWriteOnce (rwo), ReadWriteMany (rwm), or ReadOnlyMany (rom)")
}
return nil
}
func (v *VolumeOptions) RunVolume(args []string, f *clientcmd.Factory) error {
b := f.NewBuilder().
Internal().
LocalParam(v.Local).
ContinueOnError().
NamespaceParam(v.DefaultNamespace).DefaultNamespace().
FilenameParam(v.ExplicitNamespace, &resource.FilenameOptions{Recursive: false, Filenames: v.Filenames}).
Flatten()
if !v.Local {
b = b.
LabelSelectorParam(v.Selector).
ResourceTypeOrNameArgs(v.All, args...)
}
singleItemImplied := false
infos, err := b.Do().IntoSingleItemImplied(&singleItemImplied).Infos()
if err != nil {
return err
}
if v.List {
listingErrors := v.printVolumes(infos)
if len(listingErrors) > 0 {
return kcmdutil.ErrExit
}
return nil
}
updateInfos := []*resource.Info{}
// if a claim should be created, generate the info we'll add to the flow
if v.Add && v.AddOpts.CreateClaim {
claim := v.AddOpts.createClaim()
m, err := v.Mapper.RESTMapping(kapi.Kind("PersistentVolumeClaim"))
if err != nil {
return err
}
mapper := resource.ClientMapperFunc(v.RESTClientFactory)
client, err := mapper.ClientForMapping(m)
if err != nil {
return err
}
info := &resource.Info{
Mapping: m,
Client: client,
Namespace: v.DefaultNamespace,
Object: claim,
}
infos = append(infos, info)
updateInfos = append(updateInfos, info)
}
patches, patchError := v.getVolumeUpdatePatches(infos, singleItemImplied)
if patchError != nil {
return patchError
}
if len(v.Output) > 0 || v.Local || kcmdutil.GetDryRunFlag(v.Cmd) {
return v.PrintObject(infos)
}
failed := false
for _, info := range updateInfos {
var obj runtime.Object
if len(info.ResourceVersion) == 0 {
obj, err = resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, false, info.Object)
} else {
obj, err = resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object)
}
if err != nil {
handlePodUpdateError(v.Err, err, "volume")
failed = true
continue
}
info.Refresh(obj, true)
fmt.Fprintf(v.Out, "%s/%s\n", info.Mapping.Resource, info.Name)
}
for _, patch := range patches {
info := patch.Info
if patch.Err != nil {
failed = true
fmt.Fprintf(v.Err, "error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err)
continue
}
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
fmt.Fprintf(v.Err, "info: %s %q was not changed\n", info.Mapping.Resource, info.Name)
continue
}
glog.V(4).Infof("Calculated patch %s", patch.Patch)
obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch)
if err != nil {
handlePodUpdateError(v.Err, err, "volume")
failed = true
continue
}
info.Refresh(obj, true)
kcmdutil.PrintSuccess(false, v.Out, info.Object, false, "updated")
}
if failed {
return kcmdutil.ErrExit
}
return nil
}
func (v *VolumeOptions) getVolumeUpdatePatches(infos []*resource.Info, singleItemImplied bool) ([]*Patch, error) {
skipped := 0
patches := CalculatePatches(infos, v.Encoder, func(info *resource.Info) (bool, error) {
transformed := false
ok, err := v.UpdatePodSpecForObject(info.Object, clientcmd.ConvertInteralPodSpecToExternal(func(spec *kapi.PodSpec) error {
var e error
switch {
case v.Add:
e = v.addVolumeToSpec(spec, info, singleItemImplied)
transformed = true
case v.Remove:
e = v.removeVolumeFromSpec(spec, info)
transformed = true
}
return e
}))
if !ok {
skipped++
}
return transformed, err
})
if singleItemImplied && skipped == len(infos) {
patchError := fmt.Errorf("the %s %s is not a pod or does not have a pod template", infos[0].Mapping.Resource, infos[0].Name)
return patches, patchError
}
return patches, nil
}
func setVolumeSourceByType(kv *kapi.Volume, opts *AddVolumeOptions) error {
switch strings.ToLower(opts.Type) {
case "emptydir":
kv.EmptyDir = &kapi.EmptyDirVolumeSource{}
case "hostpath":
kv.HostPath = &kapi.HostPathVolumeSource{
Path: opts.Path,
}
case "secret":
defaultMode, err := strconv.ParseUint(opts.DefaultMode, 8, 32)
if err != nil {
return err
}
defaultMode32 := int32(defaultMode)
kv.Secret = &kapi.SecretVolumeSource{
SecretName: opts.SecretName,
DefaultMode: &defaultMode32,
}
case "configmap":
defaultMode, err := strconv.ParseUint(opts.DefaultMode, 8, 32)
if err != nil {
return err
}
defaultMode32 := int32(defaultMode)
kv.ConfigMap = &kapi.ConfigMapVolumeSource{
LocalObjectReference: kapi.LocalObjectReference{
Name: opts.ConfigMapName,
},
DefaultMode: &defaultMode32,
}
case "persistentvolumeclaim", "pvc":
kv.PersistentVolumeClaim = &kapi.PersistentVolumeClaimVolumeSource{
ClaimName: opts.ClaimName,
}
default:
return fmt.Errorf("invalid volume type: %s", opts.Type)
}
return nil
}
func (v *VolumeOptions) printVolumes(infos []*resource.Info) []error {
listingErrors := []error{}
for _, info := range infos {
_, err := v.UpdatePodSpecForObject(info.Object, clientcmd.ConvertInteralPodSpecToExternal(func(spec *kapi.PodSpec) error {
return v.listVolumeForSpec(spec, info)
}))
if err != nil {
listingErrors = append(listingErrors, err)
fmt.Fprintf(v.Err, "error: %s/%s %v\n", info.Mapping.Resource, info.Name, err)
}
}
return listingErrors
}
func (v *AddVolumeOptions) createClaim() *kapi.PersistentVolumeClaim {
pvc := &kapi.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: v.ClaimName,
},
Spec: kapi.PersistentVolumeClaimSpec{
AccessModes: []kapi.PersistentVolumeAccessMode{kapi.PersistentVolumeAccessMode(v.ClaimMode)},
Resources: kapi.ResourceRequirements{
Requests: kapi.ResourceList{
kapi.ResourceName(kapi.ResourceStorage): kresource.MustParse(v.ClaimSize),
},
},
},
}
if len(v.ClaimClass) > 0 {
pvc.Annotations = map[string]string{
storageAnnClass: v.ClaimClass,
}
}
return pvc
}
func (v *VolumeOptions) setVolumeSource(kv *kapi.Volume) error {
var err error
opts := v.AddOpts
if len(opts.Type) > 0 {
err = setVolumeSourceByType(kv, opts)
} else if len(opts.Source) > 0 {
err = json.Unmarshal([]byte(opts.Source), &kv.VolumeSource)
}
return err
}
func (v *VolumeOptions) setVolumeMount(spec *kapi.PodSpec, info *resource.Info) error {
opts := v.AddOpts
containers, _ := selectContainers(spec.Containers, v.Containers)
if len(containers) == 0 && v.Containers != "*" {
fmt.Fprintf(v.Err, "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, v.Containers)
return nil
}
for _, c := range containers {
for _, m := range c.VolumeMounts {
if path.Clean(m.MountPath) == path.Clean(opts.MountPath) && m.Name != v.Name {
return fmt.Errorf("volume mount '%s' already exists for container '%s'", opts.MountPath, c.Name)
}
}
for i, m := range c.VolumeMounts {
if m.Name == v.Name && opts.Overwrite {
c.VolumeMounts = append(c.VolumeMounts[:i], c.VolumeMounts[i+1:]...)
break
}
}
volumeMount := &kapi.VolumeMount{
Name: v.Name,
MountPath: path.Clean(opts.MountPath),
}
if len(opts.SubPath) > 0 {
volumeMount.SubPath = path.Clean(opts.SubPath)
}
c.VolumeMounts = append(c.VolumeMounts, *volumeMount)
}
return nil
}
func (v *VolumeOptions) getVolumeName(spec *kapi.PodSpec, singleResource bool) (string, bool, error) {
opts := v.AddOpts
if opts.Overwrite {
// Multiple resources can have same mount-path for different volumes,
// so restrict it for single resource to uniquely find the volume
if !singleResource {
return "", false, fmt.Errorf("you must specify --name for the volume name when dealing with multiple resources")
}
if len(opts.MountPath) > 0 {
containers, _ := selectContainers(spec.Containers, v.Containers)
var name string
matchCount := 0
for _, c := range containers {
for _, m := range c.VolumeMounts {
if path.Clean(m.MountPath) == path.Clean(opts.MountPath) {
name = m.Name
matchCount++
break
}
}
}
switch matchCount {
case 0:
return "", false, fmt.Errorf("unable to find the volume for mount-path: %s", opts.MountPath)
case 1:
return name, false, nil
default:
return "", false, fmt.Errorf("found multiple volumes with same mount-path: %s", opts.MountPath)
}
}
return "", false, fmt.Errorf("ambiguous --overwrite, specify --name or --mount-path")
}
oldName, claimFound := v.checkForExistingClaim(spec)
if claimFound {
return oldName, true, nil
}
// Generate volume name
name := names.SimpleNameGenerator.GenerateName(volumePrefix)
if len(v.Output) == 0 {
fmt.Fprintf(v.Err, "info: Generated volume name: %s\n", name)
}
return name, false, nil
}
func (v *VolumeOptions) checkForExistingClaim(spec *kapi.PodSpec) (string, bool) {
for _, vol := range spec.Volumes {
oldSource := vol.VolumeSource.PersistentVolumeClaim
if oldSource != nil && v.AddOpts.ClaimName == oldSource.ClaimName {
return vol.Name, true
}
}
return "", false
}
func (v *VolumeOptions) addVolumeToSpec(spec *kapi.PodSpec, info *resource.Info, singleResource bool) error {
opts := v.AddOpts
claimFound := false
if len(v.Name) == 0 {
var err error
v.Name, claimFound, err = v.getVolumeName(spec, singleResource)
if err != nil {
return err
}
} else {
_, claimFound = v.checkForExistingClaim(spec)
}
newVolume := &kapi.Volume{
Name: v.Name,
}
setSource := true
vNameFound := false
for i, vol := range spec.Volumes {
if v.Name == vol.Name {
vNameFound = true
if !opts.Overwrite && !claimFound {
return fmt.Errorf("volume '%s' already exists. Use --overwrite to replace", v.Name)
}
if !opts.TypeChanged && len(opts.Source) == 0 {
newVolume.VolumeSource = vol.VolumeSource
setSource = false
}
spec.Volumes = append(spec.Volumes[:i], spec.Volumes[i+1:]...)
break
}
}
// if --overwrite was passed, but volume did not previously
// exist, log a warning that no volumes were overwritten
if !vNameFound && opts.Overwrite && len(v.Output) == 0 {
fmt.Fprintf(v.Err, "warning: volume %q did not previously exist and was not overriden. A new volume with this name has been created instead.", v.Name)
}
if setSource {
err := v.setVolumeSource(newVolume)
if err != nil {
return err
}
}
spec.Volumes = append(spec.Volumes, *newVolume)
if len(opts.MountPath) > 0 {
err := v.setVolumeMount(spec, info)
if err != nil {
return err
}
}
return nil
}
func (v *VolumeOptions) removeSpecificVolume(spec *kapi.PodSpec, containers, skippedContainers []*kapi.Container) error {
for _, c := range containers {
newMounts := c.VolumeMounts[:0]
for _, m := range c.VolumeMounts {
// Remove all volume mounts that match specified name
if v.Name != m.Name {
newMounts = append(newMounts, m)
}
}
c.VolumeMounts = newMounts
}
// Remove volume if no container is using it
found := false
for _, c := range skippedContainers {
for _, m := range c.VolumeMounts {
if v.Name == m.Name {
found = true
break
}
}
if found {
break
}
}
if !found {
foundVolume := false
for i, vol := range spec.Volumes {
if v.Name == vol.Name {
spec.Volumes = append(spec.Volumes[:i], spec.Volumes[i+1:]...)
foundVolume = true
break
}
}
if !foundVolume {
return fmt.Errorf("volume '%s' not found", v.Name)
}
}
return nil
}
func (v *VolumeOptions) removeVolumeFromSpec(spec *kapi.PodSpec, info *resource.Info) error {
containers, skippedContainers := selectContainers(spec.Containers, v.Containers)
if len(containers) == 0 && v.Containers != "*" {
fmt.Fprintf(v.Err, "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, v.Containers)
return nil
}
if len(v.Name) == 0 {
for _, c := range containers {
c.VolumeMounts = []kapi.VolumeMount{}
}
spec.Volumes = []kapi.Volume{}
} else {
err := v.removeSpecificVolume(spec, containers, skippedContainers)
if err != nil {
return err
}
}
return nil
}
func sourceAccessMode(readOnly bool) string {
if readOnly {
return " read-only"
}
return ""
}
func describePersistentVolumeClaim(claim *kapi.PersistentVolumeClaim) string {
if len(claim.Spec.VolumeName) == 0 {
// TODO: check for other dimensions of request - IOPs, etc
if val, ok := claim.Spec.Resources.Requests[kapi.ResourceStorage]; ok {
return fmt.Sprintf("waiting for %sB allocation", val.String())
}
return "waiting to allocate"
}
// TODO: check for other dimensions of capacity?
if val, ok := claim.Status.Capacity[kapi.ResourceStorage]; ok {
return fmt.Sprintf("allocated %sB", val.String())
}
return "allocated unknown size"
}
func describeVolumeSource(source *kapi.VolumeSource) string {
switch {
case source.AWSElasticBlockStore != nil:
return fmt.Sprintf("AWS EBS %s type=%s partition=%d%s", source.AWSElasticBlockStore.VolumeID, source.AWSElasticBlockStore.FSType, source.AWSElasticBlockStore.Partition, sourceAccessMode(source.AWSElasticBlockStore.ReadOnly))
case source.EmptyDir != nil:
return "empty directory"
case source.GCEPersistentDisk != nil:
return fmt.Sprintf("GCE PD %s type=%s partition=%d%s", source.GCEPersistentDisk.PDName, source.GCEPersistentDisk.FSType, source.GCEPersistentDisk.Partition, sourceAccessMode(source.GCEPersistentDisk.ReadOnly))
case source.GitRepo != nil:
if len(source.GitRepo.Revision) == 0 {
return fmt.Sprintf("Git repository %s", source.GitRepo.Repository)
}
return fmt.Sprintf("Git repository %s @ %s", source.GitRepo.Repository, source.GitRepo.Revision)
case source.Glusterfs != nil:
return fmt.Sprintf("GlusterFS %s:%s%s", source.Glusterfs.EndpointsName, source.Glusterfs.Path, sourceAccessMode(source.Glusterfs.ReadOnly))
case source.HostPath != nil:
return fmt.Sprintf("host path %s", source.HostPath.Path)
case source.ISCSI != nil:
return fmt.Sprintf("ISCSI %s target-portal=%s type=%s lun=%d%s", source.ISCSI.IQN, source.ISCSI.TargetPortal, source.ISCSI.FSType, source.ISCSI.Lun, sourceAccessMode(source.ISCSI.ReadOnly))
case source.NFS != nil:
return fmt.Sprintf("NFS %s:%s%s", source.NFS.Server, source.NFS.Path, sourceAccessMode(source.NFS.ReadOnly))
case source.PersistentVolumeClaim != nil:
return fmt.Sprintf("pvc/%s%s", source.PersistentVolumeClaim.ClaimName, sourceAccessMode(source.PersistentVolumeClaim.ReadOnly))
case source.RBD != nil:
return fmt.Sprintf("Ceph RBD %v type=%s image=%s pool=%s%s", source.RBD.CephMonitors, source.RBD.FSType, source.RBD.RBDImage, source.RBD.RBDPool, sourceAccessMode(source.RBD.ReadOnly))
case source.Secret != nil:
return fmt.Sprintf("secret/%s", source.Secret.SecretName)
case source.ConfigMap != nil:
return fmt.Sprintf("configMap/%s", source.ConfigMap.Name)
default:
return "unknown"
}
}
func (v *VolumeOptions) listVolumeForSpec(spec *kapi.PodSpec, info *resource.Info) error {
containers, _ := selectContainers(spec.Containers, v.Containers)
if len(containers) == 0 && v.Containers != "*" {
fmt.Fprintf(v.Err, "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, v.Containers)
return nil
}
fmt.Fprintf(v.Out, "%s/%s\n", info.Mapping.Resource, info.Name)
checkName := (len(v.Name) > 0)
found := false
for _, vol := range spec.Volumes {
if checkName && v.Name != vol.Name {
continue
}
found = true
refInfo := ""
if vol.VolumeSource.PersistentVolumeClaim != nil {
claimName := vol.VolumeSource.PersistentVolumeClaim.ClaimName
claim, err := v.Client.PersistentVolumeClaims(info.Namespace).Get(claimName, metav1.GetOptions{})
switch {
case err == nil:
refInfo = fmt.Sprintf("(%s)", describePersistentVolumeClaim(claim))
case apierrs.IsNotFound(err):
refInfo = "(does not exist)"
default:
fmt.Fprintf(v.Err, "error: unable to retrieve persistent volume claim %s referenced in %s/%s: %v", claimName, info.Mapping.Resource, info.Name, err)
}
}
if len(refInfo) > 0 {
refInfo = " " + refInfo
}
fmt.Fprintf(v.Out, " %s%s as %s\n", describeVolumeSource(&vol.VolumeSource), refInfo, vol.Name)
for _, c := range containers {
for _, m := range c.VolumeMounts {
if vol.Name != m.Name {
continue
}
if len(spec.Containers) == 1 {
fmt.Fprintf(v.Out, " mounted at %s\n", m.MountPath)
} else {
fmt.Fprintf(v.Out, " mounted at %s in container %s\n", m.MountPath, c.Name)
}
}
}
}
if checkName && !found {
return fmt.Errorf("volume %q not found", v.Name)
}
return nil
}