node_exporter.go 6.9 KB
Newer Older
W
wangzelin.wzl 已提交
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
// Copyright (c) 2021 OceanBase
// obagent is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//
// http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

package nodeexporter

import (
	"os"
	"sync"

	log2 "github.com/go-kit/kit/log/logrus"
	kitLog "github.com/go-kit/log"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/node_exporter/collector"
	log "github.com/sirupsen/logrus"
	"gopkg.in/alecthomas/kingpin.v2"

	"github.com/oceanbase/obagent/metric"
)

type MetricFamilies []string

const sampleConfig = `
metricFamilies: [ node_cpu_seconds_total, node_filesystem_avail_bytes, node_filesystem_size_bytes, node_filesystem_readonly, node_disk_reads_completed_total, node_disk_read_bytes_total, node_disk_read_time_seconds_total, node_disk_writes_completed_total, node_disk_written_bytes_total, node_disk_write_time_seconds_total, node_load1, node_load15, node_load5, node_memory_Buffers_bytes, node_memory_MemFree_bytes, node_memory_Cached_bytes, node_memory_MemTotal_bytes, node_network_receive_bytes_total, node_network_transmit_bytes_total ]
`
const description = `
integrate node_exporter to collect host info
`

const (
	metricFamilies = "metricFamilies"

	nodeCpuSecondsTotal           = "node_cpu_seconds_total"
	nodeFilesystemAvailBytes      = "node_filesystem_avail_bytes"
	nodeFilesystemSizeBytes       = "node_filesystem_size_bytes"
	nodeFilesystemReadonly        = "node_filesystem_readonly"
	nodeDiskReadsCompletedTotal   = "node_disk_reads_completed_total"
	nodeDiskReadBytesTotal        = "node_disk_read_bytes_total"
	nodeDiskReadTimeSecondsTotal  = "node_disk_read_time_seconds_total"
	nodeDiskWritesCompletedTotal  = "node_disk_writes_completed_total"
	nodeDiskWrittenBytesTotal     = "node_disk_written_bytes_total"
	nodeDiskWriteTimeSecondsTotal = "node_disk_write_time_seconds_total"
	nodeLoad1                     = "node_load1"
	nodeLoad15                    = "node_load15"
	nodeLoad5                     = "node_load5"
	nodeMemoryBuffersBytes        = "node_memory_Buffers_bytes"
	nodeMemoryMemFreeBytes        = "node_memory_MemFree_bytes"
	nodeMemoryCachedBytes         = "node_memory_Cached_bytes"
	nodeMemoryMemTotalBytes       = "node_memory_MemTotal_bytes"
	nodeNetworkReceiveBytesTotal  = "node_network_receive_bytes_total"
	nodeNetworkTransmitBytesTotal = "node_network_transmit_bytes_total"
	nodeNtpOffsetSeconds          = "node_ntp_offset_seconds"
)

type NodeExporter struct {
	sourceConfig map[string]interface{}

	definedMetricFamilyNameSet map[string]int
	logger                     kitLog.Logger
	nodeCollector              *collector.NodeCollector
	registry                   *prometheus.Registry
}

func (n *NodeExporter) Init(config map[string]interface{}) error {
	n.sourceConfig = config
	n.definedMetricFamilyNameSet = make(map[string]int, 32)
	if _, ok := n.sourceConfig[metricFamilies]; !ok {
		return errors.New("node exporter metric families is not exist")
	}
	families, ok := n.sourceConfig[metricFamilies].([]interface{})
	if !ok {
		return errors.New("node exporter metric families sourceConfig error")
	}

	for _, familyName := range families {
		switch familyName {
		case nodeCpuSecondsTotal:
			n.definedMetricFamilyNameSet[nodeCpuSecondsTotal] = 1

		case nodeFilesystemAvailBytes:
			n.definedMetricFamilyNameSet[nodeFilesystemAvailBytes] = 1

		case nodeFilesystemSizeBytes:
			n.definedMetricFamilyNameSet[nodeFilesystemSizeBytes] = 1

		case nodeFilesystemReadonly:
			n.definedMetricFamilyNameSet[nodeFilesystemReadonly] = 1

		case nodeDiskReadsCompletedTotal:
			n.definedMetricFamilyNameSet[nodeDiskReadsCompletedTotal] = 1

		case nodeDiskReadBytesTotal:
			n.definedMetricFamilyNameSet[nodeDiskReadBytesTotal] = 1

		case nodeDiskReadTimeSecondsTotal:
			n.definedMetricFamilyNameSet[nodeDiskReadTimeSecondsTotal] = 1

		case nodeDiskWritesCompletedTotal:
			n.definedMetricFamilyNameSet[nodeDiskWritesCompletedTotal] = 1

		case nodeDiskWrittenBytesTotal:
			n.definedMetricFamilyNameSet[nodeDiskWrittenBytesTotal] = 1

		case nodeDiskWriteTimeSecondsTotal:
			n.definedMetricFamilyNameSet[nodeDiskWriteTimeSecondsTotal] = 1

		case nodeLoad1:
			n.definedMetricFamilyNameSet[nodeLoad1] = 1

		case nodeLoad15:
			n.definedMetricFamilyNameSet[nodeLoad15] = 1

		case nodeLoad5:
			n.definedMetricFamilyNameSet[nodeLoad5] = 1

		case nodeMemoryBuffersBytes:
			n.definedMetricFamilyNameSet[nodeMemoryBuffersBytes] = 1

		case nodeMemoryMemFreeBytes:
			n.definedMetricFamilyNameSet[nodeMemoryMemFreeBytes] = 1

		case nodeMemoryCachedBytes:
			n.definedMetricFamilyNameSet[nodeMemoryCachedBytes] = 1

		case nodeMemoryMemTotalBytes:
			n.definedMetricFamilyNameSet[nodeMemoryMemTotalBytes] = 1

		case nodeNetworkReceiveBytesTotal:
			n.definedMetricFamilyNameSet[nodeNetworkReceiveBytesTotal] = 1

		case nodeNetworkTransmitBytesTotal:
			n.definedMetricFamilyNameSet[nodeNetworkTransmitBytesTotal] = 1

		case nodeNtpOffsetSeconds:
			n.definedMetricFamilyNameSet[nodeNtpOffsetSeconds] = 1

		default:
			return errors.Errorf("node exporter metric families %s is undefined", familyName)
		}
	}

	commandLineParse()

	n.logger = log2.NewLogrusLogger(log.StandardLogger())

	var err error
	n.nodeCollector, err = collector.NewNodeCollector(n.logger)
	if err != nil {
		return errors.Wrap(err, "node exporter create collector")
	}

	n.registry = prometheus.NewRegistry()
	err = n.registry.Register(n.nodeCollector)
	if err != nil {
		return errors.Wrap(err, "node exporter register collector")
	}

	return nil
}

var once sync.Once

func commandLineParse() {
	once.Do(func() {

		lastIndex := len(os.Args) - 1
		copy(os.Args[lastIndex:], os.Args)
		os.Args = os.Args[lastIndex:]

		for _, item := range collectItems {
			kingpin.CommandLine.GetFlag(item).Default("true")
		}

		for _, item := range noCollectItems {
			kingpin.CommandLine.GetFlag(item).Default("false")
		}

		kingpin.Parse()
	})
}

func (n *NodeExporter) Close() error {
	n.registry.Unregister(n.nodeCollector)
	return nil
}

func (n *NodeExporter) SampleConfig() string {
	return sampleConfig
}

func (n *NodeExporter) Description() string {
	return description
}

func (n *NodeExporter) Collect() ([]metric.Metric, error) {
	var metrics []metric.Metric

	metricFamilies, err := n.registry.Gather()
	if err != nil {
		return nil, errors.Wrap(err, "node exporter registry gather")
	}
	for _, metricFamily := range metricFamilies {

		_, exist := n.definedMetricFamilyNameSet[metricFamily.GetName()]
		if exist {

C
chris-sun-star 已提交
216 217
			metricsFromMetricFamily := metric.ParseFromMetricFamily(metricFamily)
			metrics = append(metrics, metricsFromMetricFamily...)
W
wangzelin.wzl 已提交
218 219 220 221 222
		}
	}

	return metrics, nil
}