-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
78 lines (67 loc) · 1.39 KB
/
worker.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
package distribution
import (
"fmt"
"log"
"net"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
"net/url"
"strings"
"time"
)
type NodeServer struct {
conn *net.Conn
listener net.Listener
*rpc.Server
}
func (ns *NodeServer) HandleHTTP() {
ns.Server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
}
func (ns *NodeServer) Serve() error {
for {
conn, err := ns.listener.Accept()
if err != nil {
return err
}
go ns.Server.ServeCodec(jsonrpc.NewServerCodec(conn))
}
return nil
}
// Contact the master continuously.
func registerNodeToMaster(master string) *NodeServer {
server := rpc.NewServer()
l, err := net.Listen("tcp", ":0")
if err != nil {
log.Fatal(err)
}
// register to master
port := strings.Replace(l.Addr().String(), "[", "", -1)
port = strings.Replace(port, "]", "", -1)
port = strings.Replace(port, ":", "", -1)
u := url.URL{}
u.Host = master
u.Scheme = "http"
u.Path = RegisterEndpoint
q := u.Query()
q.Set("port", port)
u.RawQuery = q.Encode()
client := http.Client{
Timeout: time.Duration(10 * time.Second),
}
fmt.Println("Contact master", u.String())
_, err = client.Get(u.String())
if err != nil {
log.Fatal(err)
}
node := NodeServer{
Server: server,
listener: l,
}
return &node
}
// RegisterNode starts the node listening process.
func RegisterNode(master string) *NodeServer {
// cleanup port
return registerNodeToMaster(master)
}