/
quartz.go
91 lines (80 loc) · 1.96 KB
/
quartz.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
package quartz
import (
"fmt"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"os"
"os/signal"
"reflect"
"strings"
"syscall"
)
// Quartz holds information about exported structs.
type Quartz struct {
Registry *Registry
}
func newQuartz() *Quartz {
return &Quartz{newRegistry()}
}
// RegisterName exports a struct via RPC and generates metadata for
// each of the struct's methods.
func (q *Quartz) RegisterName(name string, s interface{}) error {
q.Registry.data[name] = newStructMetadata(s)
t := reflect.TypeOf(s)
for i := 0; i < t.NumMethod(); i++ {
method := t.Method(i)
// TODO: only export methods with JSON serializable arguments
// and responses.
metadata := &methodMetadata{
method,
structFieldToType(method.Type.In(1)),
}
q.Registry.data[name].NameToMethodMetadata[method.Name] = metadata
}
return rpc.RegisterName(name, s)
}
// Start launches the server.
func (q *Quartz) Start() {
// The Ruby gem sets this environment variable for us.
socketPath := "/tmp/quartz.socket"
if os.Getenv("QUARTZ_SOCKET") != "" {
socketPath = os.Getenv("QUARTZ_SOCKET")
}
// Start the server and accept connections on a
// UNIX domain socket.
rpc.RegisterName("Quartz", q.Registry)
listener, err := net.Listen("unix", socketPath)
if err != nil {
panic(err)
}
// Destroy the socket file when the server is killed.
sigc := make(chan os.Signal)
signal.Notify(sigc, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)
go func() {
<-sigc
listener.Close()
os.Remove(socketPath)
os.Exit(0)
}()
// Accept connections
for {
conn, err := listener.Accept()
if err != nil {
// The connection was closed by a signal.
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
fmt.Fprintf(os.Stderr, "error accepting connection: %s", err)
continue
}
go func() {
defer func() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "Recovered from panic: %s", r)
}
}()
jsonrpc.ServeConn(conn)
}()
}
}