* restruct zap logger
This commit is contained in:
Paul Yu 2023-09-08 14:36:19 -04:00 коммит произвёл GitHub
Родитель 666f36cfb8
Коммит a90a77e0fe
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
17 изменённых файлов: 281 добавлений и 313 удалений

Просмотреть файл

@ -9,6 +9,11 @@ import (
"go.uber.org/zap"
)
var (
loggerName = "azure-vnet"
logger = log.InitZapLogCNI(loggerName, "azure-vnet.log")
)
type PodNetworkInterfaceInfo struct {
PodName string
PodNamespace string
@ -24,13 +29,13 @@ type AzureCNIState struct {
func (a *AzureCNIState) PrintResult() error {
b, err := json.MarshalIndent(a, "", " ")
if err != nil {
log.Logger.Error("Failed to unmarshall Azure CNI state", zap.Error(err))
logger.Error("Failed to unmarshall Azure CNI state", zap.Error(err))
}
// write result to stdout to be captured by caller
_, err = os.Stdout.Write(b)
if err != nil {
log.Logger.Error("Failed to write response to stdout", zap.Error(err))
logger.Error("Failed to write response to stdout", zap.Error(err))
return err
}

Просмотреть файл

@ -8,13 +8,19 @@ import (
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/api"
"github.com/Azure/azure-container-networking/log"
"github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/platform"
semver "github.com/hashicorp/go-version"
"github.com/pkg/errors"
"go.uber.org/zap"
utilexec "k8s.io/utils/exec"
)
var (
loggerName = "azure-vnet-client"
logger = log.InitZapLogCNI(loggerName, "azure-vnet.log")
)
type client struct {
exec utilexec.Interface
}
@ -30,7 +36,7 @@ func (c *client) GetEndpointState() (*api.AzureCNIState, error) {
cmd.SetDir(CNIExecDir)
envs := os.Environ()
cmdenv := fmt.Sprintf("%s=%s", cni.Cmd, cni.CmdGetEndpointsState)
log.Printf("Setting cmd to %s", cmdenv)
logger.Info("Setting cmd to", zap.String("cmdenv", cmdenv))
envs = append(envs, cmdenv)
cmd.SetEnv(envs)

Просмотреть файл

@ -21,6 +21,11 @@ import (
const ipamV6 = "azure-vnet-ipamv6"
var (
loggerName = "azure-vnet-ipam"
logger = log.InitZapLogCNI(loggerName, "azure-ipam.log")
)
var ipv4DefaultRouteDstPrefix = net.IPNet{
IP: net.IPv4zero,
Mask: net.IPv4Mask(0, 0, 0, 0),
@ -62,25 +67,25 @@ func (plugin *ipamPlugin) Start(config *common.PluginConfig) error {
// Initialize base plugin.
err := plugin.Initialize(config)
if err != nil {
log.Logger.Error("Failed to initialize base plugin.", zap.Error(err))
logger.Error("Failed to initialize base plugin.", zap.Error(err))
return err
}
// Log platform information.
log.Logger.Info("Plugin version.", zap.String("name", plugin.Name),
logger.Info("Plugin version.", zap.String("name", plugin.Name),
zap.String("version", plugin.Version))
log.Logger.Info("Running on",
logger.Info("Running on",
zap.String("platform", platform.GetOSInfo()))
// Initialize address manager. rehyrdration not required on reboot for cni ipam plugin
err = plugin.am.Initialize(config, false, plugin.Options)
if err != nil {
log.Logger.Error("Failed to initialize address manager",
zap.String("error", err.Error()))
logger.Error("Failed to initialize address manager",
zap.Error(err))
return err
}
log.Logger.Info("Plugin started")
logger.Info("Plugin started")
return nil
}
@ -89,7 +94,7 @@ func (plugin *ipamPlugin) Start(config *common.PluginConfig) error {
func (plugin *ipamPlugin) Stop() {
plugin.am.Uninitialize()
plugin.Uninitialize()
log.Logger.Info("Plugin stopped")
logger.Info("Plugin stopped")
}
// Configure parses and applies the given network configuration.
@ -100,7 +105,7 @@ func (plugin *ipamPlugin) Configure(stdinData []byte) (*cni.NetworkConfig, error
return nil, err
}
log.Logger.Info("Read network configuration",
logger.Info("Read network configuration",
zap.Any("config", nwCfg))
// Apply IPAM configuration.
@ -140,7 +145,7 @@ func (plugin *ipamPlugin) Add(args *cniSkel.CmdArgs) error {
var result *cniTypesCurr.Result
var err error
log.Logger.Info("Processing ADD command",
logger.Info("Processing ADD command",
zap.String("ContainerId", args.ContainerID),
zap.String("Netns", args.Netns),
zap.String("IfName", args.IfName),
@ -149,9 +154,9 @@ func (plugin *ipamPlugin) Add(args *cniSkel.CmdArgs) error {
zap.ByteString("StdinData", args.StdinData))
defer func() {
log.Logger.Info("ADD command completed",
logger.Info("ADD command completed",
zap.Any("result", result),
zap.Any("error:", err))
zap.Error(err))
}()
// Parse network configuration from stdin.
@ -188,14 +193,14 @@ func (plugin *ipamPlugin) Add(args *cniSkel.CmdArgs) error {
// On failure, release the address pool.
defer func() {
if err != nil && poolID != "" {
log.Logger.Info("Releasing pool",
logger.Info("Releasing pool",
zap.String("poolId", poolID))
_ = plugin.am.ReleasePool(nwCfg.IPAM.AddrSpace, poolID)
}
}()
nwCfg.IPAM.Subnet = subnet
log.Logger.Info("Allocated address with subnet",
logger.Info("Allocated address with subnet",
zap.String("poolId", poolID),
zap.String("subnet", subnet))
}
@ -210,12 +215,12 @@ func (plugin *ipamPlugin) Add(args *cniSkel.CmdArgs) error {
// On failure, release the address.
defer func() {
if err != nil && address != "" {
log.Logger.Info("Releasing address", zap.String("address", address))
logger.Info("Releasing address", zap.String("address", address))
_ = plugin.am.ReleaseAddress(nwCfg.IPAM.AddrSpace, nwCfg.IPAM.Subnet, address, options)
}
}()
log.Logger.Info("Allocated address", zap.String("address", address))
logger.Info("Allocated address", zap.String("address", address))
// Parse IP address.
ipAddress, err := platform.ConvertStringToIPNet(address)
@ -280,7 +285,7 @@ func (plugin *ipamPlugin) Get(args *cniSkel.CmdArgs) error {
func (plugin *ipamPlugin) Delete(args *cniSkel.CmdArgs) error {
var err error
log.Logger.Info("[cni-ipam] Processing DEL command",
logger.Info("[cni-ipam] Processing DEL command",
zap.String("ContainerId", args.ContainerID),
zap.String("Netns", args.Netns),
zap.String("IfName", args.IfName),
@ -289,7 +294,7 @@ func (plugin *ipamPlugin) Delete(args *cniSkel.CmdArgs) error {
zap.ByteString("StdinData", args.StdinData))
defer func() {
log.Logger.Info("[cni-ipam] DEL command completed",
logger.Info("[cni-ipam] DEL command completed",
zap.Error(err))
}()

Просмотреть файл

@ -4,31 +4,22 @@
package main
import (
"context"
"fmt"
"os"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/ipam"
zaplog "github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/common"
"github.com/Azure/azure-container-networking/log"
"go.uber.org/zap/zapcore"
)
const (
name = "azure-vnet-ipam"
maxLogFileSizeInMb = 5
maxLogFileCount = 8
component = "cni"
)
const name = "azure-vnet-ipam"
// Version is populated by make during build.
var version string
// Main is the entry point for CNI IPAM plugin.
func main() {
ctx, cancel := context.WithCancel(context.Background())
var config common.PluginConfig
config.Version = version
@ -43,16 +34,6 @@ func main() {
defer log.Close()
loggerCfg := &zaplog.Config{
Level: zapcore.DebugLevel,
LogPath: zaplog.LogPath + "azure-ipam.log",
MaxSizeInMB: maxLogFileSizeInMb,
MaxBackups: maxLogFileCount,
Name: name,
Component: component,
}
zaplog.Initialize(ctx, loggerCfg)
ipamPlugin, err := ipam.NewPlugin(name, &config)
if err != nil {
fmt.Printf("Failed to create IPAM plugin, err:%v.\n", err)
@ -83,7 +64,6 @@ func main() {
err = ipamPlugin.Execute(cni.PluginApi(ipamPlugin))
ipamPlugin.Stop()
cancel()
if err != nil {
panic("ipam plugin fatal error")

Просмотреть файл

@ -4,31 +4,22 @@
package main
import (
"context"
"fmt"
"os"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/ipam"
zaplog "github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/common"
"github.com/Azure/azure-container-networking/log"
"go.uber.org/zap/zapcore"
)
const (
name = "azure-vnet-ipamv6"
maxLogFileSizeInMb = 5
maxLogFileCount = 8
component = "cni"
)
const name = "azure-vnet-ipamv6"
// Version is populated by make during build.
var version string
// Main is the entry point for CNI IPAM plugin.
func main() {
ctx, cancel := context.WithCancel(context.Background())
var config common.PluginConfig
config.Version = version
@ -43,16 +34,6 @@ func main() {
defer log.Close()
loggerCfg := &zaplog.Config{
Level: zapcore.DebugLevel,
LogPath: zaplog.LogPath + "azure-ipam.log",
MaxSizeInMB: maxLogFileSizeInMb,
MaxBackups: maxLogFileCount,
Name: name,
Component: component,
}
zaplog.Initialize(ctx, loggerCfg)
ipamPlugin, err := ipam.NewPlugin(name, &config)
if err != nil {
fmt.Printf("Failed to create IPAM plugin, err:%v.\n", err)
@ -83,7 +64,6 @@ func main() {
err = ipamPlugin.Execute(cni.PluginApi(ipamPlugin))
ipamPlugin.Stop()
cancel()
if err != nil {
panic("ipam plugin fatal error")

Просмотреть файл

@ -1,55 +1,38 @@
package log
import (
"context"
"fmt"
"os"
"github.com/Azure/azure-container-networking/zaplog"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
type Config struct {
Level zapcore.Level
LogPath string
MaxSizeInMB int
MaxBackups int
Name string
Component string
const (
maxLogFileSizeInMb = 5
maxLogFileCount = 8
)
var (
loggerName string
loggerFile string
)
var LoggerCfg = &zaplog.Config{
Level: zapcore.DebugLevel,
LogPath: loggerFile,
MaxSizeInMB: maxLogFileSizeInMb,
MaxBackups: maxLogFileCount,
Name: loggerName,
}
var Logger *zap.Logger
func InitZapLogCNI(loggerName, loggerFile string) *zap.Logger {
LoggerCfg.Name = loggerName
LoggerCfg.LogPath = LogPath + loggerFile
logger := zaplog.InitZapLog(LoggerCfg)
// Initializes a Zap logger and returns a cleanup function so logger can be cleaned up from caller
func Initialize(ctx context.Context, cfg *Config) {
Logger = newFileLogger(cfg)
go func() {
<-ctx.Done()
err := Logger.Sync()
if err != nil {
fmt.Println("failed to sync logger")
}
}()
}
func newFileLogger(cfg *Config) *zap.Logger {
logFileWriter := zapcore.AddSync(&lumberjack.Logger{
Filename: cfg.LogPath,
MaxSize: cfg.MaxSizeInMB,
MaxBackups: cfg.MaxBackups,
})
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
jsonEncoder := zapcore.NewJSONEncoder(encoderConfig)
logLevel := cfg.Level
core := zapcore.NewCore(jsonEncoder, logFileWriter, logLevel)
Logger = zap.New(core)
Logger = Logger.With(zap.Int("pid", os.Getpid()))
Logger = Logger.With(zap.String("component", cfg.Component))
return Logger
// only log process id on CNI package
logger = logger.With(zap.Int("pid", os.Getpid()))
logger = logger.With(zap.String("component", "cni"))
return logger
}

Просмотреть файл

@ -1,7 +1,5 @@
package log
import "go.uber.org/zap"
func InitializeMock() {
Logger = zap.NewNop()
InitZapLogCNI("azure-vnet", "")
}

Просмотреть файл

@ -19,6 +19,11 @@ import (
"go.uber.org/zap"
)
var (
loggerName = "azure-vnet"
logger = log.InitZapLogCNI(loggerName, "azure-vnet.log")
)
const (
bytesSize4 = 4
bytesSize16 = 16
@ -104,7 +109,7 @@ func (invoker *AzureIPAMInvoker) Add(addConfig IPAMAddConfig) (IPAMAddResult, er
func (invoker *AzureIPAMInvoker) deleteIpamState() {
cniStateExists, err := platform.CheckIfFileExists(platform.CNIStateFilePath)
if err != nil {
log.Logger.Error("Error checking CNI state exist", zap.Error(err))
logger.Error("Error checking CNI state exist", zap.Error(err))
return
}
@ -114,15 +119,15 @@ func (invoker *AzureIPAMInvoker) deleteIpamState() {
ipamStateExists, err := platform.CheckIfFileExists(platform.CNIIpamStatePath)
if err != nil {
log.Logger.Error("Error checking IPAM state exist", zap.Error(err))
logger.Error("Error checking IPAM state exist", zap.Error(err))
return
}
if ipamStateExists {
log.Logger.Info("Deleting IPAM state file")
logger.Info("Deleting IPAM state file")
err = os.Remove(platform.CNIIpamStatePath)
if err != nil {
log.Logger.Error("Error deleting state file", zap.Error(err))
logger.Error("Error deleting state file", zap.Error(err))
return
}
}
@ -143,11 +148,11 @@ func (invoker *AzureIPAMInvoker) Delete(address *net.IPNet, nwCfg *cni.NetworkCo
}
} else if len(address.IP.To4()) == bytesSize4 { //nolint:gocritic
nwCfg.IPAM.Address = address.IP.String()
log.Logger.Info("Releasing ipv4",
logger.Info("Releasing ipv4",
zap.String("address", nwCfg.IPAM.Address),
zap.String("pool", nwCfg.IPAM.Subnet))
if err := invoker.plugin.DelegateDel(nwCfg.IPAM.Type, nwCfg); err != nil {
log.Logger.Error("Failed to release ipv4 address", zap.Error(err))
logger.Error("Failed to release ipv4 address", zap.Error(err))
return invoker.plugin.Errorf("Failed to release ipv4 address: %v", err)
}
} else if len(address.IP.To16()) == bytesSize16 {
@ -164,11 +169,11 @@ func (invoker *AzureIPAMInvoker) Delete(address *net.IPNet, nwCfg *cni.NetworkCo
}
}
log.Logger.Info("Releasing ipv6",
logger.Info("Releasing ipv6",
zap.String("address", nwCfgIpv6.IPAM.Address),
zap.String("pool", nwCfgIpv6.IPAM.Subnet))
if err := invoker.plugin.DelegateDel(nwCfgIpv6.IPAM.Type, &nwCfgIpv6); err != nil {
log.Logger.Error("Failed to release ipv6 address", zap.Error(err))
logger.Error("Failed to release ipv6 address", zap.Error(err))
return invoker.plugin.Errorf("Failed to release ipv6 address: %v", err)
}
} else {

Просмотреть файл

@ -7,7 +7,6 @@ import (
"net"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/cni/util"
"github.com/Azure/azure-container-networking/cns"
cnscli "github.com/Azure/azure-container-networking/cns/client"
@ -63,7 +62,7 @@ func (invoker *CNSIPAMInvoker) Add(addConfig IPAMAddConfig) (IPAMAddResult, erro
PodNamespace: invoker.podNamespace,
}
log.Logger.Info(podInfo.PodName)
logger.Info(podInfo.PodName)
orchestratorContext, err := json.Marshal(podInfo)
if err != nil {
return IPAMAddResult{}, errors.Wrap(err, "Failed to unmarshal orchestrator context during add: %w")
@ -79,14 +78,14 @@ func (invoker *CNSIPAMInvoker) Add(addConfig IPAMAddConfig) (IPAMAddResult, erro
InfraContainerID: addConfig.args.ContainerID,
}
log.Logger.Info("Requesting IP for pod using ipconfig",
logger.Info("Requesting IP for pod using ipconfig",
zap.Any("pod", podInfo),
zap.Any("ipconfig", ipconfigs))
response, err := invoker.cnsClient.RequestIPs(context.TODO(), ipconfigs)
if err != nil {
if cnscli.IsUnsupportedAPI(err) {
// If RequestIPs is not supported by CNS, use RequestIPAddress API
log.Logger.Error("RequestIPs not supported by CNS. Invoking RequestIPAddress API",
logger.Error("RequestIPs not supported by CNS. Invoking RequestIPAddress API",
zap.Any("infracontainerid", ipconfigs.InfraContainerID))
ipconfig := cns.IPConfigRequest{
OrchestratorContext: orchestratorContext,
@ -97,7 +96,7 @@ func (invoker *CNSIPAMInvoker) Add(addConfig IPAMAddConfig) (IPAMAddResult, erro
res, errRequestIP := invoker.cnsClient.RequestIPAddress(context.TODO(), ipconfig)
if errRequestIP != nil {
// if the old API fails as well then we just return the error
log.Logger.Error("Failed to request IP address from CNS using RequestIPAddress",
logger.Error("Failed to request IP address from CNS using RequestIPAddress",
zap.Any("infracontainerid", ipconfig.InfraContainerID),
zap.Error(errRequestIP))
return IPAMAddResult{}, errors.Wrap(errRequestIP, "Failed to get IP address from CNS")
@ -109,7 +108,7 @@ func (invoker *CNSIPAMInvoker) Add(addConfig IPAMAddConfig) (IPAMAddResult, erro
},
}
} else {
log.Logger.Info("Failed to get IP address from CNS",
logger.Info("Failed to get IP address from CNS",
zap.Error(err),
zap.Any("response", response))
return IPAMAddResult{}, errors.Wrap(err, "Failed to get IP address from CNS")
@ -135,7 +134,7 @@ func (invoker *CNSIPAMInvoker) Add(addConfig IPAMAddConfig) (IPAMAddResult, erro
addConfig.options[network.SNATIPKey] = info.ncPrimaryIP
}
log.Logger.Info("Received info for pod",
logger.Info("Received info for pod",
zap.Any("ipv4info", info),
zap.Any("podInfo", podInfo))
ip, ncIPNet, err := net.ParseCIDR(info.podIPAddress + "/" + fmt.Sprint(info.ncSubnetPrefix))
@ -302,13 +301,13 @@ func (invoker *CNSIPAMInvoker) Delete(address *net.IPNet, nwCfg *cni.NetworkConf
if address != nil {
ipConfigs.DesiredIPAddresses = append(ipConfigs.DesiredIPAddresses, address.IP.String())
} else {
log.Logger.Info("CNS invoker called with empty IP address")
logger.Info("CNS invoker called with empty IP address")
}
if err := invoker.cnsClient.ReleaseIPs(context.TODO(), ipConfigs); err != nil {
if cnscli.IsUnsupportedAPI(err) {
// If ReleaseIPs is not supported by CNS, use ReleaseIPAddress API
log.Logger.Error("ReleaseIPs not supported by CNS. Invoking ReleaseIPAddress API",
logger.Error("ReleaseIPs not supported by CNS. Invoking ReleaseIPAddress API",
zap.Any("ipconfigs", ipConfigs))
ipConfig := cns.IPConfigRequest{
@ -319,13 +318,13 @@ func (invoker *CNSIPAMInvoker) Delete(address *net.IPNet, nwCfg *cni.NetworkConf
if err = invoker.cnsClient.ReleaseIPAddress(context.TODO(), ipConfig); err != nil {
// if the old API fails as well then we just return the error
log.Logger.Error("Failed to release IP address from CNS using ReleaseIPAddress ",
logger.Error("Failed to release IP address from CNS using ReleaseIPAddress ",
zap.String("infracontainerid", ipConfigs.InfraContainerID),
zap.Error(err))
return errors.Wrap(err, fmt.Sprintf("failed to release IP %v using ReleaseIPAddress with err ", ipConfig.DesiredIPAddress)+"%w")
}
} else {
log.Logger.Error("Failed to release IP address",
logger.Error("Failed to release IP address",
zap.String("infracontainerid", ipConfigs.InfraContainerID),
zap.Error(err))
return errors.Wrap(err, fmt.Sprintf("failed to release IP %v using ReleaseIPs with err ", ipConfigs.DesiredIPAddresses)+"%w")

Просмотреть файл

@ -13,7 +13,6 @@ import (
"time"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/cns"
"github.com/Azure/azure-container-networking/cns/client"
"github.com/Azure/azure-container-networking/common"
@ -88,7 +87,7 @@ func (m *Multitenancy) DetermineSnatFeatureOnHost(snatFile, nmAgentSupportedApis
bytes, _ := io.ReadAll(jsonFile)
jsonFile.Close()
if retrieveSnatConfigErr = json.Unmarshal(bytes, &snatConfig); retrieveSnatConfigErr != nil {
log.Logger.Error("failed to unmarshal to snatConfig with error %v",
logger.Error("failed to unmarshal to snatConfig with error %v",
zap.Error(retrieveSnatConfigErr))
}
}
@ -98,10 +97,10 @@ func (m *Multitenancy) DetermineSnatFeatureOnHost(snatFile, nmAgentSupportedApis
var resp *http.Response
req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, nmAgentSupportedApisURL, nil)
if err != nil {
log.Logger.Error("failed creating http request", zap.Error(err))
logger.Error("failed creating http request", zap.Error(err))
return false, false, fmt.Errorf("%w", err)
}
log.Logger.Info("Query nma for dns snat support", zap.String("query", nmAgentSupportedApisURL))
logger.Info("Query nma for dns snat support", zap.String("query", nmAgentSupportedApisURL))
resp, retrieveSnatConfigErr = httpClient.Do(req)
if retrieveSnatConfigErr == nil {
defer resp.Body.Close()
@ -121,11 +120,11 @@ func (m *Multitenancy) DetermineSnatFeatureOnHost(snatFile, nmAgentSupportedApis
if err == nil {
_, err = fp.Write(jsonStr)
if err != nil {
log.Logger.Error("DetermineSnatFeatureOnHost: Write to json failed", zap.Error(err))
logger.Error("DetermineSnatFeatureOnHost: Write to json failed", zap.Error(err))
}
fp.Close()
} else {
log.Logger.Error("failed to save snat settings",
logger.Error("failed to save snat settings",
zap.String("snatConfgFile", snatConfigFile),
zap.Error(err))
}
@ -138,22 +137,22 @@ func (m *Multitenancy) DetermineSnatFeatureOnHost(snatFile, nmAgentSupportedApis
// Log and return the error when we fail acquire snat configuration for host and dns
if retrieveSnatConfigErr != nil {
log.Logger.Error("failed to acquire SNAT configuration with error %v",
logger.Error("failed to acquire SNAT configuration with error %v",
zap.Error(retrieveSnatConfigErr))
return snatConfig.EnableSnatForDns, snatConfig.EnableSnatOnHost, retrieveSnatConfigErr
}
log.Logger.Info("saved snat settings",
logger.Info("saved snat settings",
zap.Any("snatConfig", snatConfig),
zap.String("snatConfigfile", snatConfigFile))
if snatConfig.EnableSnatOnHost {
log.Logger.Info("enabling SNAT on container host for outbound connectivity")
logger.Info("enabling SNAT on container host for outbound connectivity")
}
if snatConfig.EnableSnatForDns {
log.Logger.Info("enabling SNAT on container host for DNS traffic")
logger.Info("enabling SNAT on container host for DNS traffic")
}
if !snatConfig.EnableSnatForDns && !snatConfig.EnableSnatOnHost {
log.Logger.Info("disabling SNAT on container host")
logger.Info("disabling SNAT on container host")
}
return snatConfig.EnableSnatForDns, snatConfig.EnableSnatOnHost, nil
@ -169,7 +168,7 @@ func (m *Multitenancy) SetupRoutingForMultitenancy(
// Adding default gateway
// if snat enabled, add 169.254.128.1 as default gateway
if nwCfg.EnableSnatOnHost {
log.Logger.Info("add default route for multitenancy.snat on host enabled")
logger.Info("add default route for multitenancy.snat on host enabled")
addDefaultRoute(cnsNetworkConfig.LocalIPConfiguration.GatewayIPAddress, epInfo, result)
} else {
_, defaultIPNet, _ := net.ParseCIDR("0.0.0.0/0")
@ -179,7 +178,7 @@ func (m *Multitenancy) SetupRoutingForMultitenancy(
result.Routes = append(result.Routes, &cniTypes.Route{Dst: dstIP, GW: gwIP})
if epInfo.EnableSnatForDns {
log.Logger.Info("add SNAT for DNS enabled")
logger.Info("add SNAT for DNS enabled")
addSnatForDNS(cnsNetworkConfig.LocalIPConfiguration.GatewayIPAddress, epInfo, result)
}
}
@ -199,7 +198,7 @@ func (m *Multitenancy) GetAllNetworkContainers(
podNameWithoutSuffix = podName
}
log.Logger.Info("Podname without suffix", zap.String("podName", podNameWithoutSuffix))
logger.Info("Podname without suffix", zap.String("podName", podNameWithoutSuffix))
ncResponses, hostSubnetPrefixes, err := m.getNetworkContainersInternal(ctx, podNamespace, podNameWithoutSuffix)
if err != nil {
@ -209,7 +208,7 @@ func (m *Multitenancy) GetAllNetworkContainers(
for i := 0; i < len(ncResponses); i++ {
if nwCfg.EnableSnatOnHost {
if ncResponses[i].LocalIPConfiguration.IPSubnet.IPAddress == "" {
log.Logger.Info("Snat IP is not populated for ncs. Got empty string",
logger.Info("Snat IP is not populated for ncs. Got empty string",
zap.Any("response", ncResponses))
return []IPAMAddResult{}, errSnatIP
}
@ -238,7 +237,7 @@ func (m *Multitenancy) getNetworkContainersInternal(
orchestratorContext, err := json.Marshal(podInfo)
if err != nil {
log.Logger.Error("Marshalling KubernetesPodInfo failed", zap.Error(err))
logger.Error("Marshalling KubernetesPodInfo failed", zap.Error(err))
return nil, []net.IPNet{}, fmt.Errorf("%w", err)
}
@ -255,13 +254,13 @@ func (m *Multitenancy) getNetworkContainersInternal(
return nil, []net.IPNet{}, fmt.Errorf("%w", err)
}
log.Logger.Info("Network config received from cns", zap.Any("nconfig", ncConfigs))
logger.Info("Network config received from cns", zap.Any("nconfig", ncConfigs))
subnetPrefixes := []net.IPNet{}
for i := 0; i < len(ncConfigs); i++ {
subnetPrefix := m.netioshim.GetInterfaceSubnetWithSpecificIP(ncConfigs[i].PrimaryInterfaceIdentifier)
if subnetPrefix == nil {
log.Logger.Error(errIfaceNotFound.Error(),
logger.Error(errIfaceNotFound.Error(),
zap.String("nodeIP", ncConfigs[i].PrimaryInterfaceIdentifier))
return nil, []net.IPNet{}, errIfaceNotFound
}

Просмотреть файл

@ -15,7 +15,6 @@ import (
"github.com/Azure/azure-container-networking/aitelemetry"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/api"
"github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/cni/util"
"github.com/Azure/azure-container-networking/cns"
cnscli "github.com/Azure/azure-container-networking/cns/client"
@ -143,23 +142,23 @@ func (plugin *NetPlugin) Start(config *common.PluginConfig) error {
// Initialize base plugin.
err := plugin.Initialize(config)
if err != nil {
log.Logger.Error("[cni-net] Failed to initialize base plugin", zap.Error(err))
logger.Error("[cni-net] Failed to initialize base plugin", zap.Error(err))
return err
}
// Log platform information.
log.Logger.Info("Plugin Info",
logger.Info("Plugin Info",
zap.String("name", plugin.Name),
zap.String("version", plugin.Version))
// Initialize network manager. rehyrdration not required on reboot for cni plugin
err = plugin.nm.Initialize(config, false)
if err != nil {
log.Logger.Error("Failed to initialize network manager", zap.Error(err))
logger.Error("Failed to initialize network manager", zap.Error(err))
return err
}
log.Logger.Info("Plugin started")
logger.Info("Plugin started")
return nil
}
@ -178,7 +177,7 @@ func (plugin *NetPlugin) GetAllEndpointState(networkid string) (*api.AzureCNISta
eps, err := plugin.nm.GetAllEndpoints(networkid)
if err == store.ErrStoreEmpty {
log.Logger.Error("failed to retrieve endpoint state", zap.Error(err))
logger.Error("failed to retrieve endpoint state", zap.Error(err))
} else if err != nil {
return nil, err
}
@ -203,7 +202,7 @@ func (plugin *NetPlugin) GetAllEndpointState(networkid string) (*api.AzureCNISta
func (plugin *NetPlugin) Stop() {
plugin.nm.Uninitialize()
plugin.Uninitialize()
log.Logger.Info("Plugin stopped")
logger.Info("Plugin stopped")
}
// FindMasterInterface returns the name of the master interface.
@ -244,21 +243,21 @@ func GetEndpointID(args *cniSkel.CmdArgs) string {
func (plugin *NetPlugin) getPodInfo(args string) (name, ns string, err error) {
podCfg, err := cni.ParseCniArgs(args)
if err != nil {
log.Logger.Error("Error while parsing CNI Args", zap.Error(err))
logger.Error("Error while parsing CNI Args", zap.Error(err))
return "", "", err
}
k8sNamespace := string(podCfg.K8S_POD_NAMESPACE)
if len(k8sNamespace) == 0 {
errMsg := "Pod Namespace not specified in CNI Args"
log.Logger.Error(errMsg)
logger.Error(errMsg)
return "", "", plugin.Errorf(errMsg)
}
k8sPodName := string(podCfg.K8S_POD_NAME)
if len(k8sPodName) == 0 {
errMsg := "Pod Name not specified in CNI Args"
log.Logger.Error(errMsg)
logger.Error(errMsg)
return "", "", plugin.Errorf(errMsg)
}
@ -267,7 +266,7 @@ func (plugin *NetPlugin) getPodInfo(args string) (name, ns string, err error) {
func SetCustomDimensions(cniMetric *telemetry.AIMetric, nwCfg *cni.NetworkConfig, err error) {
if cniMetric == nil {
log.Logger.Error("Unable to set custom dimension. Report is nil")
logger.Error("Unable to set custom dimension. Report is nil")
return
}
@ -308,7 +307,7 @@ func addNatIPV6SubnetInfo(nwCfg *cni.NetworkConfig,
Prefix: ipv6Subnet,
Gateway: resultV6.IPs[0].Gateway,
}
log.Logger.Info("ipv6 subnet info",
logger.Info("ipv6 subnet info",
zap.Any("ipv6SubnetInfo", ipv6SubnetInfo))
nwInfo.Subnets = append(nwInfo.Subnets, ipv6SubnetInfo)
}
@ -331,7 +330,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
startTime := time.Now()
log.Logger.Info("[cni-net] Processing ADD command",
logger.Info("[cni-net] Processing ADD command",
zap.String("containerId", args.ContainerID),
zap.String("netNS", args.Netns),
zap.String("ifName", args.IfName),
@ -381,7 +380,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
// Convert result to the requested CNI version.
res, vererr := ipamAddResult.ipv4Result.GetAsVersion(nwCfg.CNIVersion)
if vererr != nil {
log.Logger.Error("GetAsVersion failed", zap.Error(vererr))
logger.Error("GetAsVersion failed", zap.Error(vererr))
plugin.Error(vererr)
}
@ -390,7 +389,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
res.Print()
}
log.Logger.Info("[cni-net] ADD command completed for pod %v with IPs:%+v err:%v.",
logger.Info("[cni-net] ADD command completed for pod %v with IPs:%+v err:%v.",
zap.String("pod", k8sPodName),
zap.Any("IPs", ipamAddResult.ipv4Result.IPs),
zap.Error(err))
@ -407,21 +406,21 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
k8sContainerID := args.ContainerID
if len(k8sContainerID) == 0 {
errMsg := "Container ID not specified in CNI Args"
log.Logger.Error(errMsg)
logger.Error(errMsg)
return plugin.Errorf(errMsg)
}
k8sIfName := args.IfName
if len(k8sIfName) == 0 {
errMsg := "Interfacename not specified in CNI Args"
log.Logger.Error(errMsg)
logger.Error(errMsg)
return plugin.Errorf(errMsg)
}
platformInit(nwCfg)
if nwCfg.ExecutionMode == string(util.Baremetal) {
var res *nnscontracts.ConfigureContainerNetworkingResponse
log.Logger.Info("Baremetal mode. Calling vnet agent for ADD")
logger.Info("Baremetal mode. Calling vnet agent for ADD")
res, err = plugin.nnsClient.AddContainerNetworking(context.Background(), k8sPodName, args.Netns)
if err == nil {
@ -433,7 +432,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
for _, ns := range nwCfg.PodNamespaceForDualNetwork {
if k8sNamespace == ns {
log.Logger.Info("Enable infravnet for pod",
logger.Info("Enable infravnet for pod",
zap.String("pod", k8sPodName),
zap.String("namespace", k8sNamespace))
enableInfraVnet = true
@ -459,7 +458,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
ipamAddResults, err = plugin.multitenancyClient.GetAllNetworkContainers(context.TODO(), nwCfg, k8sPodName, k8sNamespace, args.IfName)
if err != nil {
err = fmt.Errorf("GetAllNetworkContainers failed for podname %s namespace %s. error: %w", k8sPodName, k8sNamespace, err)
log.Logger.Error("GetAllNetworkContainers failed",
logger.Error("GetAllNetworkContainers failed",
zap.String("pod", k8sPodName),
zap.String("namespace", k8sNamespace),
zap.Error(err))
@ -468,7 +467,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
if len(ipamAddResults) > 1 && !plugin.isDualNicFeatureSupported(args.Netns) {
errMsg := fmt.Sprintf("received multiple NC results %+v from CNS while dualnic feature is not supported", ipamAddResults)
log.Logger.Error("received multiple NC results from CNS while dualnic feature is not supported",
logger.Error("received multiple NC results from CNS while dualnic feature is not supported",
zap.Any("results", ipamAddResult))
return plugin.Errorf(errMsg)
}
@ -498,7 +497,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
// Issue link: https://github.com/kubernetes/kubernetes/issues/57253
if nwInfoErr == nil {
log.Logger.Info("[cni-net] Found network with subnet",
logger.Info("[cni-net] Found network with subnet",
zap.String("network", networkID),
zap.String("subnet", nwInfo.Subnets[0].Prefix.String()))
nwInfo.IPAMType = nwCfg.IPAM.Type
@ -507,7 +506,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
var resultSecondAdd *cniTypesCurr.Result
resultSecondAdd, err = plugin.handleConsecutiveAdd(args, endpointID, networkID, &nwInfo, nwCfg)
if err != nil {
log.Logger.Error("handleConsecutiveAdd failed", zap.Error(err))
logger.Error("handleConsecutiveAdd failed", zap.Error(err))
return err
}
@ -546,14 +545,14 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
// Create network
if nwInfoErr != nil {
// Network does not exist.
log.Logger.Info("[cni-net] Creating network", zap.String("networkID", networkID))
logger.Info("[cni-net] Creating network", zap.String("networkID", networkID))
sendEvent(plugin, fmt.Sprintf("[cni-net] Creating network %v.", networkID))
// opts map needs to get passed in here
if nwInfo, err = plugin.createNetworkInternal(networkID, policies, ipamAddConfig, ipamAddResult); err != nil {
log.Logger.Error("Create network failed", zap.Error(err))
logger.Error("Create network failed", zap.Error(err))
return err
}
log.Logger.Info("[cni-net] Created network",
logger.Info("[cni-net] Created network",
zap.String("networkId", networkID),
zap.String("subnet", ipamAddResult.hostSubnetPrefix.String()))
sendEvent(plugin, fmt.Sprintf("[cni-net] Created network %v with subnet %v.", networkID, ipamAddResult.hostSubnetPrefix.String()))
@ -581,7 +580,7 @@ func (plugin *NetPlugin) Add(args *cniSkel.CmdArgs) error {
var epInfo network.EndpointInfo
epInfo, err = plugin.createEndpointInternal(&createEndpointInternalOpt)
if err != nil {
log.Logger.Error("Endpoint creation failed", zap.Error(err))
logger.Error("Endpoint creation failed", zap.Error(err))
return err
}
@ -601,12 +600,12 @@ func (plugin *NetPlugin) cleanupAllocationOnError(
) {
if result != nil && len(result.IPs) > 0 {
if er := plugin.ipamInvoker.Delete(&result.IPs[0].Address, nwCfg, args, options); er != nil {
log.Logger.Error("Failed to cleanup ip allocation on failure", zap.Error(er))
logger.Error("Failed to cleanup ip allocation on failure", zap.Error(er))
}
}
if resultV6 != nil && len(resultV6.IPs) > 0 {
if er := plugin.ipamInvoker.Delete(&resultV6.IPs[0].Address, nwCfg, args, options); er != nil {
log.Logger.Error("Failed to cleanup ipv6 allocation on failure", zap.Error(er))
logger.Error("Failed to cleanup ipv6 allocation on failure", zap.Error(er))
}
}
}
@ -626,7 +625,7 @@ func (plugin *NetPlugin) createNetworkInternal(
err := plugin.Errorf("Failed to find the master interface")
return nwInfo, err
}
log.Logger.Info("[cni-net] Found master interface", zap.String("ifname", masterIfName))
logger.Info("[cni-net] Found master interface", zap.String("ifname", masterIfName))
// Add the master as an external interface.
err := plugin.nm.AddExternalInterface(masterIfName, ipamAddResult.hostSubnetPrefix.String())
@ -641,7 +640,7 @@ func (plugin *NetPlugin) createNetworkInternal(
return nwInfo, err
}
log.Logger.Info("[cni-net] DNS Info", zap.Any("info", nwDNSInfo))
logger.Info("[cni-net] DNS Info", zap.Any("info", nwDNSInfo))
// Create the network.
nwInfo = network.NetworkInfo{
@ -663,7 +662,7 @@ func (plugin *NetPlugin) createNetworkInternal(
}
if err = addSubnetToNetworkInfo(ipamAddResult, &nwInfo); err != nil {
log.Logger.Info("[cni-net] Failed to add subnets to networkInfo",
logger.Info("[cni-net] Failed to add subnets to networkInfo",
zap.Error(err))
return nwInfo, err
}
@ -746,7 +745,7 @@ func (plugin *NetPlugin) createEndpointInternal(opt *createEndpointInternalOpt)
}
endpointPolicies, err := getEndpointPolicies(policyArgs)
if err != nil {
log.Logger.Error("Failed to get endpoint policies", zap.Error(err))
logger.Error("Failed to get endpoint policies", zap.Error(err))
return epInfo, err
}
@ -816,13 +815,13 @@ func (plugin *NetPlugin) createEndpointInternal(opt *createEndpointInternalOpt)
cnsclient, err := cnscli.New(opt.nwCfg.CNSUrl, defaultRequestTimeout)
if err != nil {
log.Logger.Error("failed to initialized cns client", zap.String("url", opt.nwCfg.CNSUrl),
logger.Error("failed to initialized cns client", zap.String("url", opt.nwCfg.CNSUrl),
zap.String("error", err.Error()))
return epInfo, plugin.Errorf(err.Error())
}
// Create the endpoint.
log.Logger.Info("[cni-net] Creating endpoint", zap.String("endpointInfo", epInfo.PrettyString()))
logger.Info("[cni-net] Creating endpoint", zap.String("endpointInfo", epInfo.PrettyString()))
sendEvent(plugin, fmt.Sprintf("[cni-net] Creating endpoint %s.", epInfo.PrettyString()))
err = plugin.nm.CreateEndpoint(cnsclient, opt.nwInfo.Id, &epInfo)
if err != nil {
@ -843,7 +842,7 @@ func (plugin *NetPlugin) Get(args *cniSkel.CmdArgs) error {
networkID string
)
log.Logger.Info("[cni-net] Processing GET command",
logger.Info("[cni-net] Processing GET command",
zap.String("container", args.ContainerID),
zap.String("netns", args.Netns),
zap.String("ifname", args.IfName),
@ -860,7 +859,7 @@ func (plugin *NetPlugin) Get(args *cniSkel.CmdArgs) error {
// Convert result to the requested CNI version.
res, vererr := result.GetAsVersion(nwCfg.CNIVersion)
if vererr != nil {
log.Logger.Error("GetAsVersion failed", zap.Error(vererr))
logger.Error("GetAsVersion failed", zap.Error(vererr))
plugin.Error(vererr)
}
@ -869,7 +868,7 @@ func (plugin *NetPlugin) Get(args *cniSkel.CmdArgs) error {
res.Print()
}
log.Logger.Info("[cni-net] GET command completed", zap.Any("result", result),
logger.Info("[cni-net] GET command completed", zap.Any("result", result),
zap.Error(err))
}()
@ -879,14 +878,14 @@ func (plugin *NetPlugin) Get(args *cniSkel.CmdArgs) error {
return err
}
log.Logger.Info("[cni-net] Read network configuration", zap.Any("config", nwCfg))
logger.Info("[cni-net] Read network configuration", zap.Any("config", nwCfg))
iptables.DisableIPTableLock = nwCfg.DisableIPTableLock
// Initialize values from network config.
if networkID, err = plugin.getNetworkName(args.Netns, nil, nwCfg); err != nil {
// TODO: Ideally we should return from here only.
log.Logger.Error("[cni-net] Failed to extract network name from network config",
logger.Error("[cni-net] Failed to extract network name from network config",
zap.Error(err))
}
@ -942,7 +941,7 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
startTime := time.Now()
log.Logger.Info("[cni-net] Processing DEL command",
logger.Info("[cni-net] Processing DEL command",
zap.String("containerId", args.ContainerID),
zap.String("netNS", args.Netns),
zap.String("ifName", args.IfName),
@ -953,7 +952,7 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
args.ContainerID, args.Netns, args.IfName, args.Args, args.Path, args.StdinData))
defer func() {
log.Logger.Info("[cni-net] DEL command completed",
logger.Info("[cni-net] DEL command completed",
zap.String("pod", k8sPodName),
zap.Error(err))
}()
@ -966,7 +965,7 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
// Parse Pod arguments.
if k8sPodName, k8sNamespace, err = plugin.getPodInfo(args.Args); err != nil {
log.Logger.Error("[cni-net] Failed to get POD info", zap.Error(err))
logger.Error("[cni-net] Failed to get POD info", zap.Error(err))
}
plugin.setCNIReportDetails(nwCfg, CNI_DEL, "")
@ -988,10 +987,10 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
platformInit(nwCfg)
log.Logger.Info("Execution mode", zap.String("mode", nwCfg.ExecutionMode))
logger.Info("Execution mode", zap.String("mode", nwCfg.ExecutionMode))
if nwCfg.ExecutionMode == string(util.Baremetal) {
log.Logger.Info("Baremetal mode. Calling vnet agent for delete container")
logger.Info("Baremetal mode. Calling vnet agent for delete container")
// schedule send metric before attempting delete
defer sendMetricFunc()
@ -1006,7 +1005,7 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
case network.AzureCNS:
cnsClient, cnsErr := cnscli.New("", defaultRequestTimeout)
if cnsErr != nil {
log.Logger.Error("[cni-net] failed to create cns client", zap.Error(cnsErr))
logger.Error("[cni-net] failed to create cns client", zap.Error(cnsErr))
return errors.Wrap(cnsErr, "failed to create cns client")
}
plugin.ipamInvoker = NewCNSInvoker(k8sPodName, k8sNamespace, cnsClient, util.ExecutionMode(nwCfg.ExecutionMode), util.IpamMode(nwCfg.IPAM.Mode))
@ -1027,7 +1026,7 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
numEndpointsToDelete = plugin.nm.GetNumEndpointsByContainerID(args.ContainerID)
}
log.Logger.Info("[cni-net] Endpoints to be deleted", zap.Int("count", numEndpointsToDelete))
logger.Info("[cni-net] Endpoints to be deleted", zap.Int("count", numEndpointsToDelete))
for i := 0; i < numEndpointsToDelete; i++ {
// Initialize values from network config.
networkID, err = plugin.getNetworkName(args.Netns, nil, nwCfg)
@ -1038,14 +1037,14 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
return err
}
log.Logger.Error("[cni-net] Failed to extract network name from network config", zap.Error(err))
logger.Error("[cni-net] Failed to extract network name from network config", zap.Error(err))
err = plugin.Errorf("Failed to extract network name from network config. error: %v", err)
return err
}
// Query the network.
if nwInfo, err = plugin.nm.GetNetworkInfo(networkID); err != nil {
if !nwCfg.MultiTenancy {
log.Logger.Error("[cni-net] Failed to query network",
logger.Error("[cni-net] Failed to query network",
zap.String("network", networkID),
zap.Error(err))
// Log the error but return success if the network is not found.
@ -1059,17 +1058,17 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
endpointID := GetEndpointID(args)
// Query the endpoint.
if epInfo, err = plugin.nm.GetEndpointInfo(networkID, endpointID); err != nil {
log.Logger.Info("[cni-net] GetEndpoint",
logger.Info("[cni-net] GetEndpoint",
zap.String("endpoint", endpointID),
zap.Error(err))
if !nwCfg.MultiTenancy {
// attempt to release address associated with this Endpoint id
// This is to ensure clean up is done even in failure cases
log.Logger.Error("[cni-net] Failed to query endpoint",
logger.Error("[cni-net] Failed to query endpoint",
zap.String("endpoint", endpointID),
zap.Error(err))
log.Logger.Error("Release ip by ContainerID (endpoint not found)",
logger.Error("Release ip by ContainerID (endpoint not found)",
zap.String("containerID", args.ContainerID))
sendEvent(plugin, fmt.Sprintf("Release ip by ContainerID (endpoint not found):%v", args.ContainerID))
if err = plugin.ipamInvoker.Delete(nil, nwCfg, args, nwInfo.Options); err != nil {
@ -1083,7 +1082,7 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
// schedule send metric before attempting delete
defer sendMetricFunc() //nolint:gocritic
log.Logger.Info("Deleting endpoint",
logger.Info("Deleting endpoint",
zap.String("endpointID", endpointID))
sendEvent(plugin, fmt.Sprintf("Deleting endpoint:%v", endpointID))
// Delete the endpoint.
@ -1097,7 +1096,7 @@ func (plugin *NetPlugin) Delete(args *cniSkel.CmdArgs) error {
if !nwCfg.MultiTenancy {
// Call into IPAM plugin to release the endpoint's addresses.
for i := range epInfo.IPAddresses {
log.Logger.Info("Release ip", zap.String("ip", epInfo.IPAddresses[i].IP.String()))
logger.Info("Release ip", zap.String("ip", epInfo.IPAddresses[i].IP.String()))
sendEvent(plugin, fmt.Sprintf("Release ip:%s", epInfo.IPAddresses[i].IP.String()))
err = plugin.ipamInvoker.Delete(&epInfo.IPAddresses[i], nwCfg, args, nwInfo.Options)
if err != nil {
@ -1134,7 +1133,7 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
startTime := time.Now()
log.Logger.Info("[cni-net] Processing UPDATE command",
logger.Info("[cni-net] Processing UPDATE command",
zap.String("netns", args.Netns),
zap.String("args", args.Args),
zap.String("path", args.Path))
@ -1145,7 +1144,7 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
return err
}
log.Logger.Info("[cni-net] Read network configuration", zap.Any("config", nwCfg))
logger.Info("[cni-net] Read network configuration", zap.Any("config", nwCfg))
iptables.DisableIPTableLock = nwCfg.DisableIPTableLock
plugin.setCNIReportDetails(nwCfg, CNI_UPDATE, "")
@ -1168,7 +1167,7 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
// Convert result to the requested CNI version.
res, vererr := result.GetAsVersion(nwCfg.CNIVersion)
if vererr != nil {
log.Logger.Error("GetAsVersion failed", zap.Error(vererr))
logger.Error("GetAsVersion failed", zap.Error(vererr))
plugin.Error(vererr)
}
@ -1177,14 +1176,14 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
res.Print()
}
log.Logger.Info("[cni-net] UPDATE command completed",
logger.Info("[cni-net] UPDATE command completed",
zap.Any("result", result),
zap.Error(err))
}()
// Parse Pod arguments.
if podCfg, err = cni.ParseCniArgs(args.Args); err != nil {
log.Logger.Error("[cni-net] Error while parsing CNI Args during UPDATE",
logger.Error("[cni-net] Error while parsing CNI Args during UPDATE",
zap.Error(err))
return err
}
@ -1192,14 +1191,14 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
k8sNamespace := string(podCfg.K8S_POD_NAMESPACE)
if len(k8sNamespace) == 0 {
errMsg := "Required parameter Pod Namespace not specified in CNI Args during UPDATE"
log.Logger.Error(errMsg)
logger.Error(errMsg)
return plugin.Errorf(errMsg)
}
k8sPodName := string(podCfg.K8S_POD_NAME)
if len(k8sPodName) == 0 {
errMsg := "Required parameter Pod Name not specified in CNI Args during UPDATE"
log.Logger.Error(errMsg)
logger.Error(errMsg)
return plugin.Errorf(errMsg)
}
@ -1209,7 +1208,7 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
// Query the network.
if _, err = plugin.nm.GetNetworkInfo(networkID); err != nil {
errMsg := fmt.Sprintf("Failed to query network during CNI UPDATE: %v", err)
log.Logger.Error(errMsg)
logger.Error(errMsg)
return plugin.Errorf(errMsg)
}
@ -1221,11 +1220,11 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
return err
}
log.Logger.Info("Retrieved existing endpoint from state that may get update",
logger.Info("Retrieved existing endpoint from state that may get update",
zap.Any("info", existingEpInfo))
// now query CNS to get the target routes that should be there in the networknamespace (as a result of update)
log.Logger.Info("Going to collect target routes from CNS",
logger.Info("Going to collect target routes from CNS",
zap.String("pod", k8sPodName),
zap.String("namespace", k8sNamespace))
@ -1235,66 +1234,66 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
PodNamespace: k8sNamespace,
}
if orchestratorContext, err = json.Marshal(podInfo); err != nil {
log.Logger.Error("Marshalling KubernetesPodInfo failed",
logger.Error("Marshalling KubernetesPodInfo failed",
zap.Error(err))
return plugin.Errorf(err.Error())
}
cnsclient, err := cnscli.New(nwCfg.CNSUrl, defaultRequestTimeout)
if err != nil {
log.Logger.Error("failed to initialized cns client",
logger.Error("failed to initialized cns client",
zap.String("url", nwCfg.CNSUrl),
zap.String("error", err.Error()))
return plugin.Errorf(err.Error())
}
if targetNetworkConfig, err = cnsclient.GetNetworkContainer(context.TODO(), orchestratorContext); err != nil {
log.Logger.Info("GetNetworkContainer failed",
logger.Info("GetNetworkContainer failed",
zap.Error(err))
return plugin.Errorf(err.Error())
}
log.Logger.Info("Network config received from cns",
logger.Info("Network config received from cns",
zap.String("pod", k8sPodName),
zap.String("namespace", k8sNamespace),
zap.Any("config", targetNetworkConfig))
targetEpInfo := &network.EndpointInfo{}
// get the target routes that should replace existingEpInfo.Routes inside the network namespace
log.Logger.Info("Going to collect target routes for from targetNetworkConfig",
logger.Info("Going to collect target routes for from targetNetworkConfig",
zap.String("pod", k8sPodName),
zap.String("namespace", k8sNamespace))
if targetNetworkConfig.Routes != nil && len(targetNetworkConfig.Routes) > 0 {
for _, route := range targetNetworkConfig.Routes {
log.Logger.Info("Adding route from routes to targetEpInfo", zap.Any("route", route))
logger.Info("Adding route from routes to targetEpInfo", zap.Any("route", route))
_, dstIPNet, _ := net.ParseCIDR(route.IPAddress)
gwIP := net.ParseIP(route.GatewayIPAddress)
targetEpInfo.Routes = append(targetEpInfo.Routes, network.RouteInfo{Dst: *dstIPNet, Gw: gwIP, DevName: existingEpInfo.IfName})
log.Logger.Info("Successfully added route from routes to targetEpInfo", zap.Any("route", route))
logger.Info("Successfully added route from routes to targetEpInfo", zap.Any("route", route))
}
}
log.Logger.Info("Going to collect target routes based on Cnetaddressspace from targetNetworkConfig",
logger.Info("Going to collect target routes based on Cnetaddressspace from targetNetworkConfig",
zap.String("pod", k8sPodName),
zap.String("namespace", k8sNamespace))
ipconfig := targetNetworkConfig.IPConfiguration
for _, ipRouteSubnet := range targetNetworkConfig.CnetAddressSpace {
log.Logger.Info("Adding route from cnetAddressspace to targetEpInfo", zap.Any("subnet", ipRouteSubnet))
logger.Info("Adding route from cnetAddressspace to targetEpInfo", zap.Any("subnet", ipRouteSubnet))
dstIPNet := net.IPNet{IP: net.ParseIP(ipRouteSubnet.IPAddress), Mask: net.CIDRMask(int(ipRouteSubnet.PrefixLength), 32)}
gwIP := net.ParseIP(ipconfig.GatewayIPAddress)
route := network.RouteInfo{Dst: dstIPNet, Gw: gwIP, DevName: existingEpInfo.IfName}
targetEpInfo.Routes = append(targetEpInfo.Routes, route)
log.Logger.Info("Successfully added route from cnetAddressspace to targetEpInfo", zap.Any("subnet", ipRouteSubnet))
logger.Info("Successfully added route from cnetAddressspace to targetEpInfo", zap.Any("subnet", ipRouteSubnet))
}
log.Logger.Info("Finished collecting new routes in targetEpInfo", zap.Any("route", targetEpInfo.Routes))
log.Logger.Info("Now saving existing infravnetaddress space if needed.")
logger.Info("Finished collecting new routes in targetEpInfo", zap.Any("route", targetEpInfo.Routes))
logger.Info("Now saving existing infravnetaddress space if needed.")
for _, ns := range nwCfg.PodNamespaceForDualNetwork {
if k8sNamespace == ns {
targetEpInfo.EnableInfraVnet = true
targetEpInfo.InfraVnetAddressSpace = nwCfg.InfraVnetAddressSpace
log.Logger.Info("Saving infravnet address space",
logger.Info("Saving infravnet address space",
zap.String("space", targetEpInfo.InfraVnetAddressSpace),
zap.String("namespace", existingEpInfo.PODNameSpace),
zap.String("pod", existingEpInfo.PODName))
@ -1303,7 +1302,7 @@ func (plugin *NetPlugin) Update(args *cniSkel.CmdArgs) error {
}
// Update the endpoint.
log.Logger.Info("Now updating existing endpoint with targetNetworkConfig",
logger.Info("Now updating existing endpoint with targetNetworkConfig",
zap.String("endpoint", existingEpInfo.Id),
zap.Any("config", targetNetworkConfig))
if err = plugin.nm.UpdateEndpoint(networkID, existingEpInfo, targetEpInfo); err != nil {
@ -1338,7 +1337,7 @@ func convertNnsToCniResult(
prefixLength, err := strconv.Atoi(ip.PrefixLength)
if err != nil {
log.Logger.Error("Error parsing prefix length while converting to cni result",
logger.Error("Error parsing prefix length while converting to cni result",
zap.String("prefixLength", ip.PrefixLength),
zap.String("operation", operationName),
zap.String("pod", podName),

Просмотреть файл

@ -5,7 +5,6 @@ import (
"strconv"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/cns"
"github.com/Azure/azure-container-networking/network"
"github.com/Azure/azure-container-networking/network/policy"
@ -52,7 +51,7 @@ func addInfraRoutes(azIpamResult *cniTypesCurr.Result, result *cniTypesCurr.Resu
func setNetworkOptions(cnsNwConfig *cns.GetNetworkContainerResponse, nwInfo *network.NetworkInfo) {
if cnsNwConfig != nil && cnsNwConfig.MultiTenancyInfo.ID != 0 {
log.Logger.Info("Setting Network Options")
logger.Info("Setting Network Options")
vlanMap := make(map[string]interface{})
vlanMap[network.VlanIDKey] = strconv.Itoa(cnsNwConfig.MultiTenancyInfo.ID)
vlanMap[network.SnatBridgeIPKey] = cnsNwConfig.LocalIPConfiguration.GatewayIPAddress + "/" + strconv.Itoa(int(cnsNwConfig.LocalIPConfiguration.IPSubnet.PrefixLength))
@ -62,7 +61,7 @@ func setNetworkOptions(cnsNwConfig *cns.GetNetworkContainerResponse, nwInfo *net
func setEndpointOptions(cnsNwConfig *cns.GetNetworkContainerResponse, epInfo *network.EndpointInfo, vethName string) {
if cnsNwConfig != nil && cnsNwConfig.MultiTenancyInfo.ID != 0 {
log.Logger.Info("Setting Endpoint Options")
logger.Info("Setting Endpoint Options")
epInfo.Data[network.VlanIDKey] = cnsNwConfig.MultiTenancyInfo.ID
epInfo.Data[network.LocalIPKey] = cnsNwConfig.LocalIPConfiguration.IPSubnet.IPAddress + "/" + strconv.Itoa(int(cnsNwConfig.LocalIPConfiguration.IPSubnet.PrefixLength))
epInfo.Data[network.SnatBridgeIPKey] = cnsNwConfig.LocalIPConfiguration.GatewayIPAddress + "/" + strconv.Itoa(int(cnsNwConfig.LocalIPConfiguration.IPSubnet.PrefixLength))

Просмотреть файл

@ -11,7 +11,6 @@ import (
"strings"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/cni/util"
"github.com/Azure/azure-container-networking/cns"
"github.com/Azure/azure-container-networking/network"
@ -53,18 +52,18 @@ func (plugin *NetPlugin) handleConsecutiveAdd(args *cniSkel.CmdArgs, endpointId
hnsEndpoint, err := network.Hnsv1.GetHNSEndpointByName(endpointId)
if hnsEndpoint != nil {
log.Logger.Info("Found existing endpoint through hcsshim",
logger.Info("Found existing endpoint through hcsshim",
zap.Any("endpoint", hnsEndpoint))
endpoint, _ := network.Hnsv1.GetHNSEndpointByID(hnsEndpoint.Id)
isAttached, _ := network.Hnsv1.IsAttached(endpoint, args.ContainerID)
// Attach endpoint if it's not attached yet.
if !isAttached {
log.Logger.Info("Attaching endpoint to container",
logger.Info("Attaching endpoint to container",
zap.String("endpoint", hnsEndpoint.Id),
zap.String("container", args.ContainerID))
err := network.Hnsv1.HotAttachEndpoint(args.ContainerID, hnsEndpoint.Id)
if err != nil {
log.Logger.Error("Failed to hot attach shared endpoint to container",
logger.Error("Failed to hot attach shared endpoint to container",
zap.String("endpoint", hnsEndpoint.Id),
zap.String("container", args.ContainerID),
zap.Error(err))
@ -122,7 +121,7 @@ func addInfraRoutes(azIpamResult *cniTypesCurr.Result, result *cniTypesCurr.Resu
func setNetworkOptions(cnsNwConfig *cns.GetNetworkContainerResponse, nwInfo *network.NetworkInfo) {
if cnsNwConfig != nil && cnsNwConfig.MultiTenancyInfo.ID != 0 {
log.Logger.Info("Setting Network Options")
logger.Info("Setting Network Options")
vlanMap := make(map[string]interface{})
vlanMap[network.VlanIDKey] = strconv.Itoa(cnsNwConfig.MultiTenancyInfo.ID)
nwInfo.Options[dockerNetworkOption] = vlanMap
@ -131,7 +130,7 @@ func setNetworkOptions(cnsNwConfig *cns.GetNetworkContainerResponse, nwInfo *net
func setEndpointOptions(cnsNwConfig *cns.GetNetworkContainerResponse, epInfo *network.EndpointInfo, vethName string) {
if cnsNwConfig != nil && cnsNwConfig.MultiTenancyInfo.ID != 0 {
log.Logger.Info("Setting Endpoint Options")
logger.Info("Setting Endpoint Options")
var cnetAddressMap []string
for _, ipSubnet := range cnsNwConfig.CnetAddressSpace {
cnetAddressMap = append(cnetAddressMap, ipSubnet.IPAddress+"/"+strconv.Itoa(int(ipSubnet.PrefixLength)))
@ -165,7 +164,7 @@ func (plugin *NetPlugin) getNetworkName(netNs string, ipamAddResult *IPAMAddResu
ipAddrNet := ipamAddResult.ipv4Result.IPs[0].Address
prefix, err := netip.ParsePrefix(ipAddrNet.String())
if err != nil {
log.Logger.Error("Error parsing network CIDR",
logger.Error("Error parsing network CIDR",
zap.String("cidr", ipAddrNet.String()),
zap.Error(err))
return "", errors.Wrapf(err, "cns returned invalid CIDR %s", ipAddrNet.String())
@ -180,7 +179,7 @@ func (plugin *NetPlugin) getNetworkName(netNs string, ipamAddResult *IPAMAddResu
// This will happen during DEL call
networkName, err := plugin.nm.FindNetworkIDFromNetNs(netNs)
if err != nil {
log.Logger.Error("No endpoint available",
logger.Error("No endpoint available",
zap.String("netns", netNs),
zap.Error(err))
return "", fmt.Errorf("No endpoint available with netNs: %s: %w", netNs, err)
@ -250,7 +249,7 @@ func getEndpointDNSSettings(nwCfg *cni.NetworkConfig, result *cniTypesCurr.Resul
// getPoliciesFromRuntimeCfg returns network policies from network config.
func getPoliciesFromRuntimeCfg(nwCfg *cni.NetworkConfig, isIPv6Enabled bool) []policy.Policy {
log.Logger.Info("Runtime Info",
logger.Info("Runtime Info",
zap.Any("config", nwCfg.RuntimeConfig))
var policies []policy.Policy
var protocol uint32
@ -285,7 +284,7 @@ func getPoliciesFromRuntimeCfg(nwCfg *cni.NetworkConfig, isIPv6Enabled bool) []p
Data: hnsv2Policy,
}
log.Logger.Info("Creating port mapping policyv4",
logger.Info("Creating port mapping policyv4",
zap.Any("policy", policyv4))
policies = append(policies, policyv4)
@ -311,7 +310,7 @@ func getPoliciesFromRuntimeCfg(nwCfg *cni.NetworkConfig, isIPv6Enabled bool) []p
Data: hnsv2Policyv6,
}
log.Logger.Info("Creating port mapping policyv6",
logger.Info("Creating port mapping policyv6",
zap.Any("policy", policyv6))
policies = append(policies, policyv6)
}
@ -386,7 +385,7 @@ func getIPV6EndpointPolicy(nwInfo *network.NetworkInfo) (policy.Policy, error) {
Data: rawPolicy,
}
log.Logger.Info("[net] ipv6 outboundnat policy", zap.Any("policy", eppolicy))
logger.Info("[net] ipv6 outboundnat policy", zap.Any("policy", eppolicy))
return eppolicy, nil
}
@ -418,7 +417,7 @@ func determineWinVer() {
}
if err != nil {
log.Logger.Error(err.Error())
logger.Error(err.Error())
}
}
@ -440,7 +439,7 @@ func getNATInfo(nwCfg *cni.NetworkConfig, ncPrimaryIPIface interface{}, enableSn
func platformInit(cniConfig *cni.NetworkConfig) {
if cniConfig.WindowsSettings.HnsTimeoutDurationInSeconds > 0 {
log.Logger.Info("Enabling timeout for Hns calls",
logger.Info("Enabling timeout for Hns calls",
zap.Int("timeout", cniConfig.WindowsSettings.HnsTimeoutDurationInSeconds))
network.EnableHnsV1Timeout(cniConfig.WindowsSettings.HnsTimeoutDurationInSeconds)
network.EnableHnsV2Timeout(cniConfig.WindowsSettings.HnsTimeoutDurationInSeconds)
@ -453,12 +452,12 @@ func (plugin *NetPlugin) isDualNicFeatureSupported(netNs string) bool {
if useHnsV2 && err == nil {
return true
}
log.Logger.Error("DualNicFeature is not supported")
logger.Error("DualNicFeature is not supported")
return false
}
func getOverlayGateway(podsubnet *net.IPNet) (net.IP, error) {
log.Logger.Warn("No gateway specified for Overlay NC. CNI will choose one, but connectivity may break")
logger.Warn("No gateway specified for Overlay NC. CNI will choose one, but connectivity may break")
ncgw := podsubnet.IP
ncgw[3]++
ncgw = net.ParseIP(ncgw.String())

Просмотреть файл

@ -4,7 +4,6 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
@ -15,7 +14,7 @@ import (
"github.com/Azure/azure-container-networking/aitelemetry"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cni/api"
zaplog "github.com/Azure/azure-container-networking/cni/log"
zapLog "github.com/Azure/azure-container-networking/cni/log"
"github.com/Azure/azure-container-networking/cni/network"
"github.com/Azure/azure-container-networking/common"
"github.com/Azure/azure-container-networking/log"
@ -27,7 +26,6 @@ import (
cniTypes "github.com/containernetworking/cni/pkg/types"
"github.com/pkg/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
@ -37,14 +35,13 @@ const (
telemetryNumRetries = 5
telemetryWaitTimeInMilliseconds = 200
name = "azure-vnet"
maxLogFileSizeInMb = 5
maxLogFileCount = 8
component = "cni"
)
// Version is populated by make during build.
var version string
var logger = zapLog.InitZapLogCNI(name, "azure-vnet.log")
// Command line arguments for CNI plugin.
var args = common.ArgumentList{
{
@ -63,11 +60,11 @@ func printVersion() {
// send error report to hostnetagent if CNI encounters any error.
func reportPluginError(reportManager *telemetry.ReportManager, tb *telemetry.TelemetryBuffer, err error) {
zaplog.Logger.Error("Report plugin error")
logger.Error("Report plugin error")
reflect.ValueOf(reportManager.Report).Elem().FieldByName("ErrorMessage").SetString(err.Error())
if err := reportManager.SendReport(tb); err != nil {
zaplog.Logger.Error("SendReport failed", zap.Error(err))
logger.Error("SendReport failed", zap.Error(err))
}
}
@ -85,7 +82,7 @@ func validateConfig(jsonBytes []byte) error {
}
func getCmdArgsFromEnv() (string, *skel.CmdArgs, error) {
zaplog.Logger.Info("Going to read from stdin")
logger.Info("Going to read from stdin")
stdinData, err := io.ReadAll(os.Stdin)
if err != nil {
return "", nil, fmt.Errorf("error reading from stdin: %v", err)
@ -111,24 +108,24 @@ func handleIfCniUpdate(update func(*skel.CmdArgs) error) (bool, error) {
return false, nil
}
zaplog.Logger.Info("CNI UPDATE received")
logger.Info("CNI UPDATE received")
_, cmdArgs, err := getCmdArgsFromEnv()
if err != nil {
zaplog.Logger.Error("Received error while retrieving cmds from environment", zap.Error(err))
logger.Error("Received error while retrieving cmds from environment", zap.Error(err))
return isupdate, err
}
zaplog.Logger.Info("Retrieved command args for update", zap.Any("args", cmdArgs))
logger.Info("Retrieved command args for update", zap.Any("args", cmdArgs))
err = validateConfig(cmdArgs.StdinData)
if err != nil {
zaplog.Logger.Error("Failed to handle CNI UPDATE", zap.Error(err))
logger.Error("Failed to handle CNI UPDATE", zap.Error(err))
return isupdate, err
}
err = update(cmdArgs)
if err != nil {
zaplog.Logger.Error("Failed to handle CNI UPDATE", zap.Error(err))
logger.Error("Failed to handle CNI UPDATE", zap.Error(err))
return isupdate, err
}
@ -136,7 +133,7 @@ func handleIfCniUpdate(update func(*skel.CmdArgs) error) (bool, error) {
}
func printCNIError(msg string) {
zaplog.Logger.Error(msg)
logger.Error(msg)
cniErr := &cniTypes.Error{
Code: cniTypes.ErrTryAgainLater,
Msg: msg,
@ -180,7 +177,7 @@ func rootExecute() error {
cniCmd := os.Getenv(cni.Cmd)
if cniCmd != cni.CmdVersion {
zaplog.Logger.Info("Environment variable set", zap.String("CNI_COMMAND", cniCmd))
logger.Info("Environment variable set", zap.String("CNI_COMMAND", cniCmd))
cniReport.GetReport(pluginName, version, ipamQueryURL)
@ -196,7 +193,7 @@ func rootExecute() error {
tb = telemetry.NewTelemetryBuffer()
if tberr := tb.Connect(); tberr != nil {
zaplog.Logger.Error("Cannot connect to telemetry service", zap.Error(tberr))
logger.Error("Cannot connect to telemetry service", zap.Error(tberr))
return errors.Wrap(err, "lock acquire error")
}
@ -211,7 +208,7 @@ func rootExecute() error {
}
sendErr := telemetry.SendCNIMetric(&cniMetric, tb)
if sendErr != nil {
zaplog.Logger.Error("Couldn't send cnilocktimeout metric", zap.Error(sendErr))
logger.Error("Couldn't send cnilocktimeout metric", zap.Error(sendErr))
}
}
@ -221,7 +218,7 @@ func rootExecute() error {
defer func() {
if errUninit := netPlugin.Plugin.UninitializeKeyValueStore(); errUninit != nil {
zaplog.Logger.Error("Failed to uninitialize key-value store of network plugin", zap.Error(errUninit))
logger.Error("Failed to uninitialize key-value store of network plugin", zap.Error(errUninit))
}
if recover() != nil {
@ -248,17 +245,17 @@ func rootExecute() error {
// used to dump state
if cniCmd == cni.CmdGetEndpointsState {
zaplog.Logger.Debug("Retrieving state")
logger.Debug("Retrieving state")
var simpleState *api.AzureCNIState
simpleState, err = netPlugin.GetAllEndpointState("azure")
if err != nil {
zaplog.Logger.Error("Failed to get Azure CNI state", zap.Error(err))
logger.Error("Failed to get Azure CNI state", zap.Error(err))
return errors.Wrap(err, "Get all endpoints error")
}
err = simpleState.PrintResult()
if err != nil {
zaplog.Logger.Error("Failed to print state result to stdout", zap.Error(err))
logger.Error("Failed to print state result to stdout", zap.Error(err))
}
return errors.Wrap(err, "Get cni state printresult error")
@ -267,9 +264,9 @@ func rootExecute() error {
handled, _ := handleIfCniUpdate(netPlugin.Update)
if handled {
zaplog.Logger.Info("CNI UPDATE finished.")
logger.Info("CNI UPDATE finished.")
} else if err = netPlugin.Execute(cni.PluginApi(netPlugin)); err != nil {
zaplog.Logger.Error("Failed to execute network plugin", zap.Error(err))
logger.Error("Failed to execute network plugin", zap.Error(err))
}
if cniCmd == cni.CmdVersion {
@ -288,7 +285,6 @@ func rootExecute() error {
// Main is the entry point for CNI network plugin.
func main() {
// Initialize and parse command line arguments.
ctx, cancel := context.WithCancel(context.Background())
common.ParseArgs(&args, printVersion)
vers := common.GetArg(common.OptVersion).(bool)
@ -306,19 +302,7 @@ func main() {
defer log.Close()
loggerCfg := &zaplog.Config{
Level: zapcore.DebugLevel,
LogPath: zaplog.LogPath + name + ".log",
MaxSizeInMB: maxLogFileSizeInMb,
MaxBackups: maxLogFileCount,
Name: name,
Component: component,
}
zaplog.Initialize(ctx, loggerCfg)
if rootExecute() != nil {
os.Exit(1)
}
cancel()
}

Просмотреть файл

@ -24,6 +24,11 @@ import (
"go.uber.org/zap"
)
var (
loggerName = "azure-vnet"
logger = log.InitZapLogCNI(loggerName, "azure-vnet.log")
)
var errEmptyContent = errors.New("read content is zero bytes")
// Plugin is the parent class for CNI plugins.
@ -75,7 +80,7 @@ func (plugin *Plugin) Execute(api PluginApi) (err error) {
cniErr.Print()
err = cniErr
log.Logger.Info("Recovered panic",
logger.Info("Recovered panic",
zap.String("error", cniErr.Msg),
zap.String("details", cniErr.Details))
}
@ -99,9 +104,9 @@ func (plugin *Plugin) DelegateAdd(pluginName string, nwCfg *NetworkConfig) (*cni
var result *cniTypesCurr.Result
var err error
log.Logger.Info("Calling ADD", zap.String("plugin", pluginName))
logger.Info("Calling ADD", zap.String("plugin", pluginName))
defer func() {
log.Logger.Info("Plugin returned",
logger.Info("Plugin returned",
zap.String("plugin", pluginName),
zap.Any("result", result),
zap.Error(err))
@ -126,11 +131,11 @@ func (plugin *Plugin) DelegateAdd(pluginName string, nwCfg *NetworkConfig) (*cni
func (plugin *Plugin) DelegateDel(pluginName string, nwCfg *NetworkConfig) error {
var err error
log.Logger.Info("Calling DEL",
logger.Info("Calling DEL",
zap.String("plugin", pluginName),
zap.Any("config", nwCfg))
defer func() {
log.Logger.Info("Plugin eturned",
logger.Info("Plugin eturned",
zap.String("plugin", pluginName),
zap.Error(err))
}()
@ -155,9 +160,9 @@ func (plugin *Plugin) Error(err error) *cniTypes.Error {
cniErr = &cniTypes.Error{Code: 100, Msg: err.Error()}
}
log.Logger.Error("",
logger.Error("error",
zap.String("plugin", plugin.Name),
zap.String("error", cniErr.Error()))
zap.Error(cniErr))
return cniErr
}
@ -170,7 +175,7 @@ func (plugin *Plugin) Errorf(format string, args ...interface{}) *cniTypes.Error
// RetriableError logs and returns a CNI error with the TryAgainLater error code
func (plugin *Plugin) RetriableError(err error) *cniTypes.Error {
tryAgainErr := cniTypes.NewError(cniTypes.ErrTryAgainLater, err.Error(), "")
log.Logger.Error("",
logger.Error("retry failed",
zap.String("name", plugin.Name),
zap.String("error", tryAgainErr.Error()))
return tryAgainErr
@ -182,13 +187,13 @@ func (plugin *Plugin) InitializeKeyValueStore(config *common.PluginConfig) error
if plugin.Store == nil {
lockclient, err := processlock.NewFileLock(platform.CNILockPath + plugin.Name + store.LockExtension)
if err != nil {
log.Logger.Error("Error initializing file lock", zap.Error(err))
logger.Error("Error initializing file lock", zap.Error(err))
return errors.Wrap(err, "error creating new filelock")
}
plugin.Store, err = store.NewJsonFileStore(platform.CNIRuntimePath+plugin.Name+".json", lockclient)
if err != nil {
log.Logger.Error("Failed to create store", zap.Error(err))
logger.Error("Failed to create store", zap.Error(err))
return err
}
}
@ -200,7 +205,7 @@ func (plugin *Plugin) InitializeKeyValueStore(config *common.PluginConfig) error
}
// Acquire store lock.
if err := plugin.Store.Lock(lockTimeoutValue); err != nil {
log.Logger.Error("[cni] Failed to lock store", zap.Error(err))
logger.Error("[cni] Failed to lock store", zap.Error(err))
return errors.Wrap(err, "error Acquiring store lock")
}
@ -214,7 +219,7 @@ func (plugin *Plugin) UninitializeKeyValueStore() error {
if plugin.Store != nil {
err := plugin.Store.Unlock()
if err != nil {
log.Logger.Error("Failed to unlock store", zap.Error(err))
logger.Error("Failed to unlock store", zap.Error(err))
return err
}
}

Просмотреть файл

@ -29,7 +29,6 @@ const (
configExtension = ".config"
maxLogFileSizeInMb = 5
maxLogFileCount = 8
component = "cni"
)
var version string
@ -106,7 +105,6 @@ func main() {
var config telemetry.TelemetryConfig
var configPath string
var err error
ctx, cancel := context.WithCancel(context.Background())
acn.ParseArgs(&args, printVersion)
logLevel := acn.GetArg(acn.OptLogLevel).(zapcore.Level)
@ -118,17 +116,10 @@ func main() {
os.Exit(0)
}
loggerCfg := &log.Config{
Level: logLevel,
LogPath: log.LogPath + azureVnetTelemetry + ".log",
MaxSizeInMB: maxLogFileSizeInMb,
MaxBackups: maxLogFileCount,
Name: azureVnetTelemetry,
Component: component,
}
log.Initialize(ctx, loggerCfg)
log.LoggerCfg.Level = logLevel
logger := log.InitZapLogCNI(azureVnetTelemetry, azureVnetTelemetry+".log")
log.Logger.Info("Telemetry invocation info", zap.Any("arguments", os.Args))
logger.Info("Telemetry invocation info", zap.Any("arguments", os.Args))
if runtime.GOOS == "linux" {
configPath = fmt.Sprintf("%s/%s%s", configDirectory, azureVnetTelemetry, configExtension)
@ -136,18 +127,18 @@ func main() {
configPath = fmt.Sprintf("%s\\%s%s", configDirectory, azureVnetTelemetry, configExtension)
}
log.Logger.Info("Config path", zap.String("path", configPath))
logger.Info("Config path", zap.String("path", configPath))
config, err = telemetry.ReadConfigFile(configPath)
if err != nil {
log.Logger.Error("Error reading telemetry config", zap.Error(err))
logger.Error("Error reading telemetry config", zap.Error(err))
}
log.Logger.Info("read config returned", zap.Any("config", config))
logger.Info("read config returned", zap.Any("config", config))
setTelemetryDefaults(&config)
log.Logger.Info("Config after setting defaults", zap.Any("config", config))
logger.Info("Config after setting defaults", zap.Any("config", config))
// Cleaning up orphan socket if present
tbtemp := telemetry.NewTelemetryBuffer()
@ -156,13 +147,13 @@ func main() {
for {
tb = telemetry.NewTelemetryBuffer()
log.Logger.Info("Starting telemetry server")
logger.Info("Starting telemetry server")
err = tb.StartServer()
if err == nil || tb.FdExists {
break
}
log.Logger.Error("Telemetry service starting failed", zap.Error(err))
logger.Error("Telemetry service starting failed", zap.Error(err))
tb.Cleanup(telemetry.FdName)
time.Sleep(time.Millisecond * 200)
}
@ -180,11 +171,10 @@ func main() {
}
if telemetry.CreateAITelemetryHandle(aiConfig, config.DisableAll, config.DisableTrace, config.DisableMetric) != nil {
log.Logger.Error("[Telemetry] AI Handle creation error", zap.Error(err))
logger.Error("[Telemetry] AI Handle creation error", zap.Error(err))
}
log.Logger.Info("[Telemetry] Report to host interval", zap.Duration("seconds", config.ReportToHostIntervalInSeconds))
logger.Info("[Telemetry] Report to host interval", zap.Duration("seconds", config.ReportToHostIntervalInSeconds))
tb.PushData(context.Background())
telemetry.CloseAITelemetryHandle()
cancel()
}

32
zaplog/zaplog.go Normal file
Просмотреть файл

@ -0,0 +1,32 @@
package zaplog
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
type Config struct {
Level zapcore.Level
LogPath string
MaxSizeInMB int
MaxBackups int
Name string
}
func InitZapLog(cfg *Config) *zap.Logger {
logFileWriter := zapcore.AddSync(&lumberjack.Logger{
Filename: cfg.LogPath,
MaxSize: cfg.MaxSizeInMB,
MaxBackups: cfg.MaxBackups,
})
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
jsonEncoder := zapcore.NewJSONEncoder(encoderConfig)
logLevel := cfg.Level
core := zapcore.NewCore(jsonEncoder, logFileWriter, logLevel)
Logger := zap.New(core)
return Logger
}