-
Notifications
You must be signed in to change notification settings - Fork 105
/
nsqd.go
400 lines (344 loc) · 9.46 KB
/
nsqd.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package main
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/bitly/go-nsq"
"github.com/bitly/go-simplejson"
"github.com/bitly/nsq/util"
"github.com/bitly/nsq/util/lookupd"
)
type NSQD struct {
// 64bit atomic vars need to be first for proper alignment on 32bit platforms
clientIDSequence int64
sync.RWMutex
options *nsqdOptions
topicMap map[string]*Topic
lookupPeers []*LookupPeer
tcpAddr *net.TCPAddr
httpAddr *net.TCPAddr
tcpListener net.Listener
httpListener net.Listener
tlsConfig *tls.Config
idChan chan nsq.MessageID
notifyChan chan interface{}
exitChan chan int
waitGroup util.WaitGroupWrapper
}
func NewNSQD(options *nsqdOptions) *NSQD {
var tlsConfig *tls.Config
if options.MaxDeflateLevel < 1 || options.MaxDeflateLevel > 9 {
log.Fatalf("--max-deflate-level must be [1,9]")
}
tcpAddr, err := net.ResolveTCPAddr("tcp", options.TCPAddress)
if err != nil {
log.Fatal(err)
}
httpAddr, err := net.ResolveTCPAddr("tcp", options.HTTPAddress)
if err != nil {
log.Fatal(err)
}
if options.StatsdPrefix != "" {
statsdHostKey := util.StatsdHostKey(net.JoinHostPort(options.BroadcastAddress,
strconv.Itoa(httpAddr.Port)))
prefixWithHost := strings.Replace(options.StatsdPrefix, "%s", statsdHostKey, -1)
if prefixWithHost[len(prefixWithHost)-1] != '.' {
prefixWithHost += "."
}
options.StatsdPrefix = prefixWithHost
}
if options.TLSCert != "" || options.TLSKey != "" {
cert, err := tls.LoadX509KeyPair(options.TLSCert, options.TLSKey)
if err != nil {
log.Fatalf("ERROR: failed to LoadX509KeyPair %s", err.Error())
}
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.VerifyClientCertIfGiven,
}
tlsConfig.BuildNameToCertificate()
}
n := &NSQD{
options: options,
tcpAddr: tcpAddr,
httpAddr: httpAddr,
topicMap: make(map[string]*Topic),
idChan: make(chan nsq.MessageID, 4096),
exitChan: make(chan int),
notifyChan: make(chan interface{}),
tlsConfig: tlsConfig,
}
n.waitGroup.Wrap(func() { n.idPump() })
return n
}
func (n *NSQD) Main() {
context := &Context{n}
n.waitGroup.Wrap(func() { n.lookupLoop() })
tcpListener, err := net.Listen("tcp", n.tcpAddr.String())
if err != nil {
log.Fatalf("FATAL: listen (%s) failed - %s", n.tcpAddr, err.Error())
}
n.tcpListener = tcpListener
tcpServer := &tcpServer{context: context}
n.waitGroup.Wrap(func() { util.TCPServer(n.tcpListener, tcpServer) })
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 := &httpServer{context: context}
n.waitGroup.Wrap(func() { util.HTTPServer(n.httpListener, httpServer) })
if n.options.StatsdAddress != "" {
n.waitGroup.Wrap(func() { n.statsdLoop() })
}
}
func (n *NSQD) LoadMetadata() {
fn := fmt.Sprintf(path.Join(n.options.DataPath, "nsqd.%d.dat"), n.options.ID)
data, err := ioutil.ReadFile(fn)
if err != nil {
if !os.IsNotExist(err) {
log.Printf("ERROR: failed to read channel metadata from %s - %s", fn, err.Error())
}
return
}
js, err := simplejson.NewJson(data)
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
topics, err := js.Get("topics").Array()
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
for ti := range topics {
topicJs := js.Get("topics").GetIndex(ti)
topicName, err := topicJs.Get("name").String()
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
if !nsq.IsValidTopicName(topicName) {
log.Printf("WARNING: skipping creation of invalid topic %s", topicName)
continue
}
topic := n.GetTopic(topicName)
paused, _ := topicJs.Get("paused").Bool()
if paused {
topic.Pause()
}
channels, err := topicJs.Get("channels").Array()
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
for ci := range channels {
channelJs := topicJs.Get("channels").GetIndex(ci)
channelName, err := channelJs.Get("name").String()
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
if !nsq.IsValidChannelName(channelName) {
log.Printf("WARNING: skipping creation of invalid channel %s", channelName)
continue
}
channel := topic.GetChannel(channelName)
paused, _ = channelJs.Get("paused").Bool()
if paused {
channel.Pause()
}
}
}
}
func (n *NSQD) PersistMetadata() error {
// persist metadata about what topics/channels we have
// so that upon restart we can get back to the same state
fileName := fmt.Sprintf(path.Join(n.options.DataPath, "nsqd.%d.dat"), n.options.ID)
log.Printf("NSQ: persisting topic/channel metadata to %s", fileName)
js := make(map[string]interface{})
topics := make([]interface{}, 0)
for _, topic := range n.topicMap {
topicData := make(map[string]interface{})
topicData["name"] = topic.name
topicData["paused"] = topic.IsPaused()
channels := make([]interface{}, 0)
topic.Lock()
for _, channel := range topic.channelMap {
channel.Lock()
if !channel.ephemeralChannel {
channelData := make(map[string]interface{})
channelData["name"] = channel.name
channelData["paused"] = channel.IsPaused()
channels = append(channels, channelData)
}
channel.Unlock()
}
topic.Unlock()
topicData["channels"] = channels
topics = append(topics, topicData)
}
js["version"] = util.BINARY_VERSION
js["topics"] = topics
data, err := json.Marshal(&js)
if err != nil {
return err
}
tmpFileName := fileName + ".tmp"
f, err := os.OpenFile(tmpFileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
_, err = f.Write(data)
if err != nil {
f.Close()
return err
}
f.Sync()
f.Close()
err = os.Rename(tmpFileName, fileName)
if err != nil {
return err
}
return nil
}
func (n *NSQD) Exit() {
if n.tcpListener != nil {
n.tcpListener.Close()
}
if n.httpListener != nil {
n.httpListener.Close()
}
n.Lock()
err := n.PersistMetadata()
if err != nil {
log.Printf("ERROR: failed to persist metadata - %s", err.Error())
}
log.Printf("NSQ: closing topics")
for _, topic := range n.topicMap {
topic.Close()
}
n.Unlock()
// we want to do this last as it closes the idPump (if closed first it
// could potentially starve items in process and deadlock)
close(n.exitChan)
n.waitGroup.Wait()
}
// GetTopic performs a thread safe operation
// to return a pointer to a Topic object (potentially new)
func (n *NSQD) GetTopic(topicName string) *Topic {
n.Lock()
t, ok := n.topicMap[topicName]
if ok {
n.Unlock()
return t
} else {
t = NewTopic(topicName, &Context{n})
n.topicMap[topicName] = t
log.Printf("TOPIC(%s): created", t.name)
// release our global nsqd lock, and switch to a more granular topic lock while we init our
// channels from lookupd. This blocks concurrent PutMessages to this topic.
t.Lock()
n.Unlock()
// if using lookupd, make a blocking call to get the topics, and immediately create them.
// this makes sure that any message received is buffered to the right channels
if len(n.lookupPeers) > 0 {
channelNames, _ := lookupd.GetLookupdTopicChannels(t.name, n.lookupHttpAddrs())
for _, channelName := range channelNames {
t.getOrCreateChannel(channelName)
}
}
t.Unlock()
// NOTE: I would prefer for this to only happen in topic.GetChannel() but we're special
// casing the code above so that we can control the locks such that it is impossible
// for a message to be written to a (new) topic while we're looking up channels
// from lookupd...
//
// update messagePump state
select {
case t.channelUpdateChan <- 1:
case <-t.exitChan:
}
}
return t
}
// GetExistingTopic gets a topic only if it exists
func (n *NSQD) GetExistingTopic(topicName string) (*Topic, error) {
n.RLock()
defer n.RUnlock()
topic, ok := n.topicMap[topicName]
if !ok {
return nil, errors.New("topic does not exist")
}
return topic, nil
}
// DeleteExistingTopic removes a topic only if it exists
func (n *NSQD) DeleteExistingTopic(topicName string) error {
n.RLock()
topic, ok := n.topicMap[topicName]
if !ok {
n.RUnlock()
return errors.New("topic does not exist")
}
n.RUnlock()
// delete empties all channels and the topic itself before closing
// (so that we dont leave any messages around)
//
// we do this before removing the topic from map below (with no lock)
// so that any incoming writes will error and not create a new topic
// to enforce ordering
topic.Delete()
n.Lock()
delete(n.topicMap, topicName)
n.Unlock()
return nil
}
func (n *NSQD) idPump() {
factory := &GUIDFactory{}
lastError := time.Now()
for {
id, err := factory.NewGUID(n.options.ID)
if err != nil {
now := time.Now()
if now.Sub(lastError) > time.Second {
// only print the error once/second
log.Printf("ERROR: %s", err.Error())
lastError = now
}
runtime.Gosched()
continue
}
select {
case n.idChan <- id.Hex():
case <-n.exitChan:
goto exit
}
}
exit:
log.Printf("ID: closing")
}
func (n *NSQD) Notify(v interface{}) {
// by selecting on exitChan we guarantee that
// we do not block exit, see issue #123
select {
case <-n.exitChan:
case n.notifyChan <- v:
n.Lock()
err := n.PersistMetadata()
if err != nil {
log.Printf("ERROR: failed to persist metadata - %s", err.Error())
}
n.Unlock()
}
}