github.com/john-lin/cni@v0.6.0-rc1.0.20170712150331-b69e640cc0e2/pkg/version/plugin.go (about) 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 version 16 17 import ( 18 "encoding/json" 19 "fmt" 20 "io" 21 ) 22 23 // PluginInfo reports information about CNI versioning 24 type PluginInfo interface { 25 // SupportedVersions returns one or more CNI spec versions that the plugin 26 // supports. If input is provided in one of these versions, then the plugin 27 // promises to use the same CNI version in its response 28 SupportedVersions() []string 29 30 // Encode writes this CNI version information as JSON to the given Writer 31 Encode(io.Writer) error 32 } 33 34 type pluginInfo struct { 35 CNIVersion_ string `json:"cniVersion"` 36 SupportedVersions_ []string `json:"supportedVersions,omitempty"` 37 } 38 39 // pluginInfo implements the PluginInfo interface 40 var _ PluginInfo = &pluginInfo{} 41 42 func (p *pluginInfo) Encode(w io.Writer) error { 43 return json.NewEncoder(w).Encode(p) 44 } 45 46 func (p *pluginInfo) SupportedVersions() []string { 47 return p.SupportedVersions_ 48 } 49 50 // PluginSupports returns a new PluginInfo that will report the given versions 51 // as supported 52 func PluginSupports(supportedVersions ...string) PluginInfo { 53 if len(supportedVersions) < 1 { 54 panic("programmer error: you must support at least one version") 55 } 56 return &pluginInfo{ 57 CNIVersion_: Current(), 58 SupportedVersions_: supportedVersions, 59 } 60 } 61 62 // PluginDecoder can decode the response returned by a plugin's VERSION command 63 type PluginDecoder struct{} 64 65 func (*PluginDecoder) Decode(jsonBytes []byte) (PluginInfo, error) { 66 var info pluginInfo 67 err := json.Unmarshal(jsonBytes, &info) 68 if err != nil { 69 return nil, fmt.Errorf("decoding version info: %s", err) 70 } 71 if info.CNIVersion_ == "" { 72 return nil, fmt.Errorf("decoding version info: missing field cniVersion") 73 } 74 if len(info.SupportedVersions_) == 0 { 75 if info.CNIVersion_ == "0.2.0" { 76 return PluginSupports("0.1.0", "0.2.0"), nil 77 } 78 return nil, fmt.Errorf("decoding version info: missing field supportedVersions") 79 } 80 return &info, nil 81 }