Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions docs/runtime-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,19 @@ serverless workloads. Containers MUST use the provided temporary storage areas

### Mounts

Platform providers SHOULD NOT allow additional volume mounts. Stateless
applications should package their dependencies within the container. As
serverless applications are expected to scale horizontally and statelessly,
In general, stateless applications should package their dependencies within the
container and not rely on mutable external state for templates, logging
configuration, etc. In some cases, it may be necessary for certain application
settings to be overridden at deploy time (for example, database backends or
authentication credentials). When these settings need to be loaded via a file,
read-only mounts of application configuration and secrets are supported by
`ConfigMap` and `Secrets` volumes. Platform providers MAY apply updates to
`Secrets` and `ConfigMaps` while the application is running; these updates could
complicate rollout and rollback. It is up to the developer to choose appropriate
policies for mounting and updating `ConfigMap` and `Secrets` which are mounted
as volumes.

As serverless applications are expected to scale horizontally and statelessly,
per-container volumes are likely to introduce state and scaling bottlenecks and
are NOT RECOMMENDED.

Expand Down
30 changes: 29 additions & 1 deletion docs/spec/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,14 @@ spec:
# is a core.v1.Container; some fields not allowed, such as resources, ports
container: ... # See the Container section below

# is a heavily restricted []core.v1.Volume; only the secret and configMap
Comment thread
mattmoor marked this conversation as resolved.
Resolved
# types are allowed.
volumes:
- name: foo
secret: ...
- name: bar
configMap: ...

# +optional concurrency strategy. Defaults to Multi.
# Deprecated in favor of ContainerConcurrency.
concurrencyModel: ...
Expand Down Expand Up @@ -217,6 +225,14 @@ spec:

container: ... # See the Container section below

# is a heavily restricted []core.v1.Volume; only the secret and configMap
# types are allowed.
volumes:
- name: foo
secret: ...
- name: bar
configMap: ...

# Name of the service account the code should run as.
serviceAccountName: ...

Expand Down Expand Up @@ -302,6 +318,7 @@ spec: # One of "runLatest", "release", "pinned" (DEPRECATED), or "manual"
revisionTemplate:
spec: # serving.knative.dev/v1alpha1.RevisionSpec
container: ... # See the Container section below
volumes: ... # Optional
containerConcurrency: ... # Optional
timeoutSeconds: ... # Optional
serviceAccountName: ... # Name of the service account the code should run as
Expand All @@ -315,6 +332,7 @@ spec: # One of "runLatest", "release", "pinned" (DEPRECATED), or "manual"
revisionTemplate:
spec: # serving.knative.dev/v1alpha1.RevisionSpec
container: ... # See the Container section below
volumes: ... # Optional
containerConcurrency: ... # Optional
timeoutSeconds: ... # Optional
serviceAccountName: ... # Name of the service account the code should run as
Expand All @@ -331,6 +349,7 @@ spec: # One of "runLatest", "release", "pinned" (DEPRECATED), or "manual"
revisionTemplate:
spec: # serving.knative.dev/v1alpha1.RevisionSpec
container: ... # See the Container section below
volumes: ... # Optional
containerConcurrency: ... # Optional
timeoutSeconds: ... # Optional
serviceAccountName: ... # Name of the service account the code should run as
Expand Down Expand Up @@ -389,7 +408,7 @@ status:

This is a
[core.v1.Container](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#container-v1-core).
Some fields are not allowed, such as name and volumeMounts.
Some fields are not allowed, such as name and lifecycle.

This type is not used on its own but is found composed inside
[Service](#service), [Configuration](#configuration), and [Revision](#revision).
Expand Down Expand Up @@ -424,6 +443,15 @@ container: # v1.Container
name: ... # Optional, one of "http1", "h2c"
protocol: ... # Optional, one of "", "tcp"

# This specifies where the volumes present in the RevisionSpec will be mounted into
# the container. Each of the volumes in the RevisionSpec must be mounted here
# or it is an error.
volumeMounts:
- name: ... # This must match a name from Volumes
mountPath: ... # Where to mount the named Volume.
readOnly: ... # Must be True, will default to True, so it may be omitted.
# All other fields are disallowed.

livenessProbe: ... # Optional
readinessProbe: ... # Optional
resources: ... # Optional
Expand Down
5 changes: 5 additions & 0 deletions pkg/apis/serving/v1alpha1/revision_defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,9 @@ func (rs *RevisionSpec) SetDefaults() {
if rs.TimeoutSeconds == 0 {
rs.TimeoutSeconds = defaultTimeoutSeconds
}

vms := rs.Container.VolumeMounts
for i := range vms {
vms[i].ReadOnly = true
Comment thread
mattmoor marked this conversation as resolved.
Resolved
}
}
28 changes: 28 additions & 0 deletions pkg/apis/serving/v1alpha1/revision_defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"testing"

"github.com/google/go-cmp/cmp"
corev1 "k8s.io/api/core/v1"
)

func TestRevisionDefaulting(t *testing.T) {
Expand All @@ -36,6 +37,33 @@ func TestRevisionDefaulting(t *testing.T) {
TimeoutSeconds: defaultTimeoutSeconds,
},
},
}, {
name: "readonly volumes",
in: &Revision{
Spec: RevisionSpec{
Container: corev1.Container{
Image: "foo",
VolumeMounts: []corev1.VolumeMount{{
Name: "bar",
}},
},
ContainerConcurrency: 1,
TimeoutSeconds: 99,
},
},
want: &Revision{
Spec: RevisionSpec{
Container: corev1.Container{
Image: "foo",
VolumeMounts: []corev1.VolumeMount{{
Name: "bar",
ReadOnly: true,
Comment thread
mattmoor marked this conversation as resolved.
Resolved
}},
},
ContainerConcurrency: 1,
TimeoutSeconds: 99,
},
},
}, {
name: "no overwrite",
in: &Revision{
Expand Down
12 changes: 9 additions & 3 deletions pkg/apis/serving/v1alpha1/revision_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,18 @@ type RevisionSpec struct {

// Container defines the unit of execution for this Revision.
// In the context of a Revision, we disallow a number of the fields of
// this Container, including: name, resources, ports, and volumeMounts.
// TODO(mattmoor): Link to the runtime contract tracked by:
// https://github.com/knative/serving/issues/627
// this Container, including: name and lifecycle.
// See also the runtime contract for more information about the execution
// environment:
// https://github.com/knative/serving/blob/master/docs/runtime-contract.md
// +optional
Container corev1.Container `json:"container,omitempty"`

// Volumes defines a set of Kubernetes volumes to be mounted into the
// specified Container. Currently only ConfigMap and Secret volumes are
// supported.
Volumes []corev1.Volume `json:"volumes,omitempty"`

// TimeoutSeconds holds the max duration the instance is allowed for responding to a request.
// +optional
TimeoutSeconds int64 `json:"timeoutSeconds,omitempty"`
Expand Down
112 changes: 99 additions & 13 deletions pkg/apis/serving/v1alpha1/revision_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package v1alpha1

import (
"fmt"
"path/filepath"
"strconv"

"github.com/google/go-containerregistry/pkg/name"
Expand All @@ -27,9 +28,21 @@ import (
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
)

var (
reservedPaths = sets.NewString(
"/",
"/dev",
"/dev/log", // Should be a domain socket
"/tmp",
"/var",
"/var/log",
)
)

// Validate ensures Revision is properly configured.
func (rt *Revision) Validate() *apis.FieldError {
return ValidateObjectMetadata(rt.GetObjectMeta()).ViaField("metadata").
Expand All @@ -46,19 +59,31 @@ func (rs *RevisionSpec) Validate() *apis.FieldError {
if equality.Semantic.DeepEqual(rs, &RevisionSpec{}) {
return apis.ErrMissingField(apis.CurrentField)
}
errs := validateContainer(rs.Container).ViaField("container").
Also(validateBuildRef(rs.BuildRef).ViaField("buildRef"))

if err := rs.DeprecatedConcurrencyModel.Validate().ViaField("concurrencyModel"); err != nil {
errs = errs.Also(err)
} else if err := ValidateContainerConcurrency(rs.ContainerConcurrency, rs.DeprecatedConcurrencyModel); err != nil {
errs = errs.Also(err)
volumes := sets.NewString()
var errs *apis.FieldError
for i, volume := range rs.Volumes {
if volumes.Has(volume.Name) {
errs = errs.Also((&apis.FieldError{
Comment thread
mattmoor marked this conversation as resolved.
Resolved
Message: fmt.Sprintf("duplicate volume name %q", volume.Name),
Paths: []string{"name"},
}).ViaFieldIndex("volumes", i))
}
errs = errs.Also(validateVolume(volume).ViaFieldIndex("volumes", i))
Comment thread
mattmoor marked this conversation as resolved.
Resolved
volumes.Insert(volume.Name)
}

if err := validateTimeoutSeconds(rs.TimeoutSeconds); err != nil {
errs = errs.Also(validateContainer(rs.Container, volumes).ViaField("container"))
errs = errs.Also(validateBuildRef(rs.BuildRef).ViaField("buildRef"))

if err := rs.DeprecatedConcurrencyModel.Validate().ViaField("concurrencyModel"); err != nil {
errs = errs.Also(err)
} else {
errs = errs.Also(ValidateContainerConcurrency(
rs.ContainerConcurrency, rs.DeprecatedConcurrencyModel))
}
return errs

return errs.Also(validateTimeoutSeconds(rs.TimeoutSeconds))
}

func validateTimeoutSeconds(timeoutSeconds int64) *apis.FieldError {
Expand Down Expand Up @@ -118,24 +143,85 @@ func ValidateContainerConcurrency(cc RevisionContainerConcurrencyType, cm Revisi
return nil
}

func validateContainer(container corev1.Container) *apis.FieldError {
func validateVolume(volume corev1.Volume) *apis.FieldError {
var errs *apis.FieldError
if volume.Name == "" {
Comment thread
mattmoor marked this conversation as resolved.
Resolved
errs = apis.ErrMissingField("name")
} else if len(validation.IsDNS1123Label(volume.Name)) != 0 {
errs = apis.ErrInvalidValue(volume.Name, "name")
}

vs := volume.VolumeSource
switch {
case vs.Secret != nil, vs.ConfigMap != nil:
// These are fine.
default:
errs = errs.Also(apis.ErrMissingOneOf("secret", "configMap"))
}
return errs
}

func validateContainer(container corev1.Container, volumes sets.String) *apis.FieldError {
if equality.Semantic.DeepEqual(container, corev1.Container{}) {
return apis.ErrMissingField(apis.CurrentField)
}

// Check that volume mounts match names in "volumes", that "volumes" has 100%
// coverage, and the field restrictions.
seen := sets.NewString()
var errs *apis.FieldError
for i, vm := range container.VolumeMounts {
// This effectively checks that Name is non-empty because Volume name must be non-empty.
if !volumes.Has(vm.Name) {
errs = errs.Also((&apis.FieldError{
Message: "volumeMount has no matching volume",
Paths: []string{"name"},
}).ViaFieldIndex("volumeMounts", i))
}
seen.Insert(vm.Name)

if vm.MountPath == "" {
errs = errs.Also(apis.ErrMissingField("mountPath").ViaFieldIndex("volumeMounts", i))
} else if reservedPaths.Has(filepath.Clean(vm.MountPath)) {
Comment thread
mattmoor marked this conversation as resolved.
Resolved
errs = errs.Also((&apis.FieldError{
Message: fmt.Sprintf("mountPath %q is a reserved path", filepath.Clean(vm.MountPath)),
Paths: []string{"mountPath"},
}).ViaFieldIndex("volumeMounts", i))
} else if !filepath.IsAbs(vm.MountPath) {
errs = errs.Also(apis.ErrInvalidValue(vm.MountPath, "mountPath").ViaFieldIndex("volumeMounts", i))
}
if !vm.ReadOnly {
errs = errs.Also(apis.ErrMissingField("readOnly").ViaFieldIndex("volumeMounts", i))
Comment thread
mattmoor marked this conversation as resolved.
Resolved
}

if vm.SubPath != "" {
Comment thread
mattmoor marked this conversation as resolved.
Resolved
errs = errs.Also(
apis.ErrDisallowedFields("subPath").ViaFieldIndex("volumeMounts", i))
}
if vm.MountPropagation != nil {
errs = errs.Also(
apis.ErrDisallowedFields("mountPropagation").ViaFieldIndex("volumeMounts", i))
}
}

if missing := volumes.Difference(seen); missing.Len() > 0 {
errs = errs.Also(&apis.FieldError{
Message: fmt.Sprintf("volumes not mounted: %v", missing.List()),
Paths: []string{"volumeMounts"},
})
}

// Some corev1.Container fields are set by Knative Serving controller. We disallow them
// here to avoid silently overwriting these fields and causing confusions for
// the users. See pkg/controller/revision/resources/deploy.go#makePodSpec.
var ignoredFields []string
if container.Name != "" {
ignoredFields = append(ignoredFields, "name")
}
if len(container.VolumeMounts) > 0 {
ignoredFields = append(ignoredFields, "volumeMounts")
}

if container.Lifecycle != nil {
ignoredFields = append(ignoredFields, "lifecycle")
}
var errs *apis.FieldError
if len(ignoredFields) > 0 {
// Complain about all ignored fields so that user can remove them all at once.
errs = errs.Also(apis.ErrDisallowedFields(ignoredFields...))
Expand Down
Loading