api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. "context"
  17. "encoding/json"
  18. "fmt"
  19. "io/ioutil"
  20. "os"
  21. "path/filepath"
  22. "strings"
  23. "github.com/containernetworking/cni/pkg/invoke"
  24. "github.com/containernetworking/cni/pkg/types"
  25. "github.com/containernetworking/cni/pkg/version"
  26. )
  27. var (
  28. CacheDir = "/var/lib/cni"
  29. )
  30. // A RuntimeConf holds the arguments to one invocation of a CNI plugin
  31. // excepting the network configuration, with the nested exception that
  32. // the `runtimeConfig` from the network configuration is included
  33. // here.
  34. type RuntimeConf struct {
  35. ContainerID string
  36. NetNS string
  37. IfName string
  38. Args [][2]string
  39. // A dictionary of capability-specific data passed by the runtime
  40. // to plugins as top-level keys in the 'runtimeConfig' dictionary
  41. // of the plugin's stdin data. libcni will ensure that only keys
  42. // in this map which match the capabilities of the plugin are passed
  43. // to the plugin
  44. CapabilityArgs map[string]interface{}
  45. // A cache directory in which to library data. Defaults to CacheDir
  46. CacheDir string
  47. }
  48. type NetworkConfig struct {
  49. Network *types.NetConf
  50. Bytes []byte
  51. }
  52. type NetworkConfigList struct {
  53. Name string
  54. CNIVersion string
  55. DisableCheck bool
  56. Plugins []*NetworkConfig
  57. Bytes []byte
  58. }
  59. type CNI interface {
  60. AddNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) (types.Result, error)
  61. CheckNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error
  62. DelNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error
  63. GetNetworkListCachedResult(net *NetworkConfigList, rt *RuntimeConf) (types.Result, error)
  64. AddNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) (types.Result, error)
  65. CheckNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error
  66. DelNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error
  67. GetNetworkCachedResult(net *NetworkConfig, rt *RuntimeConf) (types.Result, error)
  68. ValidateNetworkList(ctx context.Context, net *NetworkConfigList) ([]string, error)
  69. ValidateNetwork(ctx context.Context, net *NetworkConfig) ([]string, error)
  70. }
  71. type CNIConfig struct {
  72. Path []string
  73. exec invoke.Exec
  74. }
  75. // CNIConfig implements the CNI interface
  76. var _ CNI = &CNIConfig{}
  77. // NewCNIConfig returns a new CNIConfig object that will search for plugins
  78. // in the given paths and use the given exec interface to run those plugins,
  79. // or if the exec interface is not given, will use a default exec handler.
  80. func NewCNIConfig(path []string, exec invoke.Exec) *CNIConfig {
  81. return &CNIConfig{
  82. Path: path,
  83. exec: exec,
  84. }
  85. }
  86. func buildOneConfig(name, cniVersion string, orig *NetworkConfig, prevResult types.Result, rt *RuntimeConf) (*NetworkConfig, error) {
  87. var err error
  88. inject := map[string]interface{}{
  89. "name": name,
  90. "cniVersion": cniVersion,
  91. }
  92. // Add previous plugin result
  93. if prevResult != nil {
  94. inject["prevResult"] = prevResult
  95. }
  96. // Ensure every config uses the same name and version
  97. orig, err = InjectConf(orig, inject)
  98. if err != nil {
  99. return nil, err
  100. }
  101. return injectRuntimeConfig(orig, rt)
  102. }
  103. // This function takes a libcni RuntimeConf structure and injects values into
  104. // a "runtimeConfig" dictionary in the CNI network configuration JSON that
  105. // will be passed to the plugin on stdin.
  106. //
  107. // Only "capabilities arguments" passed by the runtime are currently injected.
  108. // These capabilities arguments are filtered through the plugin's advertised
  109. // capabilities from its config JSON, and any keys in the CapabilityArgs
  110. // matching plugin capabilities are added to the "runtimeConfig" dictionary
  111. // sent to the plugin via JSON on stdin. For example, if the plugin's
  112. // capabilities include "portMappings", and the CapabilityArgs map includes a
  113. // "portMappings" key, that key and its value are added to the "runtimeConfig"
  114. // dictionary to be passed to the plugin's stdin.
  115. func injectRuntimeConfig(orig *NetworkConfig, rt *RuntimeConf) (*NetworkConfig, error) {
  116. var err error
  117. rc := make(map[string]interface{})
  118. for capability, supported := range orig.Network.Capabilities {
  119. if !supported {
  120. continue
  121. }
  122. if data, ok := rt.CapabilityArgs[capability]; ok {
  123. rc[capability] = data
  124. }
  125. }
  126. if len(rc) > 0 {
  127. orig, err = InjectConf(orig, map[string]interface{}{"runtimeConfig": rc})
  128. if err != nil {
  129. return nil, err
  130. }
  131. }
  132. return orig, nil
  133. }
  134. // ensure we have a usable exec if the CNIConfig was not given one
  135. func (c *CNIConfig) ensureExec() invoke.Exec {
  136. if c.exec == nil {
  137. c.exec = &invoke.DefaultExec{
  138. RawExec: &invoke.RawExec{Stderr: os.Stderr},
  139. PluginDecoder: version.PluginDecoder{},
  140. }
  141. }
  142. return c.exec
  143. }
  144. func getResultCacheFilePath(netName string, rt *RuntimeConf) string {
  145. cacheDir := rt.CacheDir
  146. if cacheDir == "" {
  147. cacheDir = CacheDir
  148. }
  149. return filepath.Join(cacheDir, "results", fmt.Sprintf("%s-%s-%s", netName, rt.ContainerID, rt.IfName))
  150. }
  151. func setCachedResult(result types.Result, netName string, rt *RuntimeConf) error {
  152. data, err := json.Marshal(result)
  153. if err != nil {
  154. return err
  155. }
  156. fname := getResultCacheFilePath(netName, rt)
  157. if err := os.MkdirAll(filepath.Dir(fname), 0700); err != nil {
  158. return err
  159. }
  160. return ioutil.WriteFile(fname, data, 0600)
  161. }
  162. func delCachedResult(netName string, rt *RuntimeConf) error {
  163. fname := getResultCacheFilePath(netName, rt)
  164. return os.Remove(fname)
  165. }
  166. func getCachedResult(netName, cniVersion string, rt *RuntimeConf) (types.Result, error) {
  167. fname := getResultCacheFilePath(netName, rt)
  168. data, err := ioutil.ReadFile(fname)
  169. if err != nil {
  170. // Ignore read errors; the cached result may not exist on-disk
  171. return nil, nil
  172. }
  173. // Read the version of the cached result
  174. decoder := version.ConfigDecoder{}
  175. resultCniVersion, err := decoder.Decode(data)
  176. if err != nil {
  177. return nil, err
  178. }
  179. // Ensure we can understand the result
  180. result, err := version.NewResult(resultCniVersion, data)
  181. if err != nil {
  182. return nil, err
  183. }
  184. // Convert to the config version to ensure plugins get prevResult
  185. // in the same version as the config. The cached result version
  186. // should match the config version unless the config was changed
  187. // while the container was running.
  188. result, err = result.GetAsVersion(cniVersion)
  189. if err != nil && resultCniVersion != cniVersion {
  190. return nil, fmt.Errorf("failed to convert cached result version %q to config version %q: %v", resultCniVersion, cniVersion, err)
  191. }
  192. return result, err
  193. }
  194. // GetNetworkListCachedResult returns the cached Result of the previous
  195. // previous AddNetworkList() operation for a network list, or an error.
  196. func (c *CNIConfig) GetNetworkListCachedResult(list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) {
  197. return getCachedResult(list.Name, list.CNIVersion, rt)
  198. }
  199. // GetNetworkCachedResult returns the cached Result of the previous
  200. // previous AddNetwork() operation for a network, or an error.
  201. func (c *CNIConfig) GetNetworkCachedResult(net *NetworkConfig, rt *RuntimeConf) (types.Result, error) {
  202. return getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
  203. }
  204. func (c *CNIConfig) addNetwork(ctx context.Context, name, cniVersion string, net *NetworkConfig, prevResult types.Result, rt *RuntimeConf) (types.Result, error) {
  205. c.ensureExec()
  206. pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
  207. if err != nil {
  208. return nil, err
  209. }
  210. newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt)
  211. if err != nil {
  212. return nil, err
  213. }
  214. return invoke.ExecPluginWithResult(ctx, pluginPath, newConf.Bytes, c.args("ADD", rt), c.exec)
  215. }
  216. // AddNetworkList executes a sequence of plugins with the ADD command
  217. func (c *CNIConfig) AddNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) {
  218. var err error
  219. var result types.Result
  220. for _, net := range list.Plugins {
  221. result, err = c.addNetwork(ctx, list.Name, list.CNIVersion, net, result, rt)
  222. if err != nil {
  223. return nil, err
  224. }
  225. }
  226. if err = setCachedResult(result, list.Name, rt); err != nil {
  227. return nil, fmt.Errorf("failed to set network %q cached result: %v", list.Name, err)
  228. }
  229. return result, nil
  230. }
  231. func (c *CNIConfig) checkNetwork(ctx context.Context, name, cniVersion string, net *NetworkConfig, prevResult types.Result, rt *RuntimeConf) error {
  232. c.ensureExec()
  233. pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
  234. if err != nil {
  235. return err
  236. }
  237. newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt)
  238. if err != nil {
  239. return err
  240. }
  241. return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("CHECK", rt), c.exec)
  242. }
  243. // CheckNetworkList executes a sequence of plugins with the CHECK command
  244. func (c *CNIConfig) CheckNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error {
  245. // CHECK was added in CNI spec version 0.4.0 and higher
  246. if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil {
  247. return err
  248. } else if !gtet {
  249. return fmt.Errorf("configuration version %q does not support the CHECK command", list.CNIVersion)
  250. }
  251. if list.DisableCheck {
  252. return nil
  253. }
  254. cachedResult, err := getCachedResult(list.Name, list.CNIVersion, rt)
  255. if err != nil {
  256. return fmt.Errorf("failed to get network %q cached result: %v", list.Name, err)
  257. }
  258. for _, net := range list.Plugins {
  259. if err := c.checkNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil {
  260. return err
  261. }
  262. }
  263. return nil
  264. }
  265. func (c *CNIConfig) delNetwork(ctx context.Context, name, cniVersion string, net *NetworkConfig, prevResult types.Result, rt *RuntimeConf) error {
  266. c.ensureExec()
  267. pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
  268. if err != nil {
  269. return err
  270. }
  271. newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt)
  272. if err != nil {
  273. return err
  274. }
  275. return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("DEL", rt), c.exec)
  276. }
  277. // DelNetworkList executes a sequence of plugins with the DEL command
  278. func (c *CNIConfig) DelNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error {
  279. var cachedResult types.Result
  280. // Cached result on DEL was added in CNI spec version 0.4.0 and higher
  281. if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil {
  282. return err
  283. } else if gtet {
  284. cachedResult, err = getCachedResult(list.Name, list.CNIVersion, rt)
  285. if err != nil {
  286. return fmt.Errorf("failed to get network %q cached result: %v", list.Name, err)
  287. }
  288. }
  289. for i := len(list.Plugins) - 1; i >= 0; i-- {
  290. net := list.Plugins[i]
  291. if err := c.delNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil {
  292. return err
  293. }
  294. }
  295. _ = delCachedResult(list.Name, rt)
  296. return nil
  297. }
  298. // AddNetwork executes the plugin with the ADD command
  299. func (c *CNIConfig) AddNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) (types.Result, error) {
  300. result, err := c.addNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, nil, rt)
  301. if err != nil {
  302. return nil, err
  303. }
  304. if err = setCachedResult(result, net.Network.Name, rt); err != nil {
  305. return nil, fmt.Errorf("failed to set network %q cached result: %v", net.Network.Name, err)
  306. }
  307. return result, nil
  308. }
  309. // CheckNetwork executes the plugin with the CHECK command
  310. func (c *CNIConfig) CheckNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error {
  311. // CHECK was added in CNI spec version 0.4.0 and higher
  312. if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil {
  313. return err
  314. } else if !gtet {
  315. return fmt.Errorf("configuration version %q does not support the CHECK command", net.Network.CNIVersion)
  316. }
  317. cachedResult, err := getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
  318. if err != nil {
  319. return fmt.Errorf("failed to get network %q cached result: %v", net.Network.Name, err)
  320. }
  321. return c.checkNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt)
  322. }
  323. // DelNetwork executes the plugin with the DEL command
  324. func (c *CNIConfig) DelNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error {
  325. var cachedResult types.Result
  326. // Cached result on DEL was added in CNI spec version 0.4.0 and higher
  327. if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil {
  328. return err
  329. } else if gtet {
  330. cachedResult, err = getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
  331. if err != nil {
  332. return fmt.Errorf("failed to get network %q cached result: %v", net.Network.Name, err)
  333. }
  334. }
  335. if err := c.delNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt); err != nil {
  336. return err
  337. }
  338. _ = delCachedResult(net.Network.Name, rt)
  339. return nil
  340. }
  341. // ValidateNetworkList checks that a configuration is reasonably valid.
  342. // - all the specified plugins exist on disk
  343. // - every plugin supports the desired version.
  344. //
  345. // Returns a list of all capabilities supported by the configuration, or error
  346. func (c *CNIConfig) ValidateNetworkList(ctx context.Context, list *NetworkConfigList) ([]string, error) {
  347. version := list.CNIVersion
  348. // holding map for seen caps (in case of duplicates)
  349. caps := map[string]interface{}{}
  350. errs := []error{}
  351. for _, net := range list.Plugins {
  352. if err := c.validatePlugin(ctx, net.Network.Type, version); err != nil {
  353. errs = append(errs, err)
  354. }
  355. for c, enabled := range net.Network.Capabilities {
  356. if !enabled {
  357. continue
  358. }
  359. caps[c] = struct{}{}
  360. }
  361. }
  362. if len(errs) > 0 {
  363. return nil, fmt.Errorf("%v", errs)
  364. }
  365. // make caps list
  366. cc := make([]string, 0, len(caps))
  367. for c := range caps {
  368. cc = append(cc, c)
  369. }
  370. return cc, nil
  371. }
  372. // ValidateNetwork checks that a configuration is reasonably valid.
  373. // It uses the same logic as ValidateNetworkList)
  374. // Returns a list of capabilities
  375. func (c *CNIConfig) ValidateNetwork(ctx context.Context, net *NetworkConfig) ([]string, error) {
  376. caps := []string{}
  377. for c, ok := range net.Network.Capabilities {
  378. if ok {
  379. caps = append(caps, c)
  380. }
  381. }
  382. if err := c.validatePlugin(ctx, net.Network.Type, net.Network.CNIVersion); err != nil {
  383. return nil, err
  384. }
  385. return caps, nil
  386. }
  387. // validatePlugin checks that an individual plugin's configuration is sane
  388. func (c *CNIConfig) validatePlugin(ctx context.Context, pluginName, expectedVersion string) error {
  389. pluginPath, err := invoke.FindInPath(pluginName, c.Path)
  390. if err != nil {
  391. return err
  392. }
  393. vi, err := invoke.GetVersionInfo(ctx, pluginPath, c.exec)
  394. if err != nil {
  395. return err
  396. }
  397. for _, vers := range vi.SupportedVersions() {
  398. if vers == expectedVersion {
  399. return nil
  400. }
  401. }
  402. return fmt.Errorf("plugin %s does not support config version %q", pluginName, expectedVersion)
  403. }
  404. // GetVersionInfo reports which versions of the CNI spec are supported by
  405. // the given plugin.
  406. func (c *CNIConfig) GetVersionInfo(ctx context.Context, pluginType string) (version.PluginInfo, error) {
  407. c.ensureExec()
  408. pluginPath, err := c.exec.FindInPath(pluginType, c.Path)
  409. if err != nil {
  410. return nil, err
  411. }
  412. return invoke.GetVersionInfo(ctx, pluginPath, c.exec)
  413. }
  414. // =====
  415. func (c *CNIConfig) args(action string, rt *RuntimeConf) *invoke.Args {
  416. return &invoke.Args{
  417. Command: action,
  418. ContainerID: rt.ContainerID,
  419. NetNS: rt.NetNS,
  420. PluginArgs: rt.Args,
  421. IfName: rt.IfName,
  422. Path: strings.Join(c.Path, string(os.PathListSeparator)),
  423. }
  424. }