1// Copyright 2016 The Prometheus Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// Based on gopsutil/cpu/cpu_darwin_cgo.go @ ae251eb which is licensed under
15// BSD. See https://github.com/shirou/gopsutil/blob/master/LICENSE for details.
16
17// +build !nocpu
18
19package collector
20
21import (
22	"bytes"
23	"encoding/binary"
24	"fmt"
25	"strconv"
26	"unsafe"
27
28	"github.com/go-kit/kit/log"
29	"github.com/prometheus/client_golang/prometheus"
30)
31
32/*
33#cgo LDFLAGS:
34#include <stdlib.h>
35#include <limits.h>
36#include <sys/sysctl.h>
37#include <sys/mount.h>
38#include <mach/mach_init.h>
39#include <mach/mach_host.h>
40#include <mach/host_info.h>
41#if TARGET_OS_MAC
42#include <libproc.h>
43#endif
44#include <mach/processor_info.h>
45#include <mach/vm_map.h>
46*/
47import "C"
48
49// ClocksPerSec default value. from time.h
50const ClocksPerSec = float64(C.CLK_TCK)
51
52type statCollector struct {
53	cpu    *prometheus.Desc
54	logger log.Logger
55}
56
57func init() {
58	registerCollector("cpu", defaultEnabled, NewCPUCollector)
59}
60
61// NewCPUCollector returns a new Collector exposing CPU stats.
62func NewCPUCollector(logger log.Logger) (Collector, error) {
63	return &statCollector{
64		cpu:    nodeCPUSecondsDesc,
65		logger: logger,
66	}, nil
67}
68
69func (c *statCollector) Update(ch chan<- prometheus.Metric) error {
70	var (
71		count   C.mach_msg_type_number_t
72		cpuload *C.processor_cpu_load_info_data_t
73		ncpu    C.natural_t
74	)
75
76	status := C.host_processor_info(C.host_t(C.mach_host_self()),
77		C.PROCESSOR_CPU_LOAD_INFO,
78		&ncpu,
79		(*C.processor_info_array_t)(unsafe.Pointer(&cpuload)),
80		&count)
81
82	if status != C.KERN_SUCCESS {
83		return fmt.Errorf("host_processor_info error=%d", status)
84	}
85
86	// jump through some cgo casting hoops and ensure we properly free
87	// the memory that cpuload points to
88	target := C.vm_map_t(C.mach_task_self_)
89	address := C.vm_address_t(uintptr(unsafe.Pointer(cpuload)))
90	defer C.vm_deallocate(target, address, C.vm_size_t(ncpu))
91
92	// the body of struct processor_cpu_load_info
93	// aka processor_cpu_load_info_data_t
94	var cpuTicks [C.CPU_STATE_MAX]uint32
95
96	// copy the cpuload array to a []byte buffer
97	// where we can binary.Read the data
98	size := int(ncpu) * binary.Size(cpuTicks)
99	buf := (*[1 << 30]byte)(unsafe.Pointer(cpuload))[:size:size]
100
101	bbuf := bytes.NewBuffer(buf)
102
103	for i := 0; i < int(ncpu); i++ {
104		err := binary.Read(bbuf, binary.LittleEndian, &cpuTicks)
105		if err != nil {
106			return err
107		}
108		for k, v := range map[string]int{
109			"user":   C.CPU_STATE_USER,
110			"system": C.CPU_STATE_SYSTEM,
111			"nice":   C.CPU_STATE_NICE,
112			"idle":   C.CPU_STATE_IDLE,
113		} {
114			ch <- prometheus.MustNewConstMetric(c.cpu, prometheus.CounterValue, float64(cpuTicks[v])/ClocksPerSec, strconv.Itoa(i), k)
115		}
116	}
117	return nil
118}
119