2023-03-29 08:45:13 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
|
|
|
/*
|
|
|
|
Package journald provides functions to read and collect journald logs.
|
|
|
|
*/
|
|
|
|
package journald
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-04-03 07:58:34 -04:00
|
|
|
"io"
|
2023-03-29 08:45:13 -04:00
|
|
|
"os/exec"
|
|
|
|
)
|
|
|
|
|
|
|
|
type command interface {
|
2023-04-03 07:58:34 -04:00
|
|
|
Start() error
|
|
|
|
Wait() error
|
2023-03-29 08:45:13 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Collector collects logs from journald.
|
|
|
|
type Collector struct {
|
2023-04-03 07:58:34 -04:00
|
|
|
cmd command
|
|
|
|
stdoutPipe io.ReadCloser
|
|
|
|
stderrPipe io.ReadCloser
|
2023-03-29 08:45:13 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewCollector creates a new Collector for journald logs.
|
|
|
|
func NewCollector(ctx context.Context) (*Collector, error) {
|
|
|
|
cmd := exec.CommandContext(ctx, "journalctl")
|
2023-04-03 07:58:34 -04:00
|
|
|
stdoutPipe, err := cmd.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
stderrPipe, err := cmd.StderrPipe()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
collector := Collector{cmd, stdoutPipe, stderrPipe}
|
|
|
|
return &collector, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start returns a pipe to read the systemd logs. This should be read with a bufio Reader.
|
|
|
|
func (c *Collector) Start() (io.ReadCloser, error) {
|
|
|
|
if err := c.cmd.Start(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return c.stdoutPipe, nil
|
2023-03-29 08:45:13 -04:00
|
|
|
}
|
|
|
|
|
2023-04-03 07:58:34 -04:00
|
|
|
// Error returns output to stderr as bytes as well
|
|
|
|
// as the exit code in form of an error.
|
|
|
|
func (c *Collector) Error() ([]byte, error) {
|
|
|
|
stderr, err := io.ReadAll(c.stderrPipe)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2023-03-29 08:45:13 -04:00
|
|
|
}
|
2023-04-03 07:58:34 -04:00
|
|
|
exitCode := c.cmd.Wait()
|
|
|
|
return stderr, exitCode
|
2023-03-29 08:45:13 -04:00
|
|
|
}
|