Skip to content

Commit

Permalink
metricbeat: handle nf_conntrack module not loaded in linux integration (
Browse files Browse the repository at this point in the history
#41930)

* metricbeat: handle nf_conntrack module not loaded in linux integration

* ci lint fixes

* fix error check to prevent windows failure
  • Loading branch information
mauri870 authored Dec 9, 2024
1 parent da6822b commit f86a5f0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
9 changes: 8 additions & 1 deletion metricbeat/module/linux/conntrack/conntrack.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package conntrack

import (
"fmt"
"os"

"github.com/prometheus/procfs"

Expand Down Expand Up @@ -50,7 +51,10 @@ type MetricSet struct {
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
cfgwarn.Beta("The linux conntrack metricset is beta.")

sys := base.Module().(resolve.Resolver)
sys, ok := base.Module().(resolve.Resolver)
if !ok {
return nil, fmt.Errorf("unexpected module type: %T", base.Module())
}

return &MetricSet{
BaseMetricSet: base,
Expand All @@ -68,6 +72,9 @@ func (m *MetricSet) Fetch(report mb.ReporterV2) error {
}
conntrackStats, err := newFS.ConntrackStat()
if err != nil {
if os.IsNotExist(err) {
err = mb.PartialMetricsError{Err: fmt.Errorf("nf_conntrack kernel module not loaded: %w", err)}
}
return fmt.Errorf("error fetching conntrack stats: %w", err)
}

Expand Down
22 changes: 22 additions & 0 deletions metricbeat/module/linux/conntrack/conntrack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,15 @@
package conntrack

import (
"errors"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/elastic/beats/v7/metricbeat/mb"
mbtest "github.com/elastic/beats/v7/metricbeat/mb/testing"
_ "github.com/elastic/beats/v7/metricbeat/module/linux"
"github.com/elastic/elastic-agent-libs/mapstr"
Expand Down Expand Up @@ -60,6 +65,23 @@ func TestFetch(t *testing.T) {
assert.Equal(t, testConn, rawEvent)
}

func TestFetchConntrackModuleNotLoaded(t *testing.T) {
// Create a temporary directory to simulate a missing /proc/net/stat/nf_conntrack file
tmpDir := t.TempDir()
assert.NoError(t, os.MkdirAll(filepath.Join(tmpDir, "proc/net/stat"), 0755))
c := getConfig()
c["hostfs"] = tmpDir

f := mbtest.NewReportingMetricSetV2Error(t, c)
events, errs := mbtest.ReportingFetchV2Error(f)

require.Len(t, errs, 1)
err := errors.Join(errs...)
assert.ErrorAs(t, err, &mb.PartialMetricsError{})
assert.Contains(t, err.Error(), "error fetching conntrack stats: nf_conntrack kernel module not loaded")
require.Empty(t, events)
}

func getConfig() map[string]interface{} {
return map[string]interface{}{
"module": "linux",
Expand Down

0 comments on commit f86a5f0

Please sign in to comment.