Skip to content

Commit 17c1e34

Browse files
committed
Replace glog with zap
1 parent 83306fc commit 17c1e34

14 files changed

+304
-125
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

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

pkg/oci/ccm.go

+21-13
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"
@@ -37,6 +37,7 @@ import (
3737
cloudprovider "k8s.io/kubernetes/pkg/cloudprovider"
3838
controller "k8s.io/kubernetes/pkg/controller"
3939

40+
logutil "github.com/oracle/oci-cloud-controller-manager/pkg/log"
4041
"github.com/oracle/oci-cloud-controller-manager/pkg/oci/client"
4142
"github.com/oracle/oci-cloud-controller-manager/pkg/oci/instancemeta"
4243
"github.com/oracle/oci-cloud-controller-manager/pkg/oci/util"
@@ -60,6 +61,8 @@ type CloudProvider struct {
6061

6162
securityListManagerFactory securityListManagerFactory
6263
config *Config
64+
65+
logger *zap.SugaredLogger
6366
}
6467

6568
// Compile time check that CloudProvider implements the cloudprovider.Interface
@@ -68,17 +71,21 @@ var _ cloudprovider.Interface = &CloudProvider{}
6871

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

8087
if config.CompartmentID == "" {
81-
glog.Info("Compartment not supplied in config: attempting to infer from instance metadata")
88+
logger.Info("Compartment not supplied in config: attempting to infer from instance metadata")
8289
metadata, err := instancemeta.New().Get()
8390
if err != nil {
8491
return nil, err
@@ -87,7 +94,7 @@ func NewCloudProvider(config *Config) (cloudprovider.Interface, error) {
8794
}
8895

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

@@ -132,7 +140,7 @@ func (cp *CloudProvider) Initialize(clientBuilder controller.ControllerClientBui
132140
serviceInformer := factory.Core().V1().Services()
133141
go serviceInformer.Informer().Run(wait.NeverStop)
134142

135-
glog.Info("Waiting for node informer cache to sync")
143+
cp.logger.Info("Waiting for node informer cache to sync")
136144
if !cache.WaitForCacheSync(wait.NeverStop, nodeInformer.Informer().HasSynced, serviceInformer.Informer().HasSynced) {
137145
utilruntime.HandleError(fmt.Errorf("Timed out waiting for informers to sync"))
138146
}
@@ -145,7 +153,7 @@ func (cp *CloudProvider) Initialize(clientBuilder controller.ControllerClientBui
145153
if len(mode) == 0 {
146154
mode = cp.config.LoadBalancer.SecurityListManagementMode
147155
}
148-
return newSecurityListManager(cp.client, serviceInformer, cp.config.LoadBalancer.SecurityLists, mode)
156+
return newSecurityListManager(cp.logger, cp.client, serviceInformer, cp.config.LoadBalancer.SecurityLists, mode)
149157
}
150158
}
151159

@@ -157,21 +165,21 @@ func (cp *CloudProvider) ProviderName() string {
157165
// LoadBalancer returns a balancer interface. Also returns true if the interface
158166
// is supported, false otherwise.
159167
func (cp *CloudProvider) LoadBalancer() (cloudprovider.LoadBalancer, bool) {
160-
glog.V(6).Info("Claiming to support Load Balancers")
168+
cp.logger.Debug("Claiming to support Load Balancers")
161169
return cp, !cp.config.LoadBalancer.Disabled
162170
}
163171

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

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

@@ -198,16 +206,16 @@ func (cp *CloudProvider) HasClusterID() bool {
198206
return true
199207
}
200208

201-
func buildConfigurationProvider(config *Config) (common.ConfigurationProvider, error) {
209+
func buildConfigurationProvider(logger *zap.Logger, config *Config) (common.ConfigurationProvider, error) {
202210
if config.Auth.UseInstancePrincipals {
203-
glog.V(2).Info("Using instance principals configuration provider")
211+
logger.Info("Using instance principals configuration provider")
204212
cp, err := auth.InstancePrincipalConfigurationProvider()
205213
if err != nil {
206214
return nil, errors.Wrap(err, "InstancePrincipalConfigurationProvider")
207215
}
208216
return cp, nil
209217
}
210-
glog.V(2).Info("Using raw configuration provider")
218+
logger.Info("Using raw configuration provider")
211219
cp := common.NewRawConfigurationProvider(
212220
config.Auth.TenancyID,
213221
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)