Debian Codegraph @

pkg/invoke/exec.go

raw
1 // Copyright 2015 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 invoke
16
17 import (
18 "context"
19 "encoding/json"
20 "fmt"
21 "os"
22
23 "github.com/containernetworking/cni/pkg/types"
24 "github.com/containernetworking/cni/pkg/types/create"
25 "github.com/containernetworking/cni/pkg/version"
26 )
27
28 // Exec is an interface encapsulates all operations that deal with finding
29 // and executing a CNI plugin. Tests may provide a fake implementation
30 // to avoid writing fake plugins to temporary directories during the test.
31 type Exec interface {
32 ExecPlugin(ctx context.Context, pluginPath string, stdinData []byte, environ []string) ([]byte, error)
33 FindInPath(plugin string, paths []string) (string, error)
34 Decode(jsonBytes []byte) (version.PluginInfo, error)
35 }
36
37 // Plugin must return result in same version as specified in netconf; but
38 // for backwards compatibility reasons if the result version is empty use
39 // config version (rather than technically correct 0.1.0).
40 // https://github.com/containernetworking/cni/issues/895
41 func fixupResultVersion(netconf, result []byte) (string, []byte, error) {
42 versionDecoder := &version.ConfigDecoder{}
43 confVersion, err := versionDecoder.Decode(netconf)
44 if err != nil {
45 return "", nil, err
46 }
47
48 var rawResult map[string]interface{}
49 if err := json.Unmarshal(result, &rawResult); err != nil {
50 return "", nil, fmt.Errorf("failed to unmarshal raw result: %w", err)
51 }
52
53 // plugin output of "null" is successfully unmarshalled, but results in a nil
54 // map which causes a panic when the confVersion is assigned below.
55 if rawResult == nil {
56 rawResult = make(map[string]interface{})
57 }
58
59 // Manually decode Result version; we need to know whether its cniVersion
60 // is empty, while built-in decoders (correctly) substitute 0.1.0 for an
61 // empty version per the CNI spec.
62 if resultVerRaw, ok := rawResult["cniVersion"]; ok {
63 resultVer, ok := resultVerRaw.(string)
64 if ok && resultVer != "" {
65 return resultVer, result, nil
66 }
67 }
68
69 // If the cniVersion is not present or empty, assume the result is
70 // the same CNI spec version as the config
71 rawResult["cniVersion"] = confVersion
72 newBytes, err := json.Marshal(rawResult)
73 if err != nil {
74 return "", nil, fmt.Errorf("failed to remarshal fixed result: %w", err)
75 }
76
77 return confVersion, newBytes, nil
78 }
79
80 // For example, a testcase could pass an instance of the following fakeExec
81 // object to ExecPluginWithResult() to verify the incoming stdin and environment
82 // and provide a tailored response:
83 //
84 // import (
85 // "encoding/json"
86 // "path"
87 // "strings"
88 // )
89 //
90 // type fakeExec struct {
91 // version.PluginDecoder
92 // }
93 //
94 // func (f *fakeExec) ExecPlugin(pluginPath string, stdinData []byte, environ []string) ([]byte, error) {
95 // net := &types.NetConf{}
96 // err := json.Unmarshal(stdinData, net)
97 // if err != nil {
98 // return nil, fmt.Errorf("failed to unmarshal configuration: %v", err)
99 // }
100 // pluginName := path.Base(pluginPath)
101 // if pluginName != net.Type {
102 // return nil, fmt.Errorf("plugin name %q did not match config type %q", pluginName, net.Type)
103 // }
104 // for _, e := range environ {
105 // // Check environment for forced failure request
106 // parts := strings.Split(e, "=")
107 // if len(parts) > 0 && parts[0] == "FAIL" {
108 // return nil, fmt.Errorf("failed to execute plugin %s", pluginName)
109 // }
110 // }
111 // return []byte("{\"CNIVersion\":\"0.4.0\"}"), nil
112 // }
113 //
114 // func (f *fakeExec) FindInPath(plugin string, paths []string) (string, error) {
115 // if len(paths) > 0 {
116 // return path.Join(paths[0], plugin), nil
117 // }
118 // return "", fmt.Errorf("failed to find plugin %s in paths %v", plugin, paths)
119 // }
120
121 func ExecPluginWithResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) (types.Result, error) {
122 if exec == nil {
123 exec = defaultExec
124 }
125
126 stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv())
127 if err != nil {
128 return nil, err
129 }
130
131 resultVersion, fixedBytes, err := fixupResultVersion(netconf, stdoutBytes)
132 if err != nil {
133 return nil, err
134 }
135
136 return create.Create(resultVersion, fixedBytes)
137 }
138
139 func ExecPluginWithoutResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) error {
140 if exec == nil {
141 exec = defaultExec
142 }
143 _, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv())
144 return err
145 }
146
147 // GetVersionInfo returns the version information available about the plugin.
148 // For recent-enough plugins, it uses the information returned by the VERSION
149 // command. For older plugins which do not recognize that command, it reports
150 // version 0.1.0
151 func GetVersionInfo(ctx context.Context, pluginPath string, exec Exec) (version.PluginInfo, error) {
152 if exec == nil {
153 exec = defaultExec
154 }
155 args := &Args{
156 Command: "VERSION",
157
158 // set fake values required by plugins built against an older version of skel
159 NetNS: "dummy",
160 IfName: "dummy",
161 Path: "dummy",
162 }
163 stdin := []byte(fmt.Sprintf(`{"cniVersion":%q}`, version.Current()))
164 stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, stdin, args.AsEnv())
165 if err != nil {
166 if err.Error() == "unknown CNI_COMMAND: VERSION" {
167 return version.PluginSupports("0.1.0"), nil
168 }
169 return nil, err
170 }
171
172 return exec.Decode(stdoutBytes)
173 }
174
175 // DefaultExec is an object that implements the Exec interface which looks
176 // for and executes plugins from disk.
177 type DefaultExec struct {
178 *RawExec
179 version.PluginDecoder
180 }
181
182 // DefaultExec implements the Exec interface
183 var _ Exec = &DefaultExec{}
184
185 var defaultExec = &DefaultExec{
186 RawExec: &RawExec{Stderr: os.Stderr},
187 }