-
Notifications
You must be signed in to change notification settings - Fork 65
feat(kernel): forward logs through shared logger #450
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
Open
vuanhphung
wants to merge
12
commits into
main
Choose a base branch
from
vu-phung/kernel-log-file-parity
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
496670e
feat(kernel): forward logs through shared logger
vuanhphung 83b2655
chore(kernel): update logging callback revision
vuanhphung 0b23fb1
chore(kernel): update logging callback revision
vuanhphung 1d9b9e5
chore(kernel): update logging callback revision
vuanhphung e056e93
chore(kernel): update logging callback revision
vuanhphung 90c5857
fix(kernel): harden kernel log forwarding and shared logger output
vuanhphung e1a40ee
fix(kernel): add flush, emission timestamps, and drop visibility to l…
vuanhphung 226c338
Merge branch 'main' into vu-phung/kernel-log-file-parity
vuanhphung a9bf939
fix(kernel): contain drop-warning panics and remove SetLogOutput self…
vuanhphung 759f185
fix(logger): forward kernel logs through a non-io.Writer sink
vuanhphung e09d2cd
docs(logger): warn that SetLogOutput writers must not be re-entrant
vuanhphung 29bfd33
refactor(kernel): untag pure-Go log pipeline and route drop warning o…
vuanhphung File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| eff8950428f4e6cc9975c663ec919f334962f7d0 | ||
| 2dd4739f1c20e3a560bcaf52abed8aab9bd957cf |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| //go:build cgo && databricks_kernel | ||
|
|
||
| package kernel | ||
|
|
||
| /* | ||
| #include <stdlib.h> | ||
| #include "databricks_kernel.h" | ||
|
|
||
| // The Go export below is generated with mutable char* parameters, but | ||
| // KernelLogCallback lends read-only const char*. kernelLogAdapter has the exact | ||
| // KernelLogCallback signature and forwards to the Go export, so the function | ||
| // pointer handed to the kernel needs no incompatible function-pointer cast. | ||
| void kernelLogTrampoline(char* level, char* target, char* message, void* user_data); | ||
| static void kernelLogAdapter(const char* level, const char* target, | ||
| const char* message, void* user_data) { | ||
| kernelLogTrampoline((char*)level, (char*)target, (char*)message, user_data); | ||
| } | ||
| static KernelLogCallback kernel_log_cb(void) { return kernelLogAdapter; } | ||
| */ | ||
| import "C" | ||
|
|
||
| import ( | ||
| "sync" | ||
| "time" | ||
| "unsafe" | ||
|
|
||
| "github.com/databricks/databricks-sql-go/logger" | ||
| ) | ||
|
|
||
| // This file is the thin cgo layer of the kernel log bridge: the exported callback | ||
| // trampoline and the one-time kernel_init_logging_callback install. The pure-Go | ||
| // pipeline it drives (queue, drain, flush, drop accounting) lives untagged in | ||
| // logforward_async.go so its tests run in the default CGO_ENABLED=0 build. | ||
|
|
||
| // logCallbackOnce guards the process-wide, first-call-wins install. | ||
| var logCallbackOnce sync.Once | ||
|
|
||
| //export kernelLogTrampoline | ||
| func kernelLogTrampoline(level, target, message *C.char, _ unsafe.Pointer) { | ||
| // A panic must never cross the C ABI. user_data is deliberately unused: the | ||
| // kernel is given NULL, and the destination is reached through logQueue, so no | ||
| // Go pointer is ever fabricated into a C void* (which the GC could fault on). | ||
| defer func() { _ = recover() }() | ||
| // time.Now() here is the emission time — the callback fires synchronously on the | ||
| // kernel thread as the event is logged. C.GoString copies each borrowed string | ||
| // into owned Go memory before the record can outlive the callback; the rest is | ||
| // pure Go (see enqueueKernelLog). | ||
| enqueueKernelLog(time.Now(), C.GoString(level), C.GoString(target), C.GoString(message)) | ||
| } | ||
|
|
||
| func installKernelLogCallback(level string, useNULL bool) { | ||
| logCallbackOnce.Do(func() { | ||
| // OFF intentionally installs no subscriber and starts no drain. | ||
| if !useNULL && level == "OFF" { | ||
| return | ||
| } | ||
|
|
||
| ch := make(chan kernelLogRecord, kernelLogChannelCapacity) | ||
| // Publish before installing so a callback that fires during | ||
| // kernel_init_logging_callback already has a channel to enqueue onto; | ||
| // records buffer until the drain starts just below. | ||
| logQueue.Store(&ch) | ||
|
|
||
| var clevel cStr | ||
| if !useNULL { | ||
| clevel = newCStr(level) | ||
| defer clevel.free() | ||
| } | ||
| // NULL user_data: the drain goroutine owns the sink, so nothing Go-managed | ||
| // crosses into C as a pointer. | ||
| if err := call(func() C.KernelStatusCode { | ||
| return C.kernel_init_logging_callback(clevel.c, C.kernel_log_cb(), nil) | ||
| }); err != nil { | ||
| // Install failed, so the callback layer was not installed. Unpublish the | ||
| // channel; no drain was started and nothing references it, so it is simply | ||
| // collected — no close (and thus no send-on-closed race to reason about). | ||
| logQueue.Store(nil) | ||
| logger.Logger.Warn().Msgf( | ||
|
vuanhphung marked this conversation as resolved.
|
||
| "databricks: kernel_init_logging_callback: %v (kernel logs not forwarded; proceeding)", err) | ||
| return | ||
| } | ||
| // Installed: start the single drain goroutine. Any records enqueued during | ||
| // the call above are buffered and delivered once it runs. | ||
| go drainKernelLogs(ch, newLogSink()) | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| //go:build cgo && databricks_kernel | ||
|
|
||
| package kernel | ||
|
|
||
| import ( | ||
| "os" | ||
| "os/exec" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/databricks/databricks-sql-go/logger" | ||
| ) | ||
|
|
||
| const ( | ||
| logFileHelperEnv = "DBSQL_KERNEL_LOG_FILE_HELPER" | ||
| logFilePathEnv = "DBSQL_KERNEL_LOG_FILE_PATH" | ||
| goLogFileProbe = "go local-file logging probe" | ||
| rustLogFileProbe = "retry max_wait_ms is below min_wait_ms" | ||
| ) | ||
|
|
||
| // TestKernelCallbackWritesConfiguredFileEndToEnd proves the user-visible parity | ||
| // contract in a fresh process: the same file passed to logger.SetLogOutput gets a | ||
| // native Go record and a real Rust tracing record delivered through the C ABI. | ||
| // A subprocess is required because the kernel tracing subscriber is process-wide | ||
| // and first-call-wins. | ||
| func TestKernelCallbackWritesConfiguredFileEndToEnd(t *testing.T) { | ||
| if os.Getenv(logFileHelperEnv) == "1" { | ||
| path := os.Getenv(logFilePathEnv) | ||
| file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) //nolint:gosec // Parent supplies its temp path. | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if err := logger.SetLogLevel("warn"); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| logger.SetLogOutput(file) | ||
|
|
||
| initKernelLogging() | ||
| logger.Logger.Warn().Msg(goLogFileProbe) | ||
| // The C ABI corrects this inverted range and emits a Rust klog::warn!, | ||
| // giving the test a deterministic kernel-owned record without a server. | ||
| err = trySetRetry(Config{Retry: &RetryConfig{ | ||
| MinWait: 5 * time.Second, | ||
| MaxWait: time.Second, | ||
| MaxRetries: 1, | ||
| }}) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| // The kernel record crosses an async drain goroutine, so flush it into the | ||
| // file before retargeting the output or closing it — otherwise the drain | ||
| // could write to stderr (post-retarget) or after Close. | ||
| if !flushKernelLogs(5 * time.Second) { | ||
| t.Fatal("kernel log flush timed out") | ||
| } | ||
|
|
||
| logger.SetLogOutput(os.Stderr) | ||
| if err := file.Sync(); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if err := file.Close(); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| return | ||
| } | ||
|
|
||
| logPath := filepath.Join(t.TempDir(), "driver-and-kernel.log") | ||
| cmd := exec.Command(os.Args[0], "-test.run=^TestKernelCallbackWritesConfiguredFileEndToEnd$") //nolint:gosec // Re-executes this test binary only. | ||
| cmd.Env = append(os.Environ(), logFileHelperEnv+"=1", logFilePathEnv+"="+logPath) | ||
| if output, err := cmd.CombinedOutput(); err != nil { | ||
| t.Fatalf("logging helper failed: %v\n%s", err, output) | ||
| } | ||
| contents, err := os.ReadFile(logPath) //nolint:gosec // Test-owned temporary path. | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| got := string(contents) | ||
| if !strings.Contains(got, goLogFileProbe) { | ||
| t.Errorf("local log file is missing Go record: %q", got) | ||
| } | ||
| if !strings.Contains(got, rustLogFileProbe) { | ||
| t.Errorf("local log file is missing Rust kernel record: %q", got) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| package kernel | ||
|
|
||
| import ( | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/databricks/databricks-sql-go/logger" | ||
| "github.com/rs/zerolog" | ||
| ) | ||
|
|
||
| // logSink is the Go destination for kernel tracing records. It forwards through | ||
| // logger.ForwardingSink (not a logger derived from logger.Logger), so it (a) still | ||
| // follows SetLogOutput, (b) is ungated at TraceLevel because the kernel already | ||
| // applied its configured level, (c) carries no auto-timestamp hook — forward stamps | ||
| // each record with the emission time captured on the kernel thread, not the drain | ||
| // time — and (d) cannot be round-tripped into SetLogOutput (ForwardingSink is not | ||
| // an io.Writer), which would deadlock. | ||
| type logSink struct { | ||
| sink *logger.ForwardingSink | ||
| observe func(level, target, message string) | ||
| } | ||
|
|
||
| func newLogSink() *logSink { | ||
| return &logSink{sink: logger.NewForwardingSink()} | ||
| } | ||
|
|
||
| // forward writes one kernel record. emittedAt is the time the kernel emitted the | ||
| // event (captured in the cgo callback), stamped as the record's timestamp so a | ||
| // backed-up drain does not skew kernel log times toward drain time. | ||
| func (s *logSink) forward(emittedAt time.Time, level, target, message string) { | ||
| if s == nil { | ||
| return | ||
| } | ||
| if s.observe != nil { | ||
| s.observe(level, target, message) | ||
| } | ||
| s.event(level).Time(zerolog.TimestampFieldName, emittedAt).Str("target", target).Msg(message) | ||
| } | ||
|
|
||
| // warnDropped emits a one-shot advisory that forwarded records were dropped. It | ||
| // goes through the sink's own immutable logger — not logger.Logger, whose embedded | ||
| // value SetLogLevel reassigns — so the long-lived drain goroutine never races | ||
| // SetLogLevel. Like forwarded records it is ungated, which is what we want: log loss | ||
| // should surface regardless of the driver level. | ||
| func (s *logSink) warnDropped(dropped uint64) { | ||
| s.sink.Event(zerolog.WarnLevel). | ||
| Uint64("dropped", dropped). | ||
| Time(zerolog.TimestampFieldName, time.Now()). | ||
| Msg("[kernel] kernel log records dropped; the log sink is not keeping up " + | ||
| "(raise capacity or lower kernel verbosity)") | ||
| } | ||
|
|
||
| // event picks the zerolog event for a kernel level string. An unknown level maps | ||
| // to Debug and preserves the raw kernel level as a field. | ||
| func (s *logSink) event(level string) *zerolog.Event { | ||
| switch strings.ToLower(level) { | ||
| case "error": | ||
| return s.sink.Event(zerolog.ErrorLevel) | ||
| case "warn": | ||
| return s.sink.Event(zerolog.WarnLevel) | ||
| case "info": | ||
| return s.sink.Event(zerolog.InfoLevel) | ||
| case "debug": | ||
| return s.sink.Event(zerolog.DebugLevel) | ||
| case "trace": | ||
| return s.sink.Event(zerolog.TraceLevel) | ||
| default: | ||
| return s.sink.Event(zerolog.DebugLevel).Str("kernelLevel", level) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.