summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/systemdunits/collect_unit_files.go
blob: eff2d6ecb6fa128cfc54e5483ee906faa5430fe5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// SPDX-License-Identifier: GPL-3.0-or-later

//go:build linux
// +build linux

package systemdunits

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/coreos/go-systemd/v22/dbus"
)

// https://github.com/systemd/systemd/blob/3d320785c4bbba74459096b07e85a79c4f0cdffb/src/shared/install.c#L3785
// see "is-enabled" in https://www.man7.org/linux/man-pages/man1/systemctl.1.html
var unitFileStates = []string{
	"enabled",
	"enabled-runtime",
	"linked",
	"linked-runtime",
	"alias",
	"masked",
	"masked-runtime",
	"static",
	"disabled",
	"indirect",
	"generated",
	"transient",
	"bad",
}

func (s *SystemdUnits) collectUnitFiles(mx map[string]int64, conn systemdConnection) error {
	if s.systemdVersion < 230 {
		return nil
	}

	if now := time.Now(); now.After(s.lastListUnitFilesTime.Add(s.CollectUnitFilesEvery.Duration())) {
		unitFiles, err := s.getUnitFilesByPatterns(conn)
		if err != nil {
			return err
		}
		s.lastListUnitFilesTime = now
		s.cachedUnitFiles = unitFiles
	}

	seen := make(map[string]bool)

	for _, unitFile := range s.cachedUnitFiles {
		seen[unitFile.Path] = true

		if !s.seenUnitFiles[unitFile.Path] {
			s.seenUnitFiles[unitFile.Path] = true
			s.addUnitFileCharts(unitFile.Path)
		}

		px := fmt.Sprintf("unit_file_%s_state_", unitFile.Path)
		for _, st := range unitFileStates {
			mx[px+st] = 0
		}
		mx[px+strings.ToLower(unitFile.Type)] = 1
	}

	for k := range s.seenUnitFiles {
		if !seen[k] {
			delete(s.seenUnitFiles, k)
			s.removeUnitFileCharts(k)
		}
	}

	return nil
}

func (s *SystemdUnits) getUnitFilesByPatterns(conn systemdConnection) ([]dbus.UnitFile, error) {
	ctx, cancel := context.WithTimeout(context.Background(), s.Timeout.Duration())
	defer cancel()

	s.Debugf("calling function 'ListUnitFilesByPatterns'")

	unitFiles, err := conn.ListUnitFilesByPatternsContext(ctx, nil, s.IncludeUnitFiles)
	if err != nil {
		return nil, fmt.Errorf("error on ListUnitFilesByPatterns: %v", err)
	}

	for i := range unitFiles {
		unitFiles[i].Path = cleanUnitName(unitFiles[i].Path)
	}

	s.Debugf("got %d unit files", len(unitFiles))

	return unitFiles, nil
}