Skip to content
Open
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
26 changes: 14 additions & 12 deletions block_device.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"time"

"github.com/jetkvm/kvm/internal/logging"
"github.com/pojntfx/go-nbd/pkg/server"
"github.com/rs/zerolog"
)
Expand All @@ -16,6 +17,8 @@ type remoteImageBackend struct {

func (r remoteImageBackend) ReadAt(p []byte, off int64) (n int, err error) {
virtualMediaStateMutex.RLock()

logger := logging.GetSubsystemLogger("nbd")
logger.Debug().Interface("currentVirtualMediaState", currentVirtualMediaState).Msg("currentVirtualMediaState")
logger.Debug().Int64("read size", int64(len(p))).Int64("off", off).Msg("read size and off")
if currentVirtualMediaState == nil {
Expand Down Expand Up @@ -60,14 +63,21 @@ type NBDDevice struct {
serverConn net.Conn
clientConn net.Conn
dev *os.File

l *zerolog.Logger
}

func NewNBDDevice() *NBDDevice {
return &NBDDevice{}
}

func (d *NBDDevice) getLogger() *zerolog.Logger {
logger := logging.GetSubsystemLogger("nbd").
With().
Str("socket_path", nbdSocketPath).
Str("device_path", nbdDevicePath).
Logger()
return &logger
}

func (d *NBDDevice) Start() error {
var err error

Expand All @@ -80,18 +90,10 @@ func (d *NBDDevice) Start() error {
return err
}

if d.l == nil {
scopedLogger := nbdLogger.With().
Str("socket_path", nbdSocketPath).
Str("device_path", nbdDevicePath).
Logger()
d.l = &scopedLogger
}

// Remove the socket file if it already exists
if _, err := os.Stat(nbdSocketPath); err == nil {
if err := os.Remove(nbdSocketPath); err != nil {
d.l.Error().Err(err).Msg("failed to remove existing socket file")
d.getLogger().Error().Err(err).Msg("failed to remove existing socket file")
os.Exit(1)
}
}
Expand Down Expand Up @@ -133,5 +135,5 @@ func (d *NBDDevice) runServerConn() {
SupportsMultiConn: false,
})

d.l.Info().Err(err).Msg("nbd server exited")
d.getLogger().Info().Err(err).Msg("nbd server exited")
}
4 changes: 2 additions & 2 deletions block_device_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ func (d *NBDDevice) runClientConn() {
ExportName: "jetkvm",
BlockSize: uint32(4 * 1024),
})
d.l.Info().Err(err).Msg("nbd client exited")
d.getLogger().Info().Err(err).Msg("nbd client exited")
}

func (d *NBDDevice) Close() {
if d.dev != nil {
err := client.Disconnect(d.dev)
if err != nil {
d.l.Warn().Err(err).Msg("error disconnecting nbd client")
d.getLogger().Warn().Err(err).Msg("error disconnecting nbd client")
}
_ = d.dev.Close()
}
Expand Down
4 changes: 2 additions & 2 deletions block_device_notlinux.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import (
)

func (d *NBDDevice) runClientConn() {
d.l.Error().Msg("platform not supported")
d.getLogger().Error().Msg("platform not supported")
os.Exit(1)
}

func (d *NBDDevice) Close() {
d.l.Error().Msg("platform not supported")
d.getLogger().Error().Msg("platform not supported")
os.Exit(1)
}
40 changes: 16 additions & 24 deletions cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ import (

"github.com/coder/websocket/wsjson"
"github.com/google/uuid"
"github.com/jetkvm/kvm/internal/logging"
"github.com/jetkvm/kvm/internal/utils"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"

"github.com/coreos/go-oidc/v3/oidc"

"github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
)

type CloudRegisterRequest struct {
Expand Down Expand Up @@ -284,6 +285,7 @@ func disconnectCloud(reason error) {
cloudDisconnectLock.Lock()
defer cloudDisconnectLock.Unlock()

cloudLogger := logging.GetSubsystemLogger("cloud")
if cloudDisconnectChan == nil {
cloudLogger.Trace().Msg("cloud disconnect channel is not set, no need to disconnect")
return
Expand Down Expand Up @@ -323,18 +325,13 @@ func runWebsocketClient() error {
header.Set("Authorization", "Bearer "+config.CloudToken)
dialCtx, cancelDial := context.WithTimeout(context.Background(), CloudWebSocketConnectTimeout)

l := websocketLogger.With().
Str("source", wsURL.Host).
Str("sourceType", "cloud").
Logger()

scopedLogger := &l
logger := logging.GetSubsystemLogger("cloud").With().Str("subcomponent", "websocket").Str("source", wsURL.Host).Str("sourceType", "cloud").Logger()

defer cancelDial()
c, resp, err := websocket.Dial(dialCtx, wsURL.String(), &websocket.DialOptions{
HTTPHeader: header,
OnPingReceived: func(ctx context.Context, payload []byte) bool {
scopedLogger.Debug().Bytes("payload", payload).Int("length", len(payload)).Msg("ping frame received")
logger.Debug().Object("data", utils.ByteSlice(payload)).Int("length", len(payload)).Msg("ping frame received")

metricConnectionTotalPingReceivedCount.WithLabelValues("cloud", wsURL.Host).Inc()
metricConnectionLastPingReceivedTimestamp.WithLabelValues("cloud", wsURL.Host).SetToCurrentTime()
Expand All @@ -356,15 +353,13 @@ func runWebsocketClient() error {

if connectionId == "" {
connectionId = uuid.New().String()
scopedLogger.Warn().
logger.Warn().
Str("connectionId", connectionId).
Msg("no connection id received from the server, generating a new one")
}

lWithConnectionId := scopedLogger.With().
Str("connectionID", connectionId).
Logger()
scopedLogger = &lWithConnectionId
logger = logger.With().Str("connectionID", connectionId).Logger()
cloudLogger := logging.GetSubsystemLogger("cloud")

// if the context is canceled, we don't want to return an error
if err != nil {
Expand All @@ -386,7 +381,7 @@ func runWebsocketClient() error {
wsResetMetrics(true, "cloud", wsURL.Host)

// we don't have a source for the cloud connection
return handleWebRTCSignalWsMessages(c, true, wsURL.Host, connectionId, scopedLogger)
return handleWebRTCSignalWsMessages(c, true, wsURL.Host, connectionId)
}

func authenticateSession(ctx context.Context, c *websocket.Conn, req WebRTCSessionRequest) error {
Expand All @@ -397,7 +392,7 @@ func authenticateSession(ctx context.Context, c *websocket.Conn, req WebRTCSessi
_ = wsjson.Write(context.Background(), c, gin.H{
"error": fmt.Sprintf("failed to initialize OIDC provider: %v", err),
})
cloudLogger.Warn().Err(err).Msg("failed to initialize OIDC provider")
logging.GetSubsystemLogger("cloud").Warn().Err(err).Msg("failed to initialize OIDC provider")
return err
}

Expand Down Expand Up @@ -426,7 +421,6 @@ func handleSessionRequest(
req WebRTCSessionRequest,
isCloudConnection bool,
source string,
scopedLogger *zerolog.Logger,
) error {
var sourceType string
if isCloudConnection {
Expand All @@ -453,7 +447,6 @@ func handleSessionRequest(
IsCloud: isCloudConnection,
LocalIP: req.IP,
ICEServers: req.ICEServers,
Logger: scopedLogger,
})
if err != nil {
_ = wsjson.Write(context.Background(), c, gin.H{"error": err})
Expand All @@ -474,11 +467,10 @@ func handleSessionRequest(
}()
}

cloudLogger.Info().Interface("session", session).Msg("new session accepted")
cloudLogger.Trace().Interface("session", session).Msg("new session accepted")
logging.GetSubsystemLogger("cloud").Info().Interface("session", session).Msg("new session accepted")

// Cancel any ongoing keyboard macro when session changes
cancelKeyboardMacro()
_ = cancelKeyboardMacro()

currentSession = session
_ = wsjson.Write(context.Background(), c, gin.H{"type": "answer", "data": sd})
Expand All @@ -495,21 +487,21 @@ func RunWebsocketClient() {

// If the network is not up, well, we can't connect to the cloud.
if !networkManager.IsOnline() {
cloudLogger.Warn().Msg("waiting for network to be online, will retry in 3 seconds")
logging.GetSubsystemLogger("cloud").Warn().Msg("waiting for network to be online, will retry in 3 seconds")
time.Sleep(3 * time.Second)
continue
}

// If the system time is not synchronized, the API request will fail anyway because the TLS handshake will fail.
if isTimeSyncNeeded() && !timeSync.IsSyncSuccess() {
cloudLogger.Warn().Msg("system time is not synced, will retry in 3 seconds")
logging.GetSubsystemLogger("cloud").Warn().Msg("system time is not synced, will retry in 3 seconds")
time.Sleep(3 * time.Second)
continue
}

err := runWebsocketClient()
if err != nil {
cloudLogger.Warn().Err(err).Msg("websocket client error")
logging.GetSubsystemLogger("cloud").Warn().Err(err).Msg("websocket client error")
metricCloudConnectionStatus.Set(0)
metricCloudConnectionFailureCount.Inc()
time.Sleep(5 * time.Second)
Expand Down Expand Up @@ -561,7 +553,7 @@ func rpcDeregisterDevice() error {
return fmt.Errorf("failed to save configuration after deregistering: %w", err)
}

cloudLogger.Info().Msg("device deregistered, disconnecting from cloud")
logging.GetSubsystemLogger("cloud").Info().Msg("device deregistered, disconnecting from cloud")
disconnectCloud(fmt.Errorf("device deregistered"))

setCloudConnectionState(CloudConnectionStateNotConfigured)
Expand Down
3 changes: 2 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import (
"syscall"
"time"

"github.com/erikdubbelboer/gspt"
"github.com/jetkvm/kvm"
"github.com/jetkvm/kvm/internal/native"
"github.com/jetkvm/kvm/internal/supervisor"

"github.com/erikdubbelboer/gspt"
)

var (
Expand Down
10 changes: 6 additions & 4 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"github.com/jetkvm/kvm/internal/confparser"
"github.com/jetkvm/kvm/internal/logging"
"github.com/jetkvm/kvm/internal/network/types"
"github.com/jetkvm/kvm/internal/usbgadget"

Check failure on line 14 in config.go

View workflow job for this annotation

GitHub Actions / lint

could not import github.com/jetkvm/kvm/internal/usbgadget (-: # github.com/jetkvm/kvm/internal/usbgadget
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
Expand Down Expand Up @@ -128,7 +128,7 @@
func (c *Config) GetDisplayRotation() uint16 {
rotationInt, err := strconv.ParseUint(c.DisplayRotation, 10, 16)
if err != nil {
logger.Warn().Err(err).Msg("invalid display rotation, using default")
logging.GetSubsystemLogger("config").Warn().Err(err).Msg("invalid display rotation, using default")
return 270
}
return uint16(rotationInt)
Expand All @@ -138,7 +138,7 @@
func (c *Config) SetDisplayRotation(rotation string) error {
_, err := strconv.ParseUint(rotation, 10, 16)
if err != nil {
logger.Warn().Err(err).Msg("invalid display rotation, using default")
logging.GetSubsystemLogger("config").Warn().Err(err).Msg("invalid display rotation, using default")
return err
}
c.DisplayRotation = rotation
Expand Down Expand Up @@ -224,6 +224,8 @@
configLock.Lock()
defer configLock.Unlock()

logger := logging.GetSubsystemLogger("config")

if config != nil {
logger.Debug().Msg("config already loaded, skipping")
return
Expand Down Expand Up @@ -272,10 +274,9 @@
loadedConfig.KeyboardLayout = "en-US"
}

logging.UpdateConfigLogLevel(loadedConfig.DefaultLogLevel)
config = &loadedConfig

logging.GetRootLogger().UpdateLogLevel(config.DefaultLogLevel)

configSuccess.Set(1.0)
configSuccessTime.SetToCurrentTime()

Expand All @@ -294,6 +295,7 @@
configLock.Lock()
defer configLock.Unlock()

logger := logging.GetSubsystemLogger("config")
logger.Trace().Str("path", path).Msg("Saving config")

// fixup old keyboard layout value
Expand Down
Loading