Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add producer API to write specs #233

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
2 changes: 2 additions & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
# pull-requests: read
# Optional: allow write access to checks to allow the action to annotate code in the PR.
checks: write

jobs:
golangci:
Expand Down
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,11 @@ clean-schema:

# tests for go packages
test-gopkgs:
$(Q)$(GO_TEST) ./...
$(Q)for mod in $$(find . -name go.mod -not -path "./schema/*"); do \
echo "Testing $$(dirname $$mod)..."; ( \
cd $$(dirname $$mod) && $(GO_TEST) ./... \
) || exit 1; \
done

# tests for CDI Spec JSON schema
test-schema: bin/validate
Expand Down
145 changes: 145 additions & 0 deletions api/producer/annotations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
Copyright © 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 producer

import (
"errors"
"fmt"
"strings"

"tags.cncf.io/container-device-interface/api/producer/k8s"
)

const (
// AnnotationPrefix is the prefix for CDI container annotation keys.
AnnotationPrefix = "cdi.k8s.io/"
)

// UpdateAnnotations updates annotations with a plugin-specific CDI device
// injection request for the given devices. Upon any error a non-nil error
// is returned and annotations are left intact. By convention plugin should
// be in the format of "vendor.device-type".
func UpdateAnnotations(annotations map[string]string, plugin string, deviceID string, devices []string) (map[string]string, error) {
key, err := AnnotationKey(plugin, deviceID)
if err != nil {
return annotations, fmt.Errorf("CDI annotation failed: %w", err)
}
if _, ok := annotations[key]; ok {
return annotations, fmt.Errorf("CDI annotation failed, key %q used", key)
}
value, err := AnnotationValue(devices)
if err != nil {
return annotations, fmt.Errorf("CDI annotation failed: %w", err)
}

if annotations == nil {
annotations = make(map[string]string)
}
annotations[key] = value

return annotations, nil
}

// AnnotationKey returns a unique annotation key for an device allocation
// by a K8s device plugin. pluginName should be in the format of
// "vendor.device-type". deviceID is the ID of the device the plugin is
// allocating. It is used to make sure that the generated key is unique
// even if multiple allocations by a single plugin needs to be annotated.
func AnnotationKey(pluginName, deviceID string) (string, error) {
const maxNameLen = 63

if pluginName == "" {
return "", errors.New("invalid plugin name, empty")
}
if deviceID == "" {
return "", errors.New("invalid deviceID, empty")
}

name := pluginName + "_" + strings.ReplaceAll(deviceID, "/", "_")

if len(name) > maxNameLen {
return "", fmt.Errorf("invalid plugin+deviceID %q, too long", name)
}

if c := rune(name[0]); !isAlphaNumeric(c) {
return "", fmt.Errorf("invalid name %q, first '%c' should be alphanumeric",
name, c)
}
if len(name) > 2 {
for _, c := range name[1 : len(name)-1] {
switch {
case isAlphaNumeric(c):
case c == '_' || c == '-' || c == '.':
default:
return "", fmt.Errorf("invalid name %q, invalid character '%c'",
name, c)
}
}
}
if c := rune(name[len(name)-1]); !isAlphaNumeric(c) {
return "", fmt.Errorf("invalid name %q, last '%c' should be alphanumeric",
name, c)
}

return AnnotationPrefix + name, nil
}

// AnnotationValue returns an annotation value for the given devices.
func AnnotationValue(devices []string) (string, error) {
value, sep := "", ""
for _, d := range devices {
if err := ValidateQualifiedName(d); err != nil {
return "", err
}
value += sep + d
sep = ","
}

return value, nil
}

// ValidateSpecAnnotations checks whether spec annotations are valid.
func ValidateSpecAnnotations(name string, any interface{}) error {
if any == nil {
return nil
}

switch v := any.(type) {
case map[string]interface{}:
annotations := make(map[string]string)
for k, v := range v {
if s, ok := v.(string); ok {
annotations[k] = s
} else {
return fmt.Errorf("invalid annotation %v.%v; %v is not a string", name, k, any)
}
}
return validateSpecAnnotations(name, annotations)
}

return nil
}

// validateSpecAnnotations checks whether spec annotations are valid.
func validateSpecAnnotations(name string, annotations map[string]string) error {
path := "annotations"
if name != "" {
path = strings.Join([]string{name, path}, ".")
}

return k8s.ValidateAnnotations(annotations, path)
}
Loading