Files
uncloud/internal/journal/logs.go
T
Miek GiebenandGitHub 6fb68c22c5 fix: correctly wait for journalctl processes to not leave zombies when streaming machine logs (#325)
* fix: call cmd.Wait()

Even though the context is cancelled we still need to call cmd.Wait()
after a cmd.Start() to clean up the child (reap) process. Not doing so
results in a zombie journalctl.

I have manually tested this, as I'm still not sure how to e2e test for
this in a simple manner.

Before:

```
root@uncloud2:~# ps aux|grep jou
root         313  0.0  1.2  42272 23352 ?        S<s  Apr20   0:10 /usr/lib/systemd/systemd-journald
root       15751  0.0  0.0      0     0 pts/0    Z+   07:02   0:00 [journalctl] <defunct>
root       15754  0.0  0.0      0     0 pts/0    Z+   07:02   0:00 [journalctl] <defunct>
```

After:

```
root         313  0.0  1.2  42272 23592 ?        S<s  Apr20   0:10 /usr/lib/systemd/systemd-journald
```

* follow() doesnt need wait

We can keep the wait function more contraint, as follow does not need it

Signed-off-by: Miek Gieben <miek@miek.nl>

---------

Signed-off-by: Miek Gieben <miek@miek.nl>
2026-04-22 19:00:15 +10:00

57 lines
1.2 KiB
Go

package journal
import (
"bytes"
"context"
"fmt"
"slices"
"time"
"github.com/psviderski/uncloud/pkg/api"
)
// Logs streams logs from a service and returns entries via a channel.
func Logs(ctx context.Context, unit string, opts api.ServiceLogsOptions) (<-chan api.LogEntry, error) {
if !ValidUnit(unit) {
return nil, fmt.Errorf("journal logs: invalid unit: %s", unit)
}
reader, wait, err := logs(ctx, unit, opts)
if err != nil {
return nil, err
}
outCh := make(chan api.LogEntry)
go func() {
defer close(outCh)
follow(ctx, reader, outCh)
wait()
}()
return outCh, nil
}
func entry(data []byte) api.LogEntry {
// 2025-10-12T11:03:27+02:00 systemd[1]:
timestamp := time.Time{}
message := data
if len(data) > 30 && data[4] == '-' && data[7] == '-' && data[10] == 'T' {
timestampPart, messagePart, found := bytes.Cut(data, []byte(" "))
var err error
if found {
timestamp, err = time.Parse(time.RFC3339Nano, string(timestampPart))
if err != nil {
timestamp = time.Time{}
}
message = messagePart
}
}
return api.LogEntry{
Timestamp: timestamp,
Message: append(slices.Clone(message), '\n'), // scanner controls the buffer so Clone and re-add newline
Stream: api.LogStreamStdout,
}
}