Skip to content

Commit 15c45a4

Browse files
committed
Replace glog with zap
1 parent 895b107 commit 15c45a4

12 files changed

+292
-123
lines changed

cmd/oci-cloud-controller-manager/main.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ import (
2121
"os"
2222
"time"
2323

24-
"github.com/golang/glog"
2524
"github.com/spf13/pflag"
25+
"go.uber.org/zap"
2626

2727
utilflag "k8s.io/apiserver/pkg/util/flag"
2828
"k8s.io/apiserver/pkg/util/logs"
@@ -50,7 +50,7 @@ func main() {
5050
logs.InitLogs()
5151
defer logs.FlushLogs()
5252

53-
glog.V(1).Infof("oci-cloud-controller-manager version: %s (%s)", version, build)
53+
zap.S().Infof("oci-cloud-controller-manager version: %s (%s)", version, build)
5454

5555
if err := command.Execute(); err != nil {
5656
fmt.Fprintf(os.Stderr, "error: %v\n", err)

pkg/log/log.go

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// Copyright 2018 Oracle and/or its affiliates. All rights reserved.
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+
15+
package log
16+
17+
import (
18+
"flag"
19+
"fmt"
20+
"sync"
21+
22+
"go.uber.org/zap"
23+
"go.uber.org/zap/zapcore"
24+
)
25+
26+
var (
27+
lvlString = "info"
28+
logJSON = false
29+
config *zap.Config
30+
mu sync.Mutex
31+
glogVerbosity string
32+
)
33+
34+
func init() {
35+
flag.StringVar(&lvlString, "log-level", lvlString, "Adjusts the level of the logs that will be omitted.")
36+
flag.BoolVar(&logJSON, "log-json", logJSON, "Log in json format.")
37+
_ = flag.String("v", "", "For glog backwards compat. Does nothing.")
38+
}
39+
40+
// Options holds the zap logger configuration.
41+
type Options struct {
42+
LogLevel *zapcore.Level
43+
Config *zap.Config
44+
}
45+
46+
// Level gets the current log level.
47+
func Level() *zap.AtomicLevel {
48+
return &config.Level
49+
}
50+
51+
func levelFromString(level string) (*zapcore.Level, error) {
52+
var zapLevel zapcore.Level
53+
if err := zapLevel.UnmarshalText([]byte(level)); err != nil {
54+
return nil, fmt.Errorf("invalid logging level: %v", level)
55+
}
56+
return &zapLevel, nil
57+
}
58+
59+
// Logger builds a new logger based on the given flags.
60+
func Logger() *zap.Logger {
61+
mu.Lock()
62+
defer mu.Unlock()
63+
64+
var cfg zap.Config
65+
66+
if !logJSON {
67+
cfg = zap.NewDevelopmentConfig()
68+
} else {
69+
cfg = zap.NewProductionConfig()
70+
}
71+
72+
if config == nil {
73+
config = &cfg
74+
if level, err := levelFromString(lvlString); err == nil {
75+
config.Level = zap.NewAtomicLevelAt(*level)
76+
}
77+
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
78+
}
79+
80+
logger, err := config.Build(
81+
// We handle this via errors package for 99% of the stuff so only
82+
// enable this at the fatal/panic level.
83+
zap.AddStacktrace(zapcore.FatalLevel),
84+
)
85+
if err != nil {
86+
panic(err)
87+
}
88+
89+
return logger
90+
}

pkg/oci/ccm.go

+22-14
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ import (
2323

2424
"time"
2525

26-
"github.com/golang/glog"
2726
"github.com/oracle/oci-go-sdk/common"
2827
"github.com/oracle/oci-go-sdk/common/auth"
2928
"github.com/pkg/errors"
29+
"go.uber.org/zap"
3030

3131
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
3232
wait "k8s.io/apimachinery/pkg/util/wait"
@@ -38,6 +38,7 @@ import (
3838
cloudprovider "k8s.io/kubernetes/pkg/cloudprovider"
3939
controller "k8s.io/kubernetes/pkg/controller"
4040

41+
logutil "github.com/oracle/oci-cloud-controller-manager/pkg/log"
4142
"github.com/oracle/oci-cloud-controller-manager/pkg/oci/client"
4243
"github.com/oracle/oci-cloud-controller-manager/pkg/oci/instancemeta"
4344
"github.com/oracle/oci-cloud-controller-manager/pkg/oci/util"
@@ -61,6 +62,8 @@ type CloudProvider struct {
6162

6263
securityListManager securityListManager
6364
config *Config
65+
66+
logger *zap.SugaredLogger
6467
}
6568

6669
// Compile time check that CloudProvider implements the cloudprovider.Interface
@@ -69,17 +72,21 @@ var _ cloudprovider.Interface = &CloudProvider{}
6972

7073
// NewCloudProvider creates a new oci.CloudProvider.
7174
func NewCloudProvider(config *Config) (cloudprovider.Interface, error) {
72-
cp, err := buildConfigurationProvider(config)
75+
logger := logutil.Logger()
76+
defer logger.Sync()
77+
zap.ReplaceGlobals(logger)
78+
79+
cp, err := buildConfigurationProvider(logger, config)
7380
if err != nil {
7481
return nil, err
7582
}
76-
c, err := client.New(cp)
83+
c, err := client.New(logger.Sugar(), cp)
7784
if err != nil {
7885
return nil, err
7986
}
8087

8188
if config.CompartmentID == "" {
82-
glog.Info("Compartment not supplied in config: attempting to infer from instance metadata")
89+
logger.Info("Compartment not supplied in config: attempting to infer from instance metadata")
8390
metadata, err := instancemeta.New().Get()
8491
if err != nil {
8592
return nil, err
@@ -88,7 +95,7 @@ func NewCloudProvider(config *Config) (cloudprovider.Interface, error) {
8895
}
8996

9097
if !config.LoadBalancer.Disabled && config.VCNID == "" {
91-
glog.Infof("No vcn provided in cloud provider config. Falling back to looking up VCN via LB subnet.")
98+
logger.Info("No VCN provided in cloud provider config. Falling back to looking up VCN via LB subnet.")
9299
subnet, err := c.Networking().GetSubnet(context.Background(), config.LoadBalancer.Subnet1)
93100
if err != nil {
94101
return nil, errors.Wrap(err, "get subnet for loadBalancer.subnet1")
@@ -99,6 +106,7 @@ func NewCloudProvider(config *Config) (cloudprovider.Interface, error) {
99106
return &CloudProvider{
100107
client: c,
101108
config: config,
109+
logger: logger.Sugar(),
102110
}, nil
103111
}
104112

@@ -130,7 +138,7 @@ func (cp *CloudProvider) Initialize(clientBuilder controller.ControllerClientBui
130138

131139
nodeInformer := factory.Core().V1().Nodes()
132140
go nodeInformer.Informer().Run(wait.NeverStop)
133-
glog.Info("Waiting for node informer cache to sync")
141+
cp.logger.Info("Waiting for node informer cache to sync")
134142
if !cache.WaitForCacheSync(wait.NeverStop, nodeInformer.Informer().HasSynced) {
135143
utilruntime.HandleError(fmt.Errorf("Timed out waiting for node informer to sync"))
136144
}
@@ -141,13 +149,13 @@ func (cp *CloudProvider) Initialize(clientBuilder controller.ControllerClientBui
141149
if cp.config.LoadBalancer.SecurityListManagementMode != ManagementModeNone {
142150
serviceInformer = factory.Core().V1().Services()
143151
go serviceInformer.Informer().Run(wait.NeverStop)
144-
glog.Info("Waiting for service informer cache to sync")
152+
cp.logger.Info("Waiting for service informer cache to sync")
145153
if !cache.WaitForCacheSync(wait.NeverStop, serviceInformer.Informer().HasSynced) {
146154
utilruntime.HandleError(fmt.Errorf("Timed out waiting for service informer to sync"))
147155
}
148156
}
149157

150-
cp.securityListManager = newSecurityListManager(cp.client, serviceInformer, cp.config.LoadBalancer.SecurityLists, cp.config.LoadBalancer.SecurityListManagementMode)
158+
cp.securityListManager = newSecurityListManager(cp.logger, cp.client, serviceInformer, cp.config.LoadBalancer.SecurityLists, cp.config.LoadBalancer.SecurityListManagementMode)
151159
}
152160
}
153161

@@ -159,21 +167,21 @@ func (cp *CloudProvider) ProviderName() string {
159167
// LoadBalancer returns a balancer interface. Also returns true if the interface
160168
// is supported, false otherwise.
161169
func (cp *CloudProvider) LoadBalancer() (cloudprovider.LoadBalancer, bool) {
162-
glog.V(6).Info("Claiming to support Load Balancers")
170+
cp.logger.Debug("Claiming to support Load Balancers")
163171
return cp, !cp.config.LoadBalancer.Disabled
164172
}
165173

166174
// Instances returns an instances interface. Also returns true if the interface
167175
// is supported, false otherwise.
168176
func (cp *CloudProvider) Instances() (cloudprovider.Instances, bool) {
169-
glog.V(6).Info("Claiming to support instances")
177+
cp.logger.Debug("Claiming to support instances")
170178
return cp, true
171179
}
172180

173181
// Zones returns a zones interface. Also returns true if the interface is
174182
// supported, false otherwise.
175183
func (cp *CloudProvider) Zones() (cloudprovider.Zones, bool) {
176-
glog.V(6).Info("Claiming to support Zones")
184+
cp.logger.Debug("Claiming to support Zones")
177185
return cp, true
178186
}
179187

@@ -200,16 +208,16 @@ func (cp *CloudProvider) HasClusterID() bool {
200208
return true
201209
}
202210

203-
func buildConfigurationProvider(config *Config) (common.ConfigurationProvider, error) {
211+
func buildConfigurationProvider(logger *zap.Logger, config *Config) (common.ConfigurationProvider, error) {
204212
if config.Auth.UseInstancePrincipals {
205-
glog.V(2).Info("Using instance principals configuration provider")
213+
logger.Info("Using instance principals configuration provider")
206214
cp, err := auth.InstancePrincipalConfigurationProvider()
207215
if err != nil {
208216
return nil, errors.Wrap(err, "InstancePrincipalConfigurationProvider")
209217
}
210218
return cp, nil
211219
}
212-
glog.V(2).Info("Using raw configuration provider")
220+
logger.Info("Using raw configuration provider")
213221
cp := common.NewRawConfigurationProvider(
214222
config.Auth.TenancyID,
215223
config.Auth.UserID,

pkg/oci/client/client.go

+10-7
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ import (
2424
"os"
2525
"time"
2626

27+
"go.uber.org/zap"
2728
"k8s.io/client-go/tools/cache"
2829

29-
"github.com/golang/glog"
3030
"github.com/oracle/oci-go-sdk/common"
3131
"github.com/oracle/oci-go-sdk/core"
3232
"github.com/oracle/oci-go-sdk/loadbalancer"
@@ -46,16 +46,18 @@ type client struct {
4646
loadbalancer *loadbalancer.LoadBalancerClient
4747

4848
subnetCache cache.Store
49+
logger *zap.SugaredLogger
4950
}
5051

5152
// New constructs an OCI API client.
52-
func New(cp common.ConfigurationProvider) (Interface, error) {
53+
func New(logger *zap.SugaredLogger, cp common.ConfigurationProvider) (Interface, error) {
54+
logger = logger.Named("ociClient")
5355
compute, err := core.NewComputeClientWithConfigurationProvider(cp)
5456
if err != nil {
5557
return nil, errors.Wrap(err, "NewComputeClientWithConfigurationProvider")
5658
}
5759

58-
err = configureCustomTransport(&compute.BaseClient)
60+
err = configureCustomTransport(logger, &compute.BaseClient)
5961
if err != nil {
6062
return nil, errors.Wrap(err, "configuring load balancer client custom transport")
6163
}
@@ -65,7 +67,7 @@ func New(cp common.ConfigurationProvider) (Interface, error) {
6567
return nil, errors.Wrap(err, "NewVirtualNetworkClientWithConfigurationProvider")
6668
}
6769

68-
err = configureCustomTransport(&network.BaseClient)
70+
err = configureCustomTransport(logger, &network.BaseClient)
6971
if err != nil {
7072
return nil, errors.Wrap(err, "configuring load balancer client custom transport")
7173
}
@@ -75,7 +77,7 @@ func New(cp common.ConfigurationProvider) (Interface, error) {
7577
return nil, errors.Wrap(err, "NewLoadBalancerClientWithConfigurationProvider")
7678
}
7779

78-
err = configureCustomTransport(&lb.BaseClient)
80+
err = configureCustomTransport(logger, &lb.BaseClient)
7981
if err != nil {
8082
return nil, errors.Wrap(err, "configuring load balancer client custom transport")
8183
}
@@ -86,6 +88,7 @@ func New(cp common.ConfigurationProvider) (Interface, error) {
8688
loadbalancer: &lb,
8789

8890
subnetCache: cache.NewTTLStore(subnetCacheKeyFn, time.Duration(24)*time.Hour),
91+
logger: logger,
8992
}
9093

9194
return c, nil
@@ -103,7 +106,7 @@ func (c *client) Compute() ComputeInterface {
103106
return c
104107
}
105108

106-
func configureCustomTransport(baseClient *common.BaseClient) error {
109+
func configureCustomTransport(logger *zap.SugaredLogger, baseClient *common.BaseClient) error {
107110
httpClient := baseClient.HTTPClient.(*http.Client)
108111

109112
var transport *http.Transport
@@ -136,7 +139,7 @@ func configureCustomTransport(baseClient *common.BaseClient) error {
136139

137140
trustedCACertPath := os.Getenv("TRUSTED_CA_CERT_PATH")
138141
if trustedCACertPath != "" {
139-
glog.Infof("configuring OCI client with a new trusted ca: %s", trustedCACertPath)
142+
logger.With("path", trustedCACertPath).Infof("Configuring OCI client with a new trusted ca")
140143
trustedCACert, err := ioutil.ReadFile(trustedCACertPath)
141144
if err != nil {
142145
return errors.Wrapf(err, "failed to read root certificate: %s", trustedCACertPath)

pkg/oci/client/compute.go

+18-8
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import (
1818
"context"
1919
"strings"
2020

21-
"github.com/golang/glog"
2221
"github.com/oracle/oci-go-sdk/core"
2322
"github.com/pkg/errors"
2423
)
@@ -106,14 +105,19 @@ func (c *client) GetPrimaryVNICForInstance(ctx context.Context, compartmentID, i
106105

107106
for _, attachment := range resp.Items {
108107
if attachment.LifecycleState != core.VnicAttachmentLifecycleStateAttached {
109-
glog.Infof("VNIC attachment %q for instance %q has a state of %q (not %q)",
110-
*attachment.Id, instanceID, attachment.LifecycleState, core.VnicAttachmentLifecycleStateAttached)
108+
c.logger.With(
109+
"instanceID", instanceID,
110+
"vnicAttachmentID", *attachment.Id,
111+
"expectedLifecycleState", core.VnicAttachmentLifecycleStateAttached,
112+
"actualLifecycleState", attachment.LifecycleState,
113+
).Info("VNIC attachment in unexpected lifecycle state")
111114
continue
112115
}
113116

114117
if attachment.VnicId == nil {
115118
// Should never happen but lets be extra cautious as field is non-mandatory in OCI API.
116-
glog.Errorf("VNIC attachment %q for instance %q is attached but has no VNIC ID", *attachment.Id, instanceID)
119+
c.logger.With("instanceID", instanceID,
120+
"vnicAttachmentID", *attachment.Id).Error("VNIC attachment is attached but has no VNIC ID")
117121
continue
118122
}
119123

@@ -158,14 +162,19 @@ func (c *client) GetInstanceByNodeName(ctx context.Context, compartmentID, vcnID
158162

159163
for _, attachment := range resp.Items {
160164
if attachment.LifecycleState != core.VnicAttachmentLifecycleStateAttached {
161-
glog.Infof("VNIC attachment %q for instance %q has a life cycle state of %q (not %q)",
162-
*attachment.Id, nodeName, attachment.LifecycleState, core.VnicAttachmentLifecycleStateAttached)
165+
c.logger.With(
166+
"nodeName", nodeName,
167+
"vnicAttachmentID", *attachment.Id,
168+
"expectedLifecycleState", core.VnicAttachmentLifecycleStateAttached,
169+
"actualLifecycleState", attachment.LifecycleState,
170+
).Info("VNIC attachment in unexpected lifecycle state")
163171
continue
164172
}
165173

166174
if attachment.VnicId == nil {
167175
// Should never happen but lets be extra cautious as field is non-mandatory in OCI API.
168-
glog.Errorf("VNIC attachment %q for instance %q is attached but has no VNIC ID", *attachment.Id, nodeName)
176+
c.logger.With("nodeName", nodeName,
177+
"vnicAttachmentID", *attachment.Id).Error("VNIC attachment is attached but has no VNIC ID")
169178
continue
170179
}
171180

@@ -191,7 +200,8 @@ func (c *client) GetInstanceByNodeName(ctx context.Context, compartmentID, vcnID
191200
}
192201

193202
if IsInstanceInTerminalState(instance) {
194-
glog.Warningf("Instance %q is in state %q which is a terminal state", instance.Id, instance.LifecycleState)
203+
c.logger.With("instanceID", *instance.Id,
204+
"lifecycleState", instance.LifecycleState).Warn("Instance in a terminal state")
195205
continue
196206
}
197207

0 commit comments

Comments
 (0)