Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 85 lines (68 sloc) 1.507 kb
718f5e6b »
2012-07-06 Wrapper for RPC server configuration and lifecycle
1 // Copyright (c) 2012 VMware, Inc.
2
3 // Wrapper for RPC server configuration and lifecycle
4
5 package gonit
6
7 import (
8 "fmt"
9 "net"
10 "net/rpc/jsonrpc"
11 "net/url"
12 "os"
13 )
14
15 type RpcServer struct {
16 listener net.Listener
17 cleanup func()
18 }
19
20 // Construct a new RpcServer via string URL
21 // Currently supporting json RPC over unix or tcp socket
22 func NewRpcServer(listenURL string) (*RpcServer, error) {
23 var listener net.Listener
24 var cleanup func()
25
26 url, err := url.Parse(listenURL)
27 if err != nil {
28 return nil, err
29 }
30
31 switch url.Scheme {
32 case "tcp":
33 if url.Host == "" {
34 err = fmt.Errorf("Invalid URL %q", listenURL)
35 } else {
36 listener, err = net.Listen("tcp", url.Host)
37 }
38 case "", "unix":
81ee759c »
2012-09-25 Fix gonit unix socket bug.
39 // If the file already exists, we need to remove it otherwise gonit can't
40 // start.
41 os.Remove(url.Path)
718f5e6b »
2012-07-06 Wrapper for RPC server configuration and lifecycle
42 listener, err = net.Listen("unix", url.Path)
43 cleanup = func() { os.Remove(url.Path) }
44 default:
45 err = net.UnknownNetworkError(url.Scheme)
46 }
47
48 if err != nil {
49 return nil, err
50 }
51
52 server := &RpcServer{
53 listener: listener,
54 cleanup: cleanup,
55 }
56
57 return server, nil
58 }
59
60 // Close listener socket
61 // In the case of unix socket, remove socket file.
62 func (s *RpcServer) Shutdown() {
63 s.listener.Close()
64 if s.cleanup != nil {
65 s.cleanup()
66 }
67 }
68
69 // Accept unix|tcp connections and serve json RPCs
70 func (s *RpcServer) Serve() error {
71 defer s.Shutdown()
72
73 for {
74 conn, err := s.listener.Accept()
75
76 if err != nil {
77 return err
78 }
79
80 go jsonrpc.ServeConn(conn)
81 }
82
83 panic("not reached")
84 }
Something went wrong with that request. Please try again.