Skip to content

Commit

Permalink
Add producer API to write specs
Browse files Browse the repository at this point in the history
Signed-off-by: Evan Lezar <[email protected]>
  • Loading branch information
elezar committed Oct 15, 2024
1 parent 91c77d0 commit b67d046
Show file tree
Hide file tree
Showing 7 changed files with 250 additions and 42 deletions.
29 changes: 29 additions & 0 deletions pkg/cdi/producer/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
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

type specFormat string

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")
)
44 changes: 44 additions & 0 deletions pkg/cdi/producer/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
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"

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

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

// WithOverwrite specifies whether a producer should overwrite a CDI spec when
// saving to file.
func WithOverwrite(overwrite bool) Option {
return func(p *Producer) error {
p.failIfExists = !overwrite
return nil
}
}
86 changes: 86 additions & 0 deletions pkg/cdi/producer/producer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
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 (
"path/filepath"

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

// A Producer defines a structure for outputting CDI specifications.
type Producer struct {
format specFormat
failIfExists bool
}

// New creates a new producer with the supplied options.
func New(opts ...Option) (*Producer, error) {
p := &Producer{
format: DefaultSpecFormat,
}
for _, opt := range opts {
err := opt(p)
if err != nil {
return nil, err
}
}
return p, nil
}

// SaveSpec writes the specified 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 Producer was
// configured.
func (p *Producer) SaveSpec(s *cdi.Spec, filename string) (string, error) {
filename = p.normalizeFilename(filename)

sp := spec{
Spec: s,
format: p.specFormatFromFilename(filename),
}

if err := sp.save(filename, !p.failIfExists); err != nil {
return "", err
}

return filename, nil
}

// specFormatFromFilename determines the CDI spec format for the given filename.
func (p *Producer) specFormatFromFilename(filename string) specFormat {
switch filepath.Ext(filename) {
case ".json":
return SpecFormatJSON
case ".yaml", ".yml":
return SpecFormatYAML
default:
return p.format
}
}

// normalizeFilename ensures that the specified filename ends in a supported extension.
func (p *Producer) normalizeFilename(filename string) string {
switch filepath.Ext(filename) {
case ".json":
fallthrough
case ".yaml", ".yml":
return filename
default:
return filename + string(p.format)
}
}
82 changes: 82 additions & 0 deletions pkg/cdi/producer/spec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
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"
"os"
"path/filepath"

"sigs.k8s.io/yaml"

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

type spec struct {
*cdi.Spec
format specFormat
}

// save saves a CDI spec to the specified filename.
func (s *spec) save(filename string, overwrite bool) error {
data, err := s.contents()
if err != nil {
return fmt.Errorf("failed to marshal Spec file: %w", err)
}

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 = tmp.Write(data)
tmp.Close()
if err != nil {
return fmt.Errorf("failed to write Spec file: %w", err)
}

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

// contents returns the raw contents of a CDI specification.
func (s *spec) contents() ([]byte, error) {
switch s.format {
case SpecFormatYAML:
data, err := yaml.Marshal(s.Spec)
if err != nil {
return nil, err
}
data = append([]byte("---\n"), data...)
return data, nil
case SpecFormatJSON:
return json.Marshal(s.Spec)
default:
return nil, fmt.Errorf("undefined CDI spec format %v", s.format)
}
}
2 changes: 1 addition & 1 deletion pkg/cdi/spec_linux.go → pkg/cdi/producer/spec_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 → pkg/cdi/producer/spec_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
47 changes: 7 additions & 40 deletions pkg/cdi/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package cdi

import (
"encoding/json"
"fmt"
"os"
"path/filepath"
Expand All @@ -28,6 +27,7 @@ import (
"sigs.k8s.io/yaml"

"tags.cncf.io/container-device-interface/internal/validation"
"tags.cncf.io/container-device-interface/pkg/cdi/producer"
"tags.cncf.io/container-device-interface/pkg/parser"
cdi "tags.cncf.io/container-device-interface/specs-go"
)
Expand Down Expand Up @@ -118,52 +118,19 @@ func newSpec(raw *cdi.Spec, path string, priority int) (*Spec, error) {
// Write the CDI Spec to the file associated with it during instantiation
// by newSpec() or ReadSpec().
func (s *Spec) write(overwrite bool) error {
var (
data []byte
dir string
tmp *os.File
err error
p, err := producer.New(
producer.WithOverwrite(overwrite),
)

err = validateSpec(s.Spec)
if err != nil {
return err
}

if filepath.Ext(s.path) == ".yaml" {
data, err = yaml.Marshal(s.Spec)
data = append([]byte("---\n"), data...)
} else {
data, err = json.Marshal(s.Spec)
}
if err != nil {
return fmt.Errorf("failed to marshal Spec file: %w", err)
}

dir = filepath.Dir(s.path)
err = os.MkdirAll(dir, 0o755)
savedPath, err := p.SaveSpec(s.Spec, s.path)
if 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 = tmp.Write(data)
tmp.Close()
if err != nil {
return fmt.Errorf("failed to write Spec file: %w", err)
}

err = renameIn(dir, filepath.Base(tmp.Name()), filepath.Base(s.path), overwrite)

if err != nil {
os.Remove(tmp.Name())
err = fmt.Errorf("failed to write Spec file: %w", err)
return err
}

return err
s.path = savedPath
return nil
}

// GetVendor returns the vendor of this Spec.
Expand Down

0 comments on commit b67d046

Please sign in to comment.