From 1d534255a733f840c89a92470b7cebb4ff2ff1e5 Mon Sep 17 00:00:00 2001 From: Matthew Endsley Date: Thu, 21 Nov 2024 18:33:08 -0800 Subject: [PATCH] feat: Use MAC address provided by nerdctl The nerdctl `--mac-address` command line passes the address to the CNI plugin with the `MAC` arg. See `getCNINamespaceOpts`: https://github.com/containerd/nerdctl/blob/main/pkg/containerutil/container_network_manager_windows.go#L184-L186 --- cni/cni.go | 16 ++++++++++++++++ common/core/network.go | 15 +++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/cni/cni.go b/cni/cni.go index 4a58dcc1..67586440 100644 --- a/cni/cni.go +++ b/cni/cni.go @@ -105,6 +105,11 @@ type K8SPodEnvArgs struct { K8S_POD_INFRA_CONTAINER_ID cniTypes.UnmarshallableString `json:"K8S_POD_INFRA_CONTAINER_ID,omitempty"` } +type EndpointArgs struct { + cniTypes.CommonArgs + MAC cniTypes.UnmarshallableString +} + type OptionalFlags struct { LocalRoutePortMapping bool `json:"localRoutedPortMapping"` AllowAclPortMapping bool `json:"allowAclPortMapping"` @@ -194,6 +199,17 @@ func ParseCniArgs(args string) (*K8SPodEnvArgs, error) { return &podConfig, nil } +// ParseCniEndpointArgs +func ParseCniEndpointArgs(args string) (*EndpointArgs, error) { + epArgs := EndpointArgs{} + err := cniTypes.LoadArgs(args, &epArgs) + if err != nil { + return nil, err + } + + return &epArgs, nil +} + // Serialize marshals a network configuration to bytes. func (config *NetworkConfig) Serialize() []byte { bytes, _ := json.Marshal(config) diff --git a/common/core/network.go b/common/core/network.go index d15dd2a4..a8fa157c 100644 --- a/common/core/network.go +++ b/common/core/network.go @@ -105,6 +105,12 @@ func (plugin *netPlugin) Add(args *cniSkel.CmdArgs) (resultError error) { k8sNamespace = string(podConfig.K8S_POD_NAMESPACE) } + epConfig, err := cni.ParseCniEndpointArgs(args.Args) + if err != nil { + logrus.Errorf("[cni-net] Failed to parse endpoint args, err:%v", err) + return err + } + // Parse network configuration from stdin. cniConfig, err := cni.ParseNetworkConfig(args.StdinData) if err != nil { @@ -133,6 +139,15 @@ func (plugin *netPlugin) Add(args *cniSkel.CmdArgs) (resultError error) { return err } + if epConfig.MAC != "" { + hwAddr, err := net.ParseMAC(string(epConfig.MAC)) + if err != nil { + logrus.Errorf("[cni-net] Failed to parse MAC addres '%s', err:%v", epConfig.MAC, err) + return err + } + + epInfo.MacAddress = hwAddr + } epInfo.DualStack = cniConfig.OptionalFlags.EnableDualStack // Check for missing namespace