-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
314 lines (291 loc) · 8.17 KB
/
client.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
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package main
import (
"bytes"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type MinerCommand struct {
Command string `json:"command"`
Parameter string `json:"parameter"`
}
type Config struct {
Interval int `json:"interval"`
ParsedInterval time.Duration `json:"-"`
ServerHost string `json:"serverHost"`
ServerPort string `json:"serverPort"`
MinerHost string `json:"minerHost"`
MinerPort string `json:"minerPort"`
DeviceName string `json:"deviceName"`
ServerPassword string `json:"serverPassword"`
}
type CgMinerStats struct {
DeviceName string `json:"deviceName"`
When int64 `json:"when"`
Status []struct {
When int64 `json:"When"`
} `json:"STATUS"`
Devs []struct {
GPU int `json:"GPU"`
Enabled string `json:"Enabled"`
Status string `json:"Status"`
Temperature float64 `json:"Temperature"`
FanSpeed int `json:"Fan Speed"`
FanPercent int `json:"Fan Percent"`
GpuClock int `json:"GPU Clock"`
MemClock int `json:"Memory Clock"`
GpuVoltage float64 `json:"GPU Voltage"`
GpuActivity int `json:"GPU Activity"`
Powertune int `json:"Powertune"`
MhsAv float64 `json:"MHS av"`
MhsFiveSeconds float64 `json:"MHS 5s"`
Accepted int `json:"Accepted"`
Rejected int `json:"Rejected"`
HardwareErrors int `json:"Hardware Errors"`
Utility float64 `json:"Utility"`
Intensity string `json:"Intensity"`
LastSharePool int64 `json:"Last Share Pool"`
LastShareTime int64 `json:"Last Share Time"`
TotalMh float64 `json:"Total MH"`
DiffOneWork int64 `json:"Diff1 Work"`
DiffAccepted float64 `json:"Difficulty Accepted"`
DiffRejected float64 `json:"Difficulty Rejected"`
LastShareDiff float64 `json:"Last Share Difficulty"`
LastValidWorkd int64 `json:"Last Valid Work"`
DeviceHardwarePct float64 `json:"Device Hardware%"`
DeviceRejectedPct float64 `json:"Device Rejected%"`
DeviceElapsed int64 `json:"Device Elapsed"`
} `json:"DEVS"`
}
var (
uploadQueue = make(chan (os.FileInfo))
config Config
)
func main() {
loadConfig()
os.Mkdir("./stats", 7777)
go uploadStatsOnFs()
go uploadStatQueue()
for {
//var i int
//_, err := fmt.Scanf("%d", &i)
response, err := queryMiner("devs", "")
if err != nil {
continue
}
var devs CgMinerStats
err = json.Unmarshal([]byte(response), &devs)
if err != nil {
fmt.Println("Parse Error:", err)
continue
} else {
//fmt.Println("Response:", strings.TrimRight(string(response), "\x00"))
}
//go uploadStat(devs)
go writeCgMinerStats(devs)
time.Sleep(config.ParsedInterval * time.Second)
}
}
func queryMiner(command, param string) (string, error) {
commandDto := MinerCommand{
Command: command,
Parameter: param,
}
commandBytes, err := json.Marshal(commandDto)
if err != nil {
fmt.Println("Marshal Error:", err)
return "", err
}
conn, err := net.Dial("tcp", config.MinerHost+":"+config.MinerPort)
if err != nil {
fmt.Println("Dail Error:", err)
return "", err
}
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
_, err = conn.Write(commandBytes)
if err != nil {
fmt.Println("Write Error:", err)
return "", err
}
response := make([]byte, 4096, 4096)
conn.Read(response)
if err != nil {
fmt.Println("Read Error:", err)
return "", err
}
return strings.TrimRight(string(response), "\x00"), nil
}
func loadConfig() {
content, err := ioutil.ReadFile("config.json")
if err != nil {
panic(err)
}
err = json.Unmarshal(content, &config)
if err != nil {
panic(err)
}
config.ParsedInterval = time.Duration(config.Interval)
fmt.Println("Server is: " + config.ServerHost + ":" + config.ServerPort)
fmt.Println("Miner is: " + config.MinerHost + ":" + config.MinerPort)
fmt.Println("Querying every", config.Interval, "seconds")
}
func writeCgMinerStats(minerStats CgMinerStats) {
minerStats.DeviceName = config.DeviceName
minerStats.When = minerStats.Status[0].When
stats, err := json.Marshal(minerStats)
if err != nil {
fmt.Println("Failed marshaling minerStats", err)
return
}
err = ioutil.WriteFile("stats/"+getStatsName(minerStats), stats, 0644)
if err != nil {
fmt.Println("Failed writing the file", err)
return
}
uploadStatsOnFs()
}
func getStatsName(stats CgMinerStats) string {
return config.DeviceName + "_" + strconv.FormatInt(stats.When, 10)
}
func uploadStat(devs CgMinerStats) {
content, err := json.Marshal(devs)
if err != nil {
fmt.Println("F, no idea:", err)
return
}
err = postStatString(content, getStatsName(devs))
if err != nil {
fmt.Println("Couldn't upload without write:", err)
writeCgMinerStats(devs)
} else {
fmt.Println("Uploaded without writing to disk. Yay")
}
}
func uploadStatsOnFs() {
fmt.Println("Scanning for files to upload")
files, err := ioutil.ReadDir("./stats/")
if err != nil {
fmt.Println("Failed reading ./stats/ dir", err)
}
fmt.Println("Found", len(files), "files to upload")
for _, file := range files {
uploadQueue <- file
}
}
func uploadStatQueue() {
for {
select {
case file := <-uploadQueue:
fmt.Println("Uploading", file.Name())
if err := postStatFile(file); err != nil {
fmt.Println("Failed to upload file", err)
} else {
err := os.Remove("./stats/" + file.Name())
if err != nil {
fmt.Println("Failed deleting", file.Name(), err)
} else {
fmt.Println("Deleted", file.Name(), "after successful upload")
}
}
break
}
}
}
func postStatFile(file os.FileInfo) error {
extraParams := map[string]string{
"name": file.Name(),
}
request, err := newfileUploadRequest("http://"+config.ServerHost+":"+config.ServerPort+"/stats", extraParams, "file", "./stats/"+file.Name())
if err != nil {
return err
}
return postRequest(request)
}
func postStatString(body []byte, fileName string) error {
extraParams := map[string]string{
"name": fileName,
}
request, err := newStringBodyRequest("http://"+config.ServerHost+":"+config.ServerPort+"/stats", extraParams, "file", body)
if err != nil {
return err
}
return postRequest(request)
}
func postRequest(request *http.Request) error {
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
return err
} else {
body := &bytes.Buffer{}
_, err := body.ReadFrom(resp.Body)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode != 201 {
fmt.Println("Server said:", body.String())
return errors.New("Status code returned was: " + strconv.Itoa(resp.StatusCode))
}
}
return nil
}
// Creates a new file upload http request with optional extra params
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", uri, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Server-Password", config.ServerPassword)
return req, nil
}
// Creates a new file upload http request with optional extra params
func newStringBodyRequest(uri string, params map[string]string, paramName string, body []byte) (*http.Request, error) {
req, err := http.NewRequest("POST", uri, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "multipart/form-data; boundary="+randString(60))
req.Header.Set("Server-Password", config.ServerPassword)
return req, nil
}
func randString(n int) string {
const alphanum = "0123456789abcdef"
var bytes = make([]byte, n)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
return string(bytes)
}