conf.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. type NotFoundError struct {
  24. Dir string
  25. Name string
  26. }
  27. func (e NotFoundError) Error() string {
  28. return fmt.Sprintf(`no net configuration with name "%s" in %s`, e.Name, e.Dir)
  29. }
  30. type NoConfigsFoundError struct {
  31. Dir string
  32. }
  33. func (e NoConfigsFoundError) Error() string {
  34. return fmt.Sprintf(`no net configurations found in %s`, e.Dir)
  35. }
  36. func ConfFromBytes(bytes []byte) (*NetworkConfig, error) {
  37. conf := &NetworkConfig{Bytes: bytes}
  38. if err := json.Unmarshal(bytes, &conf.Network); err != nil {
  39. return nil, fmt.Errorf("error parsing configuration: %s", err)
  40. }
  41. return conf, nil
  42. }
  43. func ConfFromFile(filename string) (*NetworkConfig, error) {
  44. bytes, err := ioutil.ReadFile(filename)
  45. if err != nil {
  46. return nil, fmt.Errorf("error reading %s: %s", filename, err)
  47. }
  48. return ConfFromBytes(bytes)
  49. }
  50. func ConfListFromBytes(bytes []byte) (*NetworkConfigList, error) {
  51. rawList := make(map[string]interface{})
  52. if err := json.Unmarshal(bytes, &rawList); err != nil {
  53. return nil, fmt.Errorf("error parsing configuration list: %s", err)
  54. }
  55. rawName, ok := rawList["name"]
  56. if !ok {
  57. return nil, fmt.Errorf("error parsing configuration list: no name")
  58. }
  59. name, ok := rawName.(string)
  60. if !ok {
  61. return nil, fmt.Errorf("error parsing configuration list: invalid name type %T", rawName)
  62. }
  63. var cniVersion string
  64. rawVersion, ok := rawList["cniVersion"]
  65. if ok {
  66. cniVersion, ok = rawVersion.(string)
  67. if !ok {
  68. return nil, fmt.Errorf("error parsing configuration list: invalid cniVersion type %T", rawVersion)
  69. }
  70. }
  71. list := &NetworkConfigList{
  72. Name: name,
  73. CNIVersion: cniVersion,
  74. Bytes: bytes,
  75. }
  76. var plugins []interface{}
  77. plug, ok := rawList["plugins"]
  78. if !ok {
  79. return nil, fmt.Errorf("error parsing configuration list: no 'plugins' key")
  80. }
  81. plugins, ok = plug.([]interface{})
  82. if !ok {
  83. return nil, fmt.Errorf("error parsing configuration list: invalid 'plugins' type %T", plug)
  84. }
  85. if len(plugins) == 0 {
  86. return nil, fmt.Errorf("error parsing configuration list: no plugins in list")
  87. }
  88. for i, conf := range plugins {
  89. newBytes, err := json.Marshal(conf)
  90. if err != nil {
  91. return nil, fmt.Errorf("Failed to marshal plugin config %d: %v", i, err)
  92. }
  93. netConf, err := ConfFromBytes(newBytes)
  94. if err != nil {
  95. return nil, fmt.Errorf("Failed to parse plugin config %d: %v", i, err)
  96. }
  97. list.Plugins = append(list.Plugins, netConf)
  98. }
  99. return list, nil
  100. }
  101. func ConfListFromFile(filename string) (*NetworkConfigList, error) {
  102. bytes, err := ioutil.ReadFile(filename)
  103. if err != nil {
  104. return nil, fmt.Errorf("error reading %s: %s", filename, err)
  105. }
  106. return ConfListFromBytes(bytes)
  107. }
  108. func ConfFiles(dir string, extensions []string) ([]string, error) {
  109. // In part, adapted from rkt/networking/podenv.go#listFiles
  110. files, err := ioutil.ReadDir(dir)
  111. switch {
  112. case err == nil: // break
  113. case os.IsNotExist(err):
  114. return nil, nil
  115. default:
  116. return nil, err
  117. }
  118. confFiles := []string{}
  119. for _, f := range files {
  120. if f.IsDir() {
  121. continue
  122. }
  123. fileExt := filepath.Ext(f.Name())
  124. for _, ext := range extensions {
  125. if fileExt == ext {
  126. confFiles = append(confFiles, filepath.Join(dir, f.Name()))
  127. }
  128. }
  129. }
  130. return confFiles, nil
  131. }
  132. func LoadConf(dir, name string) (*NetworkConfig, error) {
  133. files, err := ConfFiles(dir, []string{".conf", ".json"})
  134. switch {
  135. case err != nil:
  136. return nil, err
  137. case len(files) == 0:
  138. return nil, NoConfigsFoundError{Dir: dir}
  139. }
  140. sort.Strings(files)
  141. for _, confFile := range files {
  142. conf, err := ConfFromFile(confFile)
  143. if err != nil {
  144. return nil, err
  145. }
  146. if conf.Network.Name == name {
  147. return conf, nil
  148. }
  149. }
  150. return nil, NotFoundError{dir, name}
  151. }
  152. func LoadConfList(dir, name string) (*NetworkConfigList, error) {
  153. files, err := ConfFiles(dir, []string{".conflist"})
  154. if err != nil {
  155. return nil, err
  156. }
  157. sort.Strings(files)
  158. for _, confFile := range files {
  159. conf, err := ConfListFromFile(confFile)
  160. if err != nil {
  161. return nil, err
  162. }
  163. if conf.Name == name {
  164. return conf, nil
  165. }
  166. }
  167. // Try and load a network configuration file (instead of list)
  168. // from the same name, then upconvert.
  169. singleConf, err := LoadConf(dir, name)
  170. if err != nil {
  171. // A little extra logic so the error makes sense
  172. if _, ok := err.(NoConfigsFoundError); len(files) != 0 && ok {
  173. // Config lists found but no config files found
  174. return nil, NotFoundError{dir, name}
  175. }
  176. return nil, err
  177. }
  178. return ConfListFromConf(singleConf)
  179. }
  180. func InjectConf(original *NetworkConfig, newValues map[string]interface{}) (*NetworkConfig, error) {
  181. config := make(map[string]interface{})
  182. err := json.Unmarshal(original.Bytes, &config)
  183. if err != nil {
  184. return nil, fmt.Errorf("unmarshal existing network bytes: %s", err)
  185. }
  186. for key, value := range newValues {
  187. if key == "" {
  188. return nil, fmt.Errorf("keys cannot be empty")
  189. }
  190. if value == nil {
  191. return nil, fmt.Errorf("key '%s' value must not be nil", key)
  192. }
  193. config[key] = value
  194. }
  195. newBytes, err := json.Marshal(config)
  196. if err != nil {
  197. return nil, err
  198. }
  199. return ConfFromBytes(newBytes)
  200. }
  201. // ConfListFromConf "upconverts" a network config in to a NetworkConfigList,
  202. // with the single network as the only entry in the list.
  203. func ConfListFromConf(original *NetworkConfig) (*NetworkConfigList, error) {
  204. // Re-deserialize the config's json, then make a raw map configlist.
  205. // This may seem a bit strange, but it's to make the Bytes fields
  206. // actually make sense. Otherwise, the generated json is littered with
  207. // golang default values.
  208. rawConfig := make(map[string]interface{})
  209. if err := json.Unmarshal(original.Bytes, &rawConfig); err != nil {
  210. return nil, err
  211. }
  212. rawConfigList := map[string]interface{}{
  213. "name": original.Network.Name,
  214. "cniVersion": original.Network.CNIVersion,
  215. "plugins": []interface{}{rawConfig},
  216. }
  217. b, err := json.Marshal(rawConfigList)
  218. if err != nil {
  219. return nil, err
  220. }
  221. return ConfListFromBytes(b)
  222. }