namespace.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright The containerd Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cni
  14. import (
  15. "context"
  16. cnilibrary "github.com/containernetworking/cni/libcni"
  17. types100 "github.com/containernetworking/cni/pkg/types/100"
  18. )
  19. type Network struct {
  20. cni cnilibrary.CNI
  21. config *cnilibrary.NetworkConfigList
  22. ifName string
  23. }
  24. func (n *Network) Attach(ctx context.Context, ns *Namespace) (*types100.Result, error) {
  25. r, err := n.cni.AddNetworkList(ctx, n.config, ns.config(n.ifName))
  26. if err != nil {
  27. return nil, err
  28. }
  29. return types100.NewResultFromResult(r)
  30. }
  31. func (n *Network) Remove(ctx context.Context, ns *Namespace) error {
  32. return n.cni.DelNetworkList(ctx, n.config, ns.config(n.ifName))
  33. }
  34. func (n *Network) Check(ctx context.Context, ns *Namespace) error {
  35. return n.cni.CheckNetworkList(ctx, n.config, ns.config(n.ifName))
  36. }
  37. type Namespace struct {
  38. id string
  39. path string
  40. capabilityArgs map[string]interface{}
  41. args map[string]string
  42. }
  43. func newNamespace(id, path string, opts ...NamespaceOpts) (*Namespace, error) {
  44. ns := &Namespace{
  45. id: id,
  46. path: path,
  47. capabilityArgs: make(map[string]interface{}),
  48. args: make(map[string]string),
  49. }
  50. for _, o := range opts {
  51. if err := o(ns); err != nil {
  52. return nil, err
  53. }
  54. }
  55. return ns, nil
  56. }
  57. func (ns *Namespace) config(ifName string) *cnilibrary.RuntimeConf {
  58. c := &cnilibrary.RuntimeConf{
  59. ContainerID: ns.id,
  60. NetNS: ns.path,
  61. IfName: ifName,
  62. }
  63. for k, v := range ns.args {
  64. c.Args = append(c.Args, [2]string{k, v})
  65. }
  66. c.CapabilityArgs = ns.capabilityArgs
  67. return c
  68. }