1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
|
/*
Copyright © 2021 The CDI Authors
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 cdi
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
oci "github.com/opencontainers/runtime-spec/specs-go"
ocigen "github.com/opencontainers/runtime-tools/generate"
cdi "tags.cncf.io/container-device-interface/specs-go"
)
const (
// PrestartHook is the name of the OCI "prestart" hook.
PrestartHook = "prestart"
// CreateRuntimeHook is the name of the OCI "createRuntime" hook.
CreateRuntimeHook = "createRuntime"
// CreateContainerHook is the name of the OCI "createContainer" hook.
CreateContainerHook = "createContainer"
// StartContainerHook is the name of the OCI "startContainer" hook.
StartContainerHook = "startContainer"
// PoststartHook is the name of the OCI "poststart" hook.
PoststartHook = "poststart"
// PoststopHook is the name of the OCI "poststop" hook.
PoststopHook = "poststop"
)
var (
// Names of recognized hooks.
validHookNames = map[string]struct{}{
PrestartHook: {},
CreateRuntimeHook: {},
CreateContainerHook: {},
StartContainerHook: {},
PoststartHook: {},
PoststopHook: {},
}
)
// ContainerEdits represent updates to be applied to an OCI Spec.
// These updates can be specific to a CDI device, or they can be
// specific to a CDI Spec. In the former case these edits should
// be applied to all OCI Specs where the corresponding CDI device
// is injected. In the latter case, these edits should be applied
// to all OCI Specs where at least one devices from the CDI Spec
// is injected.
type ContainerEdits struct {
*cdi.ContainerEdits
}
// Apply edits to the given OCI Spec. Updates the OCI Spec in place.
// Returns an error if the update fails.
func (e *ContainerEdits) Apply(spec *oci.Spec) error {
if spec == nil {
return errors.New("can't edit nil OCI Spec")
}
if e == nil || e.ContainerEdits == nil {
return nil
}
specgen := ocigen.NewFromSpec(spec)
if len(e.Env) > 0 {
specgen.AddMultipleProcessEnv(e.Env)
}
for _, d := range e.DeviceNodes {
dn := DeviceNode{d}
err := dn.fillMissingInfo()
if err != nil {
return err
}
dev := dn.toOCI()
if dev.UID == nil && spec.Process != nil {
if uid := spec.Process.User.UID; uid > 0 {
dev.UID = &uid
}
}
if dev.GID == nil && spec.Process != nil {
if gid := spec.Process.User.GID; gid > 0 {
dev.GID = &gid
}
}
specgen.RemoveDevice(dev.Path)
specgen.AddDevice(dev)
if dev.Type == "b" || dev.Type == "c" {
access := d.Permissions
if access == "" {
access = "rwm"
}
specgen.AddLinuxResourcesDevice(true, dev.Type, &dev.Major, &dev.Minor, access)
}
}
if len(e.Mounts) > 0 {
for _, m := range e.Mounts {
specgen.RemoveMount(m.ContainerPath)
specgen.AddMount((&Mount{m}).toOCI())
}
sortMounts(&specgen)
}
for _, h := range e.Hooks {
ociHook := (&Hook{h}).toOCI()
switch h.HookName {
case PrestartHook:
specgen.AddPreStartHook(ociHook)
case PoststartHook:
specgen.AddPostStartHook(ociHook)
case PoststopHook:
specgen.AddPostStopHook(ociHook)
// TODO: Maybe runtime-tools/generate should be updated with these...
case CreateRuntimeHook:
ensureOCIHooks(spec)
spec.Hooks.CreateRuntime = append(spec.Hooks.CreateRuntime, ociHook)
case CreateContainerHook:
ensureOCIHooks(spec)
spec.Hooks.CreateContainer = append(spec.Hooks.CreateContainer, ociHook)
case StartContainerHook:
ensureOCIHooks(spec)
spec.Hooks.StartContainer = append(spec.Hooks.StartContainer, ociHook)
default:
return fmt.Errorf("unknown hook name %q", h.HookName)
}
}
if e.IntelRdt != nil {
// The specgen is missing functionality to set all parameters so we
// just piggy-back on it to initialize all structs and the copy over.
specgen.SetLinuxIntelRdtClosID(e.IntelRdt.ClosID)
spec.Linux.IntelRdt = (&IntelRdt{e.IntelRdt}).toOCI()
}
for _, additionalGID := range e.AdditionalGIDs {
if additionalGID == 0 {
continue
}
specgen.AddProcessAdditionalGid(additionalGID)
}
return nil
}
// Validate container edits.
func (e *ContainerEdits) Validate() error {
if e == nil || e.ContainerEdits == nil {
return nil
}
if err := ValidateEnv(e.Env); err != nil {
return fmt.Errorf("invalid container edits: %w", err)
}
for _, d := range e.DeviceNodes {
if err := (&DeviceNode{d}).Validate(); err != nil {
return err
}
}
for _, h := range e.Hooks {
if err := (&Hook{h}).Validate(); err != nil {
return err
}
}
for _, m := range e.Mounts {
if err := (&Mount{m}).Validate(); err != nil {
return err
}
}
if e.IntelRdt != nil {
if err := (&IntelRdt{e.IntelRdt}).Validate(); err != nil {
return err
}
}
return nil
}
// Append other edits into this one. If called with a nil receiver,
// allocates and returns newly allocated edits.
func (e *ContainerEdits) Append(o *ContainerEdits) *ContainerEdits {
if o == nil || o.ContainerEdits == nil {
return e
}
if e == nil {
e = &ContainerEdits{}
}
if e.ContainerEdits == nil {
e.ContainerEdits = &cdi.ContainerEdits{}
}
e.Env = append(e.Env, o.Env...)
e.DeviceNodes = append(e.DeviceNodes, o.DeviceNodes...)
e.Hooks = append(e.Hooks, o.Hooks...)
e.Mounts = append(e.Mounts, o.Mounts...)
if o.IntelRdt != nil {
e.IntelRdt = o.IntelRdt
}
e.AdditionalGIDs = append(e.AdditionalGIDs, o.AdditionalGIDs...)
return e
}
// isEmpty returns true if these edits are empty. This is valid in a
// global Spec context but invalid in a Device context.
func (e *ContainerEdits) isEmpty() bool {
if e == nil {
return false
}
if len(e.Env) > 0 {
return false
}
if len(e.DeviceNodes) > 0 {
return false
}
if len(e.Hooks) > 0 {
return false
}
if len(e.Mounts) > 0 {
return false
}
if len(e.AdditionalGIDs) > 0 {
return false
}
if e.IntelRdt != nil {
return false
}
return true
}
// ValidateEnv validates the given environment variables.
func ValidateEnv(env []string) error {
for _, v := range env {
if strings.IndexByte(v, byte('=')) <= 0 {
return fmt.Errorf("invalid environment variable %q", v)
}
}
return nil
}
// DeviceNode is a CDI Spec DeviceNode wrapper, used for validating DeviceNodes.
type DeviceNode struct {
*cdi.DeviceNode
}
// Validate a CDI Spec DeviceNode.
func (d *DeviceNode) Validate() error {
validTypes := map[string]struct{}{
"": {},
"b": {},
"c": {},
"u": {},
"p": {},
}
if d.Path == "" {
return errors.New("invalid (empty) device path")
}
if _, ok := validTypes[d.Type]; !ok {
return fmt.Errorf("device %q: invalid type %q", d.Path, d.Type)
}
for _, bit := range d.Permissions {
if bit != 'r' && bit != 'w' && bit != 'm' {
return fmt.Errorf("device %q: invalid permissions %q",
d.Path, d.Permissions)
}
}
return nil
}
// Hook is a CDI Spec Hook wrapper, used for validating hooks.
type Hook struct {
*cdi.Hook
}
// Validate a hook.
func (h *Hook) Validate() error {
if _, ok := validHookNames[h.HookName]; !ok {
return fmt.Errorf("invalid hook name %q", h.HookName)
}
if h.Path == "" {
return fmt.Errorf("invalid hook %q with empty path", h.HookName)
}
if err := ValidateEnv(h.Env); err != nil {
return fmt.Errorf("invalid hook %q: %w", h.HookName, err)
}
return nil
}
// Mount is a CDI Mount wrapper, used for validating mounts.
type Mount struct {
*cdi.Mount
}
// Validate a mount.
func (m *Mount) Validate() error {
if m.HostPath == "" {
return errors.New("invalid mount, empty host path")
}
if m.ContainerPath == "" {
return errors.New("invalid mount, empty container path")
}
return nil
}
// IntelRdt is a CDI IntelRdt wrapper.
// This is used for validation and conversion to OCI specifications.
type IntelRdt struct {
*cdi.IntelRdt
}
// ValidateIntelRdt validates the IntelRdt configuration.
//
// Deprecated: ValidateIntelRdt is deprecated use IntelRdt.Validate() instead.
func ValidateIntelRdt(i *cdi.IntelRdt) error {
return (&IntelRdt{i}).Validate()
}
// Validate validates the IntelRdt configuration.
func (i *IntelRdt) Validate() error {
// ClosID must be a valid Linux filename
if len(i.ClosID) >= 4096 || i.ClosID == "." || i.ClosID == ".." || strings.ContainsAny(i.ClosID, "/\n") {
return errors.New("invalid ClosID")
}
return nil
}
// Ensure OCI Spec hooks are not nil so we can add hooks.
func ensureOCIHooks(spec *oci.Spec) {
if spec.Hooks == nil {
spec.Hooks = &oci.Hooks{}
}
}
// sortMounts sorts the mounts in the given OCI Spec.
func sortMounts(specgen *ocigen.Generator) {
mounts := specgen.Mounts()
specgen.ClearMounts()
sort.Stable(orderedMounts(mounts))
specgen.Config.Mounts = mounts
}
// orderedMounts defines how to sort an OCI Spec Mount slice.
// This is the almost the same implementation sa used by CRI-O and Docker,
// with a minor tweak for stable sorting order (easier to test):
//
// https://github.com/moby/moby/blob/17.05.x/daemon/volumes.go#L26
type orderedMounts []oci.Mount
// Len returns the number of mounts. Used in sorting.
func (m orderedMounts) Len() int {
return len(m)
}
// Less returns true if the number of parts (a/b/c would be 3 parts) in the
// mount indexed by parameter 1 is less than that of the mount indexed by
// parameter 2. Used in sorting.
func (m orderedMounts) Less(i, j int) bool {
return m.parts(i) < m.parts(j)
}
// Swap swaps two items in an array of mounts. Used in sorting
func (m orderedMounts) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
// parts returns the number of parts in the destination of a mount. Used in sorting.
func (m orderedMounts) parts(i int) int {
return strings.Count(filepath.Clean(m[i].Destination), string(os.PathSeparator))
}
|