/
procd.go
106 lines (88 loc) · 1.88 KB
/
procd.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
package main
import (
"flag"
"http"
"io"
"io/ioutil"
"log"
"net"
"rpc"
"rpc/jsonrpc"
"sync"
"time"
"github.com/bytbox/procfs.go/procfs"
)
var pfs *procfs.ProcFS
var pfsMutex sync.Mutex
var interval = flag.Int64("interval", 10, "update interval")
var http_port = flag.String("http", ":6070", "HTTP service port")
func main() {
flag.Parse()
go updater()
go serveHTTP()
<-make(chan int)
}
// Maintain an updated version of ProcFS
func updater() {
ticker := time.Tick(1e9 * *interval)
for true {
log.Print("Updating...")
sn := time.Nanoseconds()
var pfs2 procfs.ProcFS
pfs2.Fill()
pfsMutex.Lock()
pfs = &pfs2
pfsMutex.Unlock()
en := time.Nanoseconds()
log.Print("Done in ", (en-sn)/1000, "μs")
<-ticker
}
}
type ProcFSServer struct {}
func (ProcFSServer) Get(req string, reply **procfs.ProcFS) error {
*reply = pfs
return nil
}
func serveHTTP() {
server := ProcFSServer{}
rpc.RegisterName("ProcFS", server)
http.HandleFunc("/", HTMLServer)
http.HandleFunc("/rpc", RPCServer)
err := http.ListenAndServe(*http_port, http.DefaultServeMux)
if err != nil {
log.Print("ERR: ", err)
}
}
func HTMLServer(w http.ResponseWriter, req *http.Request) {
c, err := ioutil.ReadFile("proc.html")
if err != nil {
log.Fatal("ERR: html/index.html not openable")
return
}
w.Write(c)
}
type combo struct{
a net.Conn
b io.ReadWriter
}
func (c combo) Close() error {
return c.a.Close()
}
func (c combo) Read(b []byte) (int, error) {
return c.b.Read(b)
}
func (c combo) Write(b []byte) (int, error) {
return c.a.Write(b)
}
func RPCServer(w http.ResponseWriter, req *http.Request) {
h, buf, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Print("ERR: ", err)
}
connected := "200 Connected to JSON-RPC"
io.WriteString(h, "HTTP/1.0 "+connected+"\n\n")
log.Print("Serving")
codec := jsonrpc.NewServerCodec(combo{h, buf})
rpc.ServeRequest(codec)
h.Close()
}