Debian Codegraph @

plugins/test/noop/main.go

raw
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 /*
16 Noop plugin is a CNI plugin designed for use as a test-double.
17
18 When calling, set the CNI_ARGS env var equal to the path of a file containing
19 the JSON encoding of a Debug.
20 */
21
22 package main
23
24 import (
25 "encoding/json"
26 "fmt"
27 "io"
28 "os"
29 "strings"
30
31 "github.com/containernetworking/cni/pkg/skel"
32 "github.com/containernetworking/cni/pkg/types"
33 current "github.com/containernetworking/cni/pkg/types/100"
34 "github.com/containernetworking/cni/pkg/version"
35 noop_debug "github.com/containernetworking/cni/plugins/test/noop/debug"
36 )
37
38 type NetConf struct {
39 types.PluginConf
40 DebugFile string `json:"debugFile"`
41 CommandLog string `json:"commandLog"`
42 }
43
44 func loadConf(bytes []byte) (*NetConf, error) {
45 n := &NetConf{}
46 if err := json.Unmarshal(bytes, n); err != nil {
47 return nil, fmt.Errorf("failed to load netconf: %w %q", err, string(bytes))
48 }
49 if err := version.ParsePrevResult(&n.PluginConf); err != nil {
50 return nil, err
51 }
52 return n, nil
53 }
54
55 // parse extra args i.e. FOO=BAR;ABC=123
56 func parseExtraArgs(args string) (map[string]string, error) {
57 m := make(map[string]string)
58 if len(args) == 0 {
59 return m, nil
60 }
61
62 items := strings.Split(args, ";")
63 for _, item := range items {
64 kv := strings.Split(item, "=")
65 if len(kv) != 2 {
66 return nil, fmt.Errorf("CNI_ARGS invalid key/value pair: %s", kv)
67 }
68 m[kv[0]] = kv[1]
69 }
70 return m, nil
71 }
72
73 func getConfig(stdinData []byte, args string) (string, *NetConf, error) {
74 netConf, err := loadConf(stdinData)
75 if err != nil {
76 return "", nil, err
77 }
78
79 extraArgs, err := parseExtraArgs(args)
80 if err != nil {
81 return "", nil, err
82 }
83
84 debugFilePath, ok := extraArgs["DEBUG"]
85 if !ok {
86 debugFilePath = netConf.DebugFile
87 }
88
89 return debugFilePath, netConf, nil
90 }
91
92 func debugBehavior(args *skel.CmdArgs, command string) error {
93 debugFilePath, netConf, err := getConfig(args.StdinData, args.Args)
94 if err != nil {
95 return err
96 }
97
98 if debugFilePath == "" {
99 fmt.Printf(`{}`)
100 _, err = os.Stderr.WriteString("CNI_ARGS or config empty, no debug behavior\n")
101 if err != nil {
102 return err
103 }
104 return nil
105 }
106
107 debug, err := noop_debug.ReadDebug(debugFilePath)
108 if err != nil {
109 return err
110 }
111
112 debug.CmdArgs = *args
113 debug.Command = command
114
115 err = debug.WriteDebug(debugFilePath)
116 if err != nil {
117 return err
118 }
119
120 if netConf.CommandLog != "" {
121 if err = noop_debug.WriteCommandLog(
122 netConf.CommandLog,
123 noop_debug.CmdLogEntry{
124 Command: command,
125 CmdArgs: *args,
126 }); err != nil {
127 return err
128 }
129 }
130
131 if debug.ReportStderr != "" {
132 if _, err = os.Stderr.WriteString(debug.ReportStderr); err != nil {
133 return err
134 }
135 }
136 switch {
137 case debug.ReportError != "":
138 ec := debug.ReportErrorCode
139 if ec == 0 {
140 ec = types.ErrInternal
141 }
142 return &types.Error{
143 Msg: debug.ReportError,
144 Code: ec,
145 }
146 case debug.ReportResult == "PASSTHROUGH" || debug.ReportResult == "INJECT-DNS":
147 prevResult := netConf.PrevResult
148 if debug.ReportResult == "INJECT-DNS" {
149 newResult, err := current.NewResultFromResult(netConf.PrevResult)
150 if err != nil {
151 return err
152 }
153 newResult.DNS.Nameservers = []string{"1.2.3.4"}
154 prevResult = newResult
155 }
156
157 // Must print the prevResult as the CNIVersion of the config
158 newResult, err := prevResult.GetAsVersion(netConf.CNIVersion)
159 if err != nil {
160 return fmt.Errorf("failed to convert result to config %q: %w", netConf.CNIVersion, err)
161 }
162 resultBytes, err := json.Marshal(newResult)
163 if err != nil {
164 return fmt.Errorf("failed to marshal new result: %w", err)
165 }
166 _, err = os.Stdout.WriteString(string(resultBytes))
167 if err != nil {
168 return err
169 }
170 case debug.ReportResult != "":
171 _, err = os.Stdout.WriteString(debug.ReportResult)
172 if err != nil {
173 return err
174 }
175 }
176
177 if debug.ExitWithCode > 0 {
178 os.Exit(debug.ExitWithCode)
179 }
180 return nil
181 }
182
183 func debugGetSupportedVersions(stdinData []byte) []string {
184 vers := []string{"0.-42.0", "0.1.0", "0.2.0", "0.3.0", "0.3.1", "0.4.0", "1.0.0", "1.1.0"}
185 cniArgs := os.Getenv("CNI_ARGS")
186 if cniArgs == "" {
187 return vers
188 }
189
190 debugFilePath, _, err := getConfig(stdinData, cniArgs)
191 if err != nil {
192 panic("test setup error: unable to get debug file path: " + err.Error())
193 }
194
195 debug, err := noop_debug.ReadDebug(debugFilePath)
196 if err != nil {
197 panic("test setup error: unable to read debug file: " + err.Error())
198 }
199 if debug.ReportVersionSupport == nil {
200 return vers
201 }
202 return debug.ReportVersionSupport
203 }
204
205 func cmdAdd(args *skel.CmdArgs) error {
206 return debugBehavior(args, "ADD")
207 }
208
209 func cmdCheck(args *skel.CmdArgs) error {
210 return debugBehavior(args, "CHECK")
211 }
212
213 func cmdDel(args *skel.CmdArgs) error {
214 return debugBehavior(args, "DEL")
215 }
216
217 func cmdGC(args *skel.CmdArgs) error {
218 return debugBehavior(args, "GC")
219 }
220
221 func cmdStatus(args *skel.CmdArgs) error {
222 return debugBehavior(args, "STATUS")
223 }
224
225 func saveStdin() ([]byte, error) {
226 // Read original stdin
227 stdinData, err := io.ReadAll(os.Stdin)
228 if err != nil {
229 return nil, err
230 }
231
232 // Make a new pipe for stdin, and write original stdin data to it
233 r, w, err := os.Pipe()
234 if err != nil {
235 return nil, err
236 }
237 if _, err := w.Write(stdinData); err != nil {
238 return nil, err
239 }
240 if err := w.Close(); err != nil {
241 return nil, err
242 }
243
244 os.Stdin = r
245 return stdinData, nil
246 }
247
248 func main() {
249 // Grab and read stdin before pkg/skel gets it
250 stdinData, err := saveStdin()
251 if err != nil {
252 panic("test setup error: unable to read stdin: " + err.Error())
253 }
254
255 supportedVersions := debugGetSupportedVersions(stdinData)
256 skel.PluginMainFuncs(skel.CNIFuncs{
257 Add: cmdAdd,
258 Check: cmdCheck,
259 Del: cmdDel,
260 GC: cmdGC,
261 Status: cmdStatus,
262 }, version.PluginSupports(supportedVersions...), "CNI noop plugin v0.7.0")
263 }