api.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "strings"
  17. "github.com/containernetworking/cni/pkg/invoke"
  18. "github.com/containernetworking/cni/pkg/types"
  19. )
  20. type RuntimeConf struct {
  21. ContainerID string
  22. NetNS string
  23. IfName string
  24. Args [][2]string
  25. }
  26. type NetworkConfig struct {
  27. Network *types.NetConf
  28. Bytes []byte
  29. }
  30. type CNI interface {
  31. AddNetwork(net *NetworkConfig, rt *RuntimeConf) (*types.Result, error)
  32. DelNetwork(net *NetworkConfig, rt *RuntimeConf) error
  33. }
  34. type CNIConfig struct {
  35. Path []string
  36. }
  37. func (c *CNIConfig) AddNetwork(net *NetworkConfig, rt *RuntimeConf) (*types.Result, error) {
  38. pluginPath, err := invoke.FindInPath(net.Network.Type, c.Path)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return invoke.ExecPluginWithResult(pluginPath, net.Bytes, c.args("ADD", rt))
  43. }
  44. func (c *CNIConfig) DelNetwork(net *NetworkConfig, rt *RuntimeConf) error {
  45. pluginPath, err := invoke.FindInPath(net.Network.Type, c.Path)
  46. if err != nil {
  47. return err
  48. }
  49. return invoke.ExecPluginWithoutResult(pluginPath, net.Bytes, c.args("DEL", rt))
  50. }
  51. // =====
  52. func (c *CNIConfig) args(action string, rt *RuntimeConf) *invoke.Args {
  53. return &invoke.Args{
  54. Command: action,
  55. ContainerID: rt.ContainerID,
  56. NetNS: rt.NetNS,
  57. PluginArgs: rt.Args,
  58. IfName: rt.IfName,
  59. Path: strings.Join(c.Path, ":"),
  60. }
  61. }