Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add log sub command for kmesh-daemon #459

Merged
merged 4 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions daemon/manager/log/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
* Copyright 2024 The Kmesh Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package logs

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"

"github.com/spf13/cobra"

"kmesh.net/kmesh/pkg/status"
)

func NewCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "log",
Short: "Get or set kmesh-daemon's logger level",
Example: `Set default logger's level as "debug":
kmesh-daemon log --set default:debug

Get default logger's level:
kmesh-daemon log default`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
RunGetOrSetLoggerLevel(cmd, args)
},
}
cmd.Flags().String("set", "", "Set the logger level (e.g., default:debug)")
return cmd
}

func GetLoggerLevel(args []string) {
if len(args) != 1 {
fmt.Println("Missing logger name argument")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: if we donot know what logger it is in kmesh, should we support kmesh log shows all the logger

os.Exit(1)
}
loggerName := args[0]
url := status.GetLoggerLevelAddr() + "?name=" + loggerName

resp, err := http.Get(url)
if err != nil {
fmt.Printf("Error making GET request: %v\n", err)
return
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return
}

if resp.StatusCode != http.StatusOK {
fmt.Printf("Error: received status code %d\n", resp.StatusCode)
fmt.Printf("Response body: %s\n", body)
return
}

var loggerInfo status.LoggerInfo
err = json.Unmarshal(body, &loggerInfo)
if err != nil {
fmt.Printf("Error unmarshaling response body: %v\n", err)
return
}

fmt.Printf("Logger Name: %s\n", loggerInfo.Name)
fmt.Printf("Logger Level: %s\n", loggerInfo.Level)
}

func SetLoggerLevel(setFlag string) {
if !strings.Contains(setFlag, ":") {
fmt.Println("Invalid set flag, which should be loggerName:loggerLevel (e.g. default:debug)")
os.Exit(1)
}
splits := strings.Split(setFlag, ":")
loggerName := splits[0]
loggerLevel := splits[1]

loggerInfo := status.LoggerInfo{
Name: loggerName,
Level: loggerLevel,
}
data, err := json.Marshal(loggerInfo)
if err != nil {
fmt.Printf("Error marshaling logger info: %v\n", err)
return
}

url := status.GetLoggerLevelAddr()
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(data))
if err != nil {
fmt.Printf("Error creating request: %v\n", err)
return
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error making request: %v\n", err)
return
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
fmt.Printf("Error: received status code %d\n", resp.StatusCode)
return
}

body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return
}
fmt.Println(string(body))
}

func RunGetOrSetLoggerLevel(cmd *cobra.Command, args []string) {
setFlag, _ := cmd.Flags().GetString("set")
if setFlag == "" {
GetLoggerLevel(args)
} else {
SetLoggerLevel(setFlag)
}
}
46 changes: 46 additions & 0 deletions daemon/manager/logs/logs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2024 The Kmesh Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package logs

import (
"fmt"

"github.com/spf13/cobra"

"kmesh.net/kmesh/pkg/logger"
)

func NewCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "logs",
Short: "Print kmesh-daemon's logs",
Example: "kmesh-daemon logs",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
_ = RunPrintLogs()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove, Does it worth doing this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it adds a shortcut for 'cat LOG_FILE_PATH', where LOG_FILE_PATH is the logs file path, like '/var/run/kmesh/daemon.log'. For people not informed of the log path, they can type logs command to print logs.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should remove the print to files in future.

},
}
return cmd
}

func RunPrintLogs() error {
err := logger.PrintLogs()
if err != nil {
fmt.Printf("Error printing logs: %v", err)
}
return nil
}
4 changes: 4 additions & 0 deletions daemon/manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import (
"github.com/spf13/pflag"

"kmesh.net/kmesh/daemon/manager/dump"
logcmd "kmesh.net/kmesh/daemon/manager/log"
"kmesh.net/kmesh/daemon/manager/logs"
"kmesh.net/kmesh/daemon/manager/version"
"kmesh.net/kmesh/daemon/options"
"kmesh.net/kmesh/pkg/bpf"
Expand Down Expand Up @@ -65,6 +67,8 @@ func NewCommand() *cobra.Command {
// add sub commands
cmd.AddCommand(version.NewCmd())
cmd.AddCommand(dump.NewCmd())
cmd.AddCommand(logs.NewCmd())
cmd.AddCommand(logcmd.NewCmd())

return cmd
}
Expand Down
16 changes: 16 additions & 0 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,22 @@ var (
}
)

func PrintLogs() error {
logsPath := defaultLogFile
file, err := os.Open(logsPath)
if err != nil {
return err
}
defer file.Close()

// Redirct file contents to STDOUT
_, err = io.Copy(os.Stdout, file)
if err != nil {
return err
}
return nil
}

func SetLoggerLevel(loggerName string, level logrus.Level) error {
logger, exists := loggerMap[loggerName]
if !exists || logger == nil {
Expand Down
14 changes: 9 additions & 5 deletions pkg/status/status_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ func GetConfigDumpAddr(mode string) string {
return "http://" + adminAddr + configDumpPrefix + "/" + mode
}

func GetLoggerLevelAddr() string {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
func GetLoggerLevelAddr() string {
func GetLoggerURL() string {

return "http://" + adminAddr + patternLoggers
}

func NewServer(c *controller.XdsClient, configs *options.BootstrapConfigs, bpfWorkloadObj *bpf.BpfKmeshWorkload) *Server {
s := &Server{
config: configs,
Expand Down Expand Up @@ -170,7 +174,7 @@ func (s *Server) getLoggerLevel(w http.ResponseWriter, r *http.Request) {
loggerLevel, err := logger.GetLoggerLevel(loggerName)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "\t%s\n", err.Error())
fmt.Fprintf(w, "\t%v\n", err)
return
}
loggerInfo := LoggerInfo{
Expand All @@ -196,25 +200,25 @@ func (s *Server) setLoggerLevel(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "\t%s: %s\n", "Error reading request body", err.Error())
fmt.Fprintf(w, "\t%s: %v\n", "Error reading request body", err)
return
}

if err = json.Unmarshal(body, &loggerInfo); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "\t%s: %s\n", "Invalid request body format", err.Error())
fmt.Fprintf(w, "\t%s: %v\n", "Invalid request body format", err)
return
}

if loggerLevel, err = logrus.ParseLevel(loggerInfo.Level); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "\t%s: %s\n", "Invalid request body format", err.Error())
fmt.Fprintf(w, "\t%s: %v\n", "Invalid request body format", err)
return
}

if err = logger.SetLoggerLevel(loggerInfo.Name, loggerLevel); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "\t%s\n", err.Error())
fmt.Fprintf(w, "\t%v\n", err)
return
}

Expand Down
6 changes: 3 additions & 3 deletions pkg/status/status_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ func TestServer_getLoggerLevel(t *testing.T) {
var loggerInfo LoggerInfo
err := json.Unmarshal(w.Body.Bytes(), &loggerInfo)
if err != nil {
t.Errorf("Unexpected error: %s", err.Error())
t.Errorf("Unexpected error: %v", err)
}

expectedLoggerLevel, err := logger.GetLoggerLevel(loggerName)
if err != nil {
t.Errorf("Unexpected error: %s", err.Error())
t.Errorf("Unexpected error: %v", err)
}

if expectedLoggerLevel.String() != loggerInfo.Level {
Expand Down Expand Up @@ -110,7 +110,7 @@ func TestServer_setLoggerLevel(t *testing.T) {

actualLoggerLevel, err := logger.GetLoggerLevel(loggerName)
if err != nil {
t.Errorf("Unexpected error: %s", err.Error())
t.Errorf("Unexpected error: %v", err)
}

if actualLoggerLevel.String() != loggerInfo.Level {
Expand Down
Loading