-
Notifications
You must be signed in to change notification settings - Fork 113
/
admin_server.go
113 lines (100 loc) · 2.55 KB
/
admin_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
package p2p
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/iost-official/go-iost/ilog"
peer "github.com/libp2p/go-libp2p-peer"
)
type adminServer struct {
srv *http.Server
pm *PeerManager
}
func newAdminServer(port string, pm *PeerManager) *adminServer {
mux := http.NewServeMux()
as := &adminServer{
srv: &http.Server{
Addr: "127.0.0.1:" + port,
Handler: mux,
},
pm: pm,
}
as.registerRoute(mux)
return as
}
func (as *adminServer) Start() {
go func() {
if err := as.srv.ListenAndServe(); err != http.ErrServerClosed {
ilog.Errorf("p2p admin server start failed. err=%v", err)
}
}()
}
func (as *adminServer) Stop() {
ctx, _ := context.WithTimeout(context.Background(), time.Second) // nolint
as.srv.Shutdown(ctx)
}
func (as *adminServer) registerRoute(mux *http.ServeMux) {
mux.HandleFunc("/ping", Ping)
mux.HandleFunc("/stats", as.Stats)
mux.HandleFunc("/closepeer", as.ClosePeer)
mux.HandleFunc("/putipblack", as.PutIPBlack)
mux.HandleFunc("/putpidblack", as.PutPIDBlack)
}
// Ping returns a "pong" to client.
func Ping(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("pong"))
}
// Stats returns information of neighbors.
func (as *adminServer) Stats(rw http.ResponseWriter, r *http.Request) {
bytes, err := json.MarshalIndent(as.pm.NeighborStat(), "", " ")
if err != nil {
rw.Write([]byte(fmt.Sprintf("marshal error. err=%v", err)))
return
}
rw.Write(bytes)
}
// ClosePeer close the peer's connection.
func (as *adminServer) ClosePeer(rw http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
if len(params["pid"]) == 0 {
rw.Write([]byte("params error. pid is missed."))
return
}
pid := params["pid"][0]
peerID, err := peer.IDB58Decode(pid)
if err != nil {
rw.Write([]byte("invalid peer id"))
return
}
as.pm.RemoveNeighbor(peerID)
rw.Write([]byte("ok"))
}
// PutPIDBlack puts a ip to black list.
func (as *adminServer) PutPIDBlack(rw http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
if len(params["pid"]) == 0 {
rw.Write([]byte("params error. pid is missed."))
return
}
pid := params["pid"][0]
peerID, err := peer.IDB58Decode(pid)
if err != nil {
rw.Write([]byte("invalid peer id"))
return
}
as.pm.PutPIDToBlack(peerID)
rw.Write([]byte("ok"))
}
// PutIPBlack puts a ip to black list.
func (as *adminServer) PutIPBlack(rw http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
if len(params["ip"]) == 0 {
rw.Write([]byte("params error. ip is missed."))
return
}
ip := params["ip"][0]
as.pm.PutIPToBlack(ip)
rw.Write([]byte("ok"))
}