-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
307 lines (268 loc) · 8.54 KB
/
server.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
package api
import (
"encoding/json"
"net/http"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/mux"
"github.com/PowPool/ltcpool/storage"
. "github.com/PowPool/ltcpool/util"
)
type ApiConfig struct {
Enabled bool `json:"enabled"`
Listen string `json:"listen"`
StatsCollectInterval string `json:"statsCollectInterval"`
HashrateWindow string `json:"hashrateWindow"`
HashrateLargeWindow string `json:"hashrateLargeWindow"`
StatsReservedInterval string `json:"statsReservedInterval"`
LuckWindow []int `json:"luckWindow"`
Payments int64 `json:"payments"`
Blocks int64 `json:"blocks"`
PurgeOnly bool `json:"purgeOnly"`
PurgeInterval string `json:"purgeInterval"`
}
type ApiServer struct {
config *ApiConfig
backend *storage.RedisClient
hashrateWindow time.Duration
hashrateLargeWindow time.Duration
stats atomic.Value
miners map[string]*Entry
minersMu sync.RWMutex
statsIntv time.Duration
}
type Entry struct {
stats map[string]interface{}
updatedAt int64
}
func NewApiServer(cfg *ApiConfig, backend *storage.RedisClient) *ApiServer {
hashrateWindow := MustParseDuration(cfg.HashrateWindow)
hashrateLargeWindow := MustParseDuration(cfg.HashrateLargeWindow)
return &ApiServer{
config: cfg,
backend: backend,
hashrateWindow: hashrateWindow,
hashrateLargeWindow: hashrateLargeWindow,
miners: make(map[string]*Entry),
}
}
func (s *ApiServer) Start() {
if s.config.PurgeOnly {
Info.Printf("Starting API in purge-only mode")
} else {
Info.Printf("Starting API on %v", s.config.Listen)
}
s.statsIntv = MustParseDuration(s.config.StatsCollectInterval)
statsTimer := time.NewTimer(s.statsIntv)
Info.Printf("Set stats collect interval to %v", s.statsIntv)
purgeIntv := MustParseDuration(s.config.PurgeInterval)
purgeTimer := time.NewTimer(purgeIntv)
Info.Printf("Set purge interval to %v", purgeIntv)
sort.Ints(s.config.LuckWindow)
if s.config.PurgeOnly {
s.purgeStale()
} else {
s.purgeStale()
s.collectStats()
}
go func() {
for {
select {
case <-statsTimer.C:
if !s.config.PurgeOnly {
s.collectStats()
}
statsTimer.Reset(s.statsIntv)
case <-purgeTimer.C:
s.purgeStale()
purgeTimer.Reset(purgeIntv)
}
}
}()
if !s.config.PurgeOnly {
s.listen()
}
}
func (s *ApiServer) listen() {
r := mux.NewRouter()
r.HandleFunc("/api/stats", s.StatsIndex)
r.HandleFunc("/api/miners", s.MinersIndex)
r.HandleFunc("/api/blocks", s.BlocksIndex)
r.HandleFunc("/api/payments", s.PaymentsIndex)
r.HandleFunc("/api/accounts/{login:0x[0-9a-fA-F]{40}}", s.AccountIndex)
r.NotFoundHandler = http.HandlerFunc(notFound)
err := http.ListenAndServe(s.config.Listen, r)
if err != nil {
Error.Fatalf("Failed to start API: %v", err)
}
}
func notFound(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusNotFound)
}
func (s *ApiServer) purgeStale() {
start := time.Now()
total, err := s.backend.FlushStaleStats(s.hashrateWindow, s.hashrateLargeWindow)
if err != nil {
Error.Println("Failed to purge stale data from backend:", err)
} else {
Info.Printf("Purged stale stats from backend, %v shares affected, elapsed time %v", total, time.Since(start))
}
}
func (s *ApiServer) collectStats() {
start := time.Now()
stats, err := s.backend.CollectStats(s.hashrateWindow, s.config.Blocks, s.config.Payments)
if err != nil {
Error.Printf("Failed to fetch stats from backend: %v", err)
return
}
if len(s.config.LuckWindow) > 0 {
stats["luck"], err = s.backend.CollectLuckStats(s.config.LuckWindow)
if err != nil {
Error.Printf("Failed to fetch luck stats from backend: %v", err)
return
}
}
s.stats.Store(stats)
Info.Printf("Stats collection finished %s", time.Since(start))
}
func (s *ApiServer) StatsIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
reply := make(map[string]interface{})
nodes, err := s.backend.GetNodeStates()
if err != nil {
Error.Printf("Failed to get nodes stats from backend: %v", err)
}
reply["nodes"] = nodes
stats := s.getStats()
if stats != nil {
reply["now"] = MakeTimestamp()
reply["stats"] = stats["stats"]
reply["hashrate"] = stats["hashrate"]
reply["minersTotal"] = stats["minersTotal"]
reply["maturedTotal"] = stats["maturedTotal"]
reply["immatureTotal"] = stats["immatureTotal"]
reply["candidatesTotal"] = stats["candidatesTotal"]
}
err = json.NewEncoder(w).Encode(reply)
if err != nil {
Error.Println("Error serializing API response: ", err)
}
}
func (s *ApiServer) MinersIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
reply := make(map[string]interface{})
stats := s.getStats()
if stats != nil {
reply["now"] = MakeTimestamp()
reply["miners"] = stats["miners"]
reply["hashrate"] = stats["hashrate"]
reply["minersTotal"] = stats["minersTotal"]
}
err := json.NewEncoder(w).Encode(reply)
if err != nil {
Error.Println("Error serializing API response: ", err)
}
}
func (s *ApiServer) BlocksIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
reply := make(map[string]interface{})
stats := s.getStats()
if stats != nil {
reply["matured"] = stats["matured"]
reply["maturedTotal"] = stats["maturedTotal"]
reply["immature"] = stats["immature"]
reply["immatureTotal"] = stats["immatureTotal"]
reply["candidates"] = stats["candidates"]
reply["candidatesTotal"] = stats["candidatesTotal"]
reply["luck"] = stats["luck"]
}
err := json.NewEncoder(w).Encode(reply)
if err != nil {
Error.Println("Error serializing API response: ", err)
}
}
func (s *ApiServer) PaymentsIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
reply := make(map[string]interface{})
stats := s.getStats()
if stats != nil {
reply["payments"] = stats["payments"]
reply["paymentsTotal"] = stats["paymentsTotal"]
}
err := json.NewEncoder(w).Encode(reply)
if err != nil {
Error.Println("Error serializing API response: ", err)
}
}
func (s *ApiServer) AccountIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
login := strings.ToLower(mux.Vars(r)["login"])
s.minersMu.Lock()
defer s.minersMu.Unlock()
reply, ok := s.miners[login]
now := MakeTimestamp()
cacheIntv := int64(s.statsIntv / time.Millisecond)
// Refresh stats if stale
if !ok || reply.updatedAt < now-cacheIntv {
exist, err := s.backend.IsMinerExists(login)
if !exist {
w.WriteHeader(http.StatusNotFound)
return
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Error.Printf("Failed to fetch stats from backend: %v", err)
return
}
stats, err := s.backend.GetMinerStats(login, s.config.Payments)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Error.Printf("Failed to fetch stats from backend: %v", err)
return
}
workers, err := s.backend.CollectWorkersStats(s.hashrateWindow, s.hashrateLargeWindow, login)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Error.Printf("Failed to fetch stats from backend: %v", err)
return
}
for key, value := range workers {
stats[key] = value
}
stats["pageSize"] = s.config.Payments
reply = &Entry{stats: stats, updatedAt: now}
s.miners[login] = reply
}
w.WriteHeader(http.StatusOK)
err := json.NewEncoder(w).Encode(reply.stats)
if err != nil {
Error.Println("Error serializing API response: ", err)
}
}
func (s *ApiServer) getStats() map[string]interface{} {
stats := s.stats.Load()
if stats != nil {
return stats.(map[string]interface{})
}
return nil
}