conf.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. package libcni
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path/filepath"
  21. "sort"
  22. )
  23. func ConfFromBytes(bytes []byte) (*NetworkConfig, error) {
  24. conf := &NetworkConfig{Bytes: bytes}
  25. if err := json.Unmarshal(bytes, &conf.Network); err != nil {
  26. return nil, fmt.Errorf("error parsing configuration: %s", err)
  27. }
  28. return conf, nil
  29. }
  30. func ConfFromFile(filename string) (*NetworkConfig, error) {
  31. bytes, err := ioutil.ReadFile(filename)
  32. if err != nil {
  33. return nil, fmt.Errorf("error reading %s: %s", filename, err)
  34. }
  35. return ConfFromBytes(bytes)
  36. }
  37. func ConfFiles(dir string) ([]string, error) {
  38. // In part, adapted from rkt/networking/podenv.go#listFiles
  39. files, err := ioutil.ReadDir(dir)
  40. switch {
  41. case err == nil: // break
  42. case os.IsNotExist(err):
  43. return nil, nil
  44. default:
  45. return nil, err
  46. }
  47. confFiles := []string{}
  48. for _, f := range files {
  49. if f.IsDir() {
  50. continue
  51. }
  52. if filepath.Ext(f.Name()) == ".conf" {
  53. confFiles = append(confFiles, filepath.Join(dir, f.Name()))
  54. }
  55. }
  56. return confFiles, nil
  57. }
  58. func LoadConf(dir, name string) (*NetworkConfig, error) {
  59. files, err := ConfFiles(dir)
  60. switch {
  61. case err != nil:
  62. return nil, err
  63. case len(files) == 0:
  64. return nil, fmt.Errorf("no net configurations found")
  65. }
  66. sort.Strings(files)
  67. for _, confFile := range files {
  68. conf, err := ConfFromFile(confFile)
  69. if err != nil {
  70. return nil, err
  71. }
  72. if conf.Network.Name == name {
  73. return conf, nil
  74. }
  75. }
  76. return nil, fmt.Errorf(`no net configuration with name "%s" in %s`, name, dir)
  77. }