Merge branch 'sdminonne-container_sidecar'

pull/6/head
Brendan Burns 2015-09-02 10:11:25 -07:00
commit 2df5010834
25 changed files with 1925 additions and 43 deletions

View File

@ -12557,6 +12557,10 @@
"cephfs": { "cephfs": {
"$ref": "v1.CephFSVolumeSource", "$ref": "v1.CephFSVolumeSource",
"description": "CephFS represents a Ceph FS mount on the host that shares a pod's lifetime" "description": "CephFS represents a Ceph FS mount on the host that shares a pod's lifetime"
},
"downwardAPI": {
"$ref": "v1.DownwardAPIVolumeSource",
"description": "DownwardAPI represents downward API about the pod that should populate this volume"
} }
} }
}, },
@ -12618,6 +12622,54 @@
} }
} }
}, },
"v1.DownwardAPIVolumeSource": {
"id": "v1.DownwardAPIVolumeSource",
"description": "DownwardAPIVolumeSource represents a volume containing downward API info",
"properties": {
"items": {
"type": "array",
"items": {
"$ref": "v1.DownwardAPIVolumeFile"
},
"description": "Items is a list of downward API volume file"
}
}
},
"v1.DownwardAPIVolumeFile": {
"id": "v1.DownwardAPIVolumeFile",
"description": "DownwardAPIVolumeFile represents information to create the file containing the pod field",
"required": [
"path",
"fieldRef"
],
"properties": {
"path": {
"type": "string",
"description": "Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'"
},
"fieldRef": {
"$ref": "v1.ObjectFieldSelector",
"description": "Required: Selects a field of the pod: only annotations, labels, name and namespace are supported."
}
}
},
"v1.ObjectFieldSelector": {
"id": "v1.ObjectFieldSelector",
"description": "ObjectFieldSelector selects an APIVersioned field of an object.",
"required": [
"fieldPath"
],
"properties": {
"apiVersion": {
"type": "string",
"description": "Version of the schema the FieldPath is written in terms of, defaults to \"v1\"."
},
"fieldPath": {
"type": "string",
"description": "Path of the field to select in the specified API version."
}
}
},
"v1.Container": { "v1.Container": {
"id": "v1.Container", "id": "v1.Container",
"description": "A single application container that you want to run within a pod.", "description": "A single application container that you want to run within a pod.",
@ -12775,23 +12827,6 @@
} }
} }
}, },
"v1.ObjectFieldSelector": {
"id": "v1.ObjectFieldSelector",
"description": "ObjectFieldSelector selects an APIVersioned field of an object.",
"required": [
"fieldPath"
],
"properties": {
"apiVersion": {
"type": "string",
"description": "Version of the schema the FieldPath is written in terms of, defaults to \"v1\"."
},
"fieldPath": {
"type": "string",
"description": "Path of the field to select in the specified API version."
}
}
},
"v1.VolumeMount": { "v1.VolumeMount": {
"id": "v1.VolumeMount", "id": "v1.VolumeMount",
"description": "VolumeMount describes a mounting of a Volume within a container.", "description": "VolumeMount describes a mounting of a Volume within a container.",

View File

@ -28,6 +28,7 @@ import (
"k8s.io/kubernetes/pkg/volume/aws_ebs" "k8s.io/kubernetes/pkg/volume/aws_ebs"
"k8s.io/kubernetes/pkg/volume/cephfs" "k8s.io/kubernetes/pkg/volume/cephfs"
"k8s.io/kubernetes/pkg/volume/cinder" "k8s.io/kubernetes/pkg/volume/cinder"
"k8s.io/kubernetes/pkg/volume/downwardapi"
"k8s.io/kubernetes/pkg/volume/empty_dir" "k8s.io/kubernetes/pkg/volume/empty_dir"
"k8s.io/kubernetes/pkg/volume/gce_pd" "k8s.io/kubernetes/pkg/volume/gce_pd"
"k8s.io/kubernetes/pkg/volume/git_repo" "k8s.io/kubernetes/pkg/volume/git_repo"
@ -62,7 +63,7 @@ func ProbeVolumePlugins() []volume.VolumePlugin {
allPlugins = append(allPlugins, rbd.ProbeVolumePlugins()...) allPlugins = append(allPlugins, rbd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, cinder.ProbeVolumePlugins()...) allPlugins = append(allPlugins, cinder.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, cephfs.ProbeVolumePlugins()...) allPlugins = append(allPlugins, cephfs.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, downwardapi.ProbeVolumePlugins()...)
return allPlugins return allPlugins
} }

View File

@ -58,8 +58,7 @@ More information will be exposed through this same API over time.
## Exposing pod information into a container ## Exposing pod information into a container
Containers consume information from the downward API using environment Containers consume information from the downward API using environment
variables. In the future, containers will also be able to consume the downward variables or using a volume plugin.
API via a volume plugin.
### Environment variables ### Environment variables
@ -112,6 +111,76 @@ spec:
[Download example](downward-api/dapi-pod.yaml) [Download example](downward-api/dapi-pod.yaml)
<!-- END MUNGE: EXAMPLE downward-api/dapi-pod.yaml --> <!-- END MUNGE: EXAMPLE downward-api/dapi-pod.yaml -->
### Downward API volume
Using a similar syntax it's possible to expose pod information to containers using plain text files.
Downward API are dumped to a mounted volume. This is achieved using a `downwardAPI`
volume type and the different items represent the files to be created. `fieldPath` references the field to be exposed.
Downward API volume permits to store more complex data like [`metadata.labels`](labels.md) and [`metadata.annotations`](annotations.md). Currently key/value pair set fields are saved using `key="value"` format:
```
key1="value1"
key2="value2"
```
In future, it will be possible to specify an output format option.
Downward API volumes can expose:
* The pod's name
* The pod's namespace
* The pod's labels
* The pod's annotations
The downward API volume refreshes its data in step with the kubelet refresh loop. When labels will be modifiable on the fly without respawning the pod containers will be able to detect changes through mechanisms such as [inotify](https://en.wikipedia.org/wiki/Inotify).
In future, it will be possible to specify a specific annotation or label.
## Example
This is an example of a pod that consumes its labels and annotations via the downward API volume, labels and annotations are dumped in `/etc/podlabels` and in `/etc/annotations`, respectively:
<!-- BEGIN MUNGE: EXAMPLE downward-api/volume/dapi-volume.yaml -->
```yaml
apiVersion: v1
kind: Pod
metadata:
name: kubernetes-downwardapi-volume-example
labels:
zone: us-est-coast
cluster: test-cluster1
rack: rack-22
annotations:
build: two
builder: john-doe
spec:
containers:
- name: client-container
image: gcr.io/google_containers/busybox
command: ["sh", "-c", "while true; do if [[ -e /etc/labels ]]; then cat /etc/labels; fi; if [[ -e /etc/annotations ]]; then cat /etc/annotations; fi; sleep 5; done"]
volumeMounts:
- name: podinfo
mountPath: /etc
readOnly: false
volumes:
- name: podinfo
downwardAPI:
items:
- path: "labels"
fieldRef:
fieldPath: metadata.labels
- path: "annotations"
fieldRef:
fieldPath: metadata.annotations
```
[Download example](downward-api/volume/dapi-volume.yaml)
<!-- END MUNGE: EXAMPLE downward-api/volume/dapi-volume.yaml -->
Some more thorough examples: Some more thorough examples:
* [environment variables](environment-guide/) * [environment variables](environment-guide/)
* [downward API](downward-api/) * [downward API](downward-api/)

View File

@ -0,0 +1,105 @@
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
<strong>
The latest 1.0.x release of this document can be found
[here](http://releases.k8s.io/release-1.0/docs/user-guide/downward-api/volume/README.md).
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
# Downward API volume plugin
Following this example, you will create a pod with a downward API volume.
A downward API volume is a k8s volume plugin with the ability to save some pod information in a plain text file. The pod information can be for example some [metadata](../../../../docs/devel/api-conventions.md#metadata).
Supported metadata fields:
1. `metadata.annotations`
2. `metadata.namespace`
3. `metadata.name`
4. `metadata.labels`
### Step Zero: Prerequisites
This example assumes you have a Kubernetes cluster installed and running, and the ```kubectl``` command line tool somewhere in your path. Please see the [gettingstarted](../../../../docs/getting-started-guides/) for installation instructions for your platform.
### Step One: Create the pod
Use the `docs/user-guide/downward-api/dapi-volume.yaml` file to create a Pod with a  downward API volume which stores pod labels and pod annotations to `/etc/labels` and  `/etc/annotations` respectively.
```shell
$ kubectl create -f docs/user-guide/downward-api/volume/dapi-volume.yaml
```
### Step Two: Examine pod/container output
The pod displays (every 5 seconds) the content of the dump files which can be executed via the usual `kubectl log` command
```shell
$ kubectl logs kubernetes-downwardapi-volume-example
cluster="test-cluster1"
rack="rack-22"
zone="us-est-coast"
build="two"
builder="john-doe"
kubernetes.io/config.seen="2015-08-24T13:47:23.432459138Z"
kubernetes.io/config.source="api"
```
### Internals
In pod's `/etc` directory one may find the file created by the plugin (system files elided):
```shell
$ kubectl exec kubernetes-downwardapi-volume-example -i -t -- sh
/ # ls -laR /etc
/etc:
total 32
drwxrwxrwt 3 0 0 180 Aug 24 13:03 .
drwxr-xr-x 1 0 0 4096 Aug 24 13:05 ..
drwx------ 2 0 0 80 Aug 24 13:03 ..2015_08_24_13_03_44259413923
lrwxrwxrwx 1 0 0 30 Aug 24 13:03 ..downwardapi -> ..2015_08_24_13_03_44259413923
lrwxrwxrwx 1 0 0 25 Aug 24 13:03 annotations -> ..downwardapi/annotations
lrwxrwxrwx 1 0 0 20 Aug 24 13:03 labels -> ..downwardapi/labels
/etc/..2015_08_24_13_03_44259413923:
total 8
drwx------ 2 0 0 80 Aug 24 13:03 .
drwxrwxrwt 3 0 0 180 Aug 24 13:03 ..
-rw-r--r-- 1 0 0 115 Aug 24 13:03 annotations
-rw-r--r-- 1 0 0 53 Aug 24 13:03 labels
/ #
```
The file `labels` is stored in a temporary directory (`..2015_08_24_13_03_44259413923` in the example above) which is symlinked to by `..downwardapi`. Symlinks for annotations and labels in `/etc` point to files containing the actual metadata through the `..downwardapi` indirection.  This structure allows for dynamic atomic refresh of the metadata: updates are written to a new temporary directory, and the `..downwardapi` symlink is updated atomically using `rename(2)`.
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/downward-api/volume/README.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->

View File

@ -0,0 +1,30 @@
apiVersion: v1
kind: Pod
metadata:
name: kubernetes-downwardapi-volume-example
labels:
zone: us-est-coast
cluster: test-cluster1
rack: rack-22
annotations:
build: two
builder: john-doe
spec:
containers:
- name: client-container
image: gcr.io/google_containers/busybox
command: ["sh", "-c", "while true; do if [[ -e /etc/labels ]]; then cat /etc/labels; fi; if [[ -e /etc/annotations ]]; then cat /etc/annotations; fi; sleep 5; done"]
volumeMounts:
- name: podinfo
mountPath: /etc
readOnly: false
volumes:
- name: podinfo
downwardAPI:
items:
- path: "labels"
fieldRef:
fieldPath: metadata.labels
- path: "annotations"
fieldRef:
fieldPath: metadata.annotations

View File

@ -63,6 +63,7 @@ Familiarity with [pods](pods.md) is suggested.
- [gitRepo](#gitrepo) - [gitRepo](#gitrepo)
- [secret](#secret) - [secret](#secret)
- [persistentVolumeClaim](#persistentvolumeclaim) - [persistentVolumeClaim](#persistentvolumeclaim)
- [downwardAPI](#downwardapi)
- [Resources](#resources) - [Resources](#resources)
<!-- END MUNGE: GENERATED_TOC --> <!-- END MUNGE: GENERATED_TOC -->
@ -381,6 +382,13 @@ iSCSI volume) without knowing the details of the particular cloud environment.
See the [PersistentVolumes example](persistent-volumes/) for more See the [PersistentVolumes example](persistent-volumes/) for more
details. details.
### downwardAPI
A `downwardAPI` volume is used to make downward API data available to applications.
It mounts a directory and writes the requested data in plain text files.
See the [`downwardAPI` volume example](downward-api/volume/README.md) for more details.
## Resources ## Resources
The storage media (Disk, SSD, etc) of an `emptyDir` volume is determined by the The storage media (Disk, SSD, etc) of an `emptyDir` volume is determined by the

View File

@ -236,6 +236,9 @@ func TestExampleObjectSchemas(t *testing.T) {
"../docs/user-guide/downward-api": { "../docs/user-guide/downward-api": {
"dapi-pod": &api.Pod{}, "dapi-pod": &api.Pod{},
}, },
"../docs/user-guide/downward-api/volume/": {
"dapi-volume": &api.Pod{},
},
"../examples/elasticsearch": { "../examples/elasticsearch": {
"mytunes-namespace": &api.Namespace{}, "mytunes-namespace": &api.Namespace{},
"music-rc": &api.ReplicationController{}, "music-rc": &api.ReplicationController{},

View File

@ -334,6 +334,28 @@ func deepCopy_api_DeleteOptions(in DeleteOptions, out *DeleteOptions, c *convers
return nil return nil
} }
func deepCopy_api_DownwardAPIVolumeFile(in DownwardAPIVolumeFile, out *DownwardAPIVolumeFile, c *conversion.Cloner) error {
out.Path = in.Path
if err := deepCopy_api_ObjectFieldSelector(in.FieldRef, &out.FieldRef, c); err != nil {
return err
}
return nil
}
func deepCopy_api_DownwardAPIVolumeSource(in DownwardAPIVolumeSource, out *DownwardAPIVolumeSource, c *conversion.Cloner) error {
if in.Items != nil {
out.Items = make([]DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := deepCopy_api_DownwardAPIVolumeFile(in.Items[i], &out.Items[i], c); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func deepCopy_api_EmptyDirVolumeSource(in EmptyDirVolumeSource, out *EmptyDirVolumeSource, c *conversion.Cloner) error { func deepCopy_api_EmptyDirVolumeSource(in EmptyDirVolumeSource, out *EmptyDirVolumeSource, c *conversion.Cloner) error {
out.Medium = in.Medium out.Medium = in.Medium
return nil return nil
@ -2172,6 +2194,14 @@ func deepCopy_api_VolumeSource(in VolumeSource, out *VolumeSource, c *conversion
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(DownwardAPIVolumeSource)
if err := deepCopy_api_DownwardAPIVolumeSource(*in.DownwardAPI, out.DownwardAPI, c); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -2225,6 +2255,8 @@ func init() {
deepCopy_api_ContainerStateWaiting, deepCopy_api_ContainerStateWaiting,
deepCopy_api_ContainerStatus, deepCopy_api_ContainerStatus,
deepCopy_api_DeleteOptions, deepCopy_api_DeleteOptions,
deepCopy_api_DownwardAPIVolumeFile,
deepCopy_api_DownwardAPIVolumeSource,
deepCopy_api_EmptyDirVolumeSource, deepCopy_api_EmptyDirVolumeSource,
deepCopy_api_EndpointAddress, deepCopy_api_EndpointAddress,
deepCopy_api_EndpointPort, deepCopy_api_EndpointPort,

View File

@ -236,7 +236,18 @@ func FuzzerFor(t *testing.T, version string, src rand.Source) *fuzz.Fuzzer {
i := int(c.RandUint64() % uint64(v.NumField())) i := int(c.RandUint64() % uint64(v.NumField()))
v = v.Field(i).Addr() v = v.Field(i).Addr()
// Use a new fuzzer which cannot populate nil to ensure one field will be set. // Use a new fuzzer which cannot populate nil to ensure one field will be set.
fuzz.New().NilChance(0).NumElements(1, 1).Fuzz(v.Interface()) f := fuzz.New().NilChance(0).NumElements(1, 1)
f.Funcs(
// Only api.DownwardAPIVolumeFile needs to have a specific func since FieldRef has to be
// defaulted to a version otherwise roundtrip will fail
// For the remaining volume plugins the default fuzzer is enough.
func(m *api.DownwardAPIVolumeFile, c fuzz.Continue) {
m.Path = c.RandString()
versions := []string{"v1"}
m.FieldRef.APIVersion = versions[c.Rand.Intn(len(versions))]
m.FieldRef.FieldPath = c.RandString()
},
).Fuzz(v.Interface())
}, },
func(d *api.DNSPolicy, c fuzz.Continue) { func(d *api.DNSPolicy, c fuzz.Continue) {
policies := []api.DNSPolicy{api.DNSClusterFirst, api.DNSDefault} policies := []api.DNSPolicy{api.DNSClusterFirst, api.DNSDefault}

View File

@ -226,8 +226,12 @@ type VolumeSource struct {
RBD *RBDVolumeSource `json:"rbd,omitempty"` RBD *RBDVolumeSource `json:"rbd,omitempty"`
// Cinder represents a cinder volume attached and mounted on kubelets host machine // Cinder represents a cinder volume attached and mounted on kubelets host machine
Cinder *CinderVolumeSource `json:"cinder,omitempty"` Cinder *CinderVolumeSource `json:"cinder,omitempty"`
// CephFS represents a Cephfs mount on the host that shares a pod's lifetime // CephFS represents a Cephfs mount on the host that shares a pod's lifetime
CephFS *CephFSVolumeSource `json:"cephfs,omitempty"` CephFS *CephFSVolumeSource `json:"cephfs,omitempty"`
// DownwardAPI represents metadata about the pod that should populate this volume
DownwardAPI *DownwardAPIVolumeSource `json:"downwardAPI,omitempty"`
} }
// Similar to VolumeSource but meant for the administrator who creates PVs. // Similar to VolumeSource but meant for the administrator who creates PVs.
@ -596,6 +600,20 @@ type CephFSVolumeSource struct {
ReadOnly bool `json:"readOnly,omitempty"` ReadOnly bool `json:"readOnly,omitempty"`
} }
// DownwardAPIVolumeSource represents a volume containing downward API info
type DownwardAPIVolumeSource struct {
// Items is a list of DownwardAPIVolume file
Items []DownwardAPIVolumeFile `json:"items,omitempty"`
}
// DownwardAPIVolumeFile represents a single file containing information from the downward API
type DownwardAPIVolumeFile struct {
// Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'
Path string `json:"path"`
// Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.
FieldRef ObjectFieldSelector `json:"fieldRef"`
}
// ContainerPort represents a network port in a single container // ContainerPort represents a network port in a single container
type ContainerPort struct { type ContainerPort struct {
// Optional: If specified, this must be an IANA_SVC_NAME Each named port // Optional: If specified, this must be an IANA_SVC_NAME Each named port

View File

@ -43,6 +43,8 @@ func addConversionFuncs() {
switch label { switch label {
case "metadata.name", case "metadata.name",
"metadata.namespace", "metadata.namespace",
"metadata.labels",
"metadata.annotations",
"status.phase", "status.phase",
"status.podIP", "status.podIP",
"spec.nodeName": "spec.nodeName":

View File

@ -378,6 +378,34 @@ func convert_api_DeleteOptions_To_v1_DeleteOptions(in *api.DeleteOptions, out *D
return nil return nil
} }
func convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(in *api.DownwardAPIVolumeFile, out *DownwardAPIVolumeFile, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*api.DownwardAPIVolumeFile))(in)
}
out.Path = in.Path
if err := convert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil {
return err
}
return nil
}
func convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in *api.DownwardAPIVolumeSource, out *DownwardAPIVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*api.DownwardAPIVolumeSource))(in)
}
if in.Items != nil {
out.Items = make([]DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(&in.Items[i], &out.Items[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in *api.EmptyDirVolumeSource, out *EmptyDirVolumeSource, s conversion.Scope) error { func convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in *api.EmptyDirVolumeSource, out *EmptyDirVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*api.EmptyDirVolumeSource))(in) defaulting.(func(*api.EmptyDirVolumeSource))(in)
@ -2405,6 +2433,14 @@ func convert_api_VolumeSource_To_v1_VolumeSource(in *api.VolumeSource, out *Volu
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(DownwardAPIVolumeSource)
if err := convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in.DownwardAPI, out.DownwardAPI, s); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -2760,6 +2796,34 @@ func convert_v1_DeleteOptions_To_api_DeleteOptions(in *DeleteOptions, out *api.D
return nil return nil
} }
func convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(in *DownwardAPIVolumeFile, out *api.DownwardAPIVolumeFile, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*DownwardAPIVolumeFile))(in)
}
out.Path = in.Path
if err := convert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil {
return err
}
return nil
}
func convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in *DownwardAPIVolumeSource, out *api.DownwardAPIVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*DownwardAPIVolumeSource))(in)
}
if in.Items != nil {
out.Items = make([]api.DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(&in.Items[i], &out.Items[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in *EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, s conversion.Scope) error { func convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in *EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*EmptyDirVolumeSource))(in) defaulting.(func(*EmptyDirVolumeSource))(in)
@ -4787,6 +4851,14 @@ func convert_v1_VolumeSource_To_api_VolumeSource(in *VolumeSource, out *api.Volu
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(api.DownwardAPIVolumeSource)
if err := convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in.DownwardAPI, out.DownwardAPI, s); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -4808,6 +4880,8 @@ func init() {
convert_api_ContainerStatus_To_v1_ContainerStatus, convert_api_ContainerStatus_To_v1_ContainerStatus,
convert_api_Container_To_v1_Container, convert_api_Container_To_v1_Container,
convert_api_DeleteOptions_To_v1_DeleteOptions, convert_api_DeleteOptions_To_v1_DeleteOptions,
convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile,
convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource,
convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource, convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource,
convert_api_EndpointAddress_To_v1_EndpointAddress, convert_api_EndpointAddress_To_v1_EndpointAddress,
convert_api_EndpointPort_To_v1_EndpointPort, convert_api_EndpointPort_To_v1_EndpointPort,
@ -4924,6 +4998,8 @@ func init() {
convert_v1_ContainerStatus_To_api_ContainerStatus, convert_v1_ContainerStatus_To_api_ContainerStatus,
convert_v1_Container_To_api_Container, convert_v1_Container_To_api_Container,
convert_v1_DeleteOptions_To_api_DeleteOptions, convert_v1_DeleteOptions_To_api_DeleteOptions,
convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile,
convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource,
convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource, convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource,
convert_v1_EndpointAddress_To_api_EndpointAddress, convert_v1_EndpointAddress_To_api_EndpointAddress,
convert_v1_EndpointPort_To_api_EndpointPort, convert_v1_EndpointPort_To_api_EndpointPort,

View File

@ -349,6 +349,28 @@ func deepCopy_v1_DeleteOptions(in DeleteOptions, out *DeleteOptions, c *conversi
return nil return nil
} }
func deepCopy_v1_DownwardAPIVolumeFile(in DownwardAPIVolumeFile, out *DownwardAPIVolumeFile, c *conversion.Cloner) error {
out.Path = in.Path
if err := deepCopy_v1_ObjectFieldSelector(in.FieldRef, &out.FieldRef, c); err != nil {
return err
}
return nil
}
func deepCopy_v1_DownwardAPIVolumeSource(in DownwardAPIVolumeSource, out *DownwardAPIVolumeSource, c *conversion.Cloner) error {
if in.Items != nil {
out.Items = make([]DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := deepCopy_v1_DownwardAPIVolumeFile(in.Items[i], &out.Items[i], c); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func deepCopy_v1_EmptyDirVolumeSource(in EmptyDirVolumeSource, out *EmptyDirVolumeSource, c *conversion.Cloner) error { func deepCopy_v1_EmptyDirVolumeSource(in EmptyDirVolumeSource, out *EmptyDirVolumeSource, c *conversion.Cloner) error {
out.Medium = in.Medium out.Medium = in.Medium
return nil return nil
@ -2177,6 +2199,14 @@ func deepCopy_v1_VolumeSource(in VolumeSource, out *VolumeSource, c *conversion.
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(DownwardAPIVolumeSource)
if err := deepCopy_v1_DownwardAPIVolumeSource(*in.DownwardAPI, out.DownwardAPI, c); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -2227,6 +2257,8 @@ func init() {
deepCopy_v1_ContainerStateWaiting, deepCopy_v1_ContainerStateWaiting,
deepCopy_v1_ContainerStatus, deepCopy_v1_ContainerStatus,
deepCopy_v1_DeleteOptions, deepCopy_v1_DeleteOptions,
deepCopy_v1_DownwardAPIVolumeFile,
deepCopy_v1_DownwardAPIVolumeSource,
deepCopy_v1_EmptyDirVolumeSource, deepCopy_v1_EmptyDirVolumeSource,
deepCopy_v1_EndpointAddress, deepCopy_v1_EndpointAddress,
deepCopy_v1_EndpointPort, deepCopy_v1_EndpointPort,

View File

@ -280,8 +280,12 @@ type VolumeSource struct {
// Cinder represents a cinder volume attached and mounted on kubelets host machine // Cinder represents a cinder volume attached and mounted on kubelets host machine
// More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md
Cinder *CinderVolumeSource `json:"cinder,omitempty"` Cinder *CinderVolumeSource `json:"cinder,omitempty"`
// CephFS represents a Ceph FS mount on the host that shares a pod's lifetime // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime
CephFS *CephFSVolumeSource `json:"cephfs,omitempty"` CephFS *CephFSVolumeSource `json:"cephfs,omitempty"`
// DownwardAPI represents downward API about the pod that should populate this volume
DownwardAPI *DownwardAPIVolumeSource `json:"downwardAPI,omitempty"`
} }
// PersistentVolumeClaimVolumeSource references the user's PVC in the same namespace. // PersistentVolumeClaimVolumeSource references the user's PVC in the same namespace.
@ -2526,6 +2530,20 @@ type ComponentStatusList struct {
Items []ComponentStatus `json:"items"` Items []ComponentStatus `json:"items"`
} }
// DownwardAPIVolumeSource represents a volume containing downward API info
type DownwardAPIVolumeSource struct {
// Items is a list of downward API volume file
Items []DownwardAPIVolumeFile `json:"items,omitempty"`
}
// DownwardAPIVolumeFile represents information to create the file containing the pod field
type DownwardAPIVolumeFile struct {
// Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'
Path string `json:"path"`
// Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.
FieldRef ObjectFieldSelector `json:"fieldRef"`
}
// SecurityContext holds security configuration that will be applied to a container. // SecurityContext holds security configuration that will be applied to a container.
type SecurityContext struct { type SecurityContext struct {
// The linux kernel capabilites that should be added or removed. // The linux kernel capabilites that should be added or removed.

View File

@ -232,6 +232,25 @@ func (DeleteOptions) SwaggerDoc() map[string]string {
return map_DeleteOptions return map_DeleteOptions
} }
var map_DownwardAPIVolumeFile = map[string]string{
"": "DownwardAPIVolumeFile represents information to create the file containing the pod field",
"path": "Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'",
"fieldRef": "Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.",
}
func (DownwardAPIVolumeFile) SwaggerDoc() map[string]string {
return map_DownwardAPIVolumeFile
}
var map_DownwardAPIVolumeSource = map[string]string{
"": "DownwardAPIVolumeSource represents a volume containing downward API info",
"items": "Items is a list of downward API volume file",
}
func (DownwardAPIVolumeSource) SwaggerDoc() map[string]string {
return map_DownwardAPIVolumeSource
}
var map_EmptyDirVolumeSource = map[string]string{ var map_EmptyDirVolumeSource = map[string]string{
"": "EmptyDirVolumeSource is temporary directory that shares a pod's lifetime.", "": "EmptyDirVolumeSource is temporary directory that shares a pod's lifetime.",
"medium": "What type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir", "medium": "What type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir",
@ -1387,9 +1406,10 @@ var map_VolumeSource = map[string]string{
"iscsi": "ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/HEAD/examples/iscsi/README.md", "iscsi": "ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/HEAD/examples/iscsi/README.md",
"glusterfs": "Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/glusterfs/README.md", "glusterfs": "Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/glusterfs/README.md",
"persistentVolumeClaim": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", "persistentVolumeClaim": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims",
"rbd": "RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/rbd/README.md", "rbd": "RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/rbd/README.md",
"cinder": "Cinder represents a cinder volume attached and mounted on kubelets host machine More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", "cinder": "Cinder represents a cinder volume attached and mounted on kubelets host machine More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md",
"cephfs": "CephFS represents a Ceph FS mount on the host that shares a pod's lifetime", "cephfs": "CephFS represents a Ceph FS mount on the host that shares a pod's lifetime",
"downwardAPI": "DownwardAPI represents downward API about the pod that should populate this volume",
} }
func (VolumeSource) SwaggerDoc() map[string]string { func (VolumeSource) SwaggerDoc() map[string]string {

View File

@ -20,6 +20,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net" "net"
"os"
"path" "path"
"reflect" "reflect"
"regexp" "regexp"
@ -383,6 +384,10 @@ func validateSource(source *api.VolumeSource) errs.ValidationErrorList {
numVolumes++ numVolumes++
allErrs = append(allErrs, validateCephFS(source.CephFS).Prefix("cephfs")...) allErrs = append(allErrs, validateCephFS(source.CephFS).Prefix("cephfs")...)
} }
if source.DownwardAPI != nil {
numVolumes++
allErrs = append(allErrs, validateDownwardAPIVolumeSource(source.DownwardAPI).Prefix("downwardApi")...)
}
if numVolumes != 1 { if numVolumes != 1 {
allErrs = append(allErrs, errs.NewFieldInvalid("", source, "exactly 1 volume type is required")) allErrs = append(allErrs, errs.NewFieldInvalid("", source, "exactly 1 volume type is required"))
} }
@ -492,6 +497,31 @@ func validateGlusterfs(glusterfs *api.GlusterfsVolumeSource) errs.ValidationErro
return allErrs return allErrs
} }
var validDownwardAPIFieldPathExpressions = util.NewStringSet("metadata.name", "metadata.namespace", "metadata.labels", "metadata.annotations")
func validateDownwardAPIVolumeSource(downwardAPIVolume *api.DownwardAPIVolumeSource) errs.ValidationErrorList {
allErrs := errs.ValidationErrorList{}
for _, downwardAPIVolumeFile := range downwardAPIVolume.Items {
if len(downwardAPIVolumeFile.Path) == 0 {
allErrs = append(allErrs, errs.NewFieldRequired("path"))
}
if path.IsAbs(downwardAPIVolumeFile.Path) {
allErrs = append(allErrs, errs.NewFieldForbidden("path", "must not be an absolute path"))
}
items := strings.Split(downwardAPIVolumeFile.Path, string(os.PathSeparator))
for _, item := range items {
if item == ".." {
allErrs = append(allErrs, errs.NewFieldInvalid("path", downwardAPIVolumeFile.Path, "must not contain \"..\"."))
}
}
if strings.HasPrefix(items[0], "..") && len(items[0]) > 2 {
allErrs = append(allErrs, errs.NewFieldInvalid("path", downwardAPIVolumeFile.Path, "must not start with \"..\"."))
}
allErrs = append(allErrs, validateObjectFieldSelector(&downwardAPIVolumeFile.FieldRef, &validDownwardAPIFieldPathExpressions).Prefix("FieldRef")...)
}
return allErrs
}
func validateRBD(rbd *api.RBDVolumeSource) errs.ValidationErrorList { func validateRBD(rbd *api.RBDVolumeSource) errs.ValidationErrorList {
allErrs := errs.ValidationErrorList{} allErrs := errs.ValidationErrorList{}
if len(rbd.CephMonitors) == 0 { if len(rbd.CephMonitors) == 0 {
@ -709,6 +739,8 @@ func validateEnv(vars []api.EnvVar) errs.ValidationErrorList {
return allErrs return allErrs
} }
var validFieldPathExpressionsEnv = util.NewStringSet("metadata.name", "metadata.namespace", "status.podIP")
func validateEnvVarValueFrom(ev api.EnvVar) errs.ValidationErrorList { func validateEnvVarValueFrom(ev api.EnvVar) errs.ValidationErrorList {
allErrs := errs.ValidationErrorList{} allErrs := errs.ValidationErrorList{}
@ -721,7 +753,7 @@ func validateEnvVarValueFrom(ev api.EnvVar) errs.ValidationErrorList {
switch { switch {
case ev.ValueFrom.FieldRef != nil: case ev.ValueFrom.FieldRef != nil:
numSources++ numSources++
allErrs = append(allErrs, validateObjectFieldSelector(ev.ValueFrom.FieldRef).Prefix("fieldRef")...) allErrs = append(allErrs, validateObjectFieldSelector(ev.ValueFrom.FieldRef, &validFieldPathExpressionsEnv).Prefix("fieldRef")...)
} }
if ev.Value != "" && numSources != 0 { if ev.Value != "" && numSources != 0 {
@ -731,9 +763,7 @@ func validateEnvVarValueFrom(ev api.EnvVar) errs.ValidationErrorList {
return allErrs return allErrs
} }
var validFieldPathExpressions = util.NewStringSet("metadata.name", "metadata.namespace", "status.podIP") func validateObjectFieldSelector(fs *api.ObjectFieldSelector, expressions *util.StringSet) errs.ValidationErrorList {
func validateObjectFieldSelector(fs *api.ObjectFieldSelector) errs.ValidationErrorList {
allErrs := errs.ValidationErrorList{} allErrs := errs.ValidationErrorList{}
if fs.APIVersion == "" { if fs.APIVersion == "" {
@ -744,8 +774,8 @@ func validateObjectFieldSelector(fs *api.ObjectFieldSelector) errs.ValidationErr
internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(fs.APIVersion, "Pod", fs.FieldPath, "") internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(fs.APIVersion, "Pod", fs.FieldPath, "")
if err != nil { if err != nil {
allErrs = append(allErrs, errs.NewFieldInvalid("fieldPath", fs.FieldPath, "error converting fieldPath")) allErrs = append(allErrs, errs.NewFieldInvalid("fieldPath", fs.FieldPath, "error converting fieldPath"))
} else if !validFieldPathExpressions.Has(internalFieldPath) { } else if !expressions.Has(internalFieldPath) {
allErrs = append(allErrs, errs.NewFieldValueNotSupported("fieldPath", internalFieldPath, validFieldPathExpressions.List())) allErrs = append(allErrs, errs.NewFieldValueNotSupported("fieldPath", internalFieldPath, expressions.List()))
} }
} }

View File

@ -458,6 +458,32 @@ func TestValidateVolumes(t *testing.T) {
{Name: "rbd", VolumeSource: api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{"foo"}, RBDImage: "bar", FSType: "ext4"}}}, {Name: "rbd", VolumeSource: api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{"foo"}, RBDImage: "bar", FSType: "ext4"}}},
{Name: "cinder", VolumeSource: api.VolumeSource{Cinder: &api.CinderVolumeSource{"29ea5088-4f60-4757-962e-dba678767887", "ext4", false}}}, {Name: "cinder", VolumeSource: api.VolumeSource{Cinder: &api.CinderVolumeSource{"29ea5088-4f60-4757-962e-dba678767887", "ext4", false}}},
{Name: "cephfs", VolumeSource: api.VolumeSource{CephFS: &api.CephFSVolumeSource{Monitors: []string{"foo"}}}}, {Name: "cephfs", VolumeSource: api.VolumeSource{CephFS: &api.CephFSVolumeSource{Monitors: []string{"foo"}}}},
{Name: "downwardapi", VolumeSource: api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{
{Path: "labels", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}},
{Path: "annotations", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.annotations"}},
{Path: "namespace", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.namespace"}},
{Path: "name", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.name"}},
{Path: "path/withslash/andslash", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}},
{Path: "path/./withdot", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}},
{Path: "path/with..dot", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}},
{Path: "second-level-dirent-can-have/..dot", FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}},
}}}},
} }
names, errs := validateVolumes(successCase) names, errs := validateVolumes(successCase)
if len(errs) != 0 { if len(errs) != 0 {
@ -474,22 +500,53 @@ func TestValidateVolumes(t *testing.T) {
emptyMon := api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{}, RBDImage: "bar", FSType: "ext4"}} emptyMon := api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{}, RBDImage: "bar", FSType: "ext4"}}
emptyImage := api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{"foo"}, RBDImage: "", FSType: "ext4"}} emptyImage := api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{"foo"}, RBDImage: "", FSType: "ext4"}}
emptyCephFSMon := api.VolumeSource{CephFS: &api.CephFSVolumeSource{Monitors: []string{}}} emptyCephFSMon := api.VolumeSource{CephFS: &api.CephFSVolumeSource{Monitors: []string{}}}
emptyPathName := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}}},
}}
absolutePathName := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "/absolutepath",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}}},
}}
dotDotInPath := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "../../passwd",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}}},
}}
dotDotPathName := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "..badFileName",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}}},
}}
dotDotFirstLevelDirent := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "..badDirName/goodFileName",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels"}}},
}}
errorCases := map[string]struct { errorCases := map[string]struct {
V []api.Volume V []api.Volume
T errors.ValidationErrorType T errors.ValidationErrorType
F string F string
D string
}{ }{
"zero-length name": {[]api.Volume{{Name: "", VolumeSource: emptyVS}}, errors.ValidationErrorTypeRequired, "[0].name"}, "zero-length name": {[]api.Volume{{Name: "", VolumeSource: emptyVS}}, errors.ValidationErrorTypeRequired, "[0].name", ""},
"name > 63 characters": {[]api.Volume{{Name: strings.Repeat("a", 64), VolumeSource: emptyVS}}, errors.ValidationErrorTypeInvalid, "[0].name"}, "name > 63 characters": {[]api.Volume{{Name: strings.Repeat("a", 64), VolumeSource: emptyVS}}, errors.ValidationErrorTypeInvalid, "[0].name", "must be a DNS label (at most 63 characters, matching regex [a-z0-9]([-a-z0-9]*[a-z0-9])?): e.g. \"my-name\""},
"name not a DNS label": {[]api.Volume{{Name: "a.b.c", VolumeSource: emptyVS}}, errors.ValidationErrorTypeInvalid, "[0].name"}, "name not a DNS label": {[]api.Volume{{Name: "a.b.c", VolumeSource: emptyVS}}, errors.ValidationErrorTypeInvalid, "[0].name", "must be a DNS label (at most 63 characters, matching regex [a-z0-9]([-a-z0-9]*[a-z0-9])?): e.g. \"my-name\""},
"name not unique": {[]api.Volume{{Name: "abc", VolumeSource: emptyVS}, {Name: "abc", VolumeSource: emptyVS}}, errors.ValidationErrorTypeDuplicate, "[1].name"}, "name not unique": {[]api.Volume{{Name: "abc", VolumeSource: emptyVS}, {Name: "abc", VolumeSource: emptyVS}}, errors.ValidationErrorTypeDuplicate, "[1].name", ""},
"empty portal": {[]api.Volume{{Name: "badportal", VolumeSource: emptyPortal}}, errors.ValidationErrorTypeRequired, "[0].source.iscsi.targetPortal"}, "empty portal": {[]api.Volume{{Name: "badportal", VolumeSource: emptyPortal}}, errors.ValidationErrorTypeRequired, "[0].source.iscsi.targetPortal", ""},
"empty iqn": {[]api.Volume{{Name: "badiqn", VolumeSource: emptyIQN}}, errors.ValidationErrorTypeRequired, "[0].source.iscsi.iqn"}, "empty iqn": {[]api.Volume{{Name: "badiqn", VolumeSource: emptyIQN}}, errors.ValidationErrorTypeRequired, "[0].source.iscsi.iqn", ""},
"empty hosts": {[]api.Volume{{Name: "badhost", VolumeSource: emptyHosts}}, errors.ValidationErrorTypeRequired, "[0].source.glusterfs.endpoints"}, "empty hosts": {[]api.Volume{{Name: "badhost", VolumeSource: emptyHosts}}, errors.ValidationErrorTypeRequired, "[0].source.glusterfs.endpoints", ""},
"empty path": {[]api.Volume{{Name: "badpath", VolumeSource: emptyPath}}, errors.ValidationErrorTypeRequired, "[0].source.glusterfs.path"}, "empty path": {[]api.Volume{{Name: "badpath", VolumeSource: emptyPath}}, errors.ValidationErrorTypeRequired, "[0].source.glusterfs.path", ""},
"empty mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyMon}}, errors.ValidationErrorTypeRequired, "[0].source.rbd.monitors"}, "empty mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyMon}}, errors.ValidationErrorTypeRequired, "[0].source.rbd.monitors", ""},
"empty image": {[]api.Volume{{Name: "badimage", VolumeSource: emptyImage}}, errors.ValidationErrorTypeRequired, "[0].source.rbd.image"}, "empty image": {[]api.Volume{{Name: "badimage", VolumeSource: emptyImage}}, errors.ValidationErrorTypeRequired, "[0].source.rbd.image", ""},
"empty cephfs mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyCephFSMon}}, errors.ValidationErrorTypeRequired, "[0].source.cephfs.monitors"}, "empty cephfs mon": {[]api.Volume{{Name: "badmon", VolumeSource: emptyCephFSMon}}, errors.ValidationErrorTypeRequired, "[0].source.cephfs.monitors", ""},
"empty metatada path": {[]api.Volume{{Name: "emptyname", VolumeSource: emptyPathName}}, errors.ValidationErrorTypeRequired, "[0].source.downwardApi.path", ""},
"absolute path": {[]api.Volume{{Name: "absolutepath", VolumeSource: absolutePathName}}, errors.ValidationErrorTypeForbidden, "[0].source.downwardApi.path", ""},
"dot dot path": {[]api.Volume{{Name: "dotdotpath", VolumeSource: dotDotInPath}}, errors.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not contain \"..\"."},
"dot dot file name": {[]api.Volume{{Name: "dotdotfilename", VolumeSource: dotDotPathName}}, errors.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not start with \"..\"."},
"dot dot first level dirent ": {[]api.Volume{{Name: "dotdotdirfilename", VolumeSource: dotDotFirstLevelDirent}}, errors.ValidationErrorTypeInvalid, "[0].source.downwardApi.path", "must not start with \"..\"."},
} }
for k, v := range errorCases { for k, v := range errorCases {
_, errs := validateVolumes(v.V) _, errs := validateVolumes(v.V)
@ -505,8 +562,8 @@ func TestValidateVolumes(t *testing.T) {
t.Errorf("%s: expected errors to have field %s: %v", k, v.F, errs[i]) t.Errorf("%s: expected errors to have field %s: %v", k, v.F, errs[i])
} }
detail := errs[i].(*errors.ValidationError).Detail detail := errs[i].(*errors.ValidationError).Detail
if detail != "" && detail != DNS1123LabelErrorMsg { if detail != v.D {
t.Errorf("%s: expected error detail either empty or %s, got %s", k, DNS1123LabelErrorMsg, detail) t.Errorf("%s: expected error detail \"%s\", got \"%s\"", k, v.D, detail)
} }
} }
} }
@ -657,6 +714,32 @@ func TestValidateEnv(t *testing.T) {
}}, }},
expectedError: "[0].valueFrom.fieldRef.fieldPath: invalid value 'metadata.whoops', Details: error converting fieldPath", expectedError: "[0].valueFrom.fieldRef.fieldPath: invalid value 'metadata.whoops', Details: error converting fieldPath",
}, },
{
name: "invalid fieldPath labels",
envs: []api.EnvVar{{
Name: "labels",
ValueFrom: &api.EnvVarSource{
FieldRef: &api.ObjectFieldSelector{
FieldPath: "metadata.labels",
APIVersion: "v1",
},
},
}},
expectedError: "[0].valueFrom.fieldRef.fieldPath: unsupported value 'metadata.labels', Details: supported values: metadata.name, metadata.namespace, status.podIP",
},
{
name: "invalid fieldPath annotations",
envs: []api.EnvVar{{
Name: "abc",
ValueFrom: &api.EnvVarSource{
FieldRef: &api.ObjectFieldSelector{
FieldPath: "metadata.annotations",
APIVersion: "v1",
},
},
}},
expectedError: "[0].valueFrom.fieldRef.fieldPath: unsupported value 'metadata.annotations', Details: supported values: metadata.name, metadata.namespace, status.podIP",
},
{ {
name: "unsupported fieldPath", name: "unsupported fieldPath",
envs: []api.EnvVar{{ envs: []api.EnvVar{{

View File

@ -187,6 +187,28 @@ func deepCopy_api_ContainerPort(in api.ContainerPort, out *api.ContainerPort, c
return nil return nil
} }
func deepCopy_api_DownwardAPIVolumeFile(in api.DownwardAPIVolumeFile, out *api.DownwardAPIVolumeFile, c *conversion.Cloner) error {
out.Path = in.Path
if err := deepCopy_api_ObjectFieldSelector(in.FieldRef, &out.FieldRef, c); err != nil {
return err
}
return nil
}
func deepCopy_api_DownwardAPIVolumeSource(in api.DownwardAPIVolumeSource, out *api.DownwardAPIVolumeSource, c *conversion.Cloner) error {
if in.Items != nil {
out.Items = make([]api.DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := deepCopy_api_DownwardAPIVolumeFile(in.Items[i], &out.Items[i], c); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func deepCopy_api_EmptyDirVolumeSource(in api.EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, c *conversion.Cloner) error { func deepCopy_api_EmptyDirVolumeSource(in api.EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, c *conversion.Cloner) error {
out.Medium = in.Medium out.Medium = in.Medium
return nil return nil
@ -708,6 +730,14 @@ func deepCopy_api_VolumeSource(in api.VolumeSource, out *api.VolumeSource, c *co
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(api.DownwardAPIVolumeSource)
if err := deepCopy_api_DownwardAPIVolumeSource(*in.DownwardAPI, out.DownwardAPI, c); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -1090,6 +1120,8 @@ func init() {
deepCopy_api_CinderVolumeSource, deepCopy_api_CinderVolumeSource,
deepCopy_api_Container, deepCopy_api_Container,
deepCopy_api_ContainerPort, deepCopy_api_ContainerPort,
deepCopy_api_DownwardAPIVolumeFile,
deepCopy_api_DownwardAPIVolumeSource,
deepCopy_api_EmptyDirVolumeSource, deepCopy_api_EmptyDirVolumeSource,
deepCopy_api_EnvVar, deepCopy_api_EnvVar,
deepCopy_api_EnvVarSource, deepCopy_api_EnvVarSource,

View File

@ -205,6 +205,34 @@ func convert_api_ContainerPort_To_v1_ContainerPort(in *api.ContainerPort, out *v
return nil return nil
} }
func convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(in *api.DownwardAPIVolumeFile, out *v1.DownwardAPIVolumeFile, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*api.DownwardAPIVolumeFile))(in)
}
out.Path = in.Path
if err := convert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil {
return err
}
return nil
}
func convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in *api.DownwardAPIVolumeSource, out *v1.DownwardAPIVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*api.DownwardAPIVolumeSource))(in)
}
if in.Items != nil {
out.Items = make([]v1.DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(&in.Items[i], &out.Items[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in *api.EmptyDirVolumeSource, out *v1.EmptyDirVolumeSource, s conversion.Scope) error { func convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in *api.EmptyDirVolumeSource, out *v1.EmptyDirVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*api.EmptyDirVolumeSource))(in) defaulting.(func(*api.EmptyDirVolumeSource))(in)
@ -756,6 +784,14 @@ func convert_api_VolumeSource_To_v1_VolumeSource(in *api.VolumeSource, out *v1.V
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(v1.DownwardAPIVolumeSource)
if err := convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in.DownwardAPI, out.DownwardAPI, s); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -936,6 +972,34 @@ func convert_v1_ContainerPort_To_api_ContainerPort(in *v1.ContainerPort, out *ap
return nil return nil
} }
func convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(in *v1.DownwardAPIVolumeFile, out *api.DownwardAPIVolumeFile, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*v1.DownwardAPIVolumeFile))(in)
}
out.Path = in.Path
if err := convert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil {
return err
}
return nil
}
func convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in *v1.DownwardAPIVolumeSource, out *api.DownwardAPIVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*v1.DownwardAPIVolumeSource))(in)
}
if in.Items != nil {
out.Items = make([]api.DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(&in.Items[i], &out.Items[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in *v1.EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, s conversion.Scope) error { func convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in *v1.EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, s conversion.Scope) error {
if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found {
defaulting.(func(*v1.EmptyDirVolumeSource))(in) defaulting.(func(*v1.EmptyDirVolumeSource))(in)
@ -1487,6 +1551,14 @@ func convert_v1_VolumeSource_To_api_VolumeSource(in *v1.VolumeSource, out *api.V
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(api.DownwardAPIVolumeSource)
if err := convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in.DownwardAPI, out.DownwardAPI, s); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -2196,6 +2268,8 @@ func init() {
convert_api_CinderVolumeSource_To_v1_CinderVolumeSource, convert_api_CinderVolumeSource_To_v1_CinderVolumeSource,
convert_api_ContainerPort_To_v1_ContainerPort, convert_api_ContainerPort_To_v1_ContainerPort,
convert_api_Container_To_v1_Container, convert_api_Container_To_v1_Container,
convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile,
convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource,
convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource, convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource,
convert_api_EnvVarSource_To_v1_EnvVarSource, convert_api_EnvVarSource_To_v1_EnvVarSource,
convert_api_EnvVar_To_v1_EnvVar, convert_api_EnvVar_To_v1_EnvVar,
@ -2260,6 +2334,8 @@ func init() {
convert_v1_DeploymentList_To_expapi_DeploymentList, convert_v1_DeploymentList_To_expapi_DeploymentList,
convert_v1_DeploymentStatus_To_expapi_DeploymentStatus, convert_v1_DeploymentStatus_To_expapi_DeploymentStatus,
convert_v1_Deployment_To_expapi_Deployment, convert_v1_Deployment_To_expapi_Deployment,
convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile,
convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource,
convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource, convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource,
convert_v1_EnvVarSource_To_api_EnvVarSource, convert_v1_EnvVarSource_To_api_EnvVarSource,
convert_v1_EnvVar_To_api_EnvVar, convert_v1_EnvVar_To_api_EnvVar,

View File

@ -204,6 +204,28 @@ func deepCopy_v1_ContainerPort(in v1.ContainerPort, out *v1.ContainerPort, c *co
return nil return nil
} }
func deepCopy_v1_DownwardAPIVolumeFile(in v1.DownwardAPIVolumeFile, out *v1.DownwardAPIVolumeFile, c *conversion.Cloner) error {
out.Path = in.Path
if err := deepCopy_v1_ObjectFieldSelector(in.FieldRef, &out.FieldRef, c); err != nil {
return err
}
return nil
}
func deepCopy_v1_DownwardAPIVolumeSource(in v1.DownwardAPIVolumeSource, out *v1.DownwardAPIVolumeSource, c *conversion.Cloner) error {
if in.Items != nil {
out.Items = make([]v1.DownwardAPIVolumeFile, len(in.Items))
for i := range in.Items {
if err := deepCopy_v1_DownwardAPIVolumeFile(in.Items[i], &out.Items[i], c); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func deepCopy_v1_EmptyDirVolumeSource(in v1.EmptyDirVolumeSource, out *v1.EmptyDirVolumeSource, c *conversion.Cloner) error { func deepCopy_v1_EmptyDirVolumeSource(in v1.EmptyDirVolumeSource, out *v1.EmptyDirVolumeSource, c *conversion.Cloner) error {
out.Medium = in.Medium out.Medium = in.Medium
return nil return nil
@ -726,6 +748,14 @@ func deepCopy_v1_VolumeSource(in v1.VolumeSource, out *v1.VolumeSource, c *conve
} else { } else {
out.CephFS = nil out.CephFS = nil
} }
if in.DownwardAPI != nil {
out.DownwardAPI = new(v1.DownwardAPIVolumeSource)
if err := deepCopy_v1_DownwardAPIVolumeSource(*in.DownwardAPI, out.DownwardAPI, c); err != nil {
return err
}
} else {
out.DownwardAPI = nil
}
return nil return nil
} }
@ -1113,6 +1143,8 @@ func init() {
deepCopy_v1_CinderVolumeSource, deepCopy_v1_CinderVolumeSource,
deepCopy_v1_Container, deepCopy_v1_Container,
deepCopy_v1_ContainerPort, deepCopy_v1_ContainerPort,
deepCopy_v1_DownwardAPIVolumeFile,
deepCopy_v1_DownwardAPIVolumeSource,
deepCopy_v1_EmptyDirVolumeSource, deepCopy_v1_EmptyDirVolumeSource,
deepCopy_v1_EnvVar, deepCopy_v1_EnvVar,
deepCopy_v1_EnvVarSource, deepCopy_v1_EnvVarSource,

View File

@ -22,6 +22,15 @@ import (
"k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/meta"
) )
// formatMap formats map[string]string to a string.
func formatMap(m map[string]string) string {
var l string
for key, value := range m {
l += key + "=" + fmt.Sprintf("%q", value) + "\n"
}
return l
}
// ExtractFieldPathAsString extracts the field from the given object // ExtractFieldPathAsString extracts the field from the given object
// and returns it as a string. The object must be a pointer to an // and returns it as a string. The object must be a pointer to an
// API type. // API type.
@ -37,6 +46,10 @@ func ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error)
} }
switch fieldPath { switch fieldPath {
case "metadata.annotations":
return formatMap(accessor.Annotations()), nil
case "metadata.labels":
return formatMap(accessor.Labels()), nil
case "metadata.name": case "metadata.name":
return accessor.Name(), nil return accessor.Name(), nil
case "metadata.namespace": case "metadata.namespace":

View File

@ -57,6 +57,37 @@ func TestExtractFieldPathAsString(t *testing.T) {
}, },
expectedValue: "object-name", expectedValue: "object-name",
}, },
{
name: "ok - labels",
fieldPath: "metadata.labels",
obj: &api.Pod{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{"key": "value"},
},
},
expectedValue: "key=\"value\"\n",
},
{
name: "ok - labels bslash n",
fieldPath: "metadata.labels",
obj: &api.Pod{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{"key": "value\n"},
},
},
expectedValue: "key=\"value\\n\"\n",
},
{
name: "ok - annotations",
fieldPath: "metadata.annotations",
obj: &api.Pod{
ObjectMeta: api.ObjectMeta{
Annotations: map[string]string{"builder": "john-doe"},
},
},
expectedValue: "builder=\"john-doe\"\n",
},
{ {
name: "invalid expression", name: "invalid expression",
fieldPath: "metadata.whoops", fieldPath: "metadata.whoops",

View File

@ -0,0 +1,373 @@
/*
Copyright 2015 The Kubernetes Authors 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 downwardapi
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/fieldpath"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util"
utilErrors "k8s.io/kubernetes/pkg/util/errors"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
"github.com/golang/glog"
)
// ProbeVolumePlugins is the entry point for plugin detection in a package.
func ProbeVolumePlugins() []volume.VolumePlugin {
return []volume.VolumePlugin{&downwardAPIPlugin{}}
}
const (
downwardAPIPluginName = "kubernetes.io/downward-api"
)
// downwardAPIPlugin implements the VolumePlugin interface.
type downwardAPIPlugin struct {
host volume.VolumeHost
}
var _ volume.VolumePlugin = &downwardAPIPlugin{}
func (plugin *downwardAPIPlugin) Init(host volume.VolumeHost) {
plugin.host = host
}
func (plugin *downwardAPIPlugin) Name() string {
return downwardAPIPluginName
}
func (plugin *downwardAPIPlugin) CanSupport(spec *volume.Spec) bool {
return spec.VolumeSource.DownwardAPI != nil
}
func (plugin *downwardAPIPlugin) NewBuilder(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions, mounter mount.Interface) (volume.Builder, error) {
v := &downwardAPIVolume{
volName: spec.Name,
pod: pod,
podUID: pod.UID,
plugin: plugin,
mounter: mounter,
}
v.fieldReferenceFileNames = make(map[string]string)
for _, fileInfo := range spec.VolumeSource.DownwardAPI.Items {
v.fieldReferenceFileNames[fileInfo.FieldRef.FieldPath] = path.Clean(fileInfo.Path)
}
return &downwardAPIVolumeBuilder{
downwardAPIVolume: v,
opts: &opts}, nil
}
func (plugin *downwardAPIPlugin) NewCleaner(volName string, podUID types.UID, mounter mount.Interface) (volume.Cleaner, error) {
return &downwardAPIVolumeCleaner{&downwardAPIVolume{volName: volName, podUID: podUID, plugin: plugin, mounter: mounter}}, nil
}
// downwardAPIVolume retrieves downward API data and placing them into the volume on the host.
type downwardAPIVolume struct {
volName string
fieldReferenceFileNames map[string]string
pod *api.Pod
podUID types.UID // TODO: remove this redundancy as soon NewCleaner func will have *api.POD and not only types.UID
plugin *downwardAPIPlugin
mounter mount.Interface
}
// This is the spec for the volume that this plugin wraps.
var wrappedVolumeSpec = &volume.Spec{
Name: "not-used",
VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}},
}
// downwardAPIVolumeBuilder fetches info from downward API from the pod
// and dumps it in files
type downwardAPIVolumeBuilder struct {
*downwardAPIVolume
opts *volume.VolumeOptions
}
// downwardAPIVolumeBuilder implements volume.Builder interface
var _ volume.Builder = &downwardAPIVolumeBuilder{}
// SetUp puts in place the volume plugin.
// This function is not idempotent by design. We want the data to be refreshed periodically.
// The internal sync interval of kubelet will drive the refresh of data.
// TODO: Add volume specific ticker and refresh loop
func (b *downwardAPIVolumeBuilder) SetUp() error {
return b.SetUpAt(b.GetPath())
}
func (b *downwardAPIVolumeBuilder) SetUpAt(dir string) error {
glog.V(3).Infof("Setting up a downwardAPI volume %v for pod %v/%v at %v", b.volName, b.pod.Namespace, b.pod.Name, dir)
// Wrap EmptyDir. Here we rely on the idempotency of the wrapped plugin to avoid repeatedly mounting
wrapped, err := b.plugin.host.NewWrapperBuilder(wrappedVolumeSpec, b.pod, *b.opts, b.mounter)
if err != nil {
glog.Errorf("Couldn't setup downwardAPI volume %v for pod %v/%v: %s", b.volName, b.pod.Namespace, b.pod.Name, err.Error())
return err
}
if err := wrapped.SetUpAt(dir); err != nil {
glog.Errorf("Unable to setup downwardAPI volume %v for pod %v/%v: %s", b.volName, b.pod.Namespace, b.pod.Name, err.Error())
return err
}
data, err := b.collectData()
if err != nil {
glog.Errorf("Error preparing data for downwardAPI volume %v for pod %v/%v: %s", b.volName, b.pod.Namespace, b.pod.Name, err.Error())
return err
}
if !b.isDataChanged(data) {
// No data changed: nothing to write
return nil
}
if err := b.writeData(data); err != nil {
glog.Errorf("Unable to dump files for downwardAPI volume %v for pod %v/%v: %s", b.volName, b.pod.Namespace, b.pod.Name, err.Error())
return err
}
glog.V(3).Infof("Data dumped for downwardAPI volume %v for pod %v/%v", b.volName, b.pod.Namespace, b.pod.Name)
return nil
}
// IsReadOnly func to fullfill volume.Builder interface
func (d *downwardAPIVolume) IsReadOnly() bool {
return true
}
// collectData collects requested downwardAPI in data map.
// Map's key is the requested name of file to dump
// Map's value is the (sorted) content of the field to be dumped in the file.
func (d *downwardAPIVolume) collectData() (map[string]string, error) {
errlist := []error{}
data := make(map[string]string)
for fieldReference, fileName := range d.fieldReferenceFileNames {
if values, err := fieldpath.ExtractFieldPathAsString(d.pod, fieldReference); err != nil {
glog.Errorf("Unable to extract field %s: %s", fieldReference, err.Error())
errlist = append(errlist, err)
} else {
data[fileName] = sortLines(values)
}
}
return data, utilErrors.NewAggregate(errlist)
}
// isDataChanged iterate over all the entries to check wether at least one
// file needs to be updated.
func (d *downwardAPIVolume) isDataChanged(data map[string]string) bool {
for fileName, values := range data {
if isFileToGenerate(path.Join(d.GetPath(), fileName), values) {
return true
}
}
return false
}
// isFileToGenerate compares actual file with the new values. If
// different (or the file does not exist) return true
func isFileToGenerate(fileName, values string) bool {
if _, err := os.Lstat(fileName); os.IsNotExist(err) {
return true
}
return readFile(fileName) != values
}
const (
downwardAPIDir = "..downwardapi"
downwardAPITmpDir = "..downwardapi_tmp"
// It seems reasonable to allow dot-files in the config, so we reserved double-dot-files for the implementation".
)
// writeData writes requested downwardAPI in specified files.
//
// The file visible in this volume are symlinks to files in the '..downwardapi'
// directory. Actual files are stored in an hidden timestamped directory which is
// symlinked to by '..downwardapi'. The timestamped directory and '..downwardapi' symlink
// are created in the plugin root dir.  This scheme allows the files to be
// atomically updated by changing the target of the '..downwardapi' symlink.  When new
// data is available:
//
// 1.  A new timestamped dir is created by writeDataInTimestampDir and requested data
// is written inside new timestamped directory
// 2.  Symlinks and directory for new files are created (if needed).
// For example for files:
// <volume-dir>/user_space/labels
// <volume-dir>/k8s_space/annotations
// <volume-dir>/podName
// This structure is created:
// <volume-dir>/podName -> ..downwardapi/podName
// <volume-dir>/user_space/labels -> ../..downwardapi/user_space/labels
// <volume-dir>/k8s_space/annotations -> ../..downwardapi/k8s_space/annotations
// <volume-dir>/..downwardapi -> ..downwardapi.12345678
// where ..downwardapi.12345678 is a randomly generated directory which contains
// the real data. If a file has to be dumped in subdirectory (for example <volume-dir>/user_space/labels)
// plugin builds a relative symlink (<volume-dir>/user_space/labels -> ../..downwardapi/user_space/labels)
// 3.  The previous timestamped directory is detected reading the '..downwardapi' symlink
// 4.  In case no symlink exists then it's created
// 5.  In case symlink exists a new temporary symlink is created ..downwardapi_tmp
// 6.  ..downwardapi_tmp is renamed to ..downwardapi
// 7.  The previous timestamped directory is removed
func (d *downwardAPIVolume) writeData(data map[string]string) error {
timestampDir, err := d.writeDataInTimestampDir(data)
if err != nil {
glog.Errorf("Unable to write data in temporary directory: %s", err.Error())
return err
}
// update symbolic links for relative paths
if err = d.updateSymlinksToCurrentDir(); err != nil {
os.RemoveAll(timestampDir)
glog.Errorf("Unable to create symlinks and/or directory: %s", err.Error())
return err
}
_, timestampDirBaseName := filepath.Split(timestampDir)
var oldTimestampDirectory string
oldTimestampDirectory, err = os.Readlink(path.Join(d.GetPath(), downwardAPIDir))
if err = os.Symlink(timestampDirBaseName, path.Join(d.GetPath(), downwardAPITmpDir)); err != nil {
os.RemoveAll(timestampDir)
glog.Errorf("Unable to create symolic link: %s", err.Error())
return err
}
// Rename the symbolic link downwardAPITmpDir to downwardAPIDir
if err = os.Rename(path.Join(d.GetPath(), downwardAPITmpDir), path.Join(d.GetPath(), downwardAPIDir)); err != nil {
// in case of error remove latest data and downwardAPITmpDir
os.Remove(path.Join(d.GetPath(), downwardAPITmpDir))
os.RemoveAll(timestampDir)
glog.Errorf("Unable to rename symbolic link: %s", err.Error())
return err
}
// Remove oldTimestampDirectory
if len(oldTimestampDirectory) > 0 {
if err := os.RemoveAll(path.Join(d.GetPath(), oldTimestampDirectory)); err != nil {
glog.Errorf("Unable to remove directory: %s", err.Error())
return err
}
}
return nil
}
// writeDataInTimestampDir writes the latest data into a new temporary directory with a timestamp.
func (d *downwardAPIVolume) writeDataInTimestampDir(data map[string]string) (string, error) {
errlist := []error{}
timestampDir, err := ioutil.TempDir(d.GetPath(), ".."+time.Now().Format("2006_01_02_15_04_05"))
for fileName, values := range data {
fullPathFile := path.Join(timestampDir, fileName)
dir, _ := filepath.Split(fullPathFile)
if err = os.MkdirAll(dir, os.ModePerm); err != nil {
glog.Errorf("Unable to create directory `%s`: %s", dir, err.Error())
return "", err
}
if err := ioutil.WriteFile(fullPathFile, []byte(values), 0644); err != nil {
glog.Errorf("Unable to write file `%s`: %s", fullPathFile, err.Error())
errlist = append(errlist, err)
}
}
return timestampDir, utilErrors.NewAggregate(errlist)
}
// updateSymlinksToCurrentDir creates the relative symlinks for all the files configured in this volume.
// If the directory in a file path does not exist, it is created.
//
// For example for files: "bar", "foo/bar", "baz/bar", "foo/baz/blah"
// the following symlinks and subdirectory are created:
// bar -> ..downwardapi/bar
// baz/bar -> ../..downwardapi/baz/bar
// foo/bar -> ../..downwardapi/foo/bar
// foo/baz/blah -> ../../..downwardapi/foo/baz/blah
func (d *downwardAPIVolume) updateSymlinksToCurrentDir() error {
for _, f := range d.fieldReferenceFileNames {
dir, _ := filepath.Split(f)
nbOfSubdir := 0
if len(dir) > 0 {
// if dir is not empty f contains at least a subdirectory (for example: f="foo/bar")
// since filepath.Split leaves a trailing '/' we have dir="foo/"
// and since len(strings.Split"foo/")=2 to count the number
// of sub directory you need to remove 1
nbOfSubdir = len(strings.Split(dir, "/")) - 1
if err := os.MkdirAll(path.Join(d.GetPath(), dir), os.ModePerm); err != nil {
return err
}
}
if _, err := os.Readlink(path.Join(d.GetPath(), f)); err != nil {
// link does not exist create it
presentedFile := path.Join(strings.Repeat("../", nbOfSubdir), downwardAPIDir, f)
actualFile := path.Join(d.GetPath(), f)
if err := os.Symlink(presentedFile, actualFile); err != nil {
return err
}
}
}
return nil
}
// readFile reads the file at the given path and returns the content as a string.
func readFile(path string) string {
if data, err := ioutil.ReadFile(path); err == nil {
return string(data)
}
return ""
}
// sortLines sorts the strings generated from map based data
// (annotations and labels)
func sortLines(values string) string {
splitted := strings.Split(values, "\n")
sort.Strings(splitted)
return strings.Join(splitted, "\n")
}
func (d *downwardAPIVolume) GetPath() string {
return d.plugin.host.GetPodVolumeDir(d.podUID, util.EscapeQualifiedNameForDisk(downwardAPIPluginName), d.volName)
}
// downwardAPIVolumeCleander handles cleaning up downwardAPI volumes
type downwardAPIVolumeCleaner struct {
*downwardAPIVolume
}
// downwardAPIVolumeCleaner implements volume.Cleaner interface
var _ volume.Cleaner = &downwardAPIVolumeCleaner{}
func (c *downwardAPIVolumeCleaner) TearDown() error {
return c.TearDownAt(c.GetPath())
}
func (c *downwardAPIVolumeCleaner) TearDownAt(dir string) error {
glog.V(3).Infof("Tearing down volume %v for pod %v at %v", c.volName, c.podUID, dir)
// Wrap EmptyDir, let it do the teardown.
wrapped, err := c.plugin.host.NewWrapperCleaner(wrappedVolumeSpec, c.podUID, c.mounter)
if err != nil {
return err
}
return wrapped.TearDownAt(dir)
}
func (b *downwardAPIVolumeBuilder) getMetaDir() string {
return path.Join(b.plugin.host.GetPodPluginDir(b.podUID, util.EscapeQualifiedNameForDisk(downwardAPIPluginName)), b.volName)
}

View File

@ -0,0 +1,655 @@
/*
Copyright 2015 The Kubernetes Authors 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 downwardapi
import (
"fmt"
"io/ioutil"
"os"
"path"
"testing"
"k8s.io/kubernetes/pkg/api"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/client/unversioned/testclient"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
"k8s.io/kubernetes/pkg/volume/empty_dir"
)
const basePath = "/tmp/fake"
func formatMap(m map[string]string) string {
var l string
for key, value := range m {
l += key + "=" + fmt.Sprintf("%q", value) + "\n"
}
return l
}
func newTestHost(t *testing.T, client client.Interface) volume.VolumeHost {
tempDir, err := ioutil.TempDir(basePath, "downwardApi_volume_test.")
if err != nil {
t.Fatalf("can't make a temp rootdir: %v", err)
}
return volume.NewFakeVolumeHost(tempDir, client, empty_dir.ProbeVolumePlugins())
}
func TestCanSupport(t *testing.T) {
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, nil))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
if err != nil {
t.Errorf("Can't find the plugin by name")
}
if plugin.Name() != downwardAPIPluginName {
t.Errorf("Wrong name: %s", plugin.Name())
}
}
func CleanEverything(plugin volume.VolumePlugin, testVolumeName, volumePath string, testPodUID types.UID, t *testing.T) {
cleaner, err := plugin.NewCleaner(testVolumeName, testPodUID, mount.New())
if err != nil {
t.Errorf("Failed to make a new Cleaner: %v", err)
}
if cleaner == nil {
t.Errorf("Got a nil Cleaner")
}
if err := cleaner.TearDown(); err != nil {
t.Errorf("Expected success, got: %v", err)
}
if _, err := os.Stat(volumePath); err == nil {
t.Errorf("TearDown() failed, volume path still exists: %s", volumePath)
} else if !os.IsNotExist(err) {
t.Errorf("SetUp() failed: %v", err)
}
}
func TestLabels(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_labels"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
labels := map[string]string{
"key1": "value1",
"key2": "value2"}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
Labels: labels,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "labels", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.labels"}}}},
},
}
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "labels"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(labels)) {
t.Errorf("Found `%s` expected %s", data, formatMap(labels))
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}
func TestAnnotations(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_annotations"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
annotations := map[string]string{
"a1": "value1",
"a2": "value2"}
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "annotations", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.annotations"}}}},
},
}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
Annotations: annotations,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Annotations: annotations}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "annotations"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(annotations)) {
t.Errorf("Found `%s` expected %s", data, formatMap(annotations))
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}
func TestName(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_name"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "name_file_name", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.name"}}}},
},
}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Name: testName}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "name_file_name"))
if err != nil {
t.Errorf(err.Error())
}
if string(data) != testName {
t.Errorf("Found `%s` expected %s", string(data), testName)
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}
func TestNamespace(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_namespace"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "namespace_file_name", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.namespace"}}}},
},
}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Namespace: testNamespace}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "namespace_file_name"))
if err != nil {
t.Errorf(err.Error())
}
if string(data) != testNamespace {
t.Errorf("Found `%s` expected %s", string(data), testNamespace)
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}
func TestWriteTwiceNoUpdate(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_write_twice_no_update"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
labels := map[string]string{
"key1": "value1",
"key2": "value2"}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
Labels: labels,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "labels", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.labels"}}}},
},
}
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
// get the link of the link
var currentTarget string
if currentTarget, err = os.Readlink(path.Join(volumePath, downwardAPIDir)); err != nil {
t.Errorf(".current should be a link... %s\n", err.Error())
}
err = builder.SetUp() // now re-run Setup
if err != nil {
t.Errorf("Failed to re-setup volume: %v", err)
}
// get the link of the link
var currentTarget2 string
if currentTarget2, err = os.Readlink(path.Join(volumePath, downwardAPIDir)); err != nil {
t.Errorf(".current should be a link... %s\n", err.Error())
}
if currentTarget2 != currentTarget {
t.Errorf("No update between the two Setup... Target link should be the same %s %s\n", currentTarget, currentTarget2)
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "labels"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(labels)) {
t.Errorf("Found `%s` expected %s", data, formatMap(labels))
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}
func TestWriteTwiceWithUpdate(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_write_twice_with_update"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
labels := map[string]string{
"key1": "value1",
"key2": "value2"}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
Labels: labels,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "labels", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.labels"}}}},
},
}
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
var currentTarget string
if currentTarget, err = os.Readlink(path.Join(volumePath, downwardAPIDir)); err != nil {
t.Errorf("labels file should be a link... %s\n", err.Error())
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "labels"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(labels)) {
t.Errorf("Found `%s` expected %s", data, formatMap(labels))
}
newLabels := map[string]string{
"key1": "value1",
"key2": "value2",
"key3": "value3"}
// Now update the labels
pod.ObjectMeta.Labels = newLabels
err = builder.SetUp() // now re-run Setup
if err != nil {
t.Errorf("Failed to re-setup volume: %v", err)
}
// get the link of the link
var currentTarget2 string
if currentTarget2, err = os.Readlink(path.Join(volumePath, downwardAPIDir)); err != nil {
t.Errorf(".current should be a link... %s\n", err.Error())
}
if currentTarget2 == currentTarget {
t.Errorf("Got and update between the two Setup... Target link should NOT be the same\n")
}
data, err = ioutil.ReadFile(path.Join(volumePath, "labels"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(newLabels)) {
t.Errorf("Found `%s` expected %s", data, formatMap(newLabels))
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}
func TestWriteWithUnixPath(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_write_with_unix_path"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
labels := map[string]string{
"key1": "value1",
"key2": "value2",
"key3": "value3\n"}
annotations := map[string]string{
"a1": "value1",
"a2": "value2"}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
Labels: labels,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "this/is/mine/labels", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.labels"}},
{Path: "this/is/yours/annotations", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.annotations"}},
}}},
}
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels, Annotations: annotations}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "this/is/mine/labels"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(labels)) {
t.Errorf("Found `%s` expected %s", data, formatMap(labels))
}
data, err = ioutil.ReadFile(path.Join(volumePath, "this/is/yours/annotations"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(annotations)) {
t.Errorf("Found `%s` expected %s", data, formatMap(annotations))
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}
func TestWriteWithUnixPathBadPath(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_write_with_unix_path"
testNamespace = "test_metadata_namespace"
testName = "test_metadata_name"
)
labels := map[string]string{
"key1": "value1",
"key2": "value2"}
fake := testclient.NewSimpleFake(&api.Pod{
ObjectMeta: api.ObjectMeta{
Name: testName,
Namespace: testNamespace,
Labels: labels,
},
})
pluginMgr := volume.VolumePluginMgr{}
pluginMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t, fake))
plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName)
volumeSpec := &api.Volume{
Name: testVolumeName,
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{Path: "this//labels", FieldRef: api.ObjectFieldSelector{
FieldPath: "metadata.labels"}},
}}},
}
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
var data []byte
data, err = ioutil.ReadFile(path.Join(volumePath, "this/labels"))
if err != nil {
t.Errorf(err.Error())
}
if sortLines(string(data)) != sortLines(formatMap(labels)) {
t.Errorf("Found `%s` expected %s", data, formatMap(labels))
}
CleanEverything(plugin, testVolumeName, volumePath, testPodUID, t)
}

View File

@ -0,0 +1,97 @@
/*
Copyright 2015 The Kubernetes Authors 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 e2e
import (
"fmt"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/util"
. "github.com/onsi/ginkgo"
)
var _ = Describe("Downwar dAPI volume", func() {
f := NewFramework("downward-api")
It("should provide labels and annotations files", func() {
podName := "metadata-volume-" + string(util.NewUUID())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: podName,
Labels: map[string]string{"cluster": "rack10"},
Annotations: map[string]string{"builder": "john-doe"},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "client-container",
Image: "gcr.io/google_containers/busybox",
Command: []string{"sh", "-c", "cat /etc/labels /etc/annotations /etc/podname"},
VolumeMounts: []api.VolumeMount{
{
Name: "podinfo",
MountPath: "/etc",
ReadOnly: false,
},
},
},
},
Volumes: []api.Volume{
{
Name: "podinfo",
VolumeSource: api.VolumeSource{
DownwardAPI: &api.DownwardAPIVolumeSource{
Items: []api.DownwardAPIVolumeFile{
{
Path: "labels",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.labels",
},
},
{
Path: "annotations",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.annotations",
},
},
{
Path: "podname",
FieldRef: api.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.name",
},
},
},
},
},
},
},
RestartPolicy: api.RestartPolicyNever,
},
}
testContainerOutput("downward API volume plugin", f.Client, pod, 0, []string{
fmt.Sprintf("cluster=\"rack10\"\n"),
fmt.Sprintf("builder=\"john-doe\"\n"),
fmt.Sprintf("%s\n", podName),
}, f.Namespace.Name)
})
})
// TODO: add test-webserver example as pointed out in https://github.com/kubernetes/kubernetes/pull/5093#discussion-diff-37606771