Browse Source

added the `node_uptime_seconds` metric

Nikolay Sivko 3 năm trước cách đây
mục cha
commit
7280b38d12
4 tập tin đã thay đổi với 48 bổ sung0 xóa
  1. 14 0
      node/collector.go
  2. 1 0
      node/fixtures/proc/uptime
  3. 21 0
      node/uptime.go
  4. 12 0
      node/uptime_test.go

+ 14 - 0
node/collector.go

@@ -21,6 +21,11 @@ var (
 		"Meta information about the cloud instance",
 		[]string{"provider", "account_id", "instance_id", "instance_type", "instance_life_cycle", "region", "availability_zone", "availability_zone_id", "local_ipv4", "public_ipv4"}, nil,
 	)
+	uptimeDesc = prometheus.NewDesc(
+		"node_uptime_seconds",
+		"Uptime of the node in seconds",
+		[]string{}, nil,
+	)
 	cpuUsageDesc = prometheus.NewDesc(
 		"node_resources_cpu_usage_seconds_total",
 		"The amount of CPU time spent in each mode",
@@ -159,6 +164,14 @@ func NewCollector(hostname, kernelVersion string) *Collector {
 
 func (c *Collector) Collect(ch chan<- prometheus.Metric) {
 	ch <- gauge(infoDesc, 1, c.hostname, c.kernelVersion)
+
+	v, err := uptime(procRoot)
+	if err != nil {
+		klog.Errorln(err)
+	} else {
+		ch <- gauge(uptimeDesc, v)
+	}
+
 	cpu, err := cpuStat(procRoot)
 	if err != nil {
 		if !common.IsNotExist(err) {
@@ -236,6 +249,7 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric) {
 func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
 	ch <- infoDesc
 	ch <- cloudInfoDesc
+	ch <- uptimeDesc
 	ch <- cpuUsageDesc
 	ch <- cpuLogicalCoresDesc
 	ch <- memTotalDesc

+ 1 - 0
node/fixtures/proc/uptime

@@ -0,0 +1 @@
+2659150.03 1208658.10

+ 21 - 0
node/uptime.go

@@ -0,0 +1,21 @@
+package node
+
+import (
+	"fmt"
+	"os"
+	"path"
+	"strconv"
+	"strings"
+)
+
+func uptime(procRoot string) (float64, error) {
+	data, err := os.ReadFile(path.Join(procRoot, "uptime"))
+	if err != nil {
+		return 0, err
+	}
+	fields := strings.Fields(string(data))
+	if len(fields) != 2 {
+		return 0, fmt.Errorf("invalid format of /proc/uptime")
+	}
+	return strconv.ParseFloat(fields[0], 64)
+}

+ 12 - 0
node/uptime_test.go

@@ -0,0 +1,12 @@
+package node
+
+import (
+	"github.com/stretchr/testify/assert"
+	"testing"
+)
+
+func TestNode_uptime(t *testing.T) {
+	v, err := uptime("fixtures/proc")
+	assert.Nil(t, err)
+	assert.Equal(t, 2659150.03, v)
+}