Debian Codegraph @

cpp/src/proactor_container_impl.cpp

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 #include "proactor_container_impl.hpp"
21 #include "proactor_work_queue_impl.hpp"
22
23 #include "connect_config.hpp"
24 #include "proton/error_condition.hpp"
25 #include "proton/listen_handler.hpp"
26 #include "proton/listener.hpp"
27 #include "proton/reconnect_options.hpp"
28 #include "proton/ssl.hpp"
29 #include "proton/transport.hpp"
30 #include "proton/url.hpp"
31
32 #include "proton/connection.h"
33 #include "proton/listener.h"
34 #include "proton/proactor.h"
35 #include "proton/transport.h"
36
37 #include "contexts.hpp"
38 #include "messaging_adapter.hpp"
39 #include "reconnect_options_impl.hpp"
40 #include "proton_bits.hpp"
41
42 #include <assert.h>
43 #include <string.h>
44
45 #include <algorithm>
46 #include <vector>
47 #include <thread>
48 #include <random>
49
50 // XXXX: Debug
51 //#include <iostream>
52
53 namespace proton {
54
55 class container::impl::common_work_queue : public work_queue::impl {
56 public:
57 common_work_queue(container::impl& c): container_(c), finished_(false), running_(false) {}
58
59 typedef std::vector<work> jobs;
60
61 void run_all_jobs();
62 void finished() { GUARD(lock_); finished_ = true; }
63 void schedule(duration, work);
64
65 MUTEX(lock_)
66 container::impl& container_;
67 jobs jobs_;
68 bool finished_;
69 bool running_;
70 };
71
72 void container::impl::common_work_queue::schedule(duration d, work f) {
73 // Note this is an unbounded work queue.
74 // A resource-safe implementation should be bounded.
75 if (finished_) return;
76 container_.schedule(d, make_work(&work_queue::impl::add_void, (work_queue::impl*)this, f));
77 }
78
79 void container::impl::common_work_queue::run_all_jobs() {
80 jobs j;
81 // Lock this operation for mt
82 {
83 GUARD(lock_);
84 // Ensure that we never run work from this queue concurrently
85 if (running_) return;
86 running_ = true;
87 // But allow adding to the queue concurrently to running
88 std::swap(j, jobs_);
89 }
90 // Run queued work, but ignore any exceptions
91 for (jobs::iterator f = j.begin(); f != j.end(); ++f) try {
92 (*f)();
93 } catch (...) {};
94 {
95 GUARD(lock_);
96 running_ = false;
97 }
98 return;
99 }
100
101 class container::impl::connection_work_queue : public common_work_queue {
102 public:
103 connection_work_queue(container::impl& ct, pn_connection_t* c): common_work_queue(ct), connection_(c) {}
104
105 bool add(work f);
106
107 pn_connection_t* connection_;
108 };
109
110 bool container::impl::connection_work_queue::add(work f) {
111 // Note this is an unbounded work queue.
112 // A resource-safe implementation should be bounded.
113 GUARD(lock_);
114 if (finished_) return false;
115 jobs_.push_back(f);
116 pn_connection_wake(connection_);
117 return true;
118 }
119
120 class container::impl::container_work_queue : public common_work_queue {
121 public:
122 container_work_queue(container::impl& c): common_work_queue(c) {}
123 ~container_work_queue() { container_.remove_work_queue(this); }
124
125 bool add(work f);
126 };
127
128 bool container::impl::container_work_queue::add(work f) {
129 // Note this is an unbounded work queue.
130 // A resource-safe implementation should be bounded.
131 GUARD(lock_);
132 if (finished_) return false;
133 jobs_.push_back(f);
134 pn_proactor_set_timeout(container_.proactor_, 0);
135 return true;
136 }
137
138 class work_queue::impl* container::impl::make_work_queue(container& c) {
139 return c.impl_->add_work_queue();
140 }
141
142 container::impl::impl(container& c, const std::string& id, messaging_handler* mh)
143 : threads_(0), container_(c), proactor_(pn_proactor()), handler_(mh), id_(id),
144 reconnecting_(0), auto_stop_(true), stopping_(false)
145 {}
146
147 container::impl::~impl() {
148 pn_proactor_free(proactor_);
149 }
150
151 container::impl::container_work_queue* container::impl::add_work_queue() {
152 container_work_queue* c = new container_work_queue(*this);
153 GUARD(work_queues_lock_);
154 work_queues_.insert(c);
155 return c;
156 }
157
158 void container::impl::remove_work_queue(container::impl::container_work_queue* l) {
159 GUARD(work_queues_lock_);
160 work_queues_.erase(l);
161 }
162
163 namespace {
164 void default_url_options(connection_options& opts, const url& url) {
165 opts.virtual_host(url.host());
166 if (!url.user().empty())
167 opts.user(url.user());
168 if (!url.password().empty())
169 opts.password(url.password());
170 // If scheme is amqps then use default tls settings
171 if (url.scheme()==url.AMQPS) {
172 opts.ssl_client_options(ssl_client_options());
173 }
174 }
175 }
176
177 pn_connection_t* container::impl::make_connection_lh(
178 const url& url,
179 const connection_options& user_opts)
180 {
181 if (stopping_)
182 throw proton::error("container is stopping");
183
184 connection_options opts;
185 opts.container_id(id_);
186 default_url_options(opts, url);
187 opts.update(client_connection_options_);
188 opts.update(user_opts);
189 messaging_handler* mh = opts.handler();
190
191 pn_connection_t *pnc = pn_connection();
192 connection_context& cc(connection_context::get(pnc));
193 cc.container = &container_;
194 cc.handler = mh;
195 cc.work_queue_ = new container::impl::connection_work_queue(*container_.impl_, pnc);
196 cc.reconnect_url_ = url;
197 cc.connection_options_.reset(new connection_options(opts));
198
199 make_wrapper(pnc).open(*cc.connection_options_);
200
201 return pnc; // 1 refcount from pn_connection()
202 }
203
204 // Takes ownership of pnc
205 //
206 // NOTE: After the call to start_connection() pnc is active in a proactor thread,
207 // and may even have been freed already. It is undefined to use pnc (or any
208 // object belonging to it) except in appropriate handlers.
209 //
210 // SUBTLE NOTE: There must not be any proton::object wrappers in scope when
211 // start_connection() is called. The wrapper destructor will call pn_decref()
212 // after start_connection() which is undefined!
213 //
214 void container::impl::start_connection(const url& url, pn_connection_t *pnc) {
215 pn_transport_t* pnt = pn_transport();
216 connection_context& cc = connection_context::get(pnc);
217 connection_options& co = *cc.connection_options_;
218 co.apply_unbound_client(pnt);
219
220 char caddr[PN_MAX_ADDR];
221 pn_proactor_addr(caddr, sizeof(caddr), url.host().c_str(), url.port().c_str());
222 pn_proactor_connect2(proactor_, pnc, pnt, caddr); // Takes ownership of pnc, pnt
223 }
224
225 void container::impl::reconnect(pn_connection_t* pnc) {
226 --reconnecting_;
227
228 if (stopping_ && reconnecting_==0) {
229 pn_connection_free(pnc);
230 //TODO: We've lost the error - we should really propagate it here
231 pn_proactor_disconnect(proactor_, NULL);
232 return;
233 }
234
235 connection_context& cc = connection_context::get(pnc);
236 reconnect_context& rc = *cc.reconnect_context_.get();
237
238 connection_options& co = *cc.connection_options_;
239 co.apply_reconnect_urls(pnc);
240
241 // Figure out next connection url to try
242 // rc.current_url_ == -1 means try the url specified in connect, not a failover url
243 const proton::url url(rc.current_url_==-1 ? cc.reconnect_url_ : cc.failover_urls_[rc.current_url_]);
244
245 // XXXX Debug:
246 //std::cout << "Retries: " << rc.retries_ << " Delay: " << rc.delay_ << " Trying: " << url << "@" << rc.current_url_ << std::endl;
247
248 ++rc.current_url_;
249 // Did we go through all the urls?
250 if (rc.current_url_==int(cc.failover_urls_.size())) {
251 rc.current_url_ = -1;
252 ++rc.retries_;
253 }
254
255 connection_options opts;
256 opts.container_id(id_);
257 default_url_options(opts, url);
258 opts.update(co);
259 messaging_handler* mh = opts.handler();
260 cc.handler = mh;
261
262 make_wrapper(pnc).open(co);
263 start_connection(url, pnc);
264 }
265
266 namespace {
267 duration random_between(duration min, duration max)
268 {
269 static thread_local std::default_random_engine gen;
270 std::uniform_int_distribution<duration::numeric_type> dist{min.milliseconds(), max.milliseconds()};
271 return duration(dist(gen));
272 }
273
274 duration next_delay(reconnect_context& rc) {
275 // If we've not retried before do it immediately
276 if (rc.retries_==0) return duration(0);
277
278 // If we haven't tried all failover urls yet this round do it immediately
279 if (rc.current_url_!=-1) return duration(0);
280
281 const reconnect_options_base& roi = rc.reconnect_options_;
282 if (rc.retries_==1) {
283 rc.delay_ = roi.delay;
284 } else {
285 rc.delay_ = std::min(roi.max_delay, rc.delay_ * roi.delay_multiplier);
286 }
287 return random_between(roi.delay, rc.delay_);
288 }
289
290 inline reconnect_context* get_reconnect_context(pn_connection_t* pnc) {
291 return connection_context::get(pnc).reconnect_context_.get();
292 }
293
294 void reset_reconnect(pn_connection_t* pnc) {
295 reconnect_context* rc = get_reconnect_context(pnc);
296
297 if (!rc) return;
298
299 rc->delay_ = 0;
300 rc->retries_ = 0;
301 // set retry to the initial url next
302 rc->current_url_ = -1;
303 }
304
305 }
306
307 bool container::impl::can_reconnect(pn_connection_t* pnc) {
308 reconnect_context* rc = get_reconnect_context(pnc);
309
310 // If reconnect not enabled just fail
311 if (!rc) return false;
312
313 // Don't reconnect if we are locally closed, the application will
314 // not expect a connection it closed to re-open.
315 if (rc->stop_reconnect_) return false;
316
317 // If container stopping don't try to reconnect
318 // - we pretend to have set up a reconnect attempt so
319 // that the proactor disconnect will finish and we will exit
320 // the run loop without error.
321 {
322 GUARD(lock_);
323 if (stopping_) return true;
324 }
325
326 const reconnect_options_base& roi = rc->reconnect_options_;
327
328 pn_transport_t* t = pn_connection_transport(pnc);
329 pn_condition_t* condition = pn_transport_condition(t);
330
331 // If we failed to authenticate then don't reconnect any more and just fail
332 if ( !strcmp(pn_condition_get_name(condition), "amqp:unauthorized-access") ) return false;
333
334 // If too many reconnect attempts just fail
335 if ( roi.max_attempts != 0 && rc->retries_ >= roi.max_attempts) {
336 pn_condition_format(condition, "proton:io", "Too many reconnect attempts (%d)", rc->retries_);
337 return false;
338 }
339 return true;
340 }
341
342 void container::impl::setup_reconnect(pn_connection_t* pnc) {
343 connection_context& cc = connection_context::get(pnc);
344 reconnect_context* rc = cc.reconnect_context_.get();
345 if (!rc) return;
346
347 rc->reconnected_ = true;
348
349 // Recover connection from proactor
350 pn_proactor_release_connection(pnc);
351
352 // Figure out delay till next reconnect
353 duration delay = next_delay(*rc);
354
355 // Schedule reconnect - can do this on container work queue as no one can have the connection
356 // now anyway
357 schedule(delay, make_work(&container::impl::reconnect, this, pnc));
358 ++reconnecting_;
359 }
360
361 returned<connection> container::impl::connect(
362 const std::string& addr,
363 const proton::connection_options& user_opts)
364 {
365 proton::url url(addr);
366 pn_connection_t* pnc = 0;
367 {
368 GUARD(lock_);
369 pnc = make_connection_lh(url, user_opts);
370 }
371 start_connection(url, pnc); // See comment on start_connection
372 return make_returned<proton::connection>(pnc);
373 }
374
375 returned<connection> container::impl::connect() {
376 connection_options opts;
377 std::string addr = apply_config(opts);
378 return connect(addr, opts);
379 }
380
381 returned<sender> container::impl::open_sender(const std::string &urlstr, const proton::sender_options &o1, const connection_options &o2)
382 {
383 proton::url url(urlstr);
384 pn_link_t* pnl = 0;
385 pn_connection_t* pnc = 0;
386 {
387 GUARD(lock_);
388 proton::sender_options lopts(sender_options_);
389 lopts.update(o1);
390 pnc = make_connection_lh(url, o2);
391 connection conn(make_wrapper(pnc));
392 pnl = unwrap(conn.default_session().open_sender(url.path(), lopts));
393 }
394 start_connection(url, pnc); // See comment on start_connection
395 return make_returned<sender>(pnl); // Unsafe returned pointer
396 }
397
398 returned<receiver> container::impl::open_receiver(const std::string &urlstr, const proton::receiver_options &o1, const connection_options &o2) {
399 proton::url url(urlstr);
400 pn_link_t* pnl = 0;
401 pn_connection_t* pnc = 0;
402 {
403 GUARD(lock_);
404 proton::receiver_options lopts(receiver_options_);
405 lopts.update(o1);
406 pnc = make_connection_lh(url, o2);
407 connection conn(make_wrapper(pnc));
408 pnl = unwrap(conn.default_session().open_receiver(url.path(), lopts));
409 }
410 start_connection(url, pnc); // See comment on start_connection
411 return make_returned<receiver>(pnl);
412 }
413
414 pn_listener_t* container::impl::listen_common_lh(const std::string& addr) {
415 if (stopping_)
416 throw proton::error("container is stopping");
417
418 proton::url url(addr, false); // Don't want un-helpful defaults like "localhost"
419
420 // Figure out correct string len then create connection address
421 int len = pn_proactor_addr(0, 0, url.host().c_str(), url.port().c_str());
422 std::vector<char> caddr(len+1);
423 pn_proactor_addr(&caddr[0], len+1, url.host().c_str(), url.port().c_str());
424
425 pn_listener_t* listener = pn_listener();
426 pn_listener_set_context(listener, &container_);
427 pn_proactor_listen(proactor_, listener, &caddr[0], 16);
428 return listener;
429 }
430
431 proton::listener container::impl::listen(const std::string& addr) {
432 GUARD(lock_);
433 pn_listener_t* listener = listen_common_lh(addr);
434 return proton::listener(listener);
435 }
436
437 proton::listener container::impl::listen(const std::string& addr, const proton::connection_options& opts) {
438 GUARD(lock_);
439 pn_listener_t* listener = listen_common_lh(addr);
440 listener_context& lc=listener_context::get(listener);
441 lc.connection_options_.reset(new connection_options(opts));
442 return proton::listener(listener);
443 }
444
445 proton::listener container::impl::listen(const std::string& addr, proton::listen_handler& lh) {
446 GUARD(lock_);
447 pn_listener_t* listener = listen_common_lh(addr);
448 listener_context& lc=listener_context::get(listener);
449 lc.listen_handler_ = &lh;
450 return proton::listener(listener);
451 }
452
453 void container::impl::schedule(duration delay, work f) {
454 GUARD(deferred_lock_);
455 timestamp now = timestamp::now();
456
457 // Record timeout; Add callback to timeout sorted list
458 scheduled s = {now+delay, f};
459 deferred_.push_back(s);
460 std::push_heap(deferred_.begin(), deferred_.end());
461
462 // Set timeout for current head of timeout queue
463 scheduled* next = &deferred_.front();
464 pn_millis_t timeout_ms = (now < next->time) ? (next->time-now).milliseconds() : 0;
465 pn_proactor_set_timeout(proactor_, timeout_ms);
466 }
467
468 void container::impl::client_connection_options(const connection_options &opts) {
469 GUARD(lock_);
470 client_connection_options_ = opts;
471 }
472
473 void container::impl::server_connection_options(const connection_options &opts) {
474 GUARD(lock_);
475 server_connection_options_ = opts;
476 }
477
478 void container::impl::sender_options(const proton::sender_options &opts) {
479 GUARD(lock_);
480 sender_options_ = opts;
481 }
482
483 void container::impl::receiver_options(const proton::receiver_options &opts) {
484 GUARD(lock_);
485 receiver_options_ = opts;
486 }
487
488 void container::impl::run_timer_jobs() {
489 timestamp now = timestamp::now();
490 std::vector<scheduled> tasks;
491
492 // We first extract all the runnable tasks and then run them - this is to avoid having tasks
493 // injected as we are running them (which could potentially never end)
494 {
495 GUARD(deferred_lock_);
496
497 // Figure out how many tasks we need to execute and pop them to the back of the
498 // queue (in reverse order)
499 unsigned i = 0;
500 for (;;) {
501 // Have we seen all the queued tasks?
502 if ( deferred_.size()-i==0 ) break;
503
504 // Is the next task in the future?
505 timestamp next_time = deferred_.front().time;
506 if ( next_time>now ) {
507 pn_proactor_set_timeout(proactor_, (next_time-now).milliseconds());
508 break;
509 }
510
511 std::pop_heap(deferred_.begin(), deferred_.end()-i);
512 ++i;
513 }
514 // Nothing to do
515 if ( i==0 ) return;
516
517 // Now we know how many tasks to run
518 if ( deferred_.size()==i ) {
519 // If we sorted the entire heap, then we're executing every task
520 // so don't need to copy and can just swap
521 tasks.swap(deferred_);
522 } else {
523 // Otherwise just copy the ones we sorted
524 tasks = std::vector<scheduled>(deferred_.end()-i, deferred_.end());
525
526 // Remove tasks to be executed
527 deferred_.resize(deferred_.size()-i);
528 }
529 }
530 // We've now taken the tasks to run from the deferred tasks
531 // so we can run them unlocked
532 // NB. We copied the due tasks in reverse order so execute from end
533 for (int i = tasks.size()-1; i>=0; --i) tasks[i].task();
534 }
535
536 // Return true if this thread is finished
537 container::impl::dispatch_result container::impl::dispatch(pn_event_t* event) {
538
539 // If we have any pending connection work, do it now
540 pn_connection_t* c = pn_event_connection(event);
541 if (c) {
542 work_queue::impl* queue = connection_context::get(c).work_queue_.impl_.get();
543 queue->run_all_jobs();
544 }
545
546 // Process events that shouldn't be sent to messaging_handler
547 switch (pn_event_type(event)) {
548
549 case PN_PROACTOR_INACTIVE: /* listener and all connections closed */
550 // If we're stopping interrupt all other threads still running
551 if (auto_stop_) pn_proactor_interrupt(proactor_);
552 return ContinueLoop;
553
554 // We only interrupt to stop threads
555 case PN_PROACTOR_INTERRUPT: {
556 // Interrupt any other threads still running
557 GUARD(lock_);
558 if (threads_>1) pn_proactor_interrupt(proactor_);
559 return EndLoop;
560 }
561
562 case PN_PROACTOR_TIMEOUT: {
563 // Can get an immediate timeout, if we have a container event loop inject
564 run_timer_jobs();
565
566 // Run every container event loop job
567 // This is not at all efficient and single threads all these jobs, but it does correctly
568 // serialise them
569 work_queues queues;
570 {
571 GUARD(work_queues_lock_);
572 queues = work_queues_;
573 }
574 for (work_queues::iterator queue = queues.begin(); queue!=queues.end(); ++queue) {
575 (*queue)->run_all_jobs();
576 }
577 return EndBatch;
578 }
579 case PN_LISTENER_OPEN: {
580 pn_listener_t* l = pn_event_listener(event);
581 proton::listen_handler* handler;
582 {
583 GUARD(lock_);
584 listener_context &lc(listener_context::get(l));
585 handler = lc.listen_handler_;
586 }
587 if (handler) {
588 listener lstnr(l);
589 handler->on_open(lstnr);
590 }
591 return ContinueLoop;
592 }
593 case PN_LISTENER_ACCEPT: {
594 pn_listener_t* l = pn_event_listener(event);
595 pn_connection_t* c = pn_connection();
596 pn_connection_set_container(c, id_.c_str());
597 connection_options opts = server_connection_options_;
598 listen_handler* handler;
599 listener_context* lc;
600 const connection_options* options;
601 {
602 GUARD(lock_);
603 lc = &listener_context::get(l);
604 handler = lc->listen_handler_;
605 options = lc->connection_options_.get();
606 }
607 if (handler) {
608 listener lstr(l);
609 opts.update(handler->on_accept(lstr));
610 }
611 else if (options) opts.update(*options);
612 // Handler applied separately
613 connection_context& cc = connection_context::get(c);
614 cc.container = &container_;
615 cc.listener_context_ = lc;
616 cc.handler = opts.handler();
617 cc.work_queue_ = new container::impl::connection_work_queue(*container_.impl_, c);
618 pn_transport_t* pnt = pn_transport();
619 pn_transport_set_server(pnt);
620 opts.apply_unbound_server(pnt);
621 pn_listener_accept2(l, c, pnt);
622 return ContinueLoop;
623 }
624 case PN_LISTENER_CLOSE: {
625 pn_listener_t* l = pn_event_listener(event);
626 proton::listen_handler* handler;
627 {
628 GUARD(lock_);
629 listener_context &lc(listener_context::get(l));
630 handler = lc.listen_handler_;
631 }
632 listener lstnr(l);
633 if (handler) {
634 pn_condition_t* c = pn_listener_condition(l);
635 if (pn_condition_is_set(c)) {
636 handler->on_error(lstnr, make_wrapper(c).what());
637 }
638 handler->on_close(lstnr);
639 }
640 return ContinueLoop;
641 }
642 // Connection driver will bind a new transport to the connection at this point
643 case PN_CONNECTION_INIT:
644 return ContinueLoop;
645
646 case PN_CONNECTION_REMOTE_OPEN: {
647 // This is the only event that we get indicating that the connection succeeded so
648 // it's the only place to reset the reconnection logic.
649 //
650 // Just note we have a connection then process normally
651 pn_connection_t* c = pn_event_connection(event);
652 reset_reconnect(c);
653 break;
654 }
655 case PN_CONNECTION_REMOTE_CLOSE: {
656 pn_connection_t *c = pn_event_connection(event);
657 pn_condition_t *cc = pn_connection_remote_condition(c);
658
659 // If reconnect is on, amqp:connection:forced should be treated specially:
660 // Hide the connection error/close events from the application;
661 // Then we close the connection noting the forced close;
662 // Then set up for reconnect handling.
663 if (get_reconnect_context(c) &&
664 pn_condition_is_set(cc) &&
665 !strcmp(pn_condition_get_name(cc), "amqp:connection:forced"))
666 {
667 pn_transport_t* t = pn_event_transport(event);
668 pn_condition_t* tc = pn_transport_condition(t);
669 pn_condition_copy(tc, cc);
670 pn_transport_close_tail(t);
671 pn_connection_close(c);
672 return ContinueLoop;
673 }
674 break;
675 }
676 case PN_TRANSPORT_CLOSED: {
677 // If reconnect is turned on then handle closed on error here with reconnect attempt
678 pn_connection_t* c = pn_event_connection(event);
679 pn_transport_t* t = pn_event_transport(event);
680 if (pn_condition_is_set(pn_transport_condition(t)) && can_reconnect(c)) {
681 messaging_handler *mh = get_handler(event);
682 if (mh) { // Notify handler of pending reconnect
683 transport trans = make_wrapper(t);
684 try {
685 mh->on_transport_error(trans);
686 } catch (const proton::error& e) {
687 // If this is the same error we are re-connecting for,
688 // ignore it. It was probably thrown by the default
689 // messaging_handler::on_error(), and if not the user has
690 // already seen it.
691 //
692 // If this isn't the same error, then something unexpected
693 // has happened, so re-throw.
694 if (std::string(e.what()) != trans.error().what())
695 throw;
696 }
697 }
698 // on_transport_error() may have closed the connection, check again.
699 reconnect_context* rc = get_reconnect_context(c);
700 if (rc && !(rc->stop_reconnect_)) {
701 setup_reconnect(c);
702 return ContinueLoop;
703 }
704 }
705 // Otherwise, this connection will be freed by the proactor.
706 // Mark its work_queue finished so it won't try to use the freed connection.
707 connection_context::get(c).work_queue_.impl_.get()->finished();
708 break;
709 }
710 default:
711 break;
712 }
713
714 messaging_handler *mh = get_handler(event);
715 if (mh) messaging_adapter::dispatch(*mh, event);
716 return ContinueLoop;
717 }
718
719 // Figure out the handler for the primary object for event
720 messaging_handler* container::impl::get_handler(pn_event_t *event) {
721 messaging_handler *mh = 0;
722
723 // First try for a link (send/receiver) handler
724 pn_link_t *link = pn_event_link(event);
725 if (link) mh = get_handler(link);
726
727 // Try for session handler if no link handler
728 pn_session_t *session = pn_event_session(event);
729 if (session && !mh) mh = get_handler(session);
730
731 // Try for connection handler if none of the above
732 pn_connection_t *connection = pn_event_connection(event);
733 if (connection && !mh) mh = get_handler(connection);
734
735 // Use container handler if nothing more specific (must be a container handler)
736 return mh ? mh : handler_;
737 }
738
739 void container::impl::thread() {
740 bool finished;
741 {
742 GUARD(lock_);
743 ++threads_;
744 finished = stopping_;
745 }
746 while (!finished) {
747 pn_event_batch_t *events = pn_proactor_wait(proactor_);
748 pn_event_t *e;
749 error_condition error;
750 try {
751 while ((e = pn_event_batch_next(events))) {
752 dispatch_result r = dispatch(e);
753 finished = r==EndLoop;
754 if (r!=ContinueLoop) break;
755 }
756 } catch (const std::exception& e) {
757 // If we caught an exception then shutdown the (other threads of the) container
758 error = error_condition("exception", e.what());
759 } catch (...) {
760 error = error_condition("exception", "container shut-down by unknown exception");
761 }
762 pn_proactor_done(proactor_, events);
763 if (!error.empty()) {
764 finished = true;
765 {
766 GUARD(lock_);
767 disconnect_error_ = error;
768 }
769 stop(error);
770 }
771 }
772 {
773 GUARD(lock_);
774 --threads_;
775 }
776 }
777
778 void container::impl::start_event() {
779 if (handler_) handler_->on_container_start(container_);
780 }
781
782 void container::impl::stop_event() {
783 if (handler_) handler_->on_container_stop(container_);
784 }
785
786 void container::impl::run(int threads) {
787 // Have to "manually" generate container events
788 CALL_ONCE(start_once_, &impl::start_event, this);
789
790 // Run handler threads
791 threads = std::max(threads, 1); // Ensure at least 1 thread
792 typedef std::vector<std::thread*> vt; // pointer vector to work around failures in older compilers
793 vt ts(threads-1);
794 for (vt::iterator i = ts.begin(); i != ts.end(); ++i) {
795 *i = new std::thread(&impl::thread, this);
796 }
797
798 thread(); // Use this thread too.
799
800 // Wait for the other threads to stop
801 for (vt::iterator i = ts.begin(); i != ts.end(); ++i) {
802 (*i)->join();
803 delete *i;
804 }
805
806 bool last = false;
807 {
808 GUARD(lock_);
809 last = threads_==0;
810 }
811 if (last) CALL_ONCE(stop_once_, &impl::stop_event, this);
812
813 // Throw an exception if we disconnected the proactor because of an exception
814 {
815 GUARD(lock_);
816 if (!disconnect_error_.empty()) throw proton::error(disconnect_error_.description());
817 };
818 }
819
820 void container::impl::auto_stop(bool set) {
821 GUARD(lock_);
822 auto_stop_ = set;
823 }
824
825 void container::impl::stop(const proton::error_condition& err) {
826 {
827 GUARD(lock_);
828 if (stopping_) return; // Already stopping
829 auto_stop_ = true;
830 stopping_ = true;
831 // Have to wait until actual reconnect to stop or we leak the connection
832 if (reconnecting_>0) return;
833 }
834 pn_condition_t* error_condition = pn_condition();
835 set_error_condition(err, error_condition);
836 pn_proactor_disconnect(proactor_, error_condition);
837 pn_condition_free(error_condition);
838 }
839
840 }