-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
119 lines (107 loc) · 2.41 KB
/
main.go
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
package main
import (
// "fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const magicOffset = 34
var (
powerData = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "ZJUSCT",
Name: "pdu_processed_power",
Help: "node power consumption",
},
[]string{
"node",
"place",
})
config conf
)
type conf struct {
Url string
Interval int
Nodes []struct {
Name string `yaml:"name"`
Place []int `yaml:",flow"`
}
}
func parseYamlConfig(filename string) conf {
yamlFile, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
c := conf{}
err = yaml.Unmarshal(yamlFile, &c)
if err != nil {
log.Fatalf("error: %v", err)
}
return c
}
func recordMetrics() {
go func() {
for {
resp, err := http.Get(config.Url)
if err != nil {
log.Fatalln(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
s := strings.Split(sb, "?")
for _, node := range config.Nodes {
//fmt.Printf("%s %d\n", node.Name, node.Place)
for _, place := range node.Place {
//fmt.Printf("%d\n", place)
power, _ := strconv.Atoi(s[magicOffset + (place - 1) * 7])
powerData.WithLabelValues(node.Name, strconv.Itoa(place)).Set(float64(power) / 1000)
}
}
time.Sleep(time.Duration(config.Interval) * time.Second)
}
}()
}
func main() {
app := &cli.App{
Name: "PDU Data Exporter",
Usage: "PDU power exporter for prometheus",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Usage: "Load configuration from `FILE`",
Value: "config.yaml",
EnvVars: []string{"PDU_CONFIG_FILE"},
},
&cli.StringFlag{
Name: "listen",
Aliases: []string{"l"},
Usage: "Listen at `ADDRESS`",
Value: ":2112",
EnvVars: []string{"PDU_LISTEN_ADDRESS"},
},
},
Action: func(c *cli.Context) error {
config = parseYamlConfig(c.String("config"))
log.Println("config: %v\n", config)
recordMetrics()
http.Handle("/metrics", promhttp.Handler())
return http.ListenAndServe(c.String("listen"), nil)
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}