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

Added an endpoint to be able to get the logs #270

Merged
merged 1 commit into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
148 changes: 148 additions & 0 deletions src/controllers/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package controllers

import (
"bufio"
"encoding/json"
"net/http"
"os"
"path/filepath"
"time"

"github.com/Parallels/prl-devops-service/basecontext"
"github.com/Parallels/prl-devops-service/config"
Expand All @@ -14,10 +18,12 @@ import (
"github.com/Parallels/prl-devops-service/serviceprovider/system"

"github.com/cjlapao/common-go/helper/http_helper"
"github.com/gorilla/websocket"
)

func registerConfigHandlers(ctx basecontext.ApiContext, version string) {
provider := serviceprovider.Get()
cfg := config.Get()

ctx.LogInfof("Registering version %s config handlers", version)
if provider.System.GetOperatingSystem() == "macos" {
Expand Down Expand Up @@ -66,6 +72,25 @@ func registerConfigHandlers(ctx basecontext.ApiContext, version string) {
WithPath("/health/system").
WithHandler(GetSystemHealth()).
Register()

// If logging to file is enabled, register the logs endpoints
if cfg.GetBoolKey(constants.LOG_TO_FILE_ENV_VAR) {
restapi.NewController().
WithMethod(restapi.GET).
WithVersion(version).
WithPath("/logs/stream").
WithRequiredRole(constants.SUPER_USER_ROLE).
WithHandler(StreamSystemLogs()).
Register()

restapi.NewController().
WithMethod(restapi.GET).
WithVersion(version).
WithPath("/logs").
WithRequiredRole(constants.SUPER_USER_ROLE).
WithHandler(GetSystemLogs()).
Register()
}
}

// @Summary Gets Parallels Desktop active license
Expand Down Expand Up @@ -383,3 +408,126 @@ func GetSystemHealth() restapi.ControllerHandler {
_ = json.NewEncoder(w).Encode(result)
}
}

// @Summary Gets the system logs from the disk
// @Description This endpoint returns the system logs from the disk
// @Tags Config
// @Produce plain
// @Success 200
// @Router /logs [get]
func GetSystemLogs() restapi.ControllerHandler {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
ctx := GetBaseContext(r)
defer Recover(ctx, r, w)

cfg := config.Get()
logPath := cfg.GetKey(constants.LOG_FILE_PATH_ENV_VAR)
logFile := filepath.Join(logPath, "prldevops.log")

content, err := os.ReadFile(logFile)
if err != nil {
ReturnApiError(ctx, w, models.ApiErrorResponse{
Message: "Failed to read log file: " + err.Error(),
Code: http.StatusInternalServerError,
})
return
}

w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write(content)
}
}

// @Summary Streams the system logs via WebSocket
// @Description This endpoint streams the system logs in real-time via WebSocket
// @Tags Config
// @Produce json
// @Success 101 "Switching Protocols to websocket"
// @Failure 400 {object} models.ApiErrorResponse
// @Security ApiKeyAuth
// @Security BearerAuth
// @Router /logs/stream [get]
func StreamSystemLogs() restapi.ControllerHandler {
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true // You might want to make this more restrictive
},
}

return func(w http.ResponseWriter, r *http.Request) {
ctx := GetBaseContext(r)
defer Recover(ctx, r, w)

// Upgrade HTTP connection to WebSocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
ctx.LogErrorf("Failed to upgrade connection to WebSocket: %v", err)
return
}
defer ws.Close()

// Create a done channel to signal when to stop
done := make(chan struct{})

// Start a goroutine to handle client messages and disconnection
go func() {
defer close(done)
for {
_, _, err := ws.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
ctx.LogErrorf("WebSocket read error: %v", err)
}
return
}
}
}()

// Get log file path
cfg := config.Get()
logPath := cfg.GetKey(constants.LOG_FILE_PATH_ENV_VAR)
logFile := filepath.Join(logPath, "prldevops.log")

// Open the file
file, err := os.Open(logFile)
if err != nil {
ws.WriteMessage(websocket.TextMessage, []byte("Error opening log file: "+err.Error()))
return
}
defer file.Close()

// Seek to the end of the file
_, err = file.Seek(0, 2)
if err != nil {
ws.WriteMessage(websocket.TextMessage, []byte("Error seeking log file: "+err.Error()))
return
}

reader := bufio.NewReader(file)
for {
select {
case <-done:
return
default:
line, err := reader.ReadString('\n')
if err != nil {
if err.Error() == "EOF" {
time.Sleep(100 * time.Millisecond)
continue
}
return
}

err = ws.WriteMessage(websocket.TextMessage, []byte(line))
if err != nil {
ctx.LogErrorf("Error writing to WebSocket: %v", err)
return
}
}
}
}
}
1 change: 1 addition & 0 deletions src/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ require (
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/gookit/color v1.5.4 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/jfrog/archiver/v3 v3.6.0 // indirect
github.com/jfrog/build-info-go v1.9.21 // indirect
Expand Down
2 changes: 2 additions & 0 deletions src/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyE
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jfrog/archiver/v3 v3.6.0 h1:OVZ50vudkIQmKMgA8mmFF9S0gA47lcag22N13iV3F1w=
Expand Down
Loading