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 2 commits into
base: main
Choose a base branch
from
Open
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
34 changes: 34 additions & 0 deletions api/producer/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Copyright © 2024 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 cdi "tags.cncf.io/container-device-interface/specs-go"

const (
// DefaultSpecFormat defines the default encoding used to write CDI specs.
DefaultSpecFormat = SpecFormatYAML

// SpecFormatJSON defines a CDI spec formatted as JSON.
SpecFormatJSON = SpecFormat(".json")
// SpecFormatYAML defines a CDI spec formatted as YAML.
SpecFormatYAML = SpecFormat(".yaml")
)

// A SpecValidator is used to validate a CDI spec.
type SpecValidator interface {
Validate(*cdi.Spec) error
}
23 changes: 23 additions & 0 deletions api/producer/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module tags.cncf.io/container-device-interface/api/producer

go 1.20

require (
github.com/stretchr/testify v1.7.0
golang.org/x/sys v0.1.0
sigs.k8s.io/yaml v1.3.0
tags.cncf.io/container-device-interface/specs-go v0.8.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/mod v0.19.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

replace (
tags.cncf.io/container-device-interface/api/validator => ../validator
tags.cncf.io/container-device-interface/specs-go => ../../specs-go
)
21 changes: 21 additions & 0 deletions api/producer/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8=
70 changes: 70 additions & 0 deletions api/producer/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
Copyright © 2024 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 (
"fmt"
"io/fs"
)

// An Option defines a functional option for constructing a producer.
type Option func(*options) error

type options struct {
specFormat SpecFormat
specValidator SpecValidator
overwrite bool
permissions fs.FileMode
}

// WithSpecFormat sets the output format of a CDI specification.
func WithSpecFormat(format SpecFormat) Option {
return func(o *options) error {
switch format {
case SpecFormatJSON, SpecFormatYAML:
o.specFormat = format
default:
return fmt.Errorf("invalid CDI spec format %v", format)
}
return nil
}
}

// WithSpecValidator sets a validator to be used when writing an output spec.
func WithSpecValidator(specValidator SpecValidator) Option {
return func(o *options) error {
o.specValidator = specValidator
return nil
}
}

// WithOverwrite specifies whether a producer should overwrite a CDI spec when
// saving to file.
func WithOverwrite(overwrite bool) Option {
return func(o *options) error {
o.overwrite = overwrite
return nil
}
}

// WithPermissions sets the file mode to be used for a saved CDI spec.
func WithPermissions(permissions fs.FileMode) Option {
return func(o *options) error {
o.permissions = permissions
return nil
}
}
2 changes: 1 addition & 1 deletion pkg/cdi/spec_linux.go → api/producer/renamein_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
limitations under the License.
*/

package cdi
package producer

import (
"fmt"
Expand Down
2 changes: 1 addition & 1 deletion pkg/cdi/spec_other.go → api/producer/renamein_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
limitations under the License.
*/

package cdi
package producer

import (
"os"
Expand Down
95 changes: 95 additions & 0 deletions api/producer/spec-format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
Copyright © 2024 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 (
"encoding/json"
"fmt"
"io"
"path/filepath"

"sigs.k8s.io/yaml"

cdi "tags.cncf.io/container-device-interface/specs-go"
)

// A SpecFormat defines the encoding to use when reading or writing a CDI specification.
type SpecFormat string

type specFormatter struct {
*cdi.Spec
options
}

// WriteTo writes the spec to the specified writer.
func (p *specFormatter) WriteTo(w io.Writer) (int64, error) {
data, err := p.contents()
if err != nil {
return 0, fmt.Errorf("failed to marshal Spec file: %w", err)
}

n, err := w.Write(data)
return int64(n), err
}

// marshal returns the raw contents of a CDI specification.
// No validation is performed.
func (p SpecFormat) marshal(spec *cdi.Spec) ([]byte, error) {
switch p {
case SpecFormatYAML:
data, err := yaml.Marshal(spec)
if err != nil {
return nil, err
}
data = append([]byte("---\n"), data...)
return data, nil
case SpecFormatJSON:
return json.Marshal(spec)
default:
return nil, fmt.Errorf("undefined CDI spec format %v", p)
}
}

// normalizeFilename ensures that the specified filename ends in a supported extension.
func (p SpecFormat) normalizeFilename(filename string) (string, SpecFormat) {
switch filepath.Ext(filename) {
case ".json":
return filename, SpecFormatJSON
case ".yaml":
return filename, SpecFormatYAML
default:
return filename + string(p), p
}
}

// validate performs an explicit validation of the spec.
// If no validator is configured, the spec is considered unconditionally valid.
func (p *specFormatter) validate() error {
if p == nil || p.specValidator == nil {
return nil
}
return p.specValidator.Validate(p.Spec)
}

// contents returns the raw contents of a CDI specification.
// Validation is performed before marshalling the contentent based on the spec format.
func (p *specFormatter) contents() ([]byte, error) {
if err := p.validate(); err != nil {
return nil, fmt.Errorf("spec validation failed: %w", err)
}
return p.specFormat.marshal(p.Spec)
}
108 changes: 108 additions & 0 deletions api/producer/writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
Copyright © 2024 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 (
"fmt"
"io"
"os"
"path/filepath"

cdi "tags.cncf.io/container-device-interface/specs-go"
)

// A SpecWriter defines a structure for outputting CDI specifications.
type SpecWriter struct {
options
}

// NewSpecWriter creates a spec writer with the supplied options.
func NewSpecWriter(opts ...Option) (*SpecWriter, error) {
sw := &SpecWriter{
options: options{
overwrite: true,
// TODO: This could be updated to 0644 to be world-readable.
permissions: 0600,
specFormat: DefaultSpecFormat,
},
}
for _, opt := range opts {
err := opt(&sw.options)
if err != nil {
return nil, err
}
}
return sw, nil
}

// Save writes a CDI spec to a file with the specified name.
// If the filename ends in a supported extension, the format implied by the
// extension takes precedence over the format with which the SpecWriter was
// configured.
func (p *SpecWriter) Save(spec *cdi.Spec, filename string) (string, error) {
filename, outputFormat := p.specFormat.normalizeFilename(filename)

specFormatter := specFormatter{
Spec: spec,
options: options{
specFormat: outputFormat,
specValidator: p.specValidator,
},
}

dir := filepath.Dir(filename)
if dir != "" {
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", fmt.Errorf("failed to create Spec dir: %w", err)
}
}

tmp, err := os.CreateTemp(dir, "spec.*.tmp")
if err != nil {
return "", fmt.Errorf("failed to create Spec file: %w", err)
}

_, err = specFormatter.WriteTo(tmp)
tmp.Close()
if err != nil {
return "", fmt.Errorf("failed to write Spec file: %w", err)
}

if err := os.Chmod(tmp.Name(), p.permissions); err != nil {
return "", fmt.Errorf("failed to set permissions on spec file: %w", err)
}

err = renameIn(dir, filepath.Base(tmp.Name()), filepath.Base(filename), p.overwrite)
if err != nil {
_ = os.Remove(tmp.Name())
return "", fmt.Errorf("failed to write Spec file: %w", err)
}
return filename, nil
}

// WriteSpecTo writes the specified spec to the specified writer.
func (p *SpecWriter) WriteSpecTo(spec *cdi.Spec, w io.Writer) (int64, error) {
specFormatter := specFormatter{
Spec: spec,
options: options{
specFormat: p.specFormat,
specValidator: p.specValidator,
},
}

return specFormatter.WriteTo(w)
}
Loading