File: thermal_darwin.go

package info (click to toggle)
prometheus-node-exporter 1.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,692 kB
  • sloc: sh: 800; makefile: 175; ansic: 122
file content (187 lines) | stat: -rw-r--r-- 5,394 bytes parent folder | download | duplicates (2)
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
// Copyright 2021 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !notherm
// +build !notherm

package collector

/*
#cgo LDFLAGS: -framework IOKit -framework CoreFoundation
#include <stdio.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/pwr_mgt/IOPM.h>

struct ref_with_ret {
    CFDictionaryRef ref;
    IOReturn ret;
};

struct ref_with_ret FetchThermal();

struct ref_with_ret FetchThermal() {
    CFDictionaryRef ref;
    IOReturn ret;
    ret = IOPMCopyCPUPowerStatus(&ref);
    struct ref_with_ret result = {
            ref,
            ret,
    };
    return result;
}
*/
import "C"

import (
	"errors"
	"fmt"
	"log/slog"
	"unsafe"

	"github.com/prometheus/client_golang/prometheus"
)

type thermCollector struct {
	cpuSchedulerLimit typedDesc
	cpuAvailableCPU   typedDesc
	cpuSpeedLimit     typedDesc
	logger            *slog.Logger
}

const thermal = "thermal"

func init() {
	registerCollector(thermal, defaultEnabled, NewThermCollector)
}

// NewThermCollector returns a new Collector exposing current CPU power levels.
func NewThermCollector(logger *slog.Logger) (Collector, error) {
	return &thermCollector{
		cpuSchedulerLimit: typedDesc{
			desc: prometheus.NewDesc(
				prometheus.BuildFQName(namespace, thermal, "cpu_scheduler_limit_ratio"),
				"Represents the percentage (0-100) of CPU time available. 100% at normal operation. The OS may limit this time for a percentage less than 100%.",
				nil,
				nil),
			valueType: prometheus.GaugeValue,
		},
		cpuAvailableCPU: typedDesc{
			desc: prometheus.NewDesc(
				prometheus.BuildFQName(namespace, thermal, "cpu_available_cpu"),
				"Reflects how many, if any, CPUs have been taken offline. Represented as an integer number of CPUs (0 - Max CPUs).",
				nil,
				nil,
			),
			valueType: prometheus.GaugeValue,
		},
		cpuSpeedLimit: typedDesc{
			desc: prometheus.NewDesc(
				prometheus.BuildFQName(namespace, thermal, "cpu_speed_limit_ratio"),
				"Defines the speed & voltage limits placed on the CPU. Represented as a percentage (0-100) of maximum CPU speed.",
				nil,
				nil,
			),
			valueType: prometheus.GaugeValue,
		},
		logger: logger,
	}, nil
}

func (c *thermCollector) Update(ch chan<- prometheus.Metric) error {
	cpuPowerStatus, err := fetchCPUPowerStatus()
	if err != nil {
		return err
	}
	if value, ok := cpuPowerStatus[(string(C.kIOPMCPUPowerLimitSchedulerTimeKey))]; ok {
		ch <- c.cpuSchedulerLimit.mustNewConstMetric(float64(value) / 100.0)
	}
	if value, ok := cpuPowerStatus[(string(C.kIOPMCPUPowerLimitProcessorCountKey))]; ok {
		ch <- c.cpuAvailableCPU.mustNewConstMetric(float64(value))
	}
	if value, ok := cpuPowerStatus[(string(C.kIOPMCPUPowerLimitProcessorSpeedKey))]; ok {
		ch <- c.cpuSpeedLimit.mustNewConstMetric(float64(value) / 100.0)
	}
	return nil
}

func fetchCPUPowerStatus() (map[string]int, error) {
	cfDictRef, _ := C.FetchThermal()
	defer func() {
		if cfDictRef.ref != 0x0 {
			C.CFRelease(C.CFTypeRef(cfDictRef.ref))
		}
	}()

	if C.kIOReturnNotFound == cfDictRef.ret {
		return nil, errors.New("no CPU power status has been recorded")
	}

	if C.kIOReturnSuccess != cfDictRef.ret {
		return nil, fmt.Errorf("no CPU power status with error code 0x%08x", int(cfDictRef.ret))
	}

	// mapping CFDictionary to map
	cfDict := CFDict(cfDictRef.ref)
	return mappingCFDictToMap(cfDict), nil
}

type CFDict uintptr

func mappingCFDictToMap(dict CFDict) map[string]int {
	if C.CFNullRef(dict) == C.kCFNull {
		return nil
	}
	cfDict := C.CFDictionaryRef(dict)

	var result map[string]int
	count := C.CFDictionaryGetCount(cfDict)
	if count > 0 {
		keys := make([]C.CFTypeRef, count)
		values := make([]C.CFTypeRef, count)
		C.CFDictionaryGetKeysAndValues(cfDict, (*unsafe.Pointer)(unsafe.Pointer(&keys[0])), (*unsafe.Pointer)(unsafe.Pointer(&values[0])))
		result = make(map[string]int, count)
		for i := C.CFIndex(0); i < count; i++ {
			result[mappingCFStringToString(C.CFStringRef(keys[i]))] = mappingCFNumberLongToInt(C.CFNumberRef(values[i]))
		}
	}
	return result
}

// CFStringToString converts a CFStringRef to a string.
func mappingCFStringToString(s C.CFStringRef) string {
	p := C.CFStringGetCStringPtr(s, C.kCFStringEncodingUTF8)
	if p != nil {
		return C.GoString(p)
	}
	length := C.CFStringGetLength(s)
	if length == 0 {
		return ""
	}
	maxBufLen := C.CFStringGetMaximumSizeForEncoding(length, C.kCFStringEncodingUTF8)
	if maxBufLen == 0 {
		return ""
	}
	buf := make([]byte, maxBufLen)
	var usedBufLen C.CFIndex
	_ = C.CFStringGetBytes(s, C.CFRange{0, length}, C.kCFStringEncodingUTF8, C.UInt8(0), C.false, (*C.UInt8)(&buf[0]), maxBufLen, &usedBufLen)
	return string(buf[:usedBufLen])
}

func mappingCFNumberLongToInt(n C.CFNumberRef) int {
	typ := C.CFNumberGetType(n)
	var long C.long
	C.CFNumberGetValue(n, typ, unsafe.Pointer(&long))
	return int(long)
}