-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrpcserver.go
More file actions
69 lines (56 loc) · 1.32 KB
/
rpcserver.go
File metadata and controls
69 lines (56 loc) · 1.32 KB
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
package main
import (
"github.com/pkg/errors"
"log"
"net"
"net/http"
"net/rpc"
"os"
)
type CommandQueue interface {
Enqueue(cmd *Command) (*EnqueuedCommand, error)
}
type Server struct {
commandQueue CommandQueue
sockAddress string
}
func (s *Server) Enqueue(cmd *Command, reply *EnqueuedCommand) error {
enqueued, err := s.commandQueue.Enqueue(cmd)
*reply = *enqueued
return err
}
func (s *Server) sendCommand(cmd *Command) (*EnqueuedCommand, error) {
client, err := rpc.DialHTTP("unix", s.sockAddress)
if err != nil {
return nil, err
}
log.Println("connected. assuming client role")
defer client.Close()
var reply *EnqueuedCommand
err = client.Call("Server.Enqueue", cmd, &reply)
if err != nil {
return nil, errors.Wrap(err, "send command to server")
}
return reply, nil
}
func (s *Server) serve(stopCh <-chan bool) error {
err := rpc.Register(s)
if err != nil {
log.Fatal("failed to set up rpc:", err)
}
rpc.HandleHTTP()
if err := os.RemoveAll(s.sockAddress); err != nil {
log.Printf("failed to remove old socket file: %s\n", err)
}
log.Println("assuming server role")
sock, err := net.Listen("unix", s.sockAddress)
if err != nil {
log.Fatalf("failed to listen: %s\n", err)
}
log.Println("listening on", s.sockAddress)
go func() {
<-stopCh
sock.Close()
}()
return http.Serve(sock, nil)
}