Skip to content

Commit bf436c5

Browse files
committed
Move to logging contexts
Also restructured config_tx so it doesn't need copies of config data. Fuller debug logging in hidrpc and make all reportHidRPC sends async. Pass up errors from handleHidRPCMessage. listenKeyboardEvents handles closed keyboard file and terminates loop. Excess write failures cause close/open cycle
2 parents 784af2c + f8fbb39 commit bf436c5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+979
-679
lines changed

block_device.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"os"
88
"time"
99

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

1718
func (r remoteImageBackend) ReadAt(p []byte, off int64) (n int, err error) {
1819
virtualMediaStateMutex.RLock()
20+
21+
logger := logging.GetSubsystemLogger("nbd")
1922
logger.Debug().Interface("currentVirtualMediaState", currentVirtualMediaState).Msg("currentVirtualMediaState")
2023
logger.Debug().Int64("read size", int64(len(p))).Int64("off", off).Msg("read size and off")
2124
if currentVirtualMediaState == nil {
@@ -81,7 +84,8 @@ func (d *NBDDevice) Start() error {
8184
}
8285

8386
if d.l == nil {
84-
scopedLogger := nbdLogger.With().
87+
scopedLogger := logging.GetSubsystemLogger("nbd").
88+
With().
8589
Str("socket_path", nbdSocketPath).
8690
Str("device_path", nbdDevicePath).
8791
Logger()

cloud.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313

1414
"github.com/coder/websocket/wsjson"
1515
"github.com/google/uuid"
16+
"github.com/jetkvm/kvm/internal/logging"
1617
"github.com/prometheus/client_golang/prometheus"
1718
"github.com/prometheus/client_golang/prometheus/promauto"
1819

@@ -284,6 +285,7 @@ func disconnectCloud(reason error) {
284285
cloudDisconnectLock.Lock()
285286
defer cloudDisconnectLock.Unlock()
286287

288+
cloudLogger := logging.GetSubsystemLogger("cloud")
287289
if cloudDisconnectChan == nil {
288290
cloudLogger.Trace().Msg("cloud disconnect channel is not set, no need to disconnect")
289291
return
@@ -323,7 +325,7 @@ func runWebsocketClient() error {
323325
header.Set("Authorization", "Bearer "+config.CloudToken)
324326
dialCtx, cancelDial := context.WithTimeout(context.Background(), CloudWebSocketConnectTimeout)
325327

326-
l := websocketLogger.With().
328+
l := logging.GetSubsystemLogger("websocket").With().
327329
Str("source", wsURL.Host).
328330
Str("sourceType", "cloud").
329331
Logger()
@@ -366,6 +368,8 @@ func runWebsocketClient() error {
366368
Logger()
367369
scopedLogger = &lWithConnectionId
368370

371+
cloudLogger := logging.GetSubsystemLogger("cloud")
372+
369373
// if the context is canceled, we don't want to return an error
370374
if err != nil {
371375
if errors.Is(err, context.Canceled) {
@@ -397,7 +401,7 @@ func authenticateSession(ctx context.Context, c *websocket.Conn, req WebRTCSessi
397401
_ = wsjson.Write(context.Background(), c, gin.H{
398402
"error": fmt.Sprintf("failed to initialize OIDC provider: %v", err),
399403
})
400-
cloudLogger.Warn().Err(err).Msg("failed to initialize OIDC provider")
404+
logging.GetSubsystemLogger("cloud").Warn().Err(err).Msg("failed to initialize OIDC provider")
401405
return err
402406
}
403407

@@ -474,11 +478,10 @@ func handleSessionRequest(
474478
}()
475479
}
476480

477-
cloudLogger.Info().Interface("session", session).Msg("new session accepted")
478-
cloudLogger.Trace().Interface("session", session).Msg("new session accepted")
481+
logging.GetSubsystemLogger("cloud").Info().Interface("session", session).Msg("new session accepted")
479482

480483
// Cancel any ongoing keyboard macro when session changes
481-
cancelKeyboardMacro()
484+
_ = cancelKeyboardMacro()
482485

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

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

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

510513
err := runWebsocketClient()
511514
if err != nil {
512-
cloudLogger.Warn().Err(err).Msg("websocket client error")
515+
logging.GetSubsystemLogger("cloud").Warn().Err(err).Msg("websocket client error")
513516
metricCloudConnectionStatus.Set(0)
514517
metricCloudConnectionFailureCount.Inc()
515518
time.Sleep(5 * time.Second)
@@ -561,7 +564,7 @@ func rpcDeregisterDevice() error {
561564
return fmt.Errorf("failed to save configuration after deregistering: %w", err)
562565
}
563566

564-
cloudLogger.Info().Msg("device deregistered, disconnecting from cloud")
567+
logging.GetSubsystemLogger("cloud").Info().Msg("device deregistered, disconnecting from cloud")
565568
disconnectCloud(fmt.Errorf("device deregistered"))
566569

567570
setCloudConnectionState(CloudConnectionStateNotConfigured)

config.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ func (c *Config) GetUpdateAPIURL() string {
128128
func (c *Config) GetDisplayRotation() uint16 {
129129
rotationInt, err := strconv.ParseUint(c.DisplayRotation, 10, 16)
130130
if err != nil {
131-
logger.Warn().Err(err).Msg("invalid display rotation, using default")
131+
logging.GetSubsystemLogger("config").Warn().Err(err).Msg("invalid display rotation, using default")
132132
return 270
133133
}
134134
return uint16(rotationInt)
@@ -138,7 +138,7 @@ func (c *Config) GetDisplayRotation() uint16 {
138138
func (c *Config) SetDisplayRotation(rotation string) error {
139139
_, err := strconv.ParseUint(rotation, 10, 16)
140140
if err != nil {
141-
logger.Warn().Err(err).Msg("invalid display rotation, using default")
141+
logging.GetSubsystemLogger("config").Warn().Err(err).Msg("invalid display rotation, using default")
142142
return err
143143
}
144144
c.DisplayRotation = rotation
@@ -224,6 +224,8 @@ func LoadConfig() {
224224
configLock.Lock()
225225
defer configLock.Unlock()
226226

227+
logger := logging.GetSubsystemLogger("config")
228+
227229
if config != nil {
228230
logger.Debug().Msg("config already loaded, skipping")
229231
return
@@ -272,10 +274,9 @@ func LoadConfig() {
272274
loadedConfig.KeyboardLayout = "en-US"
273275
}
274276

277+
logging.UpdateConfigLogLevel(loadedConfig.DefaultLogLevel)
275278
config = &loadedConfig
276279

277-
logging.UpdateConfigLogLevel(config.DefaultLogLevel)
278-
279280
configSuccess.Set(1.0)
280281
configSuccessTime.SetToCurrentTime()
281282

@@ -294,6 +295,7 @@ func saveConfig(path string) error {
294295
configLock.Lock()
295296
defer configLock.Unlock()
296297

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

299301
// fixup old keyboard layout value

display.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"sync"
1111
"time"
1212

13+
"github.com/jetkvm/kvm/internal/logging"
1314
"github.com/prometheus/common/version"
1415
)
1516

@@ -75,7 +76,7 @@ func updateDisplay() {
7576
nativeInstance.UpdateLabelIfChanged("hdmi_status_label", "Disconnected")
7677
_, _ = nativeInstance.UIObjClearState("hdmi_status_label", "LV_STATE_CHECKED")
7778
}
78-
nativeInstance.UpdateLabelIfChanged("cloud_status_label", fmt.Sprintf("%d active", actionSessions))
79+
nativeInstance.UpdateLabelIfChanged("cloud_status_label", fmt.Sprintf("%d active", getActiveSessions()))
7980

8081
if networkManager != nil && networkManager.IsUp() {
8182
nativeInstance.UISetVar("main_screen", "home_screen")
@@ -185,14 +186,14 @@ func requestDisplayUpdate(shouldWakeDisplay bool, reason string) {
185186
defer displayUpdateLock.Unlock()
186187

187188
if !displayInited {
188-
displayLogger.Info().Msg("display not inited, skipping updates")
189+
logging.GetSubsystemLogger("display").Info().Msg("display not inited, skipping updates")
189190
return
190191
}
191192
go func() {
192193
if shouldWakeDisplay {
193194
wakeDisplay(false, reason)
194195
}
195-
displayLogger.Debug().Msg("display updating")
196+
logging.GetSubsystemLogger("display").Debug().Msg("display updating")
196197
// TODO: only run once regardless how many pending updates
197198
updateDisplay()
198199
}()
@@ -240,7 +241,7 @@ func updateStaticContents() {
240241
// configureDisplayOnNativeRestart is called when the native process restarts
241242
// it ensures the display is configured correctly after the restart
242243
func configureDisplayOnNativeRestart() {
243-
displayLogger.Info().Msg("native restarted, configuring display")
244+
logging.GetSubsystemLogger("display").Info().Msg("native restarted, configuring display")
244245
updateStaticContents()
245246
requestDisplayUpdate(true, "native_restart")
246247
}
@@ -266,7 +267,7 @@ func setDisplayBrightness(brightness int, reason string) error {
266267
return err
267268
}
268269

269-
displayLogger.Info().Int("brightness", brightness).Str("reason", reason).Msg("set brightness")
270+
logging.GetSubsystemLogger("display").Info().Int("brightness", brightness).Str("reason", reason).Msg("set brightness")
270271
return nil
271272
}
272273

@@ -275,7 +276,7 @@ func setDisplayBrightness(brightness int, reason string) error {
275276
func tick_displayDim() {
276277
err := setDisplayBrightness(config.DisplayMaxBrightness/2, "tick_display_dim")
277278
if err != nil {
278-
displayLogger.Warn().Err(err).Msg("failed to dim display")
279+
logging.GetSubsystemLogger("display").Warn().Err(err).Msg("failed to dim display")
279280
}
280281

281282
dimTicker.Stop()
@@ -288,7 +289,7 @@ func tick_displayDim() {
288289
func tick_displayOff() {
289290
err := setDisplayBrightness(0, "tick_display_off")
290291
if err != nil {
291-
displayLogger.Warn().Err(err).Msg("failed to turn off display")
292+
logging.GetSubsystemLogger("display").Warn().Err(err).Msg("failed to turn off display")
292293
}
293294

294295
offTicker.Stop()
@@ -315,7 +316,7 @@ func wakeDisplay(force bool, reason string) {
315316

316317
err := setDisplayBrightness(config.DisplayMaxBrightness, reason)
317318
if err != nil {
318-
displayLogger.Warn().Err(err).Msg("failed to wake display")
319+
logging.GetSubsystemLogger("display").Warn().Err(err).Msg("failed to wake display")
319320
}
320321

321322
if config.DisplayDimAfterSec != 0 && dimTicker != nil {
@@ -348,6 +349,8 @@ func startBacklightTickers() {
348349
offTicker.Stop()
349350
}
350351

352+
displayLogger := logging.GetSubsystemLogger("display")
353+
351354
if config.DisplayDimAfterSec != 0 {
352355
displayLogger.Info().Msg("dim_ticker has started")
353356
dimTicker = time.NewTicker(time.Duration(config.DisplayDimAfterSec) * time.Second)
@@ -373,6 +376,7 @@ func startBacklightTickers() {
373376

374377
func initDisplay() {
375378
go func() {
379+
displayLogger := logging.GetSubsystemLogger("display")
376380
displayLogger.Info().Msg("setting initial display contents")
377381
time.Sleep(500 * time.Millisecond)
378382
updateStaticContents()

failsafe.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
package kvm
22

33
import (
4+
"errors"
45
"fmt"
6+
"io/fs"
57
"os"
68
"strings"
79
"sync"
810

11+
"github.com/jetkvm/kvm/internal/logging"
912
"github.com/jetkvm/kvm/internal/supervisor"
1013
)
1114

@@ -53,10 +56,10 @@ func checkFailsafeReason() {
5356
}
5457

5558
// check if the last crash log file exists
56-
l := failsafeLogger.With().Str("path", lastCrashPath).Logger()
59+
l := logging.GetSubsystemLogger("failsafe").With().Str("path", lastCrashPath).Logger()
5760
fi, err := os.Lstat(lastCrashPath)
5861
if err != nil {
59-
if !os.IsNotExist(err) {
62+
if !errors.Is(err, fs.ErrNotExist) {
6063
l.Warn().Err(err).Msg("failed to stat last crash log")
6164
}
6265
return
@@ -98,7 +101,7 @@ func notifyFailsafeMode(session *Session) {
98101
return
99102
}
100103

101-
jsonRpcLogger.Info().Str("reason", failsafeModeReason).Msg("sending failsafe mode notification")
104+
logging.GetSubsystemLogger("failsafe").Info().Str("reason", failsafeModeReason).Msg("sending failsafe mode notification")
102105

103106
writeJSONRPCEvent("failsafeMode", FailsafeModeNotification{
104107
Active: true,

go.mod

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.24.4
55
require (
66
github.com/Masterminds/semver/v3 v3.4.0
77
github.com/beevik/ntp v1.5.0
8+
github.com/caarlos0/env/v11 v11.3.1
89
github.com/coder/websocket v1.8.14
910
github.com/coreos/go-oidc/v3 v3.16.0
1011
github.com/creack/pty v1.1.24
@@ -36,6 +37,8 @@ require (
3637
golang.org/x/crypto v0.43.0
3738
golang.org/x/net v0.46.0
3839
golang.org/x/sys v0.37.0
40+
google.golang.org/grpc v1.76.0
41+
google.golang.org/protobuf v1.36.10
3942
)
4043

4144
replace github.com/pojntfx/go-nbd v0.3.2 => github.com/chemhack/go-nbd v0.0.0-20241006125820-59e45f5b1e7b
@@ -44,7 +47,6 @@ require (
4447
github.com/beorn7/perks v1.0.1 // indirect
4548
github.com/bytedance/sonic v1.14.0 // indirect
4649
github.com/bytedance/sonic/loader v0.3.0 // indirect
47-
github.com/caarlos0/env/v11 v11.3.1 // indirect
4850
github.com/cespare/xxhash/v2 v2.3.0 // indirect
4951
github.com/cloudwego/base64x v0.1.6 // indirect
5052
github.com/creack/goselect v0.1.2 // indirect
@@ -88,7 +90,6 @@ require (
8890
github.com/prometheus/client_model v0.6.2 // indirect
8991
github.com/robfig/cron/v3 v3.0.1 // indirect
9092
github.com/rogpeppe/go-internal v1.14.1 // indirect
91-
github.com/spf13/pflag v1.0.10 // indirect
9293
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
9394
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect
9495
github.com/ugorji/go/codec v1.3.0 // indirect
@@ -100,8 +101,5 @@ require (
100101
golang.org/x/sync v0.17.0 // indirect
101102
golang.org/x/text v0.30.0 // indirect
102103
google.golang.org/genproto/googleapis/rpc v0.0.0-20250804133106-a7a43d27e69b // indirect
103-
google.golang.org/grpc v1.76.0 // indirect
104-
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 // indirect
105-
google.golang.org/protobuf v1.36.10 // indirect
106104
gopkg.in/yaml.v3 v3.0.1 // indirect
107105
)

0 commit comments

Comments
 (0)