| 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 libcni |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding/json" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"os" |
| 22 |
"path/filepath" |
| 23 |
"slices" |
| 24 |
"sort" |
| 25 |
"strings" |
| 26 |
|
| 27 |
"github.com/containernetworking/cni/pkg/types" |
| 28 |
"github.com/containernetworking/cni/pkg/version" |
| 29 |
) |
| 30 |
|
| 31 |
type NotFoundError struct { |
| 32 |
Dir string |
| 33 |
Name string |
| 34 |
} |
| 35 |
|
| 36 |
func (e NotFoundError) Error() string { |
| 37 |
return fmt.Sprintf(`no net configuration with name "%s" in %s`, e.Name, e.Dir) |
| 38 |
} |
| 39 |
|
| 40 |
type NoConfigsFoundError struct { |
| 41 |
Dir string |
| 42 |
} |
| 43 |
|
| 44 |
func (e NoConfigsFoundError) Error() string { |
| 45 |
return fmt.Sprintf(`no net configurations found in %s`, e.Dir) |
| 46 |
} |
| 47 |
|
| 48 |
// This will not validate that the plugins actually belong to the netconfig by ensuring |
| 49 |
// that they are loaded from a directory named after the networkName, relative to the network config. |
| 50 |
// |
| 51 |
// Since here we are just accepting raw bytes, the caller is responsible for ensuring that the plugin |
| 52 |
// config provided here actually "belongs" to the networkconfig in question. |
| 53 |
func NetworkPluginConfFromBytes(pluginConfBytes []byte) (*PluginConfig, error) { |
| 54 |
// TODO why are we creating a struct that holds both the byte representation and the deserialized |
| 55 |
// representation, and returning that, instead of just returning the deserialized representation? |
| 56 |
conf := &PluginConfig{Bytes: pluginConfBytes, Network: &types.PluginConf{}} |
| 57 |
if err := json.Unmarshal(pluginConfBytes, conf.Network); err != nil { |
| 58 |
return nil, fmt.Errorf("error parsing configuration: %w", err) |
| 59 |
} |
| 60 |
if conf.Network.Type == "" { |
| 61 |
return nil, fmt.Errorf("error parsing configuration: missing 'type'") |
| 62 |
} |
| 63 |
return conf, nil |
| 64 |
} |
| 65 |
|
| 66 |
// Given a path to a directory containing a network configuration, and the name of a network, |
| 67 |
// loads all plugin definitions found at path `networkConfPath/networkName/*.conf` |
| 68 |
func NetworkPluginConfsFromFiles(networkConfPath, networkName string) ([]*PluginConfig, error) { |
| 69 |
var pConfs []*PluginConfig |
| 70 |
|
| 71 |
pluginConfPath := filepath.Join(networkConfPath, networkName) |
| 72 |
|
| 73 |
pluginConfFiles, err := ConfFiles(pluginConfPath, []string{".conf"}) |
| 74 |
if err != nil { |
| 75 |
return nil, fmt.Errorf("failed to read plugin config files in %s: %w", pluginConfPath, err) |
| 76 |
} |
| 77 |
|
| 78 |
for _, pluginConfFile := range pluginConfFiles { |
| 79 |
pluginConfBytes, err := os.ReadFile(pluginConfFile) |
| 80 |
if err != nil { |
| 81 |
return nil, fmt.Errorf("error reading %s: %w", pluginConfFile, err) |
| 82 |
} |
| 83 |
pluginConf, err := NetworkPluginConfFromBytes(pluginConfBytes) |
| 84 |
if err != nil { |
| 85 |
return nil, err |
| 86 |
} |
| 87 |
pConfs = append(pConfs, pluginConf) |
| 88 |
} |
| 89 |
return pConfs, nil |
| 90 |
} |
| 91 |
|
| 92 |
func NetworkConfFromBytes(confBytes []byte) (*NetworkConfigList, error) { |
| 93 |
rawList := make(map[string]interface{}) |
| 94 |
if err := json.Unmarshal(confBytes, &rawList); err != nil { |
| 95 |
return nil, fmt.Errorf("error parsing configuration list: %w", err) |
| 96 |
} |
| 97 |
|
| 98 |
rawName, ok := rawList["name"] |
| 99 |
if !ok { |
| 100 |
return nil, fmt.Errorf("error parsing configuration list: no name") |
| 101 |
} |
| 102 |
name, ok := rawName.(string) |
| 103 |
if !ok { |
| 104 |
return nil, fmt.Errorf("error parsing configuration list: invalid name type %T", rawName) |
| 105 |
} |
| 106 |
|
| 107 |
var cniVersion string |
| 108 |
rawVersion, ok := rawList["cniVersion"] |
| 109 |
if ok { |
| 110 |
cniVersion, ok = rawVersion.(string) |
| 111 |
if !ok { |
| 112 |
return nil, fmt.Errorf("error parsing configuration list: invalid cniVersion type %T", rawVersion) |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
rawVersions, ok := rawList["cniVersions"] |
| 117 |
if ok { |
| 118 |
// Parse the current package CNI version |
| 119 |
rvs, ok := rawVersions.([]interface{}) |
| 120 |
if !ok { |
| 121 |
return nil, fmt.Errorf("error parsing configuration list: invalid type for cniVersions: %T", rvs) |
| 122 |
} |
| 123 |
vs := make([]string, 0, len(rvs)) |
| 124 |
for i, rv := range rvs { |
| 125 |
v, ok := rv.(string) |
| 126 |
if !ok { |
| 127 |
return nil, fmt.Errorf("error parsing configuration list: invalid type for cniVersions index %d: %T", i, rv) |
| 128 |
} |
| 129 |
gt, err := version.GreaterThan(v, version.Current()) |
| 130 |
if err != nil { |
| 131 |
return nil, fmt.Errorf("error parsing configuration list: invalid cniVersions entry %s at index %d: %w", v, i, err) |
| 132 |
} else if !gt { |
| 133 |
// Skip versions "greater" than this implementation of the spec |
| 134 |
vs = append(vs, v) |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
// if cniVersion was already set, append it to the list for sorting. |
| 139 |
if cniVersion != "" { |
| 140 |
gt, err := version.GreaterThan(cniVersion, version.Current()) |
| 141 |
if err != nil { |
| 142 |
return nil, fmt.Errorf("error parsing configuration list: invalid cniVersion %s: %w", cniVersion, err) |
| 143 |
} else if !gt { |
| 144 |
// ignore any versions higher than the current implemented spec version |
| 145 |
vs = append(vs, cniVersion) |
| 146 |
} |
| 147 |
} |
| 148 |
slices.SortFunc[[]string](vs, func(v1, v2 string) int { |
| 149 |
if v1 == v2 { |
| 150 |
return 0 |
| 151 |
} |
| 152 |
if gt, _ := version.GreaterThan(v1, v2); gt { |
| 153 |
return 1 |
| 154 |
} |
| 155 |
return -1 |
| 156 |
}) |
| 157 |
if len(vs) > 0 { |
| 158 |
cniVersion = vs[len(vs)-1] |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
readBool := func(key string) (bool, error) { |
| 163 |
rawVal, ok := rawList[key] |
| 164 |
if !ok { |
| 165 |
return false, nil |
| 166 |
} |
| 167 |
if b, ok := rawVal.(bool); ok { |
| 168 |
return b, nil |
| 169 |
} |
| 170 |
|
| 171 |
s, ok := rawVal.(string) |
| 172 |
if !ok { |
| 173 |
return false, fmt.Errorf("error parsing configuration list: invalid type %T for %s", rawVal, key) |
| 174 |
} |
| 175 |
s = strings.ToLower(s) |
| 176 |
switch s { |
| 177 |
case "false": |
| 178 |
return false, nil |
| 179 |
case "true": |
| 180 |
return true, nil |
| 181 |
} |
| 182 |
return false, fmt.Errorf("error parsing configuration list: invalid value %q for %s", s, key) |
| 183 |
} |
| 184 |
|
| 185 |
disableCheck, err := readBool("disableCheck") |
| 186 |
if err != nil { |
| 187 |
return nil, err |
| 188 |
} |
| 189 |
|
| 190 |
disableGC, err := readBool("disableGC") |
| 191 |
if err != nil { |
| 192 |
return nil, err |
| 193 |
} |
| 194 |
|
| 195 |
loadOnlyInlinedPlugins, err := readBool("loadOnlyInlinedPlugins") |
| 196 |
if err != nil { |
| 197 |
return nil, err |
| 198 |
} |
| 199 |
|
| 200 |
list := &NetworkConfigList{ |
| 201 |
Name: name, |
| 202 |
DisableCheck: disableCheck, |
| 203 |
DisableGC: disableGC, |
| 204 |
LoadOnlyInlinedPlugins: loadOnlyInlinedPlugins, |
| 205 |
CNIVersion: cniVersion, |
| 206 |
Bytes: confBytes, |
| 207 |
} |
| 208 |
|
| 209 |
var plugins []interface{} |
| 210 |
plug, ok := rawList["plugins"] |
| 211 |
// We can have a `plugins` list key in the main conf, |
| 212 |
// We can also have `loadOnlyInlinedPlugins == true` |
| 213 |
// |
| 214 |
// If `plugins` is there, then `loadOnlyInlinedPlugins` can be true |
| 215 |
// |
| 216 |
// If plugins is NOT there, then `loadOnlyInlinedPlugins` cannot be true |
| 217 |
// |
| 218 |
// We have to have at least some plugins. |
| 219 |
if !ok && loadOnlyInlinedPlugins { |
| 220 |
return nil, fmt.Errorf("error parsing configuration list: `loadOnlyInlinedPlugins` is true, and no 'plugins' key") |
| 221 |
} else if !ok && !loadOnlyInlinedPlugins { |
| 222 |
return list, nil |
| 223 |
} |
| 224 |
|
| 225 |
plugins, ok = plug.([]interface{}) |
| 226 |
if !ok { |
| 227 |
return nil, fmt.Errorf("error parsing configuration list: invalid 'plugins' type %T", plug) |
| 228 |
} |
| 229 |
if len(plugins) == 0 { |
| 230 |
return nil, fmt.Errorf("error parsing configuration list: no plugins in list") |
| 231 |
} |
| 232 |
|
| 233 |
for i, conf := range plugins { |
| 234 |
newBytes, err := json.Marshal(conf) |
| 235 |
if err != nil { |
| 236 |
return nil, fmt.Errorf("failed to marshal plugin config %d: %w", i, err) |
| 237 |
} |
| 238 |
netConf, err := ConfFromBytes(newBytes) |
| 239 |
if err != nil { |
| 240 |
return nil, fmt.Errorf("failed to parse plugin config %d: %w", i, err) |
| 241 |
} |
| 242 |
list.Plugins = append(list.Plugins, netConf) |
| 243 |
} |
| 244 |
return list, nil |
| 245 |
} |
| 246 |
|
| 247 |
func NetworkConfFromFile(filename string) (*NetworkConfigList, error) { |
| 248 |
bytes, err := os.ReadFile(filename) |
| 249 |
if err != nil { |
| 250 |
return nil, fmt.Errorf("error reading %s: %w", filename, err) |
| 251 |
} |
| 252 |
|
| 253 |
conf, err := NetworkConfFromBytes(bytes) |
| 254 |
if err != nil { |
| 255 |
return nil, err |
| 256 |
} |
| 257 |
|
| 258 |
if !conf.LoadOnlyInlinedPlugins { |
| 259 |
plugins, err := NetworkPluginConfsFromFiles(filepath.Dir(filename), conf.Name) |
| 260 |
if err != nil { |
| 261 |
return nil, err |
| 262 |
} |
| 263 |
conf.Plugins = append(conf.Plugins, plugins...) |
| 264 |
} |
| 265 |
|
| 266 |
if len(conf.Plugins) == 0 { |
| 267 |
// Having 0 plugins for a given network is not necessarily a problem, |
| 268 |
// but return as error for caller to decide, since they tried to load |
| 269 |
return nil, fmt.Errorf("no plugin configs found") |
| 270 |
} |
| 271 |
return conf, nil |
| 272 |
} |
| 273 |
|
| 274 |
// Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions |
| 275 |
func ConfFromBytes(bytes []byte) (*NetworkConfig, error) { |
| 276 |
return NetworkPluginConfFromBytes(bytes) |
| 277 |
} |
| 278 |
|
| 279 |
// Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions |
| 280 |
func ConfFromFile(filename string) (*NetworkConfig, error) { |
| 281 |
bytes, err := os.ReadFile(filename) |
| 282 |
if err != nil { |
| 283 |
return nil, fmt.Errorf("error reading %s: %w", filename, err) |
| 284 |
} |
| 285 |
return ConfFromBytes(bytes) |
| 286 |
} |
| 287 |
|
| 288 |
func ConfListFromBytes(bytes []byte) (*NetworkConfigList, error) { |
| 289 |
return NetworkConfFromBytes(bytes) |
| 290 |
} |
| 291 |
|
| 292 |
func ConfListFromFile(filename string) (*NetworkConfigList, error) { |
| 293 |
return NetworkConfFromFile(filename) |
| 294 |
} |
| 295 |
|
| 296 |
// ConfFiles simply returns a slice of all files in the provided directory |
| 297 |
// with extensions matching the provided set. |
| 298 |
func ConfFiles(dir string, extensions []string) ([]string, error) { |
| 299 |
// In part, adapted from rkt/networking/podenv.go#listFiles |
| 300 |
files, err := os.ReadDir(dir) |
| 301 |
switch { |
| 302 |
case err == nil: // break |
| 303 |
case os.IsNotExist(err): |
| 304 |
// If folder not there, return no error - only return an |
| 305 |
// error if we cannot read contents or there are no contents. |
| 306 |
return nil, nil |
| 307 |
default: |
| 308 |
return nil, err |
| 309 |
} |
| 310 |
|
| 311 |
confFiles := []string{} |
| 312 |
for _, f := range files { |
| 313 |
if f.IsDir() { |
| 314 |
continue |
| 315 |
} |
| 316 |
fileExt := filepath.Ext(f.Name()) |
| 317 |
for _, ext := range extensions { |
| 318 |
if fileExt == ext { |
| 319 |
confFiles = append(confFiles, filepath.Join(dir, f.Name())) |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
return confFiles, nil |
| 324 |
} |
| 325 |
|
| 326 |
// Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions |
| 327 |
func LoadConf(dir, name string) (*NetworkConfig, error) { |
| 328 |
files, err := ConfFiles(dir, []string{".conf", ".json"}) |
| 329 |
switch { |
| 330 |
case err != nil: |
| 331 |
return nil, err |
| 332 |
case len(files) == 0: |
| 333 |
return nil, NoConfigsFoundError{Dir: dir} |
| 334 |
} |
| 335 |
sort.Strings(files) |
| 336 |
|
| 337 |
for _, confFile := range files { |
| 338 |
conf, err := ConfFromFile(confFile) |
| 339 |
if err != nil { |
| 340 |
return nil, err |
| 341 |
} |
| 342 |
if conf.Network.Name == name { |
| 343 |
return conf, nil |
| 344 |
} |
| 345 |
} |
| 346 |
return nil, NotFoundError{dir, name} |
| 347 |
} |
| 348 |
|
| 349 |
func LoadConfList(dir, name string) (*NetworkConfigList, error) { |
| 350 |
return LoadNetworkConf(dir, name) |
| 351 |
} |
| 352 |
|
| 353 |
// LoadNetworkConf looks at all the network configs in a given dir, |
| 354 |
// loads and parses them all, and returns the first one with an extension of `.conf` |
| 355 |
// that matches the provided network name predicate. |
| 356 |
func LoadNetworkConf(dir, name string) (*NetworkConfigList, error) { |
| 357 |
// TODO this .conflist/.conf extension thing is confusing and inexact |
| 358 |
// for implementors. We should pick one extension for everything and stick with it. |
| 359 |
files, err := ConfFiles(dir, []string{".conflist"}) |
| 360 |
if err != nil { |
| 361 |
return nil, err |
| 362 |
} |
| 363 |
sort.Strings(files) |
| 364 |
|
| 365 |
for _, confFile := range files { |
| 366 |
conf, err := NetworkConfFromFile(confFile) |
| 367 |
if err != nil { |
| 368 |
return nil, err |
| 369 |
} |
| 370 |
if conf.Name == name { |
| 371 |
return conf, nil |
| 372 |
} |
| 373 |
} |
| 374 |
|
| 375 |
// Deprecated: Try and load a network configuration file (instead of list) |
| 376 |
// from the same name, then upconvert. |
| 377 |
singleConf, err := LoadConf(dir, name) |
| 378 |
if err != nil { |
| 379 |
// A little extra logic so the error makes sense |
| 380 |
var ncfErr NoConfigsFoundError |
| 381 |
if len(files) != 0 && errors.As(err, &ncfErr) { |
| 382 |
// Config lists found but no config files found |
| 383 |
return nil, NotFoundError{dir, name} |
| 384 |
} |
| 385 |
|
| 386 |
return nil, err |
| 387 |
} |
| 388 |
return ConfListFromConf(singleConf) |
| 389 |
} |
| 390 |
|
| 391 |
// InjectConf takes a PluginConfig and inserts additional values into it, ensuring the result is serializable. |
| 392 |
func InjectConf(original *PluginConfig, newValues map[string]interface{}) (*PluginConfig, error) { |
| 393 |
config := make(map[string]interface{}) |
| 394 |
err := json.Unmarshal(original.Bytes, &config) |
| 395 |
if err != nil { |
| 396 |
return nil, fmt.Errorf("unmarshal existing network bytes: %w", err) |
| 397 |
} |
| 398 |
|
| 399 |
for key, value := range newValues { |
| 400 |
if key == "" { |
| 401 |
return nil, fmt.Errorf("keys cannot be empty") |
| 402 |
} |
| 403 |
|
| 404 |
if value == nil { |
| 405 |
return nil, fmt.Errorf("key '%s' value must not be nil", key) |
| 406 |
} |
| 407 |
|
| 408 |
config[key] = value |
| 409 |
} |
| 410 |
|
| 411 |
newBytes, err := json.Marshal(config) |
| 412 |
if err != nil { |
| 413 |
return nil, err |
| 414 |
} |
| 415 |
|
| 416 |
return NetworkPluginConfFromBytes(newBytes) |
| 417 |
} |
| 418 |
|
| 419 |
// ConfListFromConf "upconverts" a network config in to a NetworkConfigList, |
| 420 |
// with the single network as the only entry in the list. |
| 421 |
// |
| 422 |
// Deprecated: Non-conflist file formats are unsupported, use NetworkConfXXX and NetworkPluginXXX functions |
| 423 |
func ConfListFromConf(original *PluginConfig) (*NetworkConfigList, error) { |
| 424 |
// Re-deserialize the config's json, then make a raw map configlist. |
| 425 |
// This may seem a bit strange, but it's to make the Bytes fields |
| 426 |
// actually make sense. Otherwise, the generated json is littered with |
| 427 |
// golang default values. |
| 428 |
|
| 429 |
rawConfig := make(map[string]interface{}) |
| 430 |
if err := json.Unmarshal(original.Bytes, &rawConfig); err != nil { |
| 431 |
return nil, err |
| 432 |
} |
| 433 |
|
| 434 |
rawConfigList := map[string]interface{}{ |
| 435 |
"name": original.Network.Name, |
| 436 |
"cniVersion": original.Network.CNIVersion, |
| 437 |
"plugins": []interface{}{rawConfig}, |
| 438 |
} |
| 439 |
|
| 440 |
b, err := json.Marshal(rawConfigList) |
| 441 |
if err != nil { |
| 442 |
return nil, err |
| 443 |
} |
| 444 |
return ConfListFromBytes(b) |
| 445 |
} |