Debian Codegraph @

go/examples/proton/broker.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 //
21 // This is a simple AMQP broker implemented using the event-driven proton package.
22 //
23 // It maintains a set of named in-memory queues of messages. Clients can send
24 // messages to queues or subscribe to receive messages from them.
25 //
26
27 // TODO: show how to handle acknowledgements from receivers and put rejected or
28 // un-acknowledged messages back on their queues.
29
30 package main
31
32 import (
33 "flag"
34 "fmt"
35 "log"
36 "net"
37 "os"
38 "github.com/apache/qpid-proton/go/pkg/amqp"
39 "github.com/apache/qpid-proton/go/pkg/proton"
40 "sync"
41 )
42
43 // Usage and command-line flags
44 func usage() {
45 fmt.Fprintf(os.Stderr, `
46 Usage: %s
47 A simple broker-like demo. Queues are created automatically for sender or receiver addresses.
48 `, os.Args[0])
49 flag.PrintDefaults()
50 }
51
52 var addr = flag.String("addr", ":amqp", "Listening address")
53 var credit = flag.Int("credit", 100, "Receiver credit window")
54 var qsize = flag.Int("qsize", 1000, "Max queue size")
55 var debug = flag.Bool("debug", false, "Print detailed debug output")
56 var debugf = func(format string, data ...interface{}) {} // Default no debugging output
57
58 func main() {
59 flag.Usage = usage
60 flag.Parse()
61 if *debug {
62 debugf = func(format string, data ...interface{}) { log.Printf(format, data...) }
63 }
64 b := &broker{makeQueues(*qsize)}
65 if err := b.run(); err != nil {
66 log.Fatal(err)
67 }
68 }
69
70 // State for the broker
71 type broker struct {
72 queues queues
73 }
74
75 // Listens for connections and starts a proton.Engine for each one.
76 func (b *broker) run() error {
77 listener, err := net.Listen("tcp", *addr)
78 if err != nil {
79 return err
80 }
81 defer listener.Close()
82 fmt.Printf("Listening on %s\n", listener.Addr())
83 for {
84 conn, err := listener.Accept()
85 if err != nil {
86 debugf("Accept error: %v", err)
87 continue
88 }
89 adapter := proton.NewMessagingAdapter(newHandler(&b.queues))
90 // We want to accept messages when they are enqueued, not just when they
91 // are received, so we turn off auto-accept and prefetch by the adapter.
92 adapter.Prefetch = 0
93 adapter.AutoAccept = false
94 engine, err := proton.NewEngine(conn, adapter)
95 if err != nil {
96 debugf("Connection error: %v", err)
97 continue
98 }
99 engine.Server() // Enable server-side protocol negotiation.
100 debugf("Accepted connection %s", engine)
101 go func() { // Start goroutine to run the engine event loop
102 engine.Run()
103 debugf("Closed %s", engine)
104 }()
105 }
106 }
107
108 // handler handles AMQP events. There is one handler per connection. The
109 // handler does not need to be concurrent-safe as proton.Engine will serialize
110 // all calls to the handler. We use channels to communicate between the handler
111 // goroutine and other goroutines sending and receiving messages.
112 type handler struct {
113 queues *queues
114 receivers map[proton.Link]*receiver
115 senders map[proton.Link]*sender
116 injecter proton.Injecter
117 }
118
119 func newHandler(queues *queues) *handler {
120 return &handler{
121 queues: queues,
122 receivers: make(map[proton.Link]*receiver),
123 senders: make(map[proton.Link]*sender),
124 }
125 }
126
127 // HandleMessagingEvent handles an event, called in the handler goroutine.
128 func (h *handler) HandleMessagingEvent(t proton.MessagingEvent, e proton.Event) {
129 switch t {
130
131 case proton.MStart:
132 h.injecter = e.Injecter()
133
134 case proton.MLinkOpening:
135 if e.Link().IsReceiver() {
136 h.startReceiver(e)
137 } else {
138 h.startSender(e)
139 }
140
141 case proton.MLinkClosed:
142 h.linkClosed(e.Link(), e.Link().RemoteCondition().Error())
143
144 case proton.MSendable:
145 if s, ok := h.senders[e.Link()]; ok {
146 s.sendable() // Signal the send goroutine that we have credit.
147 } else {
148 proton.CloseError(e.Link(), amqp.Errorf(amqp.NotFound, "link %s sender not found", e.Link()))
149 }
150
151 case proton.MMessage:
152 m, err := e.Delivery().Message() // Message() must be called while handling the MMessage event.
153 if err != nil {
154 proton.CloseError(e.Link(), err)
155 break
156 }
157 r, ok := h.receivers[e.Link()]
158 if !ok {
159 proton.CloseError(e.Link(), amqp.Errorf(amqp.NotFound, "link %s receiver not found", e.Link()))
160 break
161 }
162 // This will not block as AMQP credit is set to the buffer capacity.
163 r.buffer <- receivedMessage{e.Delivery(), m}
164 debugf("link %s received %#v", e.Link(), m)
165
166 case proton.MConnectionClosed, proton.MDisconnected:
167 for l, _ := range h.receivers {
168 h.linkClosed(l, nil)
169 }
170 for l, _ := range h.senders {
171 h.linkClosed(l, nil)
172 }
173 }
174 }
175
176 // linkClosed is called when a link has been closed by both ends.
177 // It removes the link from the handlers maps and stops its goroutine.
178 func (h *handler) linkClosed(l proton.Link, err error) {
179 if s, ok := h.senders[l]; ok {
180 s.stop()
181 delete(h.senders, l)
182 } else if r, ok := h.receivers[l]; ok {
183 r.stop()
184 delete(h.receivers, l)
185 }
186 }
187
188 // link has some common data and methods that are used by the sender and receiver types.
189 //
190 // An active link is represented by a sender or receiver value and a goroutine
191 // running its run() method. The run() method communicates with the handler via
192 // channels.
193 type link struct {
194 l proton.Link
195 q queue
196 h *handler
197 }
198
199 func makeLink(l proton.Link, q queue, h *handler) link {
200 lnk := link{l: l, q: q, h: h}
201 return lnk
202 }
203
204 // receiver has a channel to buffer messages that have been received by the
205 // handler and are waiting to go on the queue. AMQP credit ensures that the
206 // handler does not overflow the buffer and block.
207 type receiver struct {
208 link
209 buffer chan receivedMessage
210 }
211
212 // receivedMessage holds a message and a Delivery so that the message can be
213 // acknowledged when it is put on the queue.
214 type receivedMessage struct {
215 delivery proton.Delivery
216 message amqp.Message
217 }
218
219 // startReceiver creates a receiver and a goroutine for its run() method.
220 func (h *handler) startReceiver(e proton.Event) {
221 q := h.queues.Get(e.Link().RemoteTarget().Address())
222 r := &receiver{
223 link: makeLink(e.Link(), q, h),
224 buffer: make(chan receivedMessage, *credit),
225 }
226 h.receivers[r.l] = r
227 r.l.Flow(cap(r.buffer)) // Give credit to fill the buffer to capacity.
228 go r.run()
229 }
230
231 // run runs in a separate goroutine. It moves messages from the buffer to the
232 // queue for a receiver link, and injects a handler function to acknowledge the
233 // message and send a credit.
234 func (r *receiver) run() {
235 for rm := range r.buffer {
236 r.q <- rm.message
237 d := rm.delivery
238 // We are not in the handler goroutine so we Inject the accept function as a closure.
239 r.h.injecter.Inject(func() {
240 // Check that the receiver is still open, it may have been closed by the remote end.
241 if r == r.h.receivers[r.l] {
242 d.Accept() // Accept the delivery
243 r.l.Flow(1) // Add one credit
244 }
245 })
246 }
247 }
248
249 // stop closes the buffer channel and waits for the run() goroutine to stop.
250 func (r *receiver) stop() {
251 close(r.buffer)
252 }
253
254 // sender has a channel that is used to signal when there is credit to send messages.
255 type sender struct {
256 link
257 credit chan struct{} // Channel to signal availability of credit.
258 }
259
260 // startSender creates a sender and starts a goroutine for sender.run()
261 func (h *handler) startSender(e proton.Event) {
262 q := h.queues.Get(e.Link().RemoteSource().Address())
263 s := &sender{
264 link: makeLink(e.Link(), q, h),
265 credit: make(chan struct{}, 1), // Capacity of 1 for signalling.
266 }
267 h.senders[e.Link()] = s
268 go s.run()
269 }
270
271 // stop closes the credit channel and waits for the run() goroutine to stop.
272 func (s *sender) stop() {
273 close(s.credit)
274 }
275
276 // sendable signals that the sender has credit, it does not block.
277 // sender.credit has capacity 1, if it is already full we carry on.
278 func (s *sender) sendable() {
279 select { // Non-blocking
280 case s.credit <- struct{}{}:
281 default:
282 }
283 }
284
285 // run runs in a separate goroutine. It monitors the queue for messages and injects
286 // a function to send them when there is credit
287 func (s *sender) run() {
288 var q queue // q is nil initially as we have no credit.
289 for {
290 select {
291 case _, ok := <-s.credit:
292 if !ok { // sender closed
293 return
294 }
295 q = s.q // We have credit, enable selecting on the queue.
296
297 case m, ok := <-q: // q is only enabled when we have credit.
298 if !ok { // queue closed
299 return
300 }
301 q = nil // Assume all credit will be used used, will be signaled otherwise.
302 s.h.injecter.Inject(func() { // Inject handler function to actually send
303 if s.h.senders[s.l] != s { // The sender has been closed by the remote end.
304 q.PutBack(m) // Put the message back on the queue but don't block
305 return
306 }
307 if s.sendOne(m) != nil {
308 return
309 }
310 // Send as many more messages as we can without blocking
311 for s.l.Credit() > 0 {
312 select { // Non blocking receive from q
313 case m, ok := <-s.q:
314 if ok {
315 s.sendOne(m)
316 }
317 default: // Queue is empty but we have credit, signal the run() goroutine.
318 s.sendable()
319 }
320 }
321 })
322 }
323 }
324 }
325
326 // sendOne runs in the handler goroutine. It sends a single message.
327 func (s *sender) sendOne(m amqp.Message) error {
328 delivery, err := s.l.Send(m)
329 if err == nil {
330 delivery.Settle() // Pre-settled, unreliable.
331 debugf("link %s sent %#v", s.l, m)
332 } else {
333 s.q.PutBack(m) // Put the message back on the queue, don't block
334 }
335 return err
336 }
337
338 // Use a buffered channel as a very simple queue.
339 type queue chan amqp.Message
340
341 // Put a message back on the queue, does not block.
342 func (q queue) PutBack(m amqp.Message) {
343 select {
344 case q <- m:
345 default:
346 // Not an efficient implementation but ensures we don't block the caller.
347 go func() { q <- m }()
348 }
349 }
350
351 // Concurrent-safe map of queues.
352 type queues struct {
353 queueSize int
354 m map[string]queue
355 lock sync.Mutex
356 }
357
358 func makeQueues(queueSize int) queues {
359 return queues{queueSize: queueSize, m: make(map[string]queue)}
360 }
361
362 // Create a queue if not found.
363 func (qs *queues) Get(name string) queue {
364 qs.lock.Lock()
365 defer qs.lock.Unlock()
366 q := qs.m[name]
367 if q == nil {
368 q = make(queue, qs.queueSize)
369 qs.m[name] = q
370 }
371 return q
372 }