forked from quarnster/completion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.go
105 lines (94 loc) · 2 KB
/
daemon.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 (
"code.google.com/p/log4go"
"flag"
"github.com/quarnster/completion/clang"
"github.com/quarnster/completion/content"
"github.com/quarnster/completion/java"
cnet "github.com/quarnster/completion/net"
"github.com/robmerrell/comandante"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"runtime/debug"
"time"
)
var (
port = ":12345"
)
func init() {
daemon := comandante.NewCommand("daemon", "Run rpc daemon", runRpcDaemon)
daemon.FlagInit = daemonFlagInit
bin.RegisterCommand(daemon)
}
func daemonFlagInit(fs *flag.FlagSet) {
fs.StringVar(&port, "port", port, "TCP port the server will listen on")
}
type Daemon struct {
l net.Listener
server *rpc.Server
}
func (d *Daemon) init() error {
ifs := []interface{}{
&content.Session{},
&clang.Clang{},
&java.Java{},
&cnet.Net{},
}
d.server = rpc.NewServer()
for _, i := range ifs {
if err := d.server.Register(i); err != nil {
return err
}
}
var err error
d.l, err = net.Listen("tcp", port)
if err != nil {
return err
}
return nil
}
func (d *Daemon) close() error {
return d.l.Close()
}
func runRpcDaemon() error {
var (
d Daemon
err error
)
if err = d.init(); err != nil {
return err
}
return d.serverloop()
}
func (d *Daemon) serverloop() error {
errorcount := 0
for {
if conn, err := d.l.Accept(); err != nil {
errorcount++
log4go.Error("Error accepting connection: %s", err)
if errorcount > 10 {
return log4go.Error("Too many errors, shutting server down")
}
} else {
go func() {
s := time.Now()
conn.SetDeadline(time.Time{})
codec := jsonrpc.NewServerCodec(conn)
defer func() {
codec.Close()
if r := recover(); r != nil {
log4go.Error("Recovered from panic: %v, stack: %s", r, string(debug.Stack()))
}
log4go.Debug("Serviced in %f milliseconds", time.Since(s).Seconds()*1000)
}()
for {
if err := d.server.ServeRequest(codec); err != nil {
log4go.Error("Error handling request: %v", err)
break
}
}
}()
}
}
}