/
nsqadmin.go
73 lines (63 loc) · 1.89 KB
/
nsqadmin.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
package main
import (
"bytes"
"encoding/json"
"log"
"net"
"net/http"
"time"
"github.com/bitly/nsq/util"
)
type NSQAdmin struct {
options *nsqadminOptions
httpAddr *net.TCPAddr
httpListener net.Listener
waitGroup util.WaitGroupWrapper
notifications chan *AdminAction
}
func NewNSQAdmin(options *nsqadminOptions) *NSQAdmin {
if len(options.NSQDHTTPAddresses) == 0 && len(options.NSQLookupdHTTPAddresses) == 0 {
log.Fatalf("--nsqd-http-address or --lookupd-http-address required.")
}
if len(options.NSQDHTTPAddresses) != 0 && len(options.NSQLookupdHTTPAddresses) != 0 {
log.Fatalf("use --nsqd-http-address or --lookupd-http-address not both")
}
httpAddr, err := net.ResolveTCPAddr("tcp", options.HTTPAddress)
if err != nil {
log.Fatal(err)
}
return &NSQAdmin{
options: options,
httpAddr: httpAddr,
notifications: make(chan *AdminAction),
}
}
func (n *NSQAdmin) handleAdminActions() {
for action := range n.notifications {
content, err := json.Marshal(action)
if err != nil {
log.Printf("Error serializing admin action! %s", err)
}
httpclient := &http.Client{Transport: util.NewDeadlineTransport(10 * time.Second)}
log.Printf("Posting notification to %s", *notificationHTTPEndpoint)
_, err = httpclient.Post(*notificationHTTPEndpoint, "application/json", bytes.NewBuffer(content))
if err != nil {
log.Printf("Error posting notification: %s", err)
}
}
}
func (n *NSQAdmin) Main() {
httpListener, err := net.Listen("tcp", n.httpAddr.String())
if err != nil {
log.Fatalf("FATAL: listen (%s) failed - %s", n.httpAddr, err.Error())
}
n.httpListener = httpListener
httpServer := NewHTTPServer(&Context{n})
n.waitGroup.Wrap(func() { util.HTTPServer(n.httpListener, httpServer, "HTTP") })
n.waitGroup.Wrap(func() { n.handleAdminActions() })
}
func (n *NSQAdmin) Exit() {
n.httpListener.Close()
close(n.notifications)
n.waitGroup.Wait()
}