Debian Codegraph @

go/pkg/proton/engine.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 package proton
21
22 import (
23 "fmt"
24 "net"
25 "os"
26 "strings"
27 "sync"
28 "time"
29 "unsafe"
30 )
31
32 /*
33 #include <proton/connection.h>
34 #include <proton/event.h>
35 #include <proton/error.h>
36 #include <proton/handlers.h>
37 #include <proton/session.h>
38 #include <proton/transport.h>
39 #include <memory.h>
40 #include <stdlib.h>
41 */
42 import "C"
43
44 // Injecter allows functions to be "injected" into the event-processing loop, to
45 // be called in the same goroutine as event handlers.
46 type Injecter interface {
47 // Inject a function into the engine goroutine.
48 //
49 // f() will be called in the same goroutine as event handlers, so it can safely
50 // use values belonging to event handlers without synchronization. f() should
51 // not block, no further events or injected functions can be processed until
52 // f() returns.
53 //
54 // Returns a non-nil error if the function could not be injected and will
55 // never be called. Otherwise the function will eventually be called.
56 //
57 // Note that proton values (Link, Session, Connection etc.) that existed when
58 // Inject(f) was called may have become invalid by the time f() is executed.
59 // Handlers should handle keep track of Closed events to ensure proton values
60 // are not used after they become invalid. One technique is to have map from
61 // proton values to application values. Check that the map has the correct
62 // proton/application value pair at the start of the injected function and
63 // delete the value from the map when handling a Closed event.
64 Inject(f func()) error
65
66 // InjectWait is like Inject but does not return till f() has completed.
67 // If f() cannot be injected it returns the error from Inject(), otherwise
68 // it returns the error from f()
69 InjectWait(f func() error) error
70 }
71
72 // Engine reads from a net.Conn, decodes AMQP events and calls the appropriate
73 // Handler functions sequentially in a single goroutine. Actions taken by
74 // Handler functions (such as sending messages) are encoded and written to the
75 // net.Conn. You can create multiple Engines to handle multiple connections
76 // concurrently.
77 //
78 // You implement the EventHandler and/or MessagingHandler interfaces and provide
79 // those values to NewEngine(). Their HandleEvent method will be called in the
80 // event-handling goroutine.
81 //
82 // Handlers can pass values from an event (Connections, Links, Deliveries etc.) to
83 // other goroutines, store them, or use them as map indexes. Effectively they are
84 // just pointers. Other goroutines cannot call their methods directly but they can
85 // can create a function closure to call such methods and pass it to Engine.Inject()
86 // to have it evaluated in the engine goroutine.
87 //
88 // You are responsible for ensuring you don't use an event value after it is
89 // invalid. The handler methods will tell you when a value is no longer valid. For
90 // example after a LinkClosed event, that link is no longer valid. If you do
91 // Link.Close() yourself (in a handler or injected function) the link remains valid
92 // until the corresponding LinkClosed event is received by the handler.
93 //
94 // Engine.Close() will take care of cleaning up any remaining values when you are
95 // done with the Engine. All values associated with a engine become invalid when you
96 // call Engine.Close()
97 //
98 // The qpid.apache.org/proton/concurrent package will do all this for you, so it
99 // may be a better choice for some applications.
100 //
101 type Engine struct {
102 // Error is set on exit from Run() if there was an error.
103 err ErrorHolder
104 inject chan func()
105
106 conn net.Conn
107 connection Connection
108 transport Transport
109 collector *C.pn_collector_t
110 handlers []EventHandler // Handlers for proton events.
111 running chan struct{} // This channel will be closed when the goroutines are done.
112 closeOnce sync.Once
113 timer *time.Timer
114 traceEvent bool
115 reading, writing bool
116 }
117
118 const bufferSize = 4096
119
120 func envBool(name string) bool {
121 v := strings.ToLower(os.Getenv(name))
122 return v == "true" || v == "1" || v == "yes" || v == "on"
123 }
124
125 // Create a new Engine and call Initialize() with conn and handlers
126 func NewEngine(conn net.Conn, handlers ...EventHandler) (*Engine, error) {
127 eng := &Engine{}
128 return eng, eng.Initialize(conn, handlers...)
129 }
130
131 // Initialize an Engine with a connection and handlers. Start it with Run()
132 func (eng *Engine) Initialize(conn net.Conn, handlers ...EventHandler) error {
133 eng.inject = make(chan func())
134 eng.conn = conn
135 eng.connection = Connection{C.pn_connection()}
136 eng.transport = Transport{C.pn_transport()}
137 eng.collector = C.pn_collector()
138 eng.handlers = handlers
139 eng.running = make(chan struct{})
140 eng.timer = time.NewTimer(0)
141 eng.traceEvent = envBool("PN_TRACE_EVT")
142 if eng.transport.IsNil() || eng.connection.IsNil() || eng.collector == nil {
143 eng.free()
144 return fmt.Errorf("proton.NewEngine cannot allocate")
145 }
146 C.pn_connection_collect(eng.connection.pn, eng.collector)
147 return nil
148 }
149
150 // Create a byte slice backed by C memory.
151 // Empty or error (size <= 0) returns a nil byte slice.
152 func cByteSlice(start unsafe.Pointer, size int) []byte {
153 if start == nil || size <= 0 {
154 return nil
155 } else {
156 // Slice from very large imaginary array in C memory
157 return (*[1 << 30]byte)(start)[:size:size]
158 }
159 }
160
161 func (eng *Engine) Connection() Connection {
162 return eng.connection
163 }
164
165 func (eng *Engine) Transport() Transport {
166 return eng.transport
167 }
168
169 func (eng *Engine) String() string {
170 return fmt.Sprintf("[%s]%s-%s", eng.Id(), eng.conn.LocalAddr(), eng.conn.RemoteAddr())
171 }
172
173 func (eng *Engine) Id() string {
174 // Use transport address to match default PN_TRACE_FRM=1 output.
175 return fmt.Sprintf("%p", eng.Transport().CPtr())
176 }
177
178 func (eng *Engine) Error() error {
179 return eng.err.Get()
180 }
181
182 // Inject a function into the Engine's event loop.
183 //
184 // f() will be called in the same event-processing goroutine that calls Handler
185 // methods. f() can safely call methods on values that belong to this engine
186 // (Sessions, Links etc)
187 //
188 // The injected function has no parameters or return values. It is normally a
189 // closure and can use channels to communicate with the injecting goroutine if
190 // necessary.
191 //
192 // Returns a non-nil error if the engine is closed before the function could be
193 // injected.
194 func (eng *Engine) Inject(f func()) error {
195 select {
196 case eng.inject <- f:
197 return nil
198 case <-eng.running:
199 return eng.Error()
200 }
201 }
202
203 // InjectWait is like Inject but does not return till f() has completed or the
204 // engine is closed, and returns an error value from f()
205 func (eng *Engine) InjectWait(f func() error) error {
206 done := make(chan error)
207 defer close(done)
208 err := eng.Inject(func() { done <- f() })
209 if err != nil {
210 return err
211 }
212 select {
213 case <-eng.running:
214 return eng.Error()
215 case err := <-done:
216 return err
217 }
218 }
219
220 // Server puts the Engine in server mode, meaning it will auto-detect security settings on
221 // the incoming connection such as use of SASL and SSL.
222 // Must be called before Run()
223 //
224 func (eng *Engine) Server() { eng.Transport().SetServer() }
225
226 func (eng *Engine) disconnect(err error) {
227 cond := eng.Transport().Condition()
228 cond.SetError(err) // Set the provided error.
229 cond.SetError(eng.conn.Close()) // Use connection error if cond is not already set.
230 eng.transport.CloseTail()
231 eng.transport.CloseHead()
232 }
233
234 // Close the engine's connection.
235 // If err != nil pass it to the remote end as the close condition.
236 // Returns when the remote end closes or disconnects.
237 func (eng *Engine) Close(err error) {
238 _ = eng.Inject(func() { CloseError(eng.Connection(), err) })
239 <-eng.running
240 }
241
242 // CloseTimeout like Close but disconnect if the remote end doesn't close within timeout.
243 func (eng *Engine) CloseTimeout(err error, timeout time.Duration) {
244 _ = eng.Inject(func() { CloseError(eng.Connection(), err) })
245 select {
246 case <-eng.running:
247 case <-time.After(timeout):
248 eng.Disconnect(err)
249 }
250 }
251
252 // Disconnect the engine's connection immediately without an AMQP close.
253 // Process any termination events before returning.
254 func (eng *Engine) Disconnect(err error) {
255 _ = eng.Inject(func() { eng.disconnect(err) })
256 <-eng.running
257 }
258
259 // For debugging purposes: like Transport.Log() but takes a format string
260 // and works even if the transport has been freed.
261 func (eng *Engine) log(format string, args ...interface{}) {
262 fmt.Fprintf(os.Stderr, "[%p]: %v", eng.transport, fmt.Sprintf(format, args...))
263 }
264
265 var processStart = time.Now() // Process start time for elapsed()
266
267 // Monotonic elapsed time since processStart
268 func elapsed() time.Duration {
269 // Time.Sub() uses monotonic time.
270 return time.Now().Sub(processStart)
271 }
272
273 // Let proton run timed activity and set up the next tick
274 func (eng *Engine) tick() {
275 // Proton wants millisecond monotonic time
276 now := int64(elapsed() / time.Millisecond)
277 next := eng.Transport().Tick(now)
278 if next != 0 {
279 eng.timer.Reset(time.Duration((next - now) * int64(time.Millisecond)))
280 }
281 }
282
283 func (eng *Engine) dispatch() bool {
284 for ce := C.pn_collector_peek(eng.collector); ce != nil; ce = C.pn_collector_peek(eng.collector) {
285 e := makeEvent(ce, eng)
286 if eng.traceEvent {
287 eng.transport.Log(e.String())
288 }
289 for _, h := range eng.handlers {
290 h.HandleEvent(e)
291 }
292 if e.Type() == EConnectionRemoteOpen {
293 eng.tick() // Update the tick if changed by remote.
294 }
295 C.pn_collector_pop(eng.collector)
296 }
297 return !eng.transport.Closed() || C.pn_collector_peek(eng.collector) != nil
298 }
299
300 func (eng *Engine) write() {
301 if !eng.writing {
302 size := eng.Transport().Pending() // Evaluate before Head(), may change buffer.
303 start := eng.Transport().Head()
304 if size > 0 {
305 eng.writing = true
306 go func() { // Blocking Write() in separate goroutineb
307 n, err := eng.conn.Write(cByteSlice(start, size))
308 eng.Inject(func() { // Inject results of Write back to engine goroutine
309 eng.writing = false
310 if n > 0 {
311 eng.transport.Pop(uint(n))
312 }
313 if err != nil {
314 eng.Transport().Condition().SetError(err)
315 eng.Transport().CloseHead()
316 }
317 })
318 }()
319 }
320 }
321 }
322
323 func (eng *Engine) read() {
324 if !eng.reading {
325 size := eng.Transport().Capacity()
326 start := eng.Transport().Tail()
327 if size > 0 {
328 eng.reading = true
329 go func() { // Blocking Read in separate goroutine
330 n, err := eng.conn.Read(cByteSlice(start, size))
331 eng.Inject(func() {
332 eng.reading = false
333 if n > 0 {
334 eng.Transport().Process(uint(n))
335 }
336 if err != nil {
337 eng.Transport().Condition().SetError(err)
338 eng.Transport().CloseTail()
339 }
340 })
341 }()
342 }
343 }
344 }
345
346 func (eng *Engine) free() {
347 if !eng.transport.IsNil() {
348 eng.transport.Unbind()
349 eng.transport.Free()
350 eng.transport = Transport{}
351 }
352 if !eng.connection.IsNil() {
353 eng.connection.Free()
354 eng.connection = Connection{}
355 }
356 if eng.collector != nil {
357 C.pn_collector_release(eng.collector)
358 C.pn_collector_free(eng.collector)
359 eng.collector = nil
360 }
361 }
362
363 // Run the engine. Engine.Run() will exit when the engine is closed or
364 // disconnected. You can check for errors after exit with Engine.Error().
365 //
366 func (eng *Engine) Run() error {
367 defer eng.free()
368 eng.transport.Bind(eng.connection)
369 eng.tick() // Start ticking if needed
370 for eng.dispatch() {
371 // Initiate read/write if needed
372 eng.read()
373 eng.write()
374 select {
375 case f := <-eng.inject: // User or IO action
376 f()
377 case <-eng.timer.C:
378 eng.tick()
379 }
380 }
381 eng.err.Set(EndpointError(eng.Connection()))
382 eng.err.Set(eng.Transport().Condition().Error())
383 close(eng.running) // Signal goroutines have exited and Error is set, disable Inject()
384 _ = eng.conn.Close() // Close conn, force read goroutine to exit (Inject will fail)
385 return eng.err.Get()
386 }