-
Notifications
You must be signed in to change notification settings - Fork 10
/
cgminer_exporter.py
213 lines (189 loc) · 7.5 KB
/
cgminer_exporter.py
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
#!/usr/bin/env python3
import asyncio
import socket
import os
import json
import pprint
import datetime
import tornado
pp = pprint.PrettyPrinter(indent=4)
statusdata = {}
threads = int(os.environ.get("THREADS", 0))
def linesplit(socket):
buffer = socket.recv(4096)
done = False
while not done:
more = socket.recv(4096)
if not more:
done = True
else:
buffer += more
if buffer:
return buffer
def getfromIP(ip):
data = {}
for func in ["stats", "version", "pools", "summary", "devs"]:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
s.connect((ip, 4028))
data[func] = getfunction(s, func)
s.close()
return data
def getfunction(s, function):
s.sendall(json.dumps({"command": function}).encode("utf-8"))
response = linesplit(s)
response = response.replace(b"\x00", b"").decode("utf-8")
response = response.replace("}{", "},{")
return json.loads(response)
class HelpHandler(tornado.web.RequestHandler):
def get(self):
self.write("Use /metrics with ?target=IP\n")
class MetricsHandler(tornado.web.RequestHandler):
def get(self):
target = self.get_argument("target", None, True)
metricdata = getfromIP(target)
if "CGMiner" in metricdata["version"]["VERSION"][0]:
tags = (
'instance="%s",cgminer_version="%s",api_version="%s",type="%s",miner="%s"'
% (
target,
metricdata["version"]["VERSION"][0]["CGMiner"],
metricdata["version"]["VERSION"][0]["API"],
metricdata["version"]["VERSION"][0]["Type"],
metricdata["version"]["VERSION"][0]["Miner"],
)
)
elif "BMMiner" in metricdata["version"]["VERSION"][0]:
tags = (
'instance="%s",bmminer_version="%s",api_version="%s",type="%s",miner="%s"'
% (
target,
metricdata["version"]["VERSION"][0]["BMMiner"],
metricdata["version"]["VERSION"][0]["API"],
metricdata["version"]["VERSION"][0]["Type"],
metricdata["version"]["VERSION"][0]["Miner"],
)
)
else:
tags = 'instance="%s",api_version="%s",type="%s",miner="%s"' % (
target,
metricdata["version"]["VERSION"][0]["API"],
metricdata["version"]["VERSION"][0]["Type"],
metricdata["version"]["VERSION"][0]["Miner"],
)
self.write("#CGMiner metrics export\n")
for type in metricdata:
if type == "pools":
self.write(metric_pool(metricdata[type], tags))
self.write("\n")
elif type == "summary":
self.write(metric_summary(metricdata[type], tags))
self.write("\n")
elif type == "stats":
self.write(metric_stats(metricdata[type], tags))
self.write("\n")
def metric_pool(data, tags):
lines = ["# Pools Data"]
lines.append(f"cgminer_pool_count{{{tags}}} {len(data['POOLS'])}")
for pool in data["POOLS"]:
localtags = f'pool="{pool["POOL"]}",url="{pool["URL"]}",stratum_url="{pool["Stratum URL"]}",{tags}'
lines.append(
f'cgminer_pool_diff_accepted{{{localtags}}} {pool["Difficulty Accepted"]}'
)
lines.append(
f'cgminer_pool_rejected{{{localtags}}} {pool["Difficulty Accepted"]}'
)
lines.append(
f'cgminer_pool_diff_rejected{{{localtags}}} {pool["Difficulty Rejected"]}'
)
lines.append(f'cgminer_pool_stale{{{localtags}}} {pool["Stale"]}')
try:
hr, mn, ss = [int(x) for x in pool["Last Share Time"].split(":")]
sharetime = datetime.timedelta(hours=hr, minutes=mn, seconds=ss).seconds
except:
sharetime = 0
lines.append(f"cgminer_pool_last_share{{{localtags}}} {sharetime}")
lines.append(f'cgminer_pool_getworks{{{localtags}}} {pool["Getworks"]}')
lines.append(
f'cgminer_pool_last_diff{{{localtags}}} {pool["Last Share Difficulty"]}'
)
status = 1 if pool["Status"] == "Alive" else 0
lines.append(f"cgminer_pool_status{{{localtags}}} {status}")
active = 1 if pool["Stratum Active"] else 0
lines.append(f"cgminer_pool_stratum_active{{{localtags}}} {active}")
return "\n".join(lines)
def metric_summary(data, tags):
lines = ["#Pool Summary"]
localtags = tags
lines.append(
f'cgminer_summary_rejected{{{localtags}}} {data["SUMMARY"][0]["Rejected"]}'
)
lines.append(
f'cgminer_summary_found_blocks{{{localtags}}} {data["SUMMARY"][0]["Found Blocks"]}'
)
lines.append(
f'cgminer_summary_elapsed{{{localtags}}} {data["SUMMARY"][0]["Elapsed"]}'
)
lines.append(
f'cgminer_summary_hardware_errors{{{localtags}}} {data["SUMMARY"][0]["Hardware Errors"]}'
)
lines.append(
f'cgminer_summary_total_mh{{{localtags}}} {data["SUMMARY"][0]["Total MH"]}'
)
lines.append(
f'cgminer_summary_ghs_average{{{localtags}}} {data["SUMMARY"][0]["GHS av"]}'
)
lines.append(
f'cgminer_summary_ghs_5s{{{localtags}}} {data["SUMMARY"][0]["GHS 5s"]}'
)
return "\n".join(lines)
def metric_stats(data, tags):
lines = ["# Stats"]
statdata = data["STATS"][1]
localtags = f"{tags}"
for entry in statdata:
if "temp" in entry:
tempnum = entry.replace("temp", "")
res = statdata[f"temp{tempnum}"]
if isinstance(res, str) and "-" in res:
# some values like temp_in_pcb_1 are "35-36" - report only the first sensor
# alternatively we'd have to split them into multiple lines
res = res.split("-")[0]
lines.append(
f'cgminer_stats_temp{{temp="{tempnum}",{localtags}}} {res}'
)
if "chain_hw" in entry:
chainnum = entry.replace("chain_hw", "")
if statdata[f"chain_rate{chainnum}"]:
lines.append(
f'cgminer_stats_chain_rate{{chain="{chainnum}",{localtags}}} {statdata[f"chain_rate{chainnum}"]}'
)
else:
lines.append(
f'cgminer_stats_chain_rate{{chain="{chainnum}",{localtags}}} 0'
)
lines.append(
f'cgminer_stats_chain_acn{{chain="{chainnum}",{localtags}}} {statdata[f"chain_acn{chainnum}"]}'
)
lines.append(
f'cgminer_stats_chain_hw{{chain="{chainnum}",{localtags}}} {statdata[f"chain_hw{chainnum}"]}'
)
if "fan" in entry:
fannum = entry.replace("fan", "")
lines.append(
f'cgminer_stats_fan{{fan="{fannum}",{localtags}}} {statdata[f"fan{fannum}"]}'
)
if "freq_avg" in entry:
freqnum = entry.replace("freq_avg", "")
lines.append(
f'cgminer_stats_freq{{freq="{freqnum}",{localtags}}} {statdata[f"freq_avg{freqnum}"]}'
)
lines.append(f'cgminer_stats_frequency{{{localtags}}} {statdata["frequency"]}')
return "\n".join(lines)
async def main():
tornado.options.parse_command_line()
app = tornado.web.Application([(r"/", HelpHandler), (r"/metrics", MetricsHandler)])
app.listen(9154)
await asyncio.Event().wait()
if __name__ == "__main__":
asyncio.run(main())