Skip to content

Commit 04e77f7

Browse files
committed
journal: add StderrIsJournalStream function
This function can be used for automatic protocol upgrade described in [1]. Both unit tests and runnable example are included. Only the latter requires systemd, as unit tests are self-sufficient, and only test that JOURNAL_STREAM environment variable is checked properly. [1] https://systemd.io/JOURNAL_NATIVE_PROTOCOL/#automatic-protocol-upgrading
1 parent 87ca09f commit 04e77f7

File tree

6 files changed

+232
-0
lines changed

6 files changed

+232
-0
lines changed

examples/journal/main.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2022 CoreOS, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License
14+
15+
package main
16+
17+
import (
18+
"fmt"
19+
"os"
20+
21+
"github.com/coreos/go-systemd/v22/journal"
22+
)
23+
24+
func main() {
25+
ok, err := journal.StderrIsJournalStream()
26+
if err != nil {
27+
panic(err)
28+
}
29+
30+
if ok {
31+
// use journal native protocol
32+
journal.Send("this is a message logged through the native protocol", journal.PriInfo, nil)
33+
} else {
34+
// use stderr
35+
fmt.Fprintln(os.Stderr, "this is a message logged through stderr")
36+
}
37+
}

examples/journal/run.sh

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/bin/bash
2+
3+
set -e
4+
5+
go build
6+
7+
echo "Running directly"
8+
./journal
9+
10+
echo "Running through systemd"
11+
unit_name="run-$(systemd-id128 new)"
12+
systemd-run -u "$unit_name" --user --wait --quiet ./journal
13+
journalctl --user -u "$unit_name"

journal/journal_unix.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,40 @@ func Enabled() bool {
6969
return true
7070
}
7171

72+
// StderrIsJournalStream returns whether the process stderr is connected
73+
// to the Journal's stream transport.
74+
//
75+
// This can be used for automatic protocol upgrading described in [Journal Native Protocol].
76+
//
77+
// Returns true if JOURNAL_STREAM environment variable is present,
78+
// and stderr's device and inode numbers match it.
79+
//
80+
// Error is returned if unexpected error occurs: e.g. if JOURNAL_STREAM environment variable
81+
// is present, but malformed, fstat syscall fails, etc.
82+
//
83+
// [Journal Native Protocol]: https://systemd.io/JOURNAL_NATIVE_PROTOCOL/#automatic-protocol-upgrading
84+
func StderrIsJournalStream() (bool, error) {
85+
journalStream := os.Getenv("JOURNAL_STREAM")
86+
if journalStream == "" {
87+
return false, nil
88+
}
89+
90+
var expectedStat syscall.Stat_t
91+
_, err := fmt.Sscanf(journalStream, "%d:%d", &expectedStat.Dev, &expectedStat.Ino)
92+
if err != nil {
93+
return false, fmt.Errorf("failed to parse JOURNAL_STREAM=%q: %v", journalStream, err)
94+
}
95+
96+
var stat syscall.Stat_t
97+
err = syscall.Fstat(syscall.Stderr, &stat)
98+
if err != nil {
99+
return false, err
100+
}
101+
102+
match := stat.Dev == expectedStat.Dev && stat.Ino == expectedStat.Ino
103+
return match, nil
104+
}
105+
72106
// Send a message to the local systemd journal. vars is a map of journald
73107
// fields to values. Fields must be composed of uppercase letters, numbers,
74108
// and underscores, but must not start with an underscore. Within these

journal/journal_unix_test.go

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
// Copyright 2022 CoreOS, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
//go:build !windows
16+
// +build !windows
17+
18+
package journal_test
19+
20+
import (
21+
"fmt"
22+
"os"
23+
"syscall"
24+
"testing"
25+
26+
"github.com/coreos/go-systemd/v22/journal"
27+
)
28+
29+
func TestStderrIsJournalStream(t *testing.T) {
30+
if _, ok := os.LookupEnv("JOURNAL_STREAM"); ok {
31+
t.Fatal("unset JOURNAL_STREAM before running this test")
32+
}
33+
34+
t.Run("Missing", func(t *testing.T) {
35+
ok, err := journal.StderrIsJournalStream()
36+
if err != nil {
37+
t.Fatal(err)
38+
}
39+
if ok {
40+
t.Error("stderr shouldn't be connected to journal stream")
41+
}
42+
})
43+
t.Run("Present", func(t *testing.T) {
44+
f, stat := getUnixStreamSocket(t)
45+
defer f.Close()
46+
os.Setenv("JOURNAL_STREAM", fmt.Sprintf("%d:%d", stat.Dev, stat.Ino))
47+
defer os.Unsetenv("JOURNAL_STREAM")
48+
replaceStderr(int(f.Fd()), func() {
49+
ok, err := journal.StderrIsJournalStream()
50+
if err != nil {
51+
t.Fatal(err)
52+
}
53+
if !ok {
54+
t.Error("stderr should've been connected to journal stream")
55+
}
56+
})
57+
})
58+
t.Run("NotMatching", func(t *testing.T) {
59+
f, stat := getUnixStreamSocket(t)
60+
defer f.Close()
61+
os.Setenv("JOURNAL_STREAM", fmt.Sprintf("%d:%d", stat.Dev+1, stat.Ino))
62+
defer os.Unsetenv("JOURNAL_STREAM")
63+
replaceStderr(int(f.Fd()), func() {
64+
ok, err := journal.StderrIsJournalStream()
65+
if err != nil {
66+
t.Fatal(err)
67+
}
68+
if ok {
69+
t.Error("stderr shouldn't be connected to journal stream")
70+
}
71+
})
72+
})
73+
t.Run("Malformed", func(t *testing.T) {
74+
f, stat := getUnixStreamSocket(t)
75+
defer f.Close()
76+
os.Setenv("JOURNAL_STREAM", fmt.Sprintf("%d-%d", stat.Dev, stat.Ino))
77+
defer os.Unsetenv("JOURNAL_STREAM")
78+
replaceStderr(int(f.Fd()), func() {
79+
_, err := journal.StderrIsJournalStream()
80+
if err == nil {
81+
t.Fatal("JOURNAL_STREAM is malformed, but no error returned")
82+
}
83+
})
84+
})
85+
}
86+
87+
func ExampleStderrIsJournalStream() {
88+
// NOTE: this is just an example. Production code
89+
// will likely use this to setup a logging library
90+
// to write messages to either journal or stderr.
91+
ok, err := journal.StderrIsJournalStream()
92+
if err != nil {
93+
panic(err)
94+
}
95+
96+
if ok {
97+
// use journal native protocol
98+
journal.Send("this is a message logged through the native protocol", journal.PriInfo, nil)
99+
} else {
100+
// use stderr
101+
fmt.Fprintln(os.Stderr, "this is a message logged through stderr")
102+
}
103+
}
104+
105+
func replaceStderr(fd int, cb func()) {
106+
savedStderr, err := syscall.Dup(syscall.Stderr)
107+
if err != nil {
108+
panic(err)
109+
}
110+
defer syscall.Close(savedStderr)
111+
err = syscall.Dup2(fd, syscall.Stderr)
112+
if err != nil {
113+
panic(err)
114+
}
115+
defer func() {
116+
err := syscall.Dup2(savedStderr, syscall.Stderr)
117+
if err != nil {
118+
panic(err)
119+
}
120+
}()
121+
cb()
122+
}
123+
124+
// getUnixStreamSocket returns a unix stream socket obtained with
125+
// socketpair(2), and its fstat result. Only one end of the socket pair
126+
// is returned, and the other end is closed immediately: we don't need
127+
// it for our purposes.
128+
func getUnixStreamSocket(t *testing.T) (*os.File, *syscall.Stat_t) {
129+
fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
130+
if err != nil {
131+
t.Fatal(os.NewSyscallError("socketpair", err))
132+
}
133+
// we don't need the remote end for our tests
134+
syscall.Close(fds[1])
135+
136+
file := os.NewFile(uintptr(fds[0]), "unix-stream")
137+
stat, err := file.Stat()
138+
if err != nil {
139+
t.Fatal(err)
140+
}
141+
return file, stat.Sys().(*syscall.Stat_t)
142+
}

journal/journal_windows.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,7 @@ func Enabled() bool {
3333
func Send(message string, priority Priority, vars map[string]string) error {
3434
return errors.New("could not initialize socket to journald")
3535
}
36+
37+
func StderrIsJournalStream() (bool, error) {
38+
return false, nil
39+
}

scripts/ci-runner.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ function build_tests {
2323
echo " - examples/${ex}"
2424
go build -o ./test_bins/${ex}.example ./examples/activation/${ex}.go
2525
done
26+
# just to make sure it's buildable
27+
go build -o ./test_bins/journal ./examples/journal/
2628
}
2729

2830
function run_tests {

0 commit comments

Comments
 (0)