Skip to content

Commit

Permalink
systemd.go: Added systemd_version metric
Browse files Browse the repository at this point in the history
Fixes: #27

Signed-off-by: Jonathan Davies <jpds@protonmail.com>
  • Loading branch information
jpds committed Nov 13, 2023
1 parent 25c6295 commit c93c811
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions systemd/systemd.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ var (
type Collector struct {
ctx context.Context
logger log.Logger
systemdVersion *prometheus.Desc
unitCPUTotal *prometheus.Desc
unitState *prometheus.Desc
unitInfo *prometheus.Desc
Expand All @@ -84,6 +85,11 @@ type Collector struct {

// NewCollector returns a new Collector exposing systemd statistics.
func NewCollector(logger log.Logger) (*Collector, error) {
systemdVersion := prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "version"),
"systemd version",
[]string{"version"}, nil,
)
// Type is labeled twice e.g. name="foo.service" and type="service" to maintain compatibility
// with users before we started exporting type label
unitState := prometheus.NewDesc(
Expand Down Expand Up @@ -194,6 +200,7 @@ func NewCollector(logger log.Logger) (*Collector, error) {
return &Collector{
ctx: ctx,
logger: logger,
systemdVersion: systemdVersion,
unitCPUTotal: unitCPUTotal,
unitState: unitState,
unitInfo: unitInfo,
Expand Down Expand Up @@ -228,6 +235,7 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric) {

// Describe gathers descriptions of Metrics
func (c *Collector) Describe(desc chan<- *prometheus.Desc) {
desc <- c.systemdVersion
desc <- c.unitCPUTotal
desc <- c.unitState
desc <- c.unitInfo
Expand Down Expand Up @@ -259,6 +267,15 @@ func (c *Collector) collect(ch chan<- prometheus.Metric) error {
}
defer conn.Close()

systemdVersion := c.getSystemdVersion(conn)

ch <- prometheus.MustNewConstMetric(
c.systemdVersion,
prometheus.GaugeValue,
1,
systemdVersion,
)

allUnits, err := conn.ListUnitsContext(c.ctx)
if err != nil {
return errors.Wrap(err, "could not get list of systemd units from dbus")
Expand Down Expand Up @@ -620,3 +637,17 @@ func (c *Collector) filterUnits(units []dbus.UnitStatus, includePattern, exclude

return filtered
}

func (c *Collector) getSystemdVersion(conn *dbus.Conn) string {
version, err := conn.GetManagerProperty("Version")

if err != nil {
level.Debug(c.logger).Log("msg", "Unable to get systemd version property, defaulting to 0")
return "0"
}

version = strings.TrimPrefix(strings.TrimSuffix(version, `"`), `"`)
level.Debug(c.logger).Log("msg", "Got systemd version", "version", version)

return version
}

0 comments on commit c93c811

Please sign in to comment.