// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 //go:build linux package journald // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/input/journald" import ( "bytes" "context" "errors" "fmt" "os" "os/exec" "path/filepath" "regexp" "sort" "strings" "syscall" "time" "go.opentelemetry.io/collector/component" "go.uber.org/zap" "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator" ) const waitDuration = 1 * time.Second func init() { operator.Register(operatorType, func() operator.Builder { return NewConfig() }) } // Build will build a journald input operator from the supplied configuration func (c Config) Build(set component.TelemetrySettings) (operator.Operator, error) { if err := c.validate(); err != nil { return nil, err } inputOperator, err := c.InputConfig.Build(set) if err != nil { return nil, err } newCmdFunc, err := c.buildNewCmdFunc(inputOperator.Logger()) if err != nil { return nil, err } return &Input{ InputOperator: inputOperator, newCmd: newCmdFunc, convertMessageBytes: c.ConvertMessageBytes, includeLogRecordOriginal: c.IncludeLogRecordOriginal, convertToSemanticConventions: c.ConvertToSemanticConventions, }, nil } func (c Config) validate() error { if c.StartAt != "end" && c.StartAt != "beginning" { return fmt.Errorf("invalid value '%s' for parameter 'start_at'", c.StartAt) } if c.RootPath != "" { if !filepath.IsAbs(c.JournalctlPath) { return errors.New("'journalctl_path' must be an absolute path when 'root_path' is set") } if !filepath.IsAbs(c.RootPath) { return errors.New("'root_path' must be an absolute path") } info, err := os.Stat(c.RootPath) if err != nil { return fmt.Errorf("cannot access root_path %q: %w", c.RootPath, err) } if !info.IsDir() { return fmt.Errorf("root_path %q is not a directory", c.RootPath) } } if strings.TrimSpace(c.JournalctlPath) == "" { return errors.New("'journalctl_path' must be non-whitespace") } return nil } func (c Config) buildArgs() ([]string, error) { args := make([]string, 0, 10) args = append(args, "--utc", // Export logs in UTC time "--output=json", // Export logs as JSON "--follow", // Continue watching logs until cancelled ) if c.StartAt == "beginning" { args = append(args, "--no-tail") } else { args = append(args, "--lines=0") } for _, unit := range c.Units { args = append(args, "--unit", unit) } for _, identifier := range c.Identifiers { args = append(args, "--identifier", identifier) } args = append(args, "--priority", c.Priority) if c.Grep != "" { args = append(args, "--grep", c.Grep) } if c.Dmesg { args = append(args, "--dmesg") } if c.Namespace != "" { args = append(args, "--namespace", c.Namespace) } switch { case c.Directory != nil: args = append(args, "--directory", *c.Directory) case len(c.Files) > 0: for _, file := range c.Files { args = append(args, "--file", file) } } if len(c.Matches) > 0 { matches, err := c.buildMatchesConfig() if err != nil { return nil, err } args = append(args, matches...) } if c.All { args = append(args, "--all") } if c.Merge { args = append(args, "--merge") } return args, nil } func buildMatchConfig(mc MatchConfig) ([]string, error) { re := regexp.MustCompile("^[_A-Z]+$") // Sort keys to be consistent with every run and to be predictable for tests sortedKeys := make([]string, 0, len(mc)) for key := range mc { if !re.MatchString(key) { return []string{}, fmt.Errorf("'%s' is not a valid Systemd field name", key) } sortedKeys = append(sortedKeys, key) } sort.Strings(sortedKeys) configs := []string{} for _, key := range sortedKeys { configs = append(configs, fmt.Sprintf("%s=%s", key, mc[key])) } return configs, nil } func (c Config) buildMatchesConfig() ([]string, error) { matches := []string{} for i, mc := range c.Matches { if i > 0 { matches = append(matches, "+") } mcs, err := buildMatchConfig(mc) if err != nil { return []string{}, err } matches = append(matches, mcs...) } return matches, nil } func (c Config) buildNewCmdFunc(logger *zap.Logger) (func(ctx context.Context, cursor []byte) cmd, error) { args, err := c.buildArgs() if err != nil { return nil, err } return func(ctx context.Context, cursor []byte) cmd { // Copy args and if needed, add the cursor flag journalArgs := append([]string{}, args...) if len(bytes.TrimSpace(cursor)) > 0 { journalArgs = append(journalArgs, "--after-cursor", string(cursor)) } cmd := exec.CommandContext(ctx, c.JournalctlPath, journalArgs...) // #nosec - ... // journalctl is an executable that is required for this operator to function if c.RootPath != "" { cmd.SysProcAttr = &syscall.SysProcAttr{ Chroot: c.RootPath, } } logCmd := fmt.Sprintf("Journalctl command: '%s %s'.", c.JournalctlPath, strings.Join(journalArgs, " ")) if c.RootPath != "" { logCmd = fmt.Sprintf("%s Chroot: %q", logCmd, c.RootPath) } logger.Info(logCmd) return cmd }, nil }