This is an automated email from the ASF dual-hosted git repository.
albumenj pushed a commit to branch refactor-with-go
in repository https://gitbox.apache.org/repos/asf/dubbo-admin.git
The following commit(s) were added to refs/heads/refactor-with-go by this push:
new 61b9f7a Update logger
61b9f7a is described below
commit 61b9f7a15b0fd8b4a36cbf6b43f922f5faaee341
Author: Albumen Kevin <[email protected]>
AuthorDate: Thu Feb 23 16:25:07 2023 +0800
Update logger
---
ca/cmd/main.go | 2 ++
ca/pkg/cert/storage.go | 6 +++---
ca/pkg/cert/util.go | 11 ++++++-----
ca/pkg/k8s/client.go | 40 ++++++++++++++++++++--------------------
ca/pkg/logger/log.go | 36 ++++++++++++++++++++++++++++++++++++
ca/pkg/security/server.go | 27 ++++++++++-----------------
ca/pkg/v1alpha1/ca_impl.go | 16 ++++++++--------
7 files changed, 85 insertions(+), 53 deletions(-)
diff --git a/ca/cmd/main.go b/ca/cmd/main.go
index 78d23b0..ddfe992 100644
--- a/ca/cmd/main.go
+++ b/ca/cmd/main.go
@@ -17,6 +17,7 @@ package main
import (
"github.com/apache/dubbo-admin/ca/pkg/config"
+ "github.com/apache/dubbo-admin/ca/pkg/logger"
"github.com/apache/dubbo-admin/ca/pkg/security"
"os"
)
@@ -25,6 +26,7 @@ import (
const namespace = "dubbo-system"
func main() {
+ logger.Init()
// TODO read options from env
options := &config.Options{
EnableKubernetes: false,
diff --git a/ca/pkg/cert/storage.go b/ca/pkg/cert/storage.go
index 357833e..2236c74 100644
--- a/ca/pkg/cert/storage.go
+++ b/ca/pkg/cert/storage.go
@@ -19,7 +19,7 @@ import (
"crypto/rsa"
"crypto/tls"
"crypto/x509"
- "log"
+ "github.com/apache/dubbo-admin/ca/pkg/logger"
"math"
"sync"
"time"
@@ -82,7 +82,7 @@ func (c *Cert) GetTlsCert() *tls.Certificate {
}
tlsCert, err := tls.X509KeyPair([]byte(c.CertPem),
[]byte(EncodePri(c.PrivateKey)))
if err != nil {
- log.Printf("Failed to load x509 cert. %v", err)
+ logger.Sugar.Infof("Failed to load x509 cert. %v", err)
}
c.tlsCert = &tlsCert
return c.tlsCert
@@ -115,7 +115,7 @@ func (s *Storage) RefreshServerCert() {
time.Sleep(time.Duration(interval) * time.Millisecond)
s.Mutex.Lock()
if s.ServerCerts == nil || !s.ServerCerts.IsValid() {
- log.Printf("Server cert is invalid, refresh it.")
+ logger.Sugar.Infof("Server cert is invalid, refresh
it.")
s.ServerCerts = SignServerCert(s.AuthorityCert,
s.ServerNames, s.CertValidity)
}
s.Mutex.Unlock()
diff --git a/ca/pkg/cert/util.go b/ca/pkg/cert/util.go
index 55d8e91..9c038d8 100644
--- a/ca/pkg/cert/util.go
+++ b/ca/pkg/cert/util.go
@@ -22,6 +22,7 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
+ "github.com/apache/dubbo-admin/ca/pkg/logger"
"log"
"math/big"
"time"
@@ -31,7 +32,7 @@ func DecodeCert(cert string) *x509.Certificate {
block, _ := pem.Decode([]byte(cert))
p, err := x509.ParseCertificate(block.Bytes)
if err != nil {
- log.Printf("Failed to parse public key. " + err.Error())
+ logger.Sugar.Warnf("Failed to parse public key. " + err.Error())
return nil
}
return p
@@ -40,7 +41,7 @@ func DecodeCert(cert string) *x509.Certificate {
func DecodePub(cert string) *rsa.PublicKey {
p, err := x509.ParsePKCS1PublicKey([]byte(cert))
if err != nil {
- log.Printf("Failed to parse public key. " + err.Error())
+ logger.Sugar.Warnf("Failed to parse public key. " + err.Error())
return nil
}
return p
@@ -51,7 +52,7 @@ func DecodePri(cert string) *rsa.PrivateKey {
p, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
- log.Printf("Failed to parse private key. " + err.Error())
+ logger.Sugar.Warnf("Failed to parse private key. " +
err.Error())
return nil
}
return p
@@ -92,7 +93,7 @@ func CreateCA(rootCert *Cert, caValidity int64) *Cert {
Bytes: caBytes,
})
if err != nil {
- log.Printf("Failed to encode certificate. " + err.Error())
+ logger.Sugar.Warnf("Failed to encode certificate. " +
err.Error())
panic(err)
}
@@ -131,7 +132,7 @@ func SignServerCert(authorityCert *Cert, serverName
[]string, certValidity int64
Bytes: c,
})
if err != nil {
- log.Printf("Failed to encode certificate. " + err.Error())
+ logger.Sugar.Warnf("Failed to encode certificate. " +
err.Error())
panic(err)
}
return &Cert{
diff --git a/ca/pkg/k8s/client.go b/ca/pkg/k8s/client.go
index 1bf7701..57e63e9 100644
--- a/ca/pkg/k8s/client.go
+++ b/ca/pkg/k8s/client.go
@@ -18,6 +18,7 @@ package k8s
import (
"context"
"flag"
+ "github.com/apache/dubbo-admin/ca/pkg/logger"
k8sauth "k8s.io/api/authentication/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -25,7 +26,6 @@ import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
- "log"
"path/filepath"
)
@@ -36,7 +36,7 @@ type Client struct {
func (c *Client) Init() bool {
config, err := rest.InClusterConfig()
if err != nil {
- log.Printf("Failed to load config from Pod. Will fall back to
kube config file.")
+ logger.Sugar.Infof("Failed to load config from Pod. Will fall
back to kube config file.")
}
var kubeconfig *string
@@ -50,14 +50,14 @@ func (c *Client) Init() bool {
// use the current context in kubeconfig
config, err = clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
- log.Printf("Failed to load config from kube config file.")
+ logger.Sugar.Warnf("Failed to load config from kube config
file.")
return false
}
// creates the clientset
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
- log.Printf("Failed to create client to kubernetes. " +
err.Error())
+ logger.Sugar.Warnf("Failed to create client to kubernetes. " +
err.Error())
return false
}
c.kubeClient = clientSet
@@ -67,7 +67,7 @@ func (c *Client) Init() bool {
func (c *Client) GetAuthorityCert(namespace string) (string, string) {
s, err := c.kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(),
"dubbo-ca-secret", metav1.GetOptions{})
if err != nil {
- log.Printf("Unable to get authority cert secret from
kubernetes. " + err.Error())
+ logger.Sugar.Warnf("Unable to get authority cert secret from
kubernetes. " + err.Error())
}
return string(s.Data["cert.pem"]), string(s.Data["pri.pem"])
}
@@ -75,7 +75,7 @@ func (c *Client) GetAuthorityCert(namespace string) (string,
string) {
func (c *Client) UpdateAuthorityCert(cert string, pri string, namespace
string) {
s, err := c.kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(),
"dubbo-ca-secret", metav1.GetOptions{})
if err != nil {
- log.Printf("Unable to get ca secret from kubernetes. Will try
to create. " + err.Error())
+ logger.Sugar.Warnf("Unable to get ca secret from kubernetes.
Will try to create. " + err.Error())
s = &v1.Secret{
Data: map[string][]byte{
"cert.pem": []byte(cert),
@@ -85,14 +85,14 @@ func (c *Client) UpdateAuthorityCert(cert string, pri
string, namespace string)
s.Name = "dubbo-ca-secret"
_, err =
c.kubeClient.CoreV1().Secrets(namespace).Create(context.TODO(), s,
metav1.CreateOptions{})
if err != nil {
- log.Printf("Failed to create ca secret to kubernetes. "
+ err.Error())
+ logger.Sugar.Warnf("Failed to create ca secret to
kubernetes. " + err.Error())
} else {
- log.Printf("Create ca secret to kubernetes success. ")
+ logger.Sugar.Info("Create ca secret to kubernetes
success. ")
}
}
if string(s.Data["cert.pem"]) == cert && string(s.Data["pri.pem"]) ==
pri {
- log.Printf("Ca secret in kubernetes is already the newest
vesion.")
+ logger.Sugar.Info("Ca secret in kubernetes is already the
newest vesion.")
return
}
@@ -100,16 +100,16 @@ func (c *Client) UpdateAuthorityCert(cert string, pri
string, namespace string)
s.Data["pri.pem"] = []byte(pri)
_, err =
c.kubeClient.CoreV1().Secrets(namespace).Update(context.TODO(), s,
metav1.UpdateOptions{})
if err != nil {
- log.Printf("Failed to update ca secret to kubernetes. " +
err.Error())
+ logger.Sugar.Warnf("Failed to update ca secret to kubernetes. "
+ err.Error())
} else {
- log.Printf("Update ca secret to kubernetes success. ")
+ logger.Sugar.Info("Update ca secret to kubernetes success. ")
}
}
func (c *Client) UpdateAuthorityPublicKey(cert string) bool {
ns, err := c.kubeClient.CoreV1().Namespaces().List(context.TODO(),
metav1.ListOptions{})
if err != nil {
- log.Printf("Failed to get namespaces. " + err.Error())
+ logger.Sugar.Warnf("Failed to get namespaces. " + err.Error())
return false
}
for _, n := range ns.Items {
@@ -118,7 +118,7 @@ func (c *Client) UpdateAuthorityPublicKey(cert string) bool
{
}
cm, err :=
c.kubeClient.CoreV1().ConfigMaps(n.Name).Get(context.TODO(), "dubbo-ca-cert",
metav1.GetOptions{})
if err != nil {
- log.Printf("Unable to find dubbo-ca-cert in " + n.Name
+ ". Will create config map. " + err.Error())
+ logger.Sugar.Warnf("Unable to find dubbo-ca-cert in " +
n.Name + ". Will create config map. " + err.Error())
cm = &v1.ConfigMap{
Data: map[string]string{
"ca.crt": cert,
@@ -127,23 +127,23 @@ func (c *Client) UpdateAuthorityPublicKey(cert string)
bool {
cm.Name = "dubbo-ca-cert"
_, err =
c.kubeClient.CoreV1().ConfigMaps(n.Name).Create(context.TODO(), cm,
metav1.CreateOptions{})
if err != nil {
- log.Printf("Failed to create config map for " +
n.Name + ". " + err.Error())
+ logger.Sugar.Warnf("Failed to create config map
for " + n.Name + ". " + err.Error())
return false
} else {
- log.Printf("Create ca config map for " + n.Name
+ " success.")
+ logger.Sugar.Info("Create ca config map for " +
n.Name + " success.")
}
}
if cm.Data["ca.crt"] == cert {
- log.Printf("Ignore override ca to " + n.Name + ".
Cause: Already exist.")
+ logger.Sugar.Info("Ignore override ca to " + n.Name +
". Cause: Already exist.")
continue
}
cm.Data["ca.crt"] = cert
_, err =
c.kubeClient.CoreV1().ConfigMaps(n.Name).Update(context.TODO(), cm,
metav1.UpdateOptions{})
if err != nil {
- log.Printf("Failed to update config map for " + n.Name
+ ". " + err.Error())
+ logger.Sugar.Warnf("Failed to update config map for " +
n.Name + ". " + err.Error())
return false
} else {
- log.Printf("Update ca config map for " + n.Name + "
success.")
+ logger.Sugar.Info("Update ca config map for " + n.Name
+ " success.")
}
}
return true
@@ -157,12 +157,12 @@ func (c *Client) VerifyServiceAccount(token string) bool {
}
reviewRes, err :=
c.kubeClient.AuthenticationV1().TokenReviews().Create(context.TODO(),
tokenReview, metav1.CreateOptions{})
if err != nil {
- log.Printf("Failed to validate token. " + err.Error())
+ logger.Sugar.Warnf("Failed to validate token. " + err.Error())
return false
}
// TODO support aud
if reviewRes.Status.Error != "" {
- log.Printf("Failed to validate token. " +
reviewRes.Status.Error)
+ logger.Sugar.Warnf("Failed to validate token. " +
reviewRes.Status.Error)
return false
}
return true
diff --git a/ca/pkg/logger/log.go b/ca/pkg/logger/log.go
new file mode 100644
index 0000000..3592e6e
--- /dev/null
+++ b/ca/pkg/logger/log.go
@@ -0,0 +1,36 @@
+package logger
+
+import (
+ grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
+ "go.uber.org/zap"
+ "go.uber.org/zap/zapcore"
+ "os"
+)
+
+var Logger *zap.Logger
+var Sugar *zap.SugaredLogger
+
+func Init() {
+ encoder := zapcore.NewConsoleEncoder(
+ zapcore.EncoderConfig{
+ MessageKey: "msg",
+ LevelKey: "level",
+ TimeKey: "time",
+ CallerKey: "line",
+ NameKey: "logger",
+ FunctionKey: "func",
+ StacktraceKey: "stacktrace",
+ EncodeLevel: zapcore.CapitalLevelEncoder,
+ EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02
15:04:05.0000"),
+ EncodeCaller: zapcore.ShortCallerEncoder,
+ EncodeDuration: zapcore.SecondsDurationEncoder,
+ })
+ core := zapcore.NewCore(encoder, os.Stdout, zap.DebugLevel)
+ Logger = zap.New(core)
+ defer Logger.Sync() // flushes buffer, if any
+ Sugar = Logger.Sugar()
+
+ // Make sure that log statements internal to gRPC library are logged
using the zapLogger as well.
+ grpc_zap.ReplaceGrpcLoggerV2(Logger)
+
+}
diff --git a/ca/pkg/security/server.go b/ca/pkg/security/server.go
index 0559c43..744be74 100644
--- a/ca/pkg/security/server.go
+++ b/ca/pkg/security/server.go
@@ -20,9 +20,8 @@ import (
"github.com/apache/dubbo-admin/ca/pkg/cert"
"github.com/apache/dubbo-admin/ca/pkg/config"
"github.com/apache/dubbo-admin/ca/pkg/k8s"
+ "github.com/apache/dubbo-admin/ca/pkg/logger"
"github.com/apache/dubbo-admin/ca/pkg/v1alpha1"
- grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
- "go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/reflection"
@@ -72,12 +71,6 @@ func (s *Server) Init() {
KubeClient: s.KubeClient,
}
- logger := zap.NewExample()
- defer logger.Sync()
-
- // Make sure that log statements internal to gRPC library are logged
using the zapLogger as well.
- grpc_zap.ReplaceGrpcLoggerV2(logger)
-
s.PlainServer = grpc.NewServer()
v1alpha1.RegisterDubboCertificateServiceServer(s.PlainServer, impl)
reflection.Register(s.PlainServer)
@@ -118,15 +111,15 @@ func (s *Server) ScheduleRefreshAuthorityCert() {
for true {
time.Sleep(time.Duration(interval) * time.Millisecond)
if s.CertStorage.AuthorityCert.NeedRefresh() {
- log.Printf("Authority cert is invalid, refresh it.")
+ logger.Sugar.Infof("Authority cert is invalid, refresh
it.")
// TODO lock if multi server
// TODO refresh signed cert
s.CertStorage.AuthorityCert =
cert.CreateCA(s.CertStorage.RootCert, s.Options.CaValidity)
s.KubeClient.UpdateAuthorityCert(s.CertStorage.AuthorityCert.CertPem,
cert.EncodePri(s.CertStorage.AuthorityCert.PrivateKey), s.Options.Namespace)
if
s.KubeClient.UpdateAuthorityPublicKey(s.CertStorage.AuthorityCert.CertPem) {
- log.Printf("Write ca to config maps success.")
+ logger.Sugar.Infof("Write ca to config maps
success.")
} else {
- log.Printf("Write ca to config maps failed.")
+ logger.Sugar.Warnf("Write ca to config maps
failed.")
}
}
}
@@ -134,9 +127,9 @@ func (s *Server) ScheduleRefreshAuthorityCert() {
func (s *Server) RefreshAuthorityCert() {
if s.CertStorage.AuthorityCert.IsValid() {
- log.Printf("Load authority cert from kubernetes secrect
success.")
+ logger.Sugar.Infof("Load authority cert from kubernetes secrect
success.")
} else {
- log.Printf("Load authority cert from kubernetes secrect
failed.")
+ logger.Sugar.Warnf("Load authority cert from kubernetes secrect
failed.")
s.CertStorage.AuthorityCert =
cert.CreateCA(s.CertStorage.RootCert, s.Options.CaValidity)
// TODO lock if multi server
@@ -144,11 +137,11 @@ func (s *Server) RefreshAuthorityCert() {
}
// TODO add task to update ca
- log.Printf("Writing ca to config maps.")
+ logger.Sugar.Info("Writing ca to config maps.")
if
s.KubeClient.UpdateAuthorityPublicKey(s.CertStorage.AuthorityCert.CertPem) {
- log.Printf("Write ca to config maps success.")
+ logger.Sugar.Info("Write ca to config maps success.")
} else {
- log.Printf("Write ca to config maps failed.")
+ logger.Sugar.Warnf("Write ca to config maps failed.")
}
s.CertStorage.TrustedCert = append(s.CertStorage.TrustedCert,
s.CertStorage.AuthorityCert)
}
@@ -175,5 +168,5 @@ func (s *Server) Start() {
}
}()
- log.Printf("Server started.")
+ logger.Sugar.Info("Server started.")
}
diff --git a/ca/pkg/v1alpha1/ca_impl.go b/ca/pkg/v1alpha1/ca_impl.go
index f07e29e..ac23c89 100644
--- a/ca/pkg/v1alpha1/ca_impl.go
+++ b/ca/pkg/v1alpha1/ca_impl.go
@@ -20,9 +20,9 @@ import (
"github.com/apache/dubbo-admin/ca/pkg/cert"
"github.com/apache/dubbo-admin/ca/pkg/config"
"github.com/apache/dubbo-admin/ca/pkg/k8s"
+ "github.com/apache/dubbo-admin/ca/pkg/logger"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
- "log"
"strings"
"time"
)
@@ -41,7 +41,7 @@ func (s *DubboCertificateServiceServerImpl)
CreateCertificate(c context.Context,
if s.Options.EnableKubernetes {
md, ok := metadata.FromIncomingContext(c)
if !ok {
- log.Printf("Failed to get metadata from context.
RemoteAddr: %s", p.Addr.String())
+ logger.Sugar.Warnf("Failed to get metadata from
context. RemoteAddr: %s", p.Addr.String())
return &DubboCertificateResponse{
Success: false,
Message: "Failed to get metadata from context.",
@@ -50,7 +50,7 @@ func (s *DubboCertificateServiceServerImpl)
CreateCertificate(c context.Context,
authorization, ok := md["authorization"]
if !ok || len(authorization) != 1 {
- log.Printf("Failed to get Authorization header from
context. RemoteAddr: %s", p.Addr.String())
+ logger.Sugar.Warnf("Failed to get Authorization header
from context. RemoteAddr: %s", p.Addr.String())
return &DubboCertificateResponse{
Success: false,
Message: "Failed to get Authorization header
from context.",
@@ -58,7 +58,7 @@ func (s *DubboCertificateServiceServerImpl)
CreateCertificate(c context.Context,
}
if !strings.HasPrefix(authorization[0], "Bearer ") {
- log.Printf("Failed to get Authorization header from
context. RemoteAddr: %s", p.Addr.String())
+ logger.Sugar.Warnf("Failed to get Authorization header
from context. RemoteAddr: %s", p.Addr.String())
return &DubboCertificateResponse{
Success: false,
Message: "Failed to get Authorization header
from context.",
@@ -69,7 +69,7 @@ func (s *DubboCertificateServiceServerImpl)
CreateCertificate(c context.Context,
// TODO load principal from k8s
if !s.KubeClient.VerifyServiceAccount(token) {
- log.Printf("Failed to verify Authorization header from
kubernetes. RemoteAddr: %s", p.Addr.String())
+ logger.Sugar.Warnf("Failed to verify Authorization
header from kubernetes. RemoteAddr: %s", p.Addr.String())
return &DubboCertificateResponse{
Success: false,
Message: "Failed to verify Authorization header
from kubernetes.",
@@ -79,7 +79,7 @@ func (s *DubboCertificateServiceServerImpl)
CreateCertificate(c context.Context,
// TODO check server token
if csr == nil {
- log.Printf("Failed to decode csr. RemoteAddr: %s",
p.Addr.String())
+ logger.Sugar.Warnf("Failed to decode csr. RemoteAddr: %s",
p.Addr.String())
return &DubboCertificateResponse{
Success: false,
Message: "Failed to read csr",
@@ -87,14 +87,14 @@ func (s *DubboCertificateServiceServerImpl)
CreateCertificate(c context.Context,
}
certPem, err := cert.SignFromCSR(csr, s.CertStorage.AuthorityCert,
s.Options.CertValidity)
if err != nil {
- log.Printf("Failed to sign certificate from csr: %v.
RemoteAddr: %s", err, p.Addr.String())
+ logger.Sugar.Warnf("Failed to sign certificate from csr: %v.
RemoteAddr: %s", err, p.Addr.String())
return &DubboCertificateResponse{
Success: false,
Message: err.Error(),
}, nil
}
- log.Printf("Success to sign certificate from csr. RemoteAddr: %s",
p.Addr.String())
+ logger.Sugar.Infof("Success to sign certificate from csr. RemoteAddr:
%s", p.Addr.String())
return &DubboCertificateResponse{
Success: true,