-
Notifications
You must be signed in to change notification settings - Fork 136
/
server.go
273 lines (222 loc) · 7.01 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
package http
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/pactus-project/pactus/types/amount"
"github.com/pactus-project/pactus/util/logger"
"github.com/pactus-project/pactus/www/grpc/basicauth"
pactus "github.com/pactus-project/pactus/www/grpc/gen/go"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
)
type Server struct {
ctx context.Context
cancel context.CancelFunc
config *Config
router *mux.Router
grpcClient *grpc.ClientConn
enableAuth bool
httpServer *http.Server
blockchain pactus.BlockchainClient
transaction pactus.TransactionClient
network pactus.NetworkClient
listener net.Listener
logger *logger.SubLogger
}
func NewServer(conf *Config, enableAuth bool) *Server {
ctx, cancel := context.WithCancel(context.Background())
return &Server{
ctx: ctx,
cancel: cancel,
config: conf,
enableAuth: enableAuth,
logger: logger.NewSubLogger("_http", nil),
}
}
func (s *Server) StartServer(grpcServer string) error {
if !s.config.Enable {
return nil
}
conn, err := grpc.NewClient(
grpcServer,
grpc.WithBlock(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
return fmt.Errorf("failed to dial server: %w", err)
}
s.grpcClient = conn
s.blockchain = pactus.NewBlockchainClient(conn)
s.transaction = pactus.NewTransactionClient(conn)
s.network = pactus.NewNetworkClient(conn)
s.router = mux.NewRouter()
s.router.HandleFunc("/", s.RootHandler)
s.router.HandleFunc("/blockchain/", s.BlockchainHandler)
s.router.HandleFunc("/consensus", s.ConsensusHandler)
s.router.HandleFunc("/network", s.NetworkHandler)
s.router.HandleFunc("/node", s.NodeHandler)
s.router.HandleFunc("/block/hash/{hash}", s.GetBlockByHashHandler)
s.router.HandleFunc("/block/height/{height}", s.GetBlockByHeightHandler)
s.router.HandleFunc("/transaction/id/{id}", s.GetTransactionHandler)
s.router.HandleFunc("/account/address/{address}", s.GetAccountHandler)
s.router.HandleFunc("/validator/address/{address}", s.GetValidatorHandler)
s.router.HandleFunc("/validator/number/{number}", s.GetValidatorByNumberHandler)
s.router.HandleFunc("/metrics/prometheus", promhttp.Handler().ServeHTTP)
http.Handle("/", handlers.RecoveryHandler()(s.router))
listener, err := net.Listen("tcp", s.config.Listen)
if err != nil {
return err
}
s.logger.Info("http started listening", "address", listener.Addr().String())
s.listener = listener
s.httpServer = &http.Server{
Addr: listener.Addr().String(),
ReadHeaderTimeout: 3 * time.Second,
}
go func() {
for {
select {
case <-s.ctx.Done():
return
default:
err := s.httpServer.Serve(listener)
if err != nil {
s.logger.Error("error on a connection", "error", err)
}
}
}
}()
return nil
}
func (s *Server) StopServer() {
s.cancel()
s.logger.Debug("context closed", "reason", s.ctx.Err())
if s.httpServer != nil {
_ = s.httpServer.Shutdown(s.ctx)
s.httpServer.Close()
s.listener.Close()
}
if s.grpcClient != nil {
s.grpcClient.Close()
}
}
func (s *Server) RootHandler(w http.ResponseWriter, r *http.Request) {
if s.enableAuth {
if _, _, ok := r.BasicAuth(); !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
}
buf := new(bytes.Buffer)
buf.WriteString("<html><body><br>")
err := s.router.Walk(func(route *mux.Route, _ *mux.Router, _ []*mux.Route) error {
pathTemplate, err := route.GetPathTemplate()
if err == nil {
link := pathTemplate
i := strings.Index(link, "{")
if i != -1 {
link = link[0:i]
}
fmt.Fprintf(buf, "<a href=\"%s\">%s</a></br>", link, pathTemplate)
}
return nil
})
if err != nil {
s.logger.Error("unable to walk through methods", "error", err)
return
}
buf.WriteString("</body></html>")
s.writeHTML(w, buf.String())
}
func (s *Server) writeError(w http.ResponseWriter, err error) int {
s.logger.Error("an error occurred", "error", err)
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusBadRequest)
n, _ := io.WriteString(w, err.Error())
return n
}
func (s *Server) writeHTML(w http.ResponseWriter, html string) int {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
n, _ := io.WriteString(w, html)
return n
}
func (s *Server) basicAuth(ctx context.Context, username, password string) context.Context {
ba := basicauth.New(username, password)
tokens, _ := ba.GetRequestMetadata(ctx)
md := metadata.New(tokens)
return metadata.NewOutgoingContext(ctx, md)
}
type tableMaker struct {
w *bytes.Buffer
}
func newTableMaker() *tableMaker {
t := &tableMaker{
w: bytes.NewBufferString("<table>"),
}
return t
}
func (t *tableMaker) addRowBlockHash(key string, val []byte) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td><a href=\"/block/hash/%x\">%x</a></td></tr>", key, val, val)
}
func (t *tableMaker) addRowAccAddress(key, val string) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td><a href=\"/account/address/%s\">%s</a></td></tr>", key, val, val)
}
func (t *tableMaker) addRowValAddress(key, val string) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td><a href=\"/validator/address/%s\">%s</a></td></tr>", key, val, val)
}
func (t *tableMaker) addRowTxID(key string, val []byte) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td><a href=\"/transaction/id/%x\">%x</a></td></tr>", key, val, val)
}
func (t *tableMaker) addRowString(key, val string) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%s</td></tr>", key, val)
}
func (t *tableMaker) addRowStrings(key string, val []string) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%v</td></tr>", key, strings.Join(val, ","))
}
func (t *tableMaker) addRowTime(key string, sec int64) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%s</td></tr>", key, time.Unix(sec, 0).String())
}
func (t *tableMaker) addRowAmount(key string, amt amount.Amount) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%s</td></tr>",
key, amt.String())
}
func (t *tableMaker) addRowPower(key string, power int64) {
amt := amount.Amount(power)
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%s</td></tr>",
key, amt.String())
}
func (t *tableMaker) addRowInt(key string, val int) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%d</td></tr>", key, val)
}
func (t *tableMaker) addRowBool(key string, val bool) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%v</td></tr>", key, val)
}
func (t *tableMaker) addRowInts(key string, vals []int32) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>", key)
for _, n := range vals {
fmt.Fprintf(t.w, "%d, ", n)
}
t.w.WriteString("</td></tr>")
}
func (t *tableMaker) addRowBytes(key string, val []byte) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%x</td></tr>", key, val)
}
func (t *tableMaker) addRowDouble(key string, val float64) {
fmt.Fprintf(t.w, "<tr><td>%s</td><td>%f</td></tr>", key, val)
}
func (t *tableMaker) html() string {
t.w.WriteString("</table>")
return t.w.String()
}