Skip to content

Commit a9df3e5

Browse files
committed
fix: add fields such as CONTAINER_NAME to journald log entries sent to by containers
In the current implementation, containers running by `nerdctl` dose not export entries containing fields such as `CONTAINER_NAME`, `IMAGE_NAME` , and etc to the journald log like containers running by `docker cli`. At this time, the journald log entry describes below when sending to the journald log using nerdctl. ``` > nerdctl run -d --name nginx-nerdctl --log-driver=journald nginx bb7df47d27fd73426cec286ed88c5abf1443e74df637e2440d2dbca7229a84dc > nerdctl ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES bb7df47d27fd docker.io/library/nginx:latest "/docker-entrypoint.…" 3 seconds ago Up nginx-nerdctl > sudo journalctl SYSLOG_IDENTIFIER=bb7df47d27fd -a -n 1 -o json-pretty { "__CURSOR" : "???", "__REALTIME_TIMESTAMP" : "1730899940827182", "__MONOTONIC_TIMESTAMP" : "10815937979908", "_BOOT_ID" : "???", "_UID" : "0", "_GID" : "0", "_CAP_EFFECTIVE" : "1ffffffffff", "_MACHINE_ID" : "???", "_HOSTNAME" : "???.us-west-2.amazon.com", "_TRANSPORT" : "journal", "_SYSTEMD_SLICE" : "system.slice", "PRIORITY" : "3", "_SYSTEMD_CGROUP" : "/system.slice/containerd.service", "_SYSTEMD_UNIT" : "containerd.service", "_COMM" : "nerdctl", "_EXE" : "/usr/local/bin/nerdctl", "_CMDLINE" : "/usr/local/bin/nerdctl _NERDCTL_INTERNAL_LOGGING /var/lib/nerdctl/1935db59", "SYSLOG_IDENTIFIER" : "bb7df47d27fd", "_PID" : "8118", "MESSAGE" : "2024/11/06 13:32:20 [notice] 1#1: start worker process 44", "_SOURCE_REALTIME_TIMESTAMP" : "1730899940825905" } ``` On the other hand, the output fields are listed below when we use the journald logging driver with docker cli. - https://docs.docker.com/engine/logging/drivers/journald/ As you can see, some entries are not output by nerdctl and are incompatible with the docker cli. This feature request is reported in the following: - #3486 Therefore, in this pull request, we will add the fields to be output in the journald log. After applying this fix, the journald log will output the following fields. ``` { "__CURSOR": "???", "__REALTIME_TIMESTAMP": "1731385591671422", "__MONOTONIC_TIMESTAMP": "11301588824148", "_BOOT_ID": "???", "_MACHINE_ID": "???", "_HOSTNAME": "???.us-west-2.amazon.com", "PRIORITY": "3", "_TRANSPORT": "journal", "_UID": "0", "_GID": "0", "_COMM": "nerdctl", "_EXE": "/usr/local/bin/nerdctl", "_CMDLINE": "/usr/local/bin/nerdctl _NERDCTL_INTERNAL_LOGGING /var/lib/nerdctl/1935db59", "_CAP_EFFECTIVE": "1ffffffffff", "_SYSTEMD_CGROUP": "/system.slice/containerd.service", "_SYSTEMD_UNIT": "containerd.service", "_SYSTEMD_SLICE": "system.slice", "CONTAINER_NAME": "nginx-nerdctl", "IMAGE_NAME": "nginx", "CONTAINER_ID_FULL": "fe22eccbd704ba799785999079ac465ed067d5914e9e3f1020e769921d5a83c5", "SYSLOG_IDENTIFIER": "fe22eccbd704", "CONTAINER_TAG": "fe22eccbd704", "CONTAINER_ID": "fe22eccbd704", "_PID": "31643", "MESSAGE": "2024/11/12 04:26:31 [notice] 1#1: start worker process 44", "_SOURCE_REALTIME_TIMESTAMP": "1731385591669765" } ``` Signed-off-by: Hayato Kiwata <[email protected]>
1 parent f128aac commit a9df3e5

File tree

8 files changed

+111
-36
lines changed

8 files changed

+111
-36
lines changed

cmd/nerdctl/container/container_run_test.go

+37-11
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import (
3535
"gotest.tools/v3/poll"
3636

3737
"github.com/containerd/nerdctl/v2/cmd/nerdctl/helpers"
38+
"github.com/containerd/nerdctl/v2/pkg/logging"
3839
"github.com/containerd/nerdctl/v2/pkg/testutil"
3940
"github.com/containerd/nerdctl/v2/pkg/testutil/nerdtest"
4041
)
@@ -329,19 +330,44 @@ func TestRunWithJournaldLogDriver(t *testing.T) {
329330
time.Sleep(3 * time.Second)
330331
journalctl, err := exec.LookPath("journalctl")
331332
assert.NilError(t, err)
333+
332334
inspectedContainer := base.InspectContainer(containerName)
333-
found := 0
334-
check := func(log poll.LogT) poll.Result {
335-
res := icmd.RunCmd(icmd.Command(journalctl, "--no-pager", "--since", "2 minutes ago", fmt.Sprintf("SYSLOG_IDENTIFIER=%s", inspectedContainer.ID[:12])))
336-
assert.Equal(t, 0, res.ExitCode, res)
337-
if strings.Contains(res.Stdout(), "bar") && strings.Contains(res.Stdout(), "foo") {
338-
found = 1
339-
return poll.Success()
340-
}
341-
return poll.Continue("reading from journald is not yet finished")
335+
336+
type testCase struct {
337+
name string
338+
filter string
339+
}
340+
testCases := []testCase{
341+
{
342+
name: "filter using SYSLOG_IDENTIFIER field",
343+
filter: fmt.Sprintf("SYSLOG_IDENTIFIER=%s", inspectedContainer.ID[:12]),
344+
},
345+
{
346+
name: "filter using CONTAINER_NAME field",
347+
filter: fmt.Sprintf("CONTAINER_NAME=%s", containerName),
348+
},
349+
{
350+
name: "filter using IMAGE_NAME field",
351+
filter: fmt.Sprintf("IMAGE_NAME=%s", logging.GetJournaldImageNameField(testutil.CommonImage)),
352+
},
353+
}
354+
for _, tc := range testCases {
355+
tc := tc
356+
t.Run(tc.name, func(t *testing.T) {
357+
found := 0
358+
check := func(log poll.LogT) poll.Result {
359+
res := icmd.RunCmd(icmd.Command(journalctl, "--no-pager", "--since", "2 minutes ago", tc.filter))
360+
assert.Equal(t, 0, res.ExitCode, res)
361+
if strings.Contains(res.Stdout(), "bar") && strings.Contains(res.Stdout(), "foo") {
362+
found = 1
363+
return poll.Success()
364+
}
365+
return poll.Continue("reading from journald is not yet finished")
366+
}
367+
poll.WaitOn(t, check, poll.WithDelay(100*time.Microsecond), poll.WithTimeout(20*time.Second))
368+
assert.Equal(t, 1, found)
369+
})
342370
}
343-
poll.WaitOn(t, check, poll.WithDelay(100*time.Microsecond), poll.WithTimeout(20*time.Second))
344-
assert.Equal(t, 1, found)
345371
}
346372

347373
func TestRunWithJournaldLogDriverAndLogOpt(t *testing.T) {

pkg/cmd/container/create.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ func Create(ctx context.Context, client *containerd.Client, args []string, netMa
218218
// 1, nerdctl run --name demo -it imagename
219219
// 2, ctrl + c to stop demo container
220220
// 3, nerdctl start/restart demo
221-
logConfig, err := generateLogConfig(dataStore, id, options.LogDriver, options.LogOpt, options.GOptions.Namespace)
221+
logConfig, err := generateLogConfig(dataStore, id, options.LogDriver, options.LogOpt, options.GOptions.Namespace, options.GOptions.Address)
222222
if err != nil {
223223
return nil, generateRemoveStateDirFunc(ctx, id, internalLabels), err
224224
}
@@ -819,12 +819,13 @@ func writeCIDFile(path, id string) error {
819819
}
820820

821821
// generateLogConfig creates a LogConfig for the current container store
822-
func generateLogConfig(dataStore string, id string, logDriver string, logOpt []string, ns string) (logConfig logging.LogConfig, err error) {
822+
func generateLogConfig(dataStore string, id string, logDriver string, logOpt []string, ns, address string) (logConfig logging.LogConfig, err error) {
823823
var u *url.URL
824824
if u, err = url.Parse(logDriver); err == nil && u.Scheme != "" {
825825
logConfig.LogURI = logDriver
826826
} else {
827827
logConfig.Driver = logDriver
828+
logConfig.Address = address
828829
logConfig.Opts, err = parseKVStringsMapFromLogOpt(logOpt, logDriver)
829830
if err != nil {
830831
return logConfig, err
@@ -834,7 +835,7 @@ func generateLogConfig(dataStore string, id string, logDriver string, logOpt []s
834835
logConfigB []byte
835836
lu *url.URL
836837
)
837-
logDriverInst, err = logging.GetDriver(logDriver, logConfig.Opts)
838+
logDriverInst, err = logging.GetDriver(logDriver, logConfig.Opts, logConfig.Address)
838839
if err != nil {
839840
return logConfig, err
840841
}

pkg/logging/fluentd_logger.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package logging
1818

1919
import (
20+
"context"
2021
"fmt"
2122
"math"
2223
"net/url"
@@ -99,7 +100,7 @@ func (f *FluentdLogger) Init(dataStore, ns, id string) error {
99100
return nil
100101
}
101102

102-
func (f *FluentdLogger) PreProcess(_ string, config *logging.Config) error {
103+
func (f *FluentdLogger) PreProcess(_ context.Context, _ string, config *logging.Config) error {
103104
if runtime.GOOS == "windows" {
104105
// TODO: support fluentd on windows
105106
return fmt.Errorf("logging to fluentd is not supported on windows")

pkg/logging/journald_logger.go

+46-3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package logging
1818

1919
import (
2020
"bytes"
21+
"context"
2122
"errors"
2223
"fmt"
2324
"io"
@@ -32,9 +33,13 @@ import (
3233
"github.com/docker/cli/templates"
3334
timetypes "github.com/docker/docker/api/types/time"
3435

36+
containerd "github.com/containerd/containerd/v2/client"
3537
"github.com/containerd/containerd/v2/core/runtime/v2/logging"
3638
"github.com/containerd/log"
3739

40+
"github.com/containerd/nerdctl/v2/pkg/clientutil"
41+
"github.com/containerd/nerdctl/v2/pkg/containerutil"
42+
"github.com/containerd/nerdctl/v2/pkg/imgutil"
3843
"github.com/containerd/nerdctl/v2/pkg/strutil"
3944
)
4045

@@ -52,8 +57,9 @@ func JournalLogOptsValidate(logOptMap map[string]string) error {
5257
}
5358

5459
type JournaldLogger struct {
55-
Opts map[string]string
56-
vars map[string]string
60+
Opts map[string]string
61+
vars map[string]string
62+
Address string
5763
}
5864

5965
type identifier struct {
@@ -66,7 +72,7 @@ func (journaldLogger *JournaldLogger) Init(dataStore, ns, id string) error {
6672
return nil
6773
}
6874

69-
func (journaldLogger *JournaldLogger) PreProcess(dataStore string, config *logging.Config) error {
75+
func (journaldLogger *JournaldLogger) PreProcess(ctx context.Context, dataStore string, config *logging.Config) error {
7076
if !journal.Enabled() {
7177
return errors.New("the local systemd journal is not available for logging")
7278
}
@@ -95,9 +101,37 @@ func (journaldLogger *JournaldLogger) PreProcess(dataStore string, config *loggi
95101
syslogIdentifier = b.String()
96102
}
97103
}
104+
105+
client, ctx, cancel, err := clientutil.NewClient(ctx, config.Namespace, journaldLogger.Address)
106+
if err != nil {
107+
return err
108+
}
109+
defer func() {
110+
cancel()
111+
client.Close()
112+
}()
113+
containerID := config.ID
114+
container, err := client.LoadContainer(ctx, containerID)
115+
if err != nil {
116+
return err
117+
}
118+
containerLabels, err := container.Labels(ctx)
119+
if err != nil {
120+
return err
121+
}
122+
info, err := container.Info(ctx, containerd.WithoutRefreshedMetadata)
123+
if err != nil {
124+
return err
125+
}
126+
98127
// construct log metadata for the container
99128
vars := map[string]string{
100129
"SYSLOG_IDENTIFIER": syslogIdentifier,
130+
"CONTAINER_TAG": syslogIdentifier,
131+
"CONTAINER_ID": shortID,
132+
"CONTAINER_ID_FULL": containerID,
133+
"CONTAINER_NAME": containerutil.GetContainerName(containerLabels),
134+
"IMAGE_NAME": GetJournaldImageNameField(info.Image),
101135
}
102136
journaldLogger.vars = vars
103137
return nil
@@ -200,3 +234,12 @@ func prepareJournalCtlDate(t string) (string, error) {
200234
s := tm.Format("2006-01-02 15:04:05")
201235
return s, nil
202236
}
237+
238+
func GetJournaldImageNameField(image string) string {
239+
imageName := image
240+
if repo, tag := imgutil.ParseRepoTag(imageName); tag == "latest" {
241+
imageName = repo
242+
}
243+
244+
return imageName
245+
}

pkg/logging/json_logger.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ func (jsonLogger *JSONLogger) Init(dataStore, ns, id string) error {
7878
return nil
7979
}
8080

81-
func (jsonLogger *JSONLogger) PreProcess(dataStore string, config *logging.Config) error {
81+
func (jsonLogger *JSONLogger) PreProcess(ctx context.Context, dataStore string, config *logging.Config) error {
8282
var jsonFilePath string
8383
if logPath, ok := jsonLogger.Opts[LogPath]; ok {
8484
jsonFilePath = logPath

pkg/logging/logging.go

+16-15
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,12 @@ const (
4949

5050
type Driver interface {
5151
Init(dataStore, ns, id string) error
52-
PreProcess(dataStore string, config *logging.Config) error
52+
PreProcess(ctx context.Context, dataStore string, config *logging.Config) error
5353
Process(stdout <-chan string, stderr <-chan string) error
5454
PostProcess() error
5555
}
5656

57-
type DriverFactory func(map[string]string) (Driver, error)
57+
type DriverFactory func(map[string]string, string) (Driver, error)
5858
type LogOptsValidateFunc func(logOptMap map[string]string) error
5959

6060
var drivers = make(map[string]DriverFactory)
@@ -81,28 +81,28 @@ func Drivers() []string {
8181
return ss
8282
}
8383

84-
func GetDriver(name string, opts map[string]string) (Driver, error) {
84+
func GetDriver(name string, opts map[string]string, address string) (Driver, error) {
8585
driverFactory, ok := drivers[name]
8686
if !ok {
8787
return nil, fmt.Errorf("unknown logging driver %q: %w", name, errdefs.ErrNotFound)
8888
}
89-
return driverFactory(opts)
89+
return driverFactory(opts, address)
9090
}
9191

9292
func init() {
93-
RegisterDriver("none", func(opts map[string]string) (Driver, error) {
93+
RegisterDriver("none", func(opts map[string]string, address string) (Driver, error) {
9494
return &NoneLogger{}, nil
9595
}, NoneLogOptsValidate)
96-
RegisterDriver("json-file", func(opts map[string]string) (Driver, error) {
96+
RegisterDriver("json-file", func(opts map[string]string, address string) (Driver, error) {
9797
return &JSONLogger{Opts: opts}, nil
9898
}, JSONFileLogOptsValidate)
99-
RegisterDriver("journald", func(opts map[string]string) (Driver, error) {
100-
return &JournaldLogger{Opts: opts}, nil
99+
RegisterDriver("journald", func(opts map[string]string, address string) (Driver, error) {
100+
return &JournaldLogger{Opts: opts, Address: address}, nil
101101
}, JournalLogOptsValidate)
102-
RegisterDriver("fluentd", func(opts map[string]string) (Driver, error) {
102+
RegisterDriver("fluentd", func(opts map[string]string, address string) (Driver, error) {
103103
return &FluentdLogger{Opts: opts}, nil
104104
}, FluentdLogOptsValidate)
105-
RegisterDriver("syslog", func(opts map[string]string) (Driver, error) {
105+
RegisterDriver("syslog", func(opts map[string]string, address string) (Driver, error) {
106106
return &SyslogLogger{Opts: opts}, nil
107107
}, SyslogOptsValidate)
108108
}
@@ -121,9 +121,10 @@ func Main(argv2 string) error {
121121

122122
// LogConfig is marshalled as "log-config.json"
123123
type LogConfig struct {
124-
Driver string `json:"driver"`
125-
Opts map[string]string `json:"opts,omitempty"`
126-
LogURI string `json:"-"`
124+
Driver string `json:"driver"`
125+
Opts map[string]string `json:"opts,omitempty"`
126+
LogURI string `json:"-"`
127+
Address string `json:"address"`
127128
}
128129

129130
// LogConfigFilePath returns the path of log-config.json
@@ -149,7 +150,7 @@ func LoadLogConfig(dataStore, ns, id string) (LogConfig, error) {
149150
}
150151

151152
func loggingProcessAdapter(ctx context.Context, driver Driver, dataStore string, config *logging.Config) error {
152-
if err := driver.PreProcess(dataStore, config); err != nil {
153+
if err := driver.PreProcess(ctx, dataStore, config); err != nil {
153154
return err
154155
}
155156

@@ -215,7 +216,7 @@ func loggerFunc(dataStore string) (logging.LoggerFunc, error) {
215216
if err != nil {
216217
return err
217218
}
218-
driver, err := GetDriver(logConfig.Driver, logConfig.Opts)
219+
driver, err := GetDriver(logConfig.Driver, logConfig.Opts, logConfig.Address)
219220
if err != nil {
220221
return err
221222
}

pkg/logging/none_logger.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
package logging
1818

1919
import (
20+
"context"
21+
2022
"github.com/containerd/containerd/v2/core/runtime/v2/logging"
2123
)
2224

@@ -28,7 +30,7 @@ func (n *NoneLogger) Init(dataStore, ns, id string) error {
2830
return nil
2931
}
3032

31-
func (n *NoneLogger) PreProcess(dataStore string, config *logging.Config) error {
33+
func (n *NoneLogger) PreProcess(ctx context.Context, dataStore string, config *logging.Config) error {
3234
return nil
3335
}
3436

pkg/logging/syslog_logger.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package logging
1818

1919
import (
20+
"context"
2021
"crypto/tls"
2122
"errors"
2223
"fmt"
@@ -122,7 +123,7 @@ func (sy *SyslogLogger) Init(dataStore string, ns string, id string) error {
122123
return nil
123124
}
124125

125-
func (sy *SyslogLogger) PreProcess(dataStore string, config *logging.Config) error {
126+
func (sy *SyslogLogger) PreProcess(ctx context.Context, dataStore string, config *logging.Config) error {
126127
logger, err := parseSyslog(config.ID, sy.Opts)
127128
if err != nil {
128129
return err

0 commit comments

Comments
 (0)