Skip to content

Commit

Permalink
1. Add remote log hook. (#1492)
Browse files Browse the repository at this point in the history
2. Support choose log color mode.
3. Support silence usage, because usage info is noisy in some cases;
4. Silence error, because sealer has already print error itself.
5. Use logrus to print the final error.

Signed-off-by: huaiyou <[email protected]>
  • Loading branch information
VinceCui authored Jun 21, 2022
1 parent fb7f0f2 commit d9eb737
Show file tree
Hide file tree
Showing 6 changed files with 147 additions and 17 deletions.
45 changes: 33 additions & 12 deletions cmd/sealer/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,32 @@ import (
"github.com/spf13/viper"

"github.com/sealerio/sealer/common"
remotelogger "github.com/sealerio/sealer/pkg/remote-logger"
"github.com/sealerio/sealer/version"
)

type rootOpts struct {
cfgFile string
debugModeOn bool
hideLogTime bool
hideLogPath bool
cfgFile string
debugModeOn bool
hideLogTime bool
hideLogPath bool
colorMode string
remoteLoggerURL string
remoteLoggerTaskName string
}

var rootOpt rootOpts

const (
colorModeNever = "never"
colorModeAlways = "always"
)

var supportedColorModes = []string{
colorModeNever,
colorModeAlways,
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "sealer",
Expand All @@ -52,7 +66,7 @@ and run it within any cluster with Clusterfile in one command.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "sealer-%s: %v\n", version.GetSingleVersion(), err)
logrus.Errorf("sealer-%s: %v", version.GetSingleVersion(), err)
os.Exit(1)
}
}
Expand All @@ -61,8 +75,12 @@ func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&rootOpt.cfgFile, "config", "", "config file of sealer tool (default is $HOME/.sealer.json)")
rootCmd.PersistentFlags().BoolVarP(&rootOpt.debugModeOn, "debug", "d", false, "turn on debug mode")
rootCmd.PersistentFlags().BoolVarP(&rootCmd.SilenceUsage, "quiet", "q", false, "silence the usage when fail")
rootCmd.PersistentFlags().BoolVar(&rootOpt.hideLogTime, "hide-time", false, "hide the log time")
rootCmd.PersistentFlags().BoolVar(&rootOpt.hideLogPath, "hide-path", false, "hide the log path")
rootCmd.PersistentFlags().StringVar(&rootOpt.colorMode, "color", colorModeAlways, fmt.Sprintf("set the log color mode, the possible values can be %v", supportedColorModes))
rootCmd.PersistentFlags().StringVar(&rootOpt.remoteLoggerURL, "remote-logger-url", "", "remote logger url, if not empty, will send log to this url")
rootCmd.PersistentFlags().StringVar(&rootOpt.remoteLoggerTaskName, "task-name", "", "task name which will embedded in the remote logger header, only valid when --remote-logger-url is set")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
rootCmd.DisableAutoGenTag = true
}
Expand All @@ -83,13 +101,16 @@ func initConfig() {
if rootOpt.debugModeOn {
logrus.SetLevel(logrus.DebugLevel)
}
/*
logrus.InitLogger(logger.Config{DebugMode: rootOpt.debugModeOn})
logrus.SetLogPath(!rootOpt.hideLogPath)

if !rootOpt.hideLogTime {
logrus.SetTimeFormat(logger.LogTimeDefaultFormat)
logrus.SetFormatter(&logrus.TextFormatter{
DisableColors: rootOpt.colorMode == colorModeNever,
})

if rootOpt.remoteLoggerURL != "" {
rl, err := remotelogger.NewRemoteLogHook(rootOpt.remoteLoggerURL, rootOpt.remoteLoggerTaskName)
if err != nil {
panic(err)
}
logrus.Cfg(rootOpt.debugModeOn)
*/
logrus.AddHook(rl)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ require (
github.com/docker/go-connections v0.4.0
github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect
github.com/go-git/go-git/v5 v5.4.2
github.com/google/uuid v1.2.0
github.com/imdario/mergo v0.3.12
github.com/mitchellh/go-homedir v1.1.0
github.com/moby/buildkit v0.9.3
Expand All @@ -34,7 +35,6 @@ require (
github.com/vbatts/tar-split v0.11.1
github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
github.com/wonderivan/logger v1.0.0
github.com/yusufpapurcu/wmi v1.2.2 // indirect
go.etcd.io/etcd/client/v3 v3.5.0
go.uber.org/zap v1.17.0
Expand Down
111 changes: 111 additions & 0 deletions pkg/remote-logger/remote-logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// alibaba-inc.com Inc.
// Copyright (c) 2004-2022 All Rights Reserved.
//
// @Author : huaiyou.cyz
// @Time : 2022/6/7 11:39 PM
// @File : remote-logger
//

package remotelogger

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"sync"

"github.com/google/uuid"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// RemoteLogHook to send logs via remote URL.
type RemoteLogHook struct {
sync.RWMutex

TaskName string
URL string
}

func NewRemoteLogHook(remoteURL, taskName string) (*RemoteLogHook, error) {
reqURL, err := url.Parse(remoteURL)
if err != nil {
return nil, err
}

return &RemoteLogHook{
TaskName: taskName,
URL: reqURL.String(),
}, err
}

// #nosec
func httpSend(url string, method string, body []byte) error {
var resp *http.Response

var err error
switch method {
case http.MethodGet:
resp, err = http.Get(url)
case http.MethodPost:
resp, err = http.Post(url, "application/json", bytes.NewBuffer(body))
}

if err != nil {
return fmt.Errorf("bad %s request to server : %w", method, err)
}
defer func() {
_ = resp.Body.Close()
}()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status code from server: [%d] %s ", resp.StatusCode, resp.Status)
}

return nil
}

func (hook *RemoteLogHook) Fire(entry *logrus.Entry) error {
line, err := entry.String()
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
return err
}

t := "Info"
if entry.Level <= logrus.ErrorLevel {
t = "Error"
}

event := &corev1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: uuid.New().String(),
},
InvolvedObject: corev1.ObjectReference{
Name: hook.TaskName,
},
Message: line,
Type: t,
}

bytesData, _ := json.Marshal(event)

hook.Lock()
defer hook.Unlock()

return httpSend(hook.URL, http.MethodPost, bytesData)
}

func (hook *RemoteLogHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
}
}
1 change: 0 additions & 1 deletion pkg/runtime/masters.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,5 @@ func (k *KubeadmRuntime) GetJoinTokenHashAndKey() error {

k.decodeMaster0Output(out)

logrus.Infof("join token: %s hash: %s certifacate key: %s", k.getJoinToken(), k.getTokenCaCertHash(), k.getCertificateKey())
return nil
}
3 changes: 1 addition & 2 deletions vendor/github.com/sealyun/lvscare/care/care.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion vendor/modules.txt
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ github.com/google/gofuzz
# github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
github.com/google/shlex
# github.com/google/uuid v1.2.0
## explicit
github.com/google/uuid
# github.com/googleapis/gnostic v0.5.1
github.com/googleapis/gnostic/compiler
Expand Down Expand Up @@ -510,7 +511,6 @@ github.com/vishvananda/netlink/nl
## explicit
github.com/vishvananda/netns
# github.com/wonderivan/logger v1.0.0
## explicit
github.com/wonderivan/logger
# github.com/xanzy/ssh-agent v0.3.0
github.com/xanzy/ssh-agent
Expand Down

0 comments on commit d9eb737

Please sign in to comment.