| 1 |
// Copyright 2016 CNI authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package create |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding/json" |
| 19 |
"fmt" |
| 20 |
|
| 21 |
"github.com/containernetworking/cni/pkg/types" |
| 22 |
_ "github.com/containernetworking/cni/pkg/types/020" |
| 23 |
_ "github.com/containernetworking/cni/pkg/types/040" |
| 24 |
_ "github.com/containernetworking/cni/pkg/types/100" |
| 25 |
convert "github.com/containernetworking/cni/pkg/types/internal" |
| 26 |
) |
| 27 |
|
| 28 |
// DecodeVersion returns the CNI version from CNI configuration or result JSON, |
| 29 |
// or an error if the operation could not be performed. |
| 30 |
func DecodeVersion(jsonBytes []byte) (string, error) { |
| 31 |
var conf struct { |
| 32 |
CNIVersion string `json:"cniVersion"` |
| 33 |
} |
| 34 |
err := json.Unmarshal(jsonBytes, &conf) |
| 35 |
if err != nil { |
| 36 |
return "", fmt.Errorf("decoding version from network config: %w", err) |
| 37 |
} |
| 38 |
if conf.CNIVersion == "" { |
| 39 |
return "0.1.0", nil |
| 40 |
} |
| 41 |
return conf.CNIVersion, nil |
| 42 |
} |
| 43 |
|
| 44 |
// Create creates a CNI Result using the given JSON with the expected |
| 45 |
// version, or an error if the creation could not be performed |
| 46 |
func Create(version string, bytes []byte) (types.Result, error) { |
| 47 |
return convert.Create(version, bytes) |
| 48 |
} |
| 49 |
|
| 50 |
// CreateFromBytes creates a CNI Result from the given JSON, automatically |
| 51 |
// detecting the CNI spec version of the result. An error is returned if the |
| 52 |
// operation could not be performed. |
| 53 |
func CreateFromBytes(bytes []byte) (types.Result, error) { |
| 54 |
version, err := DecodeVersion(bytes) |
| 55 |
if err != nil { |
| 56 |
return nil, err |
| 57 |
} |
| 58 |
return convert.Create(version, bytes) |
| 59 |
} |