Debian Codegraph @

main/stasis.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2013, Digium, Inc.
5 *
6 * David M. Lee, II <[email protected]>
7 *
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
13 *
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
17 */
18
19 /*! \file
20 *
21 * \brief Stasis Message Bus API.
22 *
23 * \author David M. Lee, II <[email protected]>
24 */
25
26 /*** MODULEINFO
27 <support_level>core</support_level>
28 ***/
29
30 #include "asterisk.h"
31
32 #include "asterisk/astobj2.h"
33 #include "asterisk/stasis_internal.h"
34 #include "asterisk/stasis.h"
35 #include "asterisk/taskprocessor.h"
36 #include "asterisk/taskpool.h"
37 #include "asterisk/utils.h"
38 #include "asterisk/uuid.h"
39 #include "asterisk/vector.h"
40 #include "asterisk/stasis_channels.h"
41 #include "asterisk/stasis_bridges.h"
42 #include "asterisk/stasis_endpoints.h"
43 #include "asterisk/config_options.h"
44 #include "asterisk/cli.h"
45
46 /*** DOCUMENTATION
47 <managerEvent language="en_US" name="UserEvent">
48 <managerEventInstance class="EVENT_FLAG_USER">
49 <since>
50 <version>12.3.0</version>
51 </since>
52 <synopsis>A user defined event raised from the dialplan.</synopsis>
53 <syntax>
54 <channel_snapshot/>
55 <parameter name="UserEvent">
56 <para>The event name, as specified in the dialplan.</para>
57 </parameter>
58 </syntax>
59 <description>
60 <para>Event may contain additional arbitrary parameters in addition to optional bridge and endpoint snapshots. Multiple snapshots of the same type are prefixed with a numeric value.</para>
61 </description>
62 <see-also>
63 <ref type="application">UserEvent</ref>
64 <ref type="managerEvent">UserEvent</ref>
65 </see-also>
66 </managerEventInstance>
67 </managerEvent>
68 <configInfo name="stasis" language="en_US">
69 <configFile name="stasis.conf">
70 <configObject name="threadpool">
71 <since>
72 <version>12.8.0</version>
73 <version>13.1.0</version>
74 </since>
75 <synopsis>Settings that configure the threadpool Stasis uses to deliver some messages.</synopsis>
76 <configOption name="initial_size" default="5">
77 <since>
78 <version>12.8.0</version>
79 <version>13.1.0</version>
80 </since>
81 <synopsis>Initial number of threads in the message bus threadpool.</synopsis>
82 </configOption>
83 <configOption name="idle_timeout_sec" default="20">
84 <since>
85 <version>12.8.0</version>
86 <version>13.1.0</version>
87 </since>
88 <synopsis>Number of seconds before an idle thread is disposed of.</synopsis>
89 </configOption>
90 <configOption name="max_size" default="50">
91 <since>
92 <version>12.8.0</version>
93 <version>13.1.0</version>
94 </since>
95 <synopsis>Maximum number of threads in the threadpool.</synopsis>
96 </configOption>
97 </configObject>
98 <configObject name="taskpool">
99 <since>
100 <version>23.1.0</version>
101 <version>22.7.0</version>
102 <version>20.17.0</version>
103 </since>
104 <synopsis>Settings that configure the taskpool Stasis uses to deliver some messages.</synopsis>
105 <configOption name="minimum_size" default="5">
106 <since>
107 <version>23.1.0</version>
108 <version>22.7.0</version>
109 <version>20.17.0</version>
110 </since>
111 <synopsis>Minimum number of taskprocessors in the message bus taskpool.</synopsis>
112 </configOption>
113 <configOption name="initial_size" default="5">
114 <since>
115 <version>23.1.0</version>
116 <version>22.7.0</version>
117 <version>20.17.0</version>
118 </since>
119 <synopsis>Initial number of taskprocessors in the message bus taskpool.</synopsis>
120 </configOption>
121 <configOption name="idle_timeout_sec" default="20">
122 <since>
123 <version>23.1.0</version>
124 <version>22.7.0</version>
125 <version>20.17.0</version>
126 </since>
127 <synopsis>Number of seconds before an idle taskprocessor is disposed of.</synopsis>
128 </configOption>
129 <configOption name="max_size" default="50">
130 <since>
131 <version>23.1.0</version>
132 <version>22.7.0</version>
133 <version>20.17.0</version>
134 </since>
135 <synopsis>Maximum number of taskprocessors in the taskpool.</synopsis>
136 </configOption>
137 </configObject>
138 <configObject name="declined_message_types">
139 <since>
140 <version>13.0.0</version>
141 </since>
142 <synopsis>Stasis message types for which to decline creation.</synopsis>
143 <configOption name="decline">
144 <since>
145 <version>12.8.0</version>
146 <version>13.1.0</version>
147 </since>
148 <synopsis>The message type to decline.</synopsis>
149 <description>
150 <para>This configuration option defines the name of the Stasis
151 message type that Asterisk is forbidden from creating and can be
152 specified as many times as necessary to achieve the desired result.</para>
153 <enumlist>
154 <enum name="stasis_app_recording_snapshot_type" />
155 <enum name="stasis_app_playback_snapshot_type" />
156 <enum name="stasis_test_message_type" />
157 <enum name="confbridge_start_type" />
158 <enum name="confbridge_end_type" />
159 <enum name="confbridge_join_type" />
160 <enum name="confbridge_leave_type" />
161 <enum name="confbridge_start_record_type" />
162 <enum name="confbridge_stop_record_type" />
163 <enum name="confbridge_mute_type" />
164 <enum name="confbridge_unmute_type" />
165 <enum name="confbridge_talking_type" />
166 <enum name="cel_generic_type" />
167 <enum name="ast_bridge_snapshot_type" />
168 <enum name="ast_bridge_merge_message_type" />
169 <enum name="ast_channel_entered_bridge_type" />
170 <enum name="ast_channel_left_bridge_type" />
171 <enum name="ast_blind_transfer_type" />
172 <enum name="ast_attended_transfer_type" />
173 <enum name="ast_endpoint_snapshot_type" />
174 <enum name="ast_endpoint_state_type" />
175 <enum name="ast_device_state_message_type" />
176 <enum name="ast_test_suite_message_type" />
177 <enum name="ast_mwi_state_type" />
178 <enum name="ast_mwi_vm_app_type" />
179 <enum name="ast_format_register_type" />
180 <enum name="ast_format_unregister_type" />
181 <enum name="ast_manager_get_generic_type" />
182 <enum name="ast_parked_call_type" />
183 <enum name="ast_channel_snapshot_type" />
184 <enum name="ast_channel_dial_type" />
185 <enum name="ast_channel_varset_type" />
186 <enum name="ast_channel_hangup_request_type" />
187 <enum name="ast_channel_dtmf_begin_type" />
188 <enum name="ast_channel_dtmf_end_type" />
189 <enum name="ast_channel_flash_type" />
190 <enum name="ast_channel_wink_type" />
191 <enum name="ast_channel_hold_type" />
192 <enum name="ast_channel_unhold_type" />
193 <enum name="ast_channel_chanspy_start_type" />
194 <enum name="ast_channel_chanspy_stop_type" />
195 <enum name="ast_channel_fax_type" />
196 <enum name="ast_channel_hangup_handler_type" />
197 <enum name="ast_channel_moh_start_type" />
198 <enum name="ast_channel_moh_stop_type" />
199 <enum name="ast_channel_mixmonitor_start_type" />
200 <enum name="ast_channel_mixmonitor_stop_type" />
201 <enum name="ast_channel_mixmonitor_mute_type" />
202 <enum name="ast_channel_agent_login_type" />
203 <enum name="ast_channel_agent_logoff_type" />
204 <enum name="ast_channel_talking_start" />
205 <enum name="ast_channel_talking_stop" />
206 <enum name="ast_channel_tone_detect" />
207 <enum name="ast_security_event_type" />
208 <enum name="ast_named_acl_change_type" />
209 <enum name="ast_local_bridge_type" />
210 <enum name="ast_local_optimization_begin_type" />
211 <enum name="ast_local_optimization_end_type" />
212 <enum name="stasis_subscription_change_type" />
213 <enum name="ast_multi_user_event_type" />
214 <enum name="stasis_cache_clear_type" />
215 <enum name="stasis_cache_update_type" />
216 <enum name="ast_network_change_type" />
217 <enum name="ast_system_registry_type" />
218 <enum name="ast_cc_available_type" />
219 <enum name="ast_cc_offertimerstart_type" />
220 <enum name="ast_cc_requested_type" />
221 <enum name="ast_cc_requestacknowledged_type" />
222 <enum name="ast_cc_callerstopmonitoring_type" />
223 <enum name="ast_cc_callerstartmonitoring_type" />
224 <enum name="ast_cc_callerrecalling_type" />
225 <enum name="ast_cc_recallcomplete_type" />
226 <enum name="ast_cc_failure_type" />
227 <enum name="ast_cc_monitorfailed_type" />
228 <enum name="ast_presence_state_message_type" />
229 <enum name="ast_rtp_rtcp_sent_type" />
230 <enum name="ast_rtp_rtcp_received_type" />
231 <enum name="ast_call_pickup_type" />
232 <enum name="aoc_s_type" />
233 <enum name="aoc_d_type" />
234 <enum name="aoc_e_type" />
235 <enum name="dahdichannel_type" />
236 <enum name="mcid_type" />
237 <enum name="session_timeout_type" />
238 <enum name="cdr_read_message_type" />
239 <enum name="cdr_write_message_type" />
240 <enum name="cdr_prop_write_message_type" />
241 <enum name="corosync_ping_message_type" />
242 <enum name="agi_exec_start_type" />
243 <enum name="agi_exec_end_type" />
244 <enum name="agi_async_start_type" />
245 <enum name="agi_async_exec_type" />
246 <enum name="agi_async_end_type" />
247 <enum name="queue_caller_join_type" />
248 <enum name="queue_caller_leave_type" />
249 <enum name="queue_caller_abandon_type" />
250 <enum name="queue_member_status_type" />
251 <enum name="queue_member_added_type" />
252 <enum name="queue_member_removed_type" />
253 <enum name="queue_member_pause_type" />
254 <enum name="queue_member_penalty_type" />
255 <enum name="queue_member_ringinuse_type" />
256 <enum name="queue_agent_called_type" />
257 <enum name="queue_agent_connect_type" />
258 <enum name="queue_agent_complete_type" />
259 <enum name="queue_agent_dump_type" />
260 <enum name="queue_agent_ringnoanswer_type" />
261 <enum name="meetme_join_type" />
262 <enum name="meetme_leave_type" />
263 <enum name="meetme_end_type" />
264 <enum name="meetme_mute_type" />
265 <enum name="meetme_talking_type" />
266 <enum name="meetme_talk_request_type" />
267 <enum name="appcdr_message_type" />
268 <enum name="forkcdr_message_type" />
269 <enum name="cdr_sync_message_type" />
270 </enumlist>
271 </description>
272 </configOption>
273 </configObject>
274 </configFile>
275 </configInfo>
276 ***/
277
278 /*!
279 * \page stasis-impl Stasis Implementation Notes
280 *
281 * \par Reference counting
282 *
283 * Stasis introduces a number of objects, which are tightly related to one
284 * another. Because we rely on ref-counting for memory management, understanding
285 * these relationships is important to understanding this code.
286 *
287 * \code{.txt}
288 *
289 * stasis_topic <----> stasis_subscription
290 * ^ ^
291 * \ /
292 * \ /
293 * dispatch
294 * |
295 * |
296 * v
297 * stasis_message
298 * |
299 * |
300 * v
301 * stasis_message_type
302 *
303 * \endcode
304 *
305 * The most troubling thing in this chart is the cyclic reference between
306 * stasis_topic and stasis_subscription. This is both unfortunate, and
307 * necessary. Topics need the subscription in order to dispatch messages;
308 * subscriptions need the topics to unsubscribe and check subscription status.
309 *
310 * The cycle is broken by stasis_unsubscribe(). The unsubscribe will remove the
311 * topic's reference to a subscription. When the subscription is destroyed, it
312 * will remove its reference to the topic.
313 *
314 * This means that until a subscription has be explicitly unsubscribed, it will
315 * not be destroyed. Neither will a topic be destroyed while it has subscribers.
316 * The destructors of both have assertions regarding this to catch ref-counting
317 * problems where a subscription or topic has had an extra ao2_cleanup().
318 *
319 * The \ref dispatch_exec_sync object is a transient object, which is posted to
320 * a subscription's taskprocessor to send a message to the subscriber. They have
321 * short life cycles, allocated on one thread, destroyed on another.
322 *
323 * During shutdown, or the deletion of a domain object, there are a flurry of
324 * ao2_cleanup()s on subscriptions and topics, as the final in-flight messages
325 * are processed. Any one of these cleanups could be the one to actually destroy
326 * a given object, so care must be taken to ensure that an object isn't
327 * referenced after an ao2_cleanup(). This includes the implicit ao2_unlock()
328 * that might happen when a RAII_VAR() goes out of scope.
329 *
330 * \par Typical life cycles
331 *
332 * \li stasis_topic - There are several topics which live for the duration of
333 * the Asterisk process (ast_channel_topic_all(), etc.) but most of these
334 * are actually fed by shorter-lived topics whose lifetime is associated
335 * with some domain object (like ast_channel_topic() for a given
336 * ast_channel).
337 *
338 * \li stasis_subscription - Subscriptions have a similar mix of lifetimes as
339 * topics, for similar reasons.
340 *
341 * \li dispatch - Very short lived; just long enough to post a message to a
342 * subscriber.
343 *
344 * \li stasis_message - Short to intermediate lifetimes, but that is mostly
345 * irrelevant. Messages are strictly data and have no behavior associated
346 * with them, so it doesn't really matter if/when they are destroyed. By
347 * design, a component could hold a ref to a message forever without any
348 * ill consequences (aside from consuming more memory).
349 *
350 * \li stasis_message_type - Long life cycles, typically only destroyed on
351 * module unloading or _clean_ process exit.
352 *
353 * \par Subscriber shutdown sequencing
354 *
355 * Subscribers are sensitive to shutdown sequencing, specifically in how the
356 * reference message types. This is fully detailed in the documentation at
357 * https://docs.asterisk.org/Development/Roadmap/Asterisk-12-Projects/Asterisk-12-API-Improvements/Stasis-Message-Bus/Using-the-Stasis-Message-Bus/Stasis-Subscriber-Shutdown-Problem/.
358 *
359 * In short, the lifetime of the \a data (and \a callback, if in a module) must
360 * be held until the stasis_subscription_final_message() has been received.
361 * Depending on the structure of the subscriber code, this can be handled by
362 * using stasis_subscription_final_message() to free resources on the final
363 * message, or using stasis_subscription_join()/stasis_unsubscribe_and_join() to
364 * block until the unsubscribe has completed.
365 */
366
367 /*! Initial size of the subscribers list. */
368 #define INITIAL_SUBSCRIBERS_MAX 4
369
370 /*! The number of buckets to use for topic pools */
371 #define TOPIC_POOL_BUCKETS 57
372
373 /*! Taskpool for topics that don't want a dedicated taskprocessor */
374 static struct ast_taskpool *taskpool;
375
376 STASIS_MESSAGE_TYPE_DEFN(stasis_subscription_change_type);
377
378 #if defined(LOW_MEMORY)
379
380 #define TOPIC_ALL_BUCKETS 257
381
382 #else
383
384 #define TOPIC_ALL_BUCKETS 997
385
386 #endif
387
388 #ifdef AST_DEVMODE
389
390 /*! The number of buckets to use for topic statistics */
391 #define TOPIC_STATISTICS_BUCKETS 57
392
393 /*! The number of buckets to use for subscription statistics */
394 #define SUBSCRIPTION_STATISTICS_BUCKETS 57
395
396 /*! Global container which stores statistics for topics */
397 static AO2_GLOBAL_OBJ_STATIC(topic_statistics);
398
399 /*! Global container which stores statistics for subscriptions */
400 static AO2_GLOBAL_OBJ_STATIC(subscription_statistics);
401
402 /*! \internal */
403 struct stasis_message_type_statistics {
404 /*! \brief The number of messages of this published */
405 int published;
406 /*! \brief The number of messages of this that did not reach a subscriber */
407 int unused;
408 /*! \brief The stasis message type */
409 struct stasis_message_type *message_type;
410 };
411
412 /*! Lock to protect the message types vector */
413 AST_MUTEX_DEFINE_STATIC(message_type_statistics_lock);
414
415 /*! Vector containing message type information */
416 static AST_VECTOR(, struct stasis_message_type_statistics) message_type_statistics;
417
418 /*! \internal */
419 struct stasis_topic_statistics {
420 /*! \brief Highest time spent dispatching messages to subscribers */
421 long highest_time_dispatched;
422 /*! \brief Lowest time spent dispatching messages to subscribers */
423 long lowest_time_dispatched;
424 /*! \brief The number of messages that were not dispatched to any subscriber */
425 int messages_not_dispatched;
426 /*! \brief The number of messages that were dispatched to at least 1 subscriber */
427 int messages_dispatched;
428 /*! \brief The ids of the subscribers to this topic */
429 struct ao2_container *subscribers;
430 /*! \brief Pointer to the topic (NOT refcounted, and must NOT be accessed) */
431 struct stasis_topic *topic;
432 /*! \brief Name of the topic */
433 char name[0];
434 };
435 #endif
436
437 /*! \internal */
438 struct stasis_topic {
439 /*! Variable length array of the subscribers */
440 AST_VECTOR(, struct stasis_subscription *) subscribers;
441
442 /*! Topics forwarding into this topic */
443 AST_VECTOR(, struct stasis_topic *) upstream_topics;
444
445 #ifdef AST_DEVMODE
446 struct stasis_topic_statistics *statistics;
447 #endif
448
449 /*! Unique incrementing integer for subscriber ids */
450 int subscriber_id;
451
452 /*! Name of the topic */
453 char *name;
454
455 /*! Detail of the topic */
456 char *detail;
457
458 /*! Creation time */
459 struct timeval *creationtime;
460 };
461
462 struct ao2_container *topic_all;
463
464 struct topic_proxy {
465 AO2_WEAKPROXY();
466
467 char *name;
468 char *detail;
469
470 struct timeval creationtime;
471
472 char buf[0];
473 };
474
475 AO2_STRING_FIELD_HASH_FN(topic_proxy, name);
476 AO2_STRING_FIELD_CMP_FN(topic_proxy, name);
477 AO2_STRING_FIELD_CASE_SORT_FN(topic_proxy, name);
478
479 static void proxy_dtor(void *weakproxy, void *container)
480 {
481 ao2_unlink(container, weakproxy);
482 ao2_cleanup(container);
483 }
484
485 /* Forward declarations for the tightly-coupled subscription object */
486 static int topic_add_subscription(struct stasis_topic *topic,
487 struct stasis_subscription *sub);
488
489 static int topic_remove_subscription(struct stasis_topic *topic, struct stasis_subscription *sub);
490
491 /*! \brief Lock two topics. */
492 #define topic_lock_both(topic1, topic2) \
493 do { \
494 ao2_lock(topic1); \
495 while (ao2_trylock(topic2)) { \
496 AO2_DEADLOCK_AVOIDANCE(topic1); \
497 } \
498 } while (0)
499
500 static void topic_dtor(void *obj)
501 {
502 struct stasis_topic *topic = obj;
503 #ifdef AST_DEVMODE
504 struct ao2_container *topic_stats;
505 #endif
506
507 ast_debug(2, "Destroying topic. name: %s, detail: %s\n",
508 topic->name, topic->detail);
509
510 /* Subscribers hold a reference to topics, so they should all be
511 * unsubscribed before we get here. */
512 ast_assert(AST_VECTOR_SIZE(&topic->subscribers) == 0);
513
514 AST_VECTOR_FREE(&topic->subscribers);
515 AST_VECTOR_FREE(&topic->upstream_topics);
516 ast_debug(1, "Topic '%s': %p destroyed\n", topic->name, topic);
517
518 #ifdef AST_DEVMODE
519 if (topic->statistics) {
520 topic_stats = ao2_global_obj_ref(topic_statistics);
521 if (topic_stats) {
522 ao2_unlink(topic_stats, topic->statistics);
523 ao2_ref(topic_stats, -1);
524 }
525 ao2_ref(topic->statistics, -1);
526 }
527 #endif
528 }
529
530 #ifdef AST_DEVMODE
531 static void topic_statistics_destroy(void *obj)
532 {
533 struct stasis_topic_statistics *statistics = obj;
534
535 ao2_cleanup(statistics->subscribers);
536 }
537
538 static struct stasis_topic_statistics *stasis_topic_statistics_create(struct stasis_topic *topic)
539 {
540 struct stasis_topic_statistics *statistics;
541 RAII_VAR(struct ao2_container *, topic_stats, ao2_global_obj_ref(topic_statistics), ao2_cleanup);
542
543 if (!topic_stats) {
544 return NULL;
545 }
546
547 statistics = ao2_alloc(sizeof(*statistics) + strlen(topic->name) + 1, topic_statistics_destroy);
548 if (!statistics) {
549 return NULL;
550 }
551
552 statistics->subscribers = ast_str_container_alloc(1);
553 if (!statistics->subscribers) {
554 ao2_ref(statistics, -1);
555 return NULL;
556 }
557
558 /* This is strictly used for the pointer address when showing the topic */
559 statistics->topic = topic;
560 strcpy(statistics->name, topic->name); /* SAFE */
561 ao2_link(topic_stats, statistics);
562
563 return statistics;
564 }
565 #endif
566
567 static int link_topic_proxy(struct stasis_topic *topic, const char *name, const char *detail)
568 {
569 struct topic_proxy *proxy;
570 struct stasis_topic* topic_tmp;
571 size_t detail_len;
572
573 if (!topic || !name || !strlen(name) || !detail) {
574 return -1;
575 }
576
577 ao2_wrlock(topic_all);
578
579 topic_tmp = stasis_topic_get(name);
580 if (topic_tmp) {
581 ast_log(LOG_ERROR, "The same topic is already exist. name: %s\n", name);
582 ao2_ref(topic_tmp, -1);
583 ao2_unlock(topic_all);
584
585 return -1;
586 }
587
588 detail_len = strlen(detail) + 1;
589
590 proxy = ao2_t_weakproxy_alloc(
591 sizeof(*proxy) + strlen(name) + 1 + detail_len, NULL, name);
592 if (!proxy) {
593 ao2_unlock(topic_all);
594
595 return -1;
596 }
597
598 /* set the proxy info */
599 proxy->name = proxy->buf;
600 proxy->detail = proxy->name + strlen(name) + 1;
601
602 strcpy(proxy->name, name); /* SAFE */
603 ast_copy_string(proxy->detail, detail, detail_len); /* SAFE */
604 proxy->creationtime = ast_tvnow();
605
606 /* We have exclusive access to proxy, no need for locking here. */
607 if (ao2_t_weakproxy_set_object(proxy, topic, OBJ_NOLOCK, "weakproxy link")) {
608 ao2_cleanup(proxy);
609 ao2_unlock(topic_all);
610
611 return -1;
612 }
613
614 if (ao2_weakproxy_subscribe(proxy, proxy_dtor, ao2_bump(topic_all), OBJ_NOLOCK)) {
615 ao2_cleanup(proxy);
616 ao2_unlock(topic_all);
617 ao2_cleanup(topic_all);
618
619 return -1;
620 }
621
622 /* setting the topic point to the proxy */
623 topic->name = proxy->name;
624 topic->detail = proxy->detail;
625 topic->creationtime = &(proxy->creationtime);
626
627 ao2_link_flags(topic_all, proxy, OBJ_NOLOCK);
628 ao2_ref(proxy, -1);
629
630 ao2_unlock(topic_all);
631
632 return 0;
633 }
634
635 struct stasis_topic *stasis_topic_create_with_detail(
636 const char *name, const char* detail
637 )
638 {
639 struct stasis_topic *topic;
640 int res = 0;
641
642 if (!name|| !strlen(name) || !detail) {
643 return NULL;
644 }
645 ast_debug(2, "Creating topic. name: %s, detail: %s\n", name, detail);
646
647 topic = stasis_topic_get(name);
648 if (topic) {
649 ast_debug(2, "Topic is already exist. name: %s, detail: %s\n",
650 name, detail);
651 return topic;
652 }
653
654 topic = ao2_t_alloc(sizeof(*topic), topic_dtor, name);
655 if (!topic) {
656 return NULL;
657 }
658
659 res |= AST_VECTOR_INIT(&topic->subscribers, INITIAL_SUBSCRIBERS_MAX);
660 res |= AST_VECTOR_INIT(&topic->upstream_topics, 0);
661 if (res) {
662 ao2_ref(topic, -1);
663 return NULL;
664 }
665
666 /* link to the proxy */
667 if (link_topic_proxy(topic, name, detail)) {
668 ao2_ref(topic, -1);
669 return NULL;
670 }
671
672 #ifdef AST_DEVMODE
673 topic->statistics = stasis_topic_statistics_create(topic);
674 if (!topic->statistics) {
675 ao2_ref(topic, -1);
676 return NULL;
677 }
678 #endif
679 ast_debug(1, "Topic '%s': %p created\n", topic->name, topic);
680
681 return topic;
682 }
683
684 struct stasis_topic *stasis_topic_create(const char *name)
685 {
686 return stasis_topic_create_with_detail(name, "");
687 }
688
689 struct stasis_topic *stasis_topic_get(const char *name)
690 {
691 return ao2_weakproxy_find(topic_all, name, OBJ_SEARCH_KEY, "");
692 }
693
694 const char *stasis_topic_name(const struct stasis_topic *topic)
695 {
696 if (!topic) {
697 return NULL;
698 }
699 return topic->name;
700 }
701
702 const char *stasis_topic_detail(const struct stasis_topic *topic)
703 {
704 if (!topic) {
705 return NULL;
706 }
707 return topic->detail;
708 }
709
710 size_t stasis_topic_subscribers(const struct stasis_topic *topic)
711 {
712 return AST_VECTOR_SIZE(&topic->subscribers);
713 }
714
715 #ifdef AST_DEVMODE
716 struct stasis_subscription_statistics {
717 /*! \brief The filename where the subscription originates */
718 const char *file;
719 /*! \brief The function where the subscription originates */
720 const char *func;
721 /*! \brief Names of the topics we are subscribed to */
722 struct ao2_container *topics;
723 /*! \brief The message type that currently took the longest to process */
724 struct stasis_message_type *highest_time_message_type;
725 /*! \brief Highest time spent invoking a message */
726 long highest_time_invoked;
727 /*! \brief Lowest time spent invoking a message */
728 long lowest_time_invoked;
729 /*! \brief The number of messages that were filtered out */
730 int messages_dropped;
731 /*! \brief The number of messages that passed filtering */
732 int messages_passed;
733 /*! \brief Using a mailbox to queue messages */
734 int uses_mailbox;
735 /*! \brief Using stasis taskpool for handling messages */
736 int uses_taskpool;
737 /*! \brief The line number where the subscription originates */
738 int lineno;
739 /*! \brief Pointer to the subscription (NOT refcounted, and must NOT be accessed) */
740 struct stasis_subscription *sub;
741 /*! \brief Unique ID of the subscription */
742 char uniqueid[0];
743 };
744 #endif
745
746 /*! \internal */
747 struct stasis_subscription {
748 /*! Unique ID for this subscription */
749 char *uniqueid;
750 /*! Topic subscribed to. */
751 struct stasis_topic *topic;
752 /*! Mailbox for processing incoming messages. */
753 struct ast_taskprocessor *mailbox;
754 /*! Callback function for incoming message processing. */
755 stasis_subscription_cb callback;
756 /*! Data pointer to be handed to the callback. */
757 void *data;
758
759 /*! Condition for joining with subscription. */
760 ast_cond_t join_cond;
761 /*! Flag set when final message for sub has been received.
762 * Be sure join_lock is held before reading/setting. */
763 int final_message_rxed;
764 /*! Flag set when final message for sub has been processed.
765 * Be sure join_lock is held before reading/setting. */
766 int final_message_processed;
767
768 /*! The message types this subscription is accepting */
769 AST_VECTOR(, char) accepted_message_types;
770 /*! The message formatters this subscription is accepting */
771 enum stasis_subscription_message_formatters accepted_formatters;
772 /*! The message filter currently in use */
773 enum stasis_subscription_message_filter filter;
774
775 #ifdef AST_DEVMODE
776 /*! Statistics information */
777 struct stasis_subscription_statistics *statistics;
778 #endif
779 };
780
781 static void subscription_dtor(void *obj)
782 {
783 struct stasis_subscription *sub = obj;
784 #ifdef AST_DEVMODE
785 struct ao2_container *subscription_stats;
786 #endif
787
788 /* Subscriptions need to be manually unsubscribed before destruction
789 * b/c there's a cyclic reference between topics and subscriptions */
790 ast_assert(!stasis_subscription_is_subscribed(sub));
791 /* If there are any messages in flight to this subscription; that would
792 * be bad. */
793 ast_assert(stasis_subscription_is_done(sub));
794
795 ast_free(sub->uniqueid);
796 ao2_cleanup(sub->topic);
797 sub->topic = NULL;
798 ast_taskprocessor_unreference(sub->mailbox);
799 sub->mailbox = NULL;
800 ast_cond_destroy(&sub->join_cond);
801
802 AST_VECTOR_FREE(&sub->accepted_message_types);
803
804 #ifdef AST_DEVMODE
805 if (sub->statistics) {
806 subscription_stats = ao2_global_obj_ref(subscription_statistics);
807 if (subscription_stats) {
808 ao2_unlink(subscription_stats, sub->statistics);
809 ao2_ref(subscription_stats, -1);
810 }
811 ao2_ref(sub->statistics, -1);
812 }
813 #endif
814 }
815
816 /*!
817 * \brief Invoke the subscription's callback.
818 * \param sub Subscription to invoke.
819 * \param message Message to send.
820 */
821 static void subscription_invoke(struct stasis_subscription *sub,
822 struct stasis_message *message)
823 {
824 unsigned int final = stasis_subscription_final_message(sub, message);
825 int message_type_id = stasis_message_type_id(stasis_subscription_change_type());
826 #ifdef AST_DEVMODE
827 struct timeval start;
828 long elapsed;
829
830 start = ast_tvnow();
831 #endif
832
833 /* Notify that the final message has been received */
834 if (final) {
835 ao2_lock(sub);
836 sub->final_message_rxed = 1;
837 ast_cond_signal(&sub->join_cond);
838 ao2_unlock(sub);
839 }
840
841 /*
842 * If filtering is turned on and this is a 'final' message, we only invoke the callback
843 * if the subscriber accepts subscription_change message types.
844 */
845 if (!final || sub->filter != STASIS_SUBSCRIPTION_FILTER_SELECTIVE ||
846 (message_type_id < AST_VECTOR_SIZE(&sub->accepted_message_types) && AST_VECTOR_GET(&sub->accepted_message_types, message_type_id))) {
847 /* Since sub is mostly immutable, no need to lock sub */
848 sub->callback(sub->data, sub, message);
849 }
850
851 /* Notify that the final message has been processed */
852 if (final) {
853 ao2_lock(sub);
854 sub->final_message_processed = 1;
855 ast_cond_signal(&sub->join_cond);
856 ao2_unlock(sub);
857 }
858
859 #ifdef AST_DEVMODE
860 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
861 if (elapsed > sub->statistics->highest_time_invoked) {
862 sub->statistics->highest_time_invoked = elapsed;
863 ao2_lock(sub->statistics);
864 sub->statistics->highest_time_message_type = stasis_message_type(message);
865 ao2_unlock(sub->statistics);
866 }
867 if (elapsed < sub->statistics->lowest_time_invoked) {
868 sub->statistics->lowest_time_invoked = elapsed;
869 }
870 #endif
871 }
872
873 static void send_subscription_subscribe(struct stasis_topic *topic, struct stasis_subscription *sub);
874 static void send_subscription_unsubscribe(struct stasis_topic *topic, struct stasis_subscription *sub);
875
876 void stasis_subscription_cb_noop(void *data, struct stasis_subscription *sub, struct stasis_message *message)
877 {
878 }
879
880 #ifdef AST_DEVMODE
881 static void subscription_statistics_destroy(void *obj)
882 {
883 struct stasis_subscription_statistics *statistics = obj;
884
885 ao2_cleanup(statistics->topics);
886 }
887
888 static struct stasis_subscription_statistics *stasis_subscription_statistics_create(struct stasis_subscription *sub,
889 int needs_mailbox, int use_taskpool, const char *file, int lineno,
890 const char *func)
891 {
892 struct stasis_subscription_statistics *statistics;
893 RAII_VAR(struct ao2_container *, subscription_stats, ao2_global_obj_ref(subscription_statistics), ao2_cleanup);
894
895 if (!subscription_stats) {
896 return NULL;
897 }
898
899 statistics = ao2_alloc(sizeof(*statistics) + strlen(sub->uniqueid) + 1, subscription_statistics_destroy);
900 if (!statistics) {
901 return NULL;
902 }
903
904 statistics->topics = ast_str_container_alloc(1);
905 if (!statistics->topics) {
906 ao2_ref(statistics, -1);
907 return NULL;
908 }
909
910 statistics->file = file;
911 statistics->lineno = lineno;
912 statistics->func = func;
913 statistics->uses_mailbox = needs_mailbox;
914 statistics->uses_taskpool = use_taskpool;
915 strcpy(statistics->uniqueid, sub->uniqueid); /* SAFE */
916 statistics->sub = sub;
917 ao2_link(subscription_stats, statistics);
918
919 return statistics;
920 }
921 #endif
922
923 struct stasis_subscription *internal_stasis_subscribe(
924 struct stasis_topic *topic,
925 stasis_subscription_cb callback,
926 void *data,
927 int needs_mailbox,
928 int use_taskpool,
929 const char *file,
930 int lineno,
931 const char *func)
932 {
933 struct stasis_subscription *sub;
934 int ret;
935
936 if (!topic) {
937 return NULL;
938 }
939
940 /* The ao2 lock is used for join_cond. */
941 sub = ao2_t_alloc(sizeof(*sub), subscription_dtor, stasis_topic_name(topic));
942 if (!sub) {
943 return NULL;
944 }
945
946 #ifdef AST_DEVMODE
947 ret = ast_asprintf(&sub->uniqueid, "%s:%s-%d", file, stasis_topic_name(topic), ast_atomic_fetchadd_int(&topic->subscriber_id, +1));
948 sub->statistics = stasis_subscription_statistics_create(sub, needs_mailbox, use_taskpool, file, lineno, func);
949 if (ret < 0 || !sub->statistics) {
950 ao2_ref(sub, -1);
951 return NULL;
952 }
953 #else
954 ret = ast_asprintf(&sub->uniqueid, "%s-%d", stasis_topic_name(topic), ast_atomic_fetchadd_int(&topic->subscriber_id, +1));
955 if (ret < 0) {
956 ao2_ref(sub, -1);
957 return NULL;
958 }
959 #endif
960
961 if (needs_mailbox) {
962 char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
963
964 /* Create name with seq number appended. */
965 ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "stasis/%c:%s",
966 use_taskpool ? 'p' : 'm',
967 stasis_topic_name(topic));
968
969 /*
970 * With a small number of subscribers, a thread-per-sub is
971 * acceptable. For a large number of subscribers, a thread
972 * pool should be used.
973 */
974 if (use_taskpool) {
975 sub->mailbox = ast_taskpool_serializer(tps_name, taskpool);
976 } else {
977 sub->mailbox = ast_taskprocessor_get(tps_name, TPS_REF_DEFAULT);
978 }
979 if (!sub->mailbox) {
980 ao2_ref(sub, -1);
981
982 return NULL;
983 }
984 ast_taskprocessor_set_local(sub->mailbox, sub);
985 /* Taskprocessor has a reference */
986 ao2_ref(sub, +1);
987 }
988
989 ao2_ref(topic, +1);
990 sub->topic = topic;
991 sub->callback = callback;
992 sub->data = data;
993 ast_cond_init(&sub->join_cond, NULL);
994 sub->filter = STASIS_SUBSCRIPTION_FILTER_NONE;
995 AST_VECTOR_INIT(&sub->accepted_message_types, 0);
996 sub->accepted_formatters = STASIS_SUBSCRIPTION_FORMATTER_NONE;
997
998 if (topic_add_subscription(topic, sub) != 0) {
999 ao2_ref(sub, -1);
1000 ao2_ref(topic, -1);
1001
1002 return NULL;
1003 }
1004 send_subscription_subscribe(topic, sub);
1005
1006 return sub;
1007 }
1008
1009 struct stasis_subscription *__stasis_subscribe(
1010 struct stasis_topic *topic,
1011 stasis_subscription_cb callback,
1012 void *data,
1013 const char *file,
1014 int lineno,
1015 const char *func)
1016 {
1017 return internal_stasis_subscribe(topic, callback, data, 1, 0, file, lineno, func);
1018 }
1019
1020 struct stasis_subscription *__stasis_subscribe_pool(
1021 struct stasis_topic *topic,
1022 stasis_subscription_cb callback,
1023 void *data,
1024 const char *file,
1025 int lineno,
1026 const char *func)
1027 {
1028 return internal_stasis_subscribe(topic, callback, data, 1, 1, file, lineno, func);
1029 }
1030
1031 static int sub_cleanup(void *data)
1032 {
1033 struct stasis_subscription *sub = data;
1034 ao2_cleanup(sub);
1035 return 0;
1036 }
1037
1038 struct stasis_subscription *stasis_unsubscribe(struct stasis_subscription *sub)
1039 {
1040 /* The subscription may be the last ref to this topic. Hold
1041 * the topic ref open until after the unlock. */
1042 struct stasis_topic *topic;
1043
1044 if (!sub) {
1045 return NULL;
1046 }
1047
1048 topic = ao2_bump(sub->topic);
1049
1050 /* We have to remove the subscription first, to ensure the unsubscribe
1051 * is the final message */
1052 if (topic_remove_subscription(sub->topic, sub) != 0) {
1053 ast_log(LOG_ERROR,
1054 "Internal error: subscription has invalid topic\n");
1055 ao2_cleanup(topic);
1056
1057 return NULL;
1058 }
1059
1060 /* Now let everyone know about the unsubscribe */
1061 send_subscription_unsubscribe(topic, sub);
1062
1063 /* When all that's done, remove the ref the mailbox has on the sub */
1064 if (sub->mailbox) {
1065 if (ast_taskprocessor_push(sub->mailbox, sub_cleanup, sub)) {
1066 /* Nothing we can do here, the conditional is just to keep
1067 * the compiler happy that we're not ignoring the result. */
1068 }
1069 }
1070
1071 /* Unsubscribing unrefs the subscription */
1072 ao2_cleanup(sub);
1073 ao2_cleanup(topic);
1074
1075 return NULL;
1076 }
1077
1078 int stasis_subscription_set_congestion_limits(struct stasis_subscription *subscription,
1079 long low_water, long high_water)
1080 {
1081 int res = -1;
1082
1083 if (subscription) {
1084 res = ast_taskprocessor_alert_set_levels(subscription->mailbox,
1085 low_water, high_water);
1086 }
1087 return res;
1088 }
1089
1090 int stasis_subscription_accept_message_type(struct stasis_subscription *subscription,
1091 const struct stasis_message_type *type)
1092 {
1093 if (!subscription) {
1094 return -1;
1095 }
1096
1097 ast_assert(type != NULL);
1098 ast_assert(stasis_message_type_name(type) != NULL);
1099
1100 if (!type || !stasis_message_type_name(type)) {
1101 /* Filtering is unreliable as this message type is not yet initialized
1102 * so force all messages through.
1103 */
1104 subscription->filter = STASIS_SUBSCRIPTION_FILTER_FORCED_NONE;
1105 return 0;
1106 }
1107
1108 ao2_lock(subscription->topic);
1109 if (AST_VECTOR_REPLACE(&subscription->accepted_message_types, stasis_message_type_id(type), 1)) {
1110 /* We do this for the same reason as above. The subscription can still operate, so allow
1111 * it to do so by forcing all messages through.
1112 */
1113 subscription->filter = STASIS_SUBSCRIPTION_FILTER_FORCED_NONE;
1114 }
1115 ao2_unlock(subscription->topic);
1116
1117 return 0;
1118 }
1119
1120 int stasis_subscription_decline_message_type(struct stasis_subscription *subscription,
1121 const struct stasis_message_type *type)
1122 {
1123 if (!subscription) {
1124 return -1;
1125 }
1126
1127 ast_assert(type != NULL);
1128 ast_assert(stasis_message_type_name(type) != NULL);
1129
1130 if (!type || !stasis_message_type_name(type)) {
1131 return 0;
1132 }
1133
1134 ao2_lock(subscription->topic);
1135 if (stasis_message_type_id(type) < AST_VECTOR_SIZE(&subscription->accepted_message_types)) {
1136 /* The memory is already allocated so this can't fail */
1137 AST_VECTOR_REPLACE(&subscription->accepted_message_types, stasis_message_type_id(type), 0);
1138 }
1139 ao2_unlock(subscription->topic);
1140
1141 return 0;
1142 }
1143
1144 int stasis_subscription_set_filter(struct stasis_subscription *subscription,
1145 enum stasis_subscription_message_filter filter)
1146 {
1147 if (!subscription) {
1148 return -1;
1149 }
1150
1151 ao2_lock(subscription->topic);
1152 if (subscription->filter != STASIS_SUBSCRIPTION_FILTER_FORCED_NONE) {
1153 subscription->filter = filter;
1154 }
1155 ao2_unlock(subscription->topic);
1156
1157 return 0;
1158 }
1159
1160 void stasis_subscription_accept_formatters(struct stasis_subscription *subscription,
1161 enum stasis_subscription_message_formatters formatters)
1162 {
1163 ast_assert(subscription != NULL);
1164
1165 ao2_lock(subscription->topic);
1166 subscription->accepted_formatters = formatters;
1167 ao2_unlock(subscription->topic);
1168
1169 return;
1170 }
1171
1172 void stasis_subscription_join(struct stasis_subscription *subscription)
1173 {
1174 if (subscription) {
1175 ao2_lock(subscription);
1176 /* Wait until the processed flag has been set */
1177 while (!subscription->final_message_processed) {
1178 ast_cond_wait(&subscription->join_cond,
1179 ao2_object_get_lockaddr(subscription));
1180 }
1181 ao2_unlock(subscription);
1182 }
1183 }
1184
1185 int stasis_subscription_is_done(struct stasis_subscription *subscription)
1186 {
1187 if (subscription) {
1188 int ret;
1189
1190 ao2_lock(subscription);
1191 ret = subscription->final_message_rxed;
1192 ao2_unlock(subscription);
1193
1194 return ret;
1195 }
1196
1197 /* Null subscription is about as done as you can get */
1198 return 1;
1199 }
1200
1201 struct stasis_subscription *stasis_unsubscribe_and_join(
1202 struct stasis_subscription *subscription)
1203 {
1204 if (!subscription) {
1205 return NULL;
1206 }
1207
1208 /* Bump refcount to hold it past the unsubscribe */
1209 ao2_ref(subscription, +1);
1210 stasis_unsubscribe(subscription);
1211 stasis_subscription_join(subscription);
1212 /* Now decrement the refcount back */
1213 ao2_cleanup(subscription);
1214 return NULL;
1215 }
1216
1217 int stasis_subscription_is_subscribed(const struct stasis_subscription *sub)
1218 {
1219 if (sub) {
1220 size_t i;
1221 struct stasis_topic *topic = sub->topic;
1222
1223 ao2_lock(topic);
1224 for (i = 0; i < AST_VECTOR_SIZE(&topic->subscribers); ++i) {
1225 if (AST_VECTOR_GET(&topic->subscribers, i) == sub) {
1226 ao2_unlock(topic);
1227 return 1;
1228 }
1229 }
1230 ao2_unlock(topic);
1231 }
1232
1233 return 0;
1234 }
1235
1236 const char *stasis_subscription_uniqueid(const struct stasis_subscription *sub)
1237 {
1238 return sub->uniqueid;
1239 }
1240
1241 int stasis_subscription_final_message(struct stasis_subscription *sub, struct stasis_message *msg)
1242 {
1243 struct stasis_subscription_change *change;
1244
1245 if (stasis_message_type(msg) != stasis_subscription_change_type()) {
1246 return 0;
1247 }
1248
1249 change = stasis_message_data(msg);
1250 if (strcmp("Unsubscribe", change->description)) {
1251 return 0;
1252 }
1253
1254 if (strcmp(stasis_subscription_uniqueid(sub), change->uniqueid)) {
1255 return 0;
1256 }
1257
1258 return 1;
1259 }
1260
1261 /*!
1262 * \brief Add a subscriber to a topic.
1263 * \param topic Topic
1264 * \param sub Subscriber
1265 * \return 0 on success
1266 * \return Non-zero on error
1267 */
1268 static int topic_add_subscription(struct stasis_topic *topic, struct stasis_subscription *sub)
1269 {
1270 size_t idx;
1271
1272 ao2_lock(topic);
1273 /* The reference from the topic to the subscription is shared with
1274 * the owner of the subscription, which will explicitly unsubscribe
1275 * to release it.
1276 *
1277 * If we bumped the refcount here, the owner would have to unsubscribe
1278 * and cleanup, which is a bit awkward. */
1279 AST_VECTOR_APPEND(&topic->subscribers, sub);
1280
1281 for (idx = 0; idx < AST_VECTOR_SIZE(&topic->upstream_topics); ++idx) {
1282 topic_add_subscription(
1283 AST_VECTOR_GET(&topic->upstream_topics, idx), sub);
1284 }
1285
1286 #ifdef AST_DEVMODE
1287 ast_str_container_add(topic->statistics->subscribers, stasis_subscription_uniqueid(sub));
1288 ast_str_container_add(sub->statistics->topics, stasis_topic_name(topic));
1289 #endif
1290
1291 ao2_unlock(topic);
1292
1293 return 0;
1294 }
1295
1296 static int topic_remove_subscription(struct stasis_topic *topic, struct stasis_subscription *sub)
1297 {
1298 size_t idx;
1299 int res;
1300
1301 ao2_lock(topic);
1302 for (idx = 0; idx < AST_VECTOR_SIZE(&topic->upstream_topics); ++idx) {
1303 topic_remove_subscription(
1304 AST_VECTOR_GET(&topic->upstream_topics, idx), sub);
1305 }
1306 res = AST_VECTOR_REMOVE_ELEM_UNORDERED(&topic->subscribers, sub,
1307 AST_VECTOR_ELEM_CLEANUP_NOOP);
1308
1309 #ifdef AST_DEVMODE
1310 if (!res) {
1311 ast_str_container_remove(topic->statistics->subscribers, stasis_subscription_uniqueid(sub));
1312 ast_str_container_remove(sub->statistics->topics, stasis_topic_name(topic));
1313 }
1314 #endif
1315
1316 ao2_unlock(topic);
1317
1318 return res;
1319 }
1320
1321 /*!
1322 * \internal \brief Dispatch a message to a subscriber asynchronously
1323 * \param local \ref ast_taskprocessor_local object
1324 * \return 0
1325 */
1326 static int dispatch_exec_async(struct ast_taskprocessor_local *local)
1327 {
1328 struct stasis_subscription *sub = local->local_data;
1329 struct stasis_message *message = local->data;
1330
1331 subscription_invoke(sub, message);
1332 ao2_cleanup(message);
1333
1334 return 0;
1335 }
1336
1337 /*!
1338 * \internal \brief Data passed to \ref dispatch_exec_sync to synchronize
1339 * a published message to a subscriber
1340 */
1341 struct sync_task_data {
1342 ast_mutex_t lock;
1343 ast_cond_t cond;
1344 int complete;
1345 void *task_data;
1346 };
1347
1348 /*!
1349 * \internal \brief Dispatch a message to a subscriber synchronously
1350 * \param local \ref ast_taskprocessor_local object
1351 * \return 0
1352 */
1353 static int dispatch_exec_sync(struct ast_taskprocessor_local *local)
1354 {
1355 struct stasis_subscription *sub = local->local_data;
1356 struct sync_task_data *std = local->data;
1357 struct stasis_message *message = std->task_data;
1358
1359 subscription_invoke(sub, message);
1360 ao2_cleanup(message);
1361
1362 ast_mutex_lock(&std->lock);
1363 std->complete = 1;
1364 ast_cond_signal(&std->cond);
1365 ast_mutex_unlock(&std->lock);
1366
1367 return 0;
1368 }
1369
1370 /*!
1371 * \internal \brief Dispatch a message to a subscriber
1372 * \param sub The subscriber to dispatch to
1373 * \param message The message to send
1374 * \param synchronous If non-zero, synchronize on the subscriber receiving
1375 * the message
1376 * \retval 0 if message was not dispatched
1377 * \retval 1 if message was dispatched
1378 */
1379 static unsigned int dispatch_message(struct stasis_subscription *sub,
1380 struct stasis_message *message,
1381 int synchronous)
1382 {
1383 int is_final = stasis_subscription_final_message(sub, message);
1384
1385 /*
1386 * The 'do while' gives us an easy way to skip remaining logic once
1387 * we determine the message should be accepted.
1388 * The code looks more verbose than it needs to be but it optimizes
1389 * down very nicely. It's just easier to understand and debug this way.
1390 */
1391 do {
1392 struct stasis_message_type *message_type = stasis_message_type(message);
1393 int type_id = stasis_message_type_id(message_type);
1394 int type_filter_specified = 0;
1395 int formatter_filter_specified = 0;
1396 int type_filter_passed = 0;
1397 int formatter_filter_passed = 0;
1398
1399 /* We always accept final messages so only run the filter logic if not final */
1400 if (is_final) {
1401 break;
1402 }
1403
1404 type_filter_specified = sub->filter & STASIS_SUBSCRIPTION_FILTER_SELECTIVE;
1405 formatter_filter_specified = sub->accepted_formatters != STASIS_SUBSCRIPTION_FORMATTER_NONE;
1406
1407 /* Accept if no filters of either type were specified */
1408 if (!type_filter_specified && !formatter_filter_specified) {
1409 break;
1410 }
1411
1412 type_filter_passed = type_filter_specified
1413 && type_id < AST_VECTOR_SIZE(&sub->accepted_message_types)
1414 && AST_VECTOR_GET(&sub->accepted_message_types, type_id);
1415
1416 /*
1417 * Since the type and formatter filters are OR'd, we can skip
1418 * the formatter check if the type check passes.
1419 */
1420 if (type_filter_passed) {
1421 break;
1422 }
1423
1424 formatter_filter_passed = formatter_filter_specified
1425 && (sub->accepted_formatters & stasis_message_type_available_formatters(message_type));
1426
1427 if (formatter_filter_passed) {
1428 break;
1429 }
1430
1431 #ifdef AST_DEVMODE
1432 ast_atomic_fetchadd_int(&sub->statistics->messages_dropped, +1);
1433 #endif
1434
1435 return 0;
1436
1437 } while (0);
1438
1439 #ifdef AST_DEVMODE
1440 ast_atomic_fetchadd_int(&sub->statistics->messages_passed, +1);
1441 #endif
1442
1443 if (!sub->mailbox) {
1444 /* Dispatch directly */
1445 subscription_invoke(sub, message);
1446 return 1;
1447 }
1448
1449 /* Bump the message for the taskprocessor push. This will get de-ref'd
1450 * by the task processor callback.
1451 */
1452 ao2_bump(message);
1453 if (!synchronous) {
1454 if (ast_taskprocessor_push_local(sub->mailbox, dispatch_exec_async, message)) {
1455 /* Push failed; ugh. */
1456 ast_log(LOG_ERROR, "Dropping async dispatch\n");
1457 ao2_cleanup(message);
1458 return 0;
1459 }
1460 } else {
1461 struct sync_task_data std;
1462
1463 ast_mutex_init(&std.lock);
1464 ast_cond_init(&std.cond, NULL);
1465 std.complete = 0;
1466 std.task_data = message;
1467
1468 if (ast_taskprocessor_push_local(sub->mailbox, dispatch_exec_sync, &std)) {
1469 /* Push failed; ugh. */
1470 ast_log(LOG_ERROR, "Dropping sync dispatch\n");
1471 ao2_cleanup(message);
1472 ast_mutex_destroy(&std.lock);
1473 ast_cond_destroy(&std.cond);
1474 return 0;
1475 }
1476
1477 ast_mutex_lock(&std.lock);
1478 while (!std.complete) {
1479 ast_cond_wait(&std.cond, &std.lock);
1480 }
1481 ast_mutex_unlock(&std.lock);
1482
1483 ast_mutex_destroy(&std.lock);
1484 ast_cond_destroy(&std.cond);
1485 }
1486
1487 return 1;
1488 }
1489
1490 /*!
1491 * \internal \brief Publish a message to a topic's subscribers
1492 * \brief topic The topic to publish to
1493 * \brief message The message to publish
1494 * \brief sync_sub An optional subscriber of the topic to publish synchronously
1495 * to
1496 */
1497 static void publish_msg(struct stasis_topic *topic,
1498 struct stasis_message *message, struct stasis_subscription *sync_sub)
1499 {
1500 size_t i;
1501 #ifdef AST_DEVMODE
1502 unsigned int dispatched = 0;
1503 int message_type_id = stasis_message_type_id(stasis_message_type(message));
1504 struct stasis_message_type_statistics *statistics;
1505 struct timeval start;
1506 long elapsed;
1507 #endif
1508
1509 ast_assert(topic != NULL);
1510 ast_assert(message != NULL);
1511
1512 #ifdef AST_DEVMODE
1513 ast_mutex_lock(&message_type_statistics_lock);
1514 if (message_type_id >= AST_VECTOR_SIZE(&message_type_statistics)) {
1515 struct stasis_message_type_statistics new_statistics = {
1516 .published = 0,
1517 };
1518 if (AST_VECTOR_REPLACE(&message_type_statistics, message_type_id, new_statistics)) {
1519 ast_mutex_unlock(&message_type_statistics_lock);
1520 return;
1521 }
1522 }
1523 statistics = AST_VECTOR_GET_ADDR(&message_type_statistics, message_type_id);
1524 statistics->message_type = stasis_message_type(message);
1525 ast_mutex_unlock(&message_type_statistics_lock);
1526
1527 ast_atomic_fetchadd_int(&statistics->published, +1);
1528 #endif
1529
1530 /* If there are no subscribers don't bother */
1531 if (!stasis_topic_subscribers(topic)) {
1532 #ifdef AST_DEVMODE
1533 ast_atomic_fetchadd_int(&statistics->unused, +1);
1534 ast_atomic_fetchadd_int(&topic->statistics->messages_not_dispatched, +1);
1535 #endif
1536 return;
1537 }
1538
1539 /*
1540 * The topic may be unref'ed by the subscription invocation.
1541 * Make sure we hold onto a reference while dispatching.
1542 */
1543 ao2_ref(topic, +1);
1544 #ifdef AST_DEVMODE
1545 start = ast_tvnow();
1546 #endif
1547 ao2_lock(topic);
1548 for (i = 0; i < AST_VECTOR_SIZE(&topic->subscribers); ++i) {
1549 struct stasis_subscription *sub = AST_VECTOR_GET(&topic->subscribers, i);
1550
1551 ast_assert(sub != NULL);
1552 #ifdef AST_DEVMODE
1553 dispatched +=
1554 #endif
1555 dispatch_message(sub, message, (sub == sync_sub));
1556 }
1557 ao2_unlock(topic);
1558
1559 #ifdef AST_DEVMODE
1560 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1561 if (elapsed > topic->statistics->highest_time_dispatched) {
1562 topic->statistics->highest_time_dispatched = elapsed;
1563 }
1564 if (elapsed < topic->statistics->lowest_time_dispatched) {
1565 topic->statistics->lowest_time_dispatched = elapsed;
1566 }
1567 if (dispatched) {
1568 ast_atomic_fetchadd_int(&topic->statistics->messages_dispatched, +1);
1569 } else {
1570 ast_atomic_fetchadd_int(&statistics->unused, +1);
1571 ast_atomic_fetchadd_int(&topic->statistics->messages_not_dispatched, +1);
1572 }
1573 #endif
1574
1575 ao2_ref(topic, -1);
1576 }
1577
1578 void stasis_publish(struct stasis_topic *topic, struct stasis_message *message)
1579 {
1580 publish_msg(topic, message, NULL);
1581 }
1582
1583 void stasis_publish_sync(struct stasis_subscription *sub, struct stasis_message *message)
1584 {
1585 ast_assert(sub != NULL);
1586
1587 publish_msg(sub->topic, message, sub);
1588 }
1589
1590 /*!
1591 * \brief Forwarding information
1592 *
1593 * Any message posted to \a from_topic is forwarded to \a to_topic.
1594 *
1595 * In cases where both the \a from_topic and \a to_topic need to be locked,
1596 * always lock the \a to_topic first, then the \a from_topic. Lest you deadlock.
1597 */
1598 struct stasis_forward {
1599 /*! Originating topic */
1600 struct stasis_topic *from_topic;
1601 /*! Destination topic */
1602 struct stasis_topic *to_topic;
1603 };
1604
1605 static void forward_dtor(void *obj)
1606 {
1607 struct stasis_forward *forward = obj;
1608
1609 ao2_cleanup(forward->from_topic);
1610 forward->from_topic = NULL;
1611 ao2_cleanup(forward->to_topic);
1612 forward->to_topic = NULL;
1613 }
1614
1615 struct stasis_forward *stasis_forward_cancel(struct stasis_forward *forward)
1616 {
1617 int idx;
1618 struct stasis_topic *from;
1619 struct stasis_topic *to;
1620
1621 if (!forward) {
1622 return NULL;
1623 }
1624
1625 from = forward->from_topic;
1626 to = forward->to_topic;
1627
1628 if (from && to) {
1629 topic_lock_both(to, from);
1630 AST_VECTOR_REMOVE_ELEM_UNORDERED(&to->upstream_topics, from,
1631 AST_VECTOR_ELEM_CLEANUP_NOOP);
1632
1633 for (idx = 0; idx < AST_VECTOR_SIZE(&to->subscribers); ++idx) {
1634 topic_remove_subscription(from, AST_VECTOR_GET(&to->subscribers, idx));
1635 }
1636 ao2_unlock(from);
1637 ao2_unlock(to);
1638 }
1639
1640 ao2_cleanup(forward);
1641
1642 return NULL;
1643 }
1644
1645 struct stasis_forward *stasis_forward_all(struct stasis_topic *from_topic,
1646 struct stasis_topic *to_topic)
1647 {
1648 int res;
1649 size_t idx;
1650 struct stasis_forward *forward;
1651
1652 if (!from_topic || !to_topic) {
1653 return NULL;
1654 }
1655
1656 forward = ao2_alloc_options(sizeof(*forward), forward_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
1657 if (!forward) {
1658 return NULL;
1659 }
1660
1661 /* Forwards to ourselves are implicit. */
1662 if (to_topic == from_topic) {
1663 return forward;
1664 }
1665
1666 forward->from_topic = ao2_bump(from_topic);
1667 forward->to_topic = ao2_bump(to_topic);
1668
1669 topic_lock_both(to_topic, from_topic);
1670 res = AST_VECTOR_APPEND(&to_topic->upstream_topics, from_topic);
1671 if (res != 0) {
1672 ao2_unlock(from_topic);
1673 ao2_unlock(to_topic);
1674 ao2_ref(forward, -1);
1675 return NULL;
1676 }
1677
1678 for (idx = 0; idx < AST_VECTOR_SIZE(&to_topic->subscribers); ++idx) {
1679 topic_add_subscription(from_topic, AST_VECTOR_GET(&to_topic->subscribers, idx));
1680 }
1681 ao2_unlock(from_topic);
1682 ao2_unlock(to_topic);
1683
1684 return forward;
1685 }
1686
1687 static void subscription_change_dtor(void *obj)
1688 {
1689 struct stasis_subscription_change *change = obj;
1690
1691 ao2_cleanup(change->topic);
1692 }
1693
1694 static struct stasis_subscription_change *subscription_change_alloc(struct stasis_topic *topic, const char *uniqueid, const char *description)
1695 {
1696 size_t description_len = strlen(description) + 1;
1697 size_t uniqueid_len = strlen(uniqueid) + 1;
1698 struct stasis_subscription_change *change;
1699
1700 change = ao2_alloc_options(sizeof(*change) + description_len + uniqueid_len,
1701 subscription_change_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
1702 if (!change) {
1703 return NULL;
1704 }
1705
1706 strcpy(change->description, description); /* SAFE */
1707 change->uniqueid = change->description + description_len;
1708 ast_copy_string(change->uniqueid, uniqueid, uniqueid_len); /* SAFE */
1709 ao2_ref(topic, +1);
1710 change->topic = topic;
1711
1712 return change;
1713 }
1714
1715 static void send_subscription_subscribe(struct stasis_topic *topic, struct stasis_subscription *sub)
1716 {
1717 struct stasis_subscription_change *change;
1718 struct stasis_message *msg;
1719
1720 /* This assumes that we have already unsubscribed */
1721 ast_assert(stasis_subscription_is_subscribed(sub));
1722
1723 if (!stasis_subscription_change_type()) {
1724 return;
1725 }
1726
1727 change = subscription_change_alloc(topic, sub->uniqueid, "Subscribe");
1728 if (!change) {
1729 return;
1730 }
1731
1732 msg = stasis_message_create(stasis_subscription_change_type(), change);
1733 if (!msg) {
1734 ao2_cleanup(change);
1735 return;
1736 }
1737
1738 stasis_publish(topic, msg);
1739 ao2_cleanup(msg);
1740 ao2_cleanup(change);
1741 }
1742
1743 static void send_subscription_unsubscribe(struct stasis_topic *topic,
1744 struct stasis_subscription *sub)
1745 {
1746 struct stasis_subscription_change *change;
1747 struct stasis_message *msg;
1748
1749 /* This assumes that we have already unsubscribed */
1750 ast_assert(!stasis_subscription_is_subscribed(sub));
1751
1752 if (!stasis_subscription_change_type()) {
1753 return;
1754 }
1755
1756 change = subscription_change_alloc(topic, sub->uniqueid, "Unsubscribe");
1757 if (!change) {
1758 return;
1759 }
1760
1761 msg = stasis_message_create(stasis_subscription_change_type(), change);
1762 if (!msg) {
1763 ao2_cleanup(change);
1764 return;
1765 }
1766
1767 stasis_publish(topic, msg);
1768
1769 /* Now we have to dispatch to the subscription itself */
1770 dispatch_message(sub, msg, 0);
1771
1772 ao2_cleanup(msg);
1773 ao2_cleanup(change);
1774 }
1775
1776 struct topic_pool_entry {
1777 struct stasis_forward *forward;
1778 struct stasis_topic *topic;
1779 /*
1780 * Per-entry initialization state. This lets us serialize creation of a
1781 * given topic name without holding the pool container lock while doing
1782 * the heavy lifting (topic creation, forwarding setup, etc).
1783 *
1784 * A topic_pool_entry starts life in an "in-flight" state where neither
1785 * initialized nor failed are set. The first thread to link the entry
1786 * into the pool becomes the creator and is responsible for completing
1787 * initialization, setting one of the flags, and broadcasting init_cond.
1788 * Other threads that find the same entry simply wait for initialization
1789 * to complete and then reuse the created topic.
1790 */
1791 ast_mutex_t init_lock;
1792 ast_cond_t init_cond;
1793 unsigned int initialized; /* terminal success state */
1794 unsigned int failed; /* terminal failure state */
1795 char name[0];
1796 };
1797
1798 static void topic_pool_entry_dtor(void *obj)
1799 {
1800 struct topic_pool_entry *entry = obj;
1801
1802 entry->forward = stasis_forward_cancel(entry->forward);
1803 ao2_cleanup(entry->topic);
1804 entry->topic = NULL;
1805 ast_cond_destroy(&entry->init_cond);
1806 ast_mutex_destroy(&entry->init_lock);
1807 }
1808
1809 static struct topic_pool_entry *topic_pool_entry_alloc(const char *topic_name)
1810 {
1811 struct topic_pool_entry *topic_pool_entry;
1812
1813 topic_pool_entry = ao2_alloc_options(sizeof(*topic_pool_entry) + strlen(topic_name) + 1,
1814 topic_pool_entry_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
1815 if (!topic_pool_entry) {
1816 return NULL;
1817 }
1818 ast_mutex_init(&topic_pool_entry->init_lock);
1819 ast_cond_init(&topic_pool_entry->init_cond, NULL);
1820 strcpy(topic_pool_entry->name, topic_name); /* Safe */
1821 return topic_pool_entry;
1822 }
1823
1824 struct stasis_topic_pool {
1825 struct ao2_container *pool_container;
1826 struct stasis_topic *pool_topic;
1827 };
1828
1829 static void topic_pool_dtor(void *obj)
1830 {
1831 struct stasis_topic_pool *pool = obj;
1832
1833 #ifdef AO2_DEBUG
1834 {
1835 char *container_name =
1836 ast_alloca(strlen(stasis_topic_name(pool->pool_topic)) + strlen("-pool") + 1);
1837 sprintf(container_name, "%s-pool", stasis_topic_name(pool->pool_topic));
1838 ao2_container_unregister(container_name);
1839 }
1840 #endif
1841
1842 ao2_cleanup(pool->pool_container);
1843 pool->pool_container = NULL;
1844 ao2_cleanup(pool->pool_topic);
1845 pool->pool_topic = NULL;
1846 }
1847
1848 static int topic_pool_entry_hash(const void *obj, const int flags)
1849 {
1850 const struct topic_pool_entry *object;
1851 const char *key;
1852
1853 switch (flags & OBJ_SEARCH_MASK) {
1854 case OBJ_SEARCH_KEY:
1855 key = obj;
1856 break;
1857 case OBJ_SEARCH_OBJECT:
1858 object = obj;
1859 key = object->name;
1860 break;
1861 default:
1862 /* Hash can only work on something with a full key. */
1863 ast_assert(0);
1864 return 0;
1865 }
1866 return ast_str_case_hash(key);
1867 }
1868
1869 static int topic_pool_entry_cmp(void *obj, void *arg, int flags)
1870 {
1871 const struct topic_pool_entry *object_left = obj;
1872 const struct topic_pool_entry *object_right = arg;
1873 const char *right_key = arg;
1874 int cmp;
1875
1876 switch (flags & OBJ_SEARCH_MASK) {
1877 case OBJ_SEARCH_OBJECT:
1878 right_key = object_right->name;
1879 /* Fall through */
1880 case OBJ_SEARCH_KEY:
1881 cmp = strcasecmp(object_left->name, right_key);
1882 break;
1883 case OBJ_SEARCH_PARTIAL_KEY:
1884 /* Not supported by container */
1885 ast_assert(0);
1886 cmp = -1;
1887 break;
1888 default:
1889 /*
1890 * What arg points to is specific to this traversal callback
1891 * and has no special meaning to astobj2.
1892 */
1893 cmp = 0;
1894 break;
1895 }
1896 if (cmp) {
1897 return 0;
1898 }
1899 /*
1900 * At this point the traversal callback is identical to a sorted
1901 * container.
1902 */
1903 return CMP_MATCH;
1904 }
1905
1906 #ifdef AO2_DEBUG
1907 static void topic_pool_prnt_obj(void *v_obj, void *where, ao2_prnt_fn *prnt)
1908 {
1909 struct topic_pool_entry *entry = v_obj;
1910
1911 if (!entry) {
1912 return;
1913 }
1914 prnt(where, "%s", stasis_topic_name(entry->topic));
1915 }
1916 #endif
1917
1918 struct stasis_topic_pool *stasis_topic_pool_create(struct stasis_topic *pooled_topic)
1919 {
1920 struct stasis_topic_pool *pool;
1921
1922 pool = ao2_alloc_options(sizeof(*pool), topic_pool_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
1923 if (!pool) {
1924 return NULL;
1925 }
1926
1927 pool->pool_container = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
1928 TOPIC_POOL_BUCKETS, topic_pool_entry_hash, NULL, topic_pool_entry_cmp);
1929 if (!pool->pool_container) {
1930 ao2_cleanup(pool);
1931 return NULL;
1932 }
1933
1934 #ifdef AO2_DEBUG
1935 {
1936 char *container_name =
1937 ast_alloca(strlen(stasis_topic_name(pooled_topic)) + strlen("-pool") + 1);
1938 sprintf(container_name, "%s-pool", stasis_topic_name(pooled_topic));
1939 ao2_container_register(container_name, pool->pool_container, topic_pool_prnt_obj);
1940 }
1941 #endif
1942
1943 ao2_ref(pooled_topic, +1);
1944 pool->pool_topic = pooled_topic;
1945
1946 return pool;
1947 }
1948
1949 void stasis_topic_pool_delete_topic(struct stasis_topic_pool *pool, const char *topic_name)
1950 {
1951 /*
1952 * The topic_name passed in could be a fully-qualified name like <pool_topic_name>/<topic_name>
1953 * or just <topic_name>. If it's fully qualified, we need to skip past <pool_topic_name>
1954 * name and search only on <topic_name>.
1955 */
1956 const char *pool_topic_name = stasis_topic_name(pool->pool_topic);
1957 int pool_topic_name_len = strlen(pool_topic_name);
1958 const char *search_topic_name;
1959
1960 if (strncmp(pool_topic_name, topic_name, pool_topic_name_len) == 0) {
1961 search_topic_name = topic_name + pool_topic_name_len + 1;
1962 } else {
1963 search_topic_name = topic_name;
1964 }
1965
1966 ao2_find(pool->pool_container, search_topic_name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1967 }
1968 /*!
1969 * \brief Get a topic from the pool for the given name.
1970 *
1971 * This returns a **borrowed** reference: the pool container owns the topic
1972 * and callers MUST NOT ao2_cleanup() the returned pointer.
1973 *
1974 * To avoid both deadlocks and wasted work we use a per-name "in-flight"
1975 * topic_pool_entry while a topic is being created:
1976 *
1977 * - The pool container lock is held only while looking up or inserting
1978 * the topic_pool_entry for a name.
1979 * - Exactly one thread becomes the creator for a given name and is
1980 * responsible for allocating the topic and wiring up forwarding.
1981 * - Other threads that race for the same name find the in-flight entry
1982 * and wait on its condition variable until initialization completes.
1983 */
1984
1985 struct stasis_topic *stasis_topic_pool_get_topic(struct stasis_topic_pool *pool, const char *topic_name)
1986 {
1987 /*
1988 * Lock ordering:
1989 *
1990 * pool->pool_container (AO2 lock)
1991 * → entry->init_lock
1992 * → topic locks (inside stasis_topic_create() /
1993 * stasis_forward_all())
1994 *
1995 * We intentionally do NOT hold the pool container lock while calling
1996 * stasis_topic_create() or stasis_forward_all() to avoid deadlocks with
1997 * other code that may take topic locks first and then need the pool lock.
1998 */
1999 RAII_VAR(struct topic_pool_entry *, entry, NULL, ao2_cleanup);
2000 char *fq = NULL;
2001 int creator = 0;
2002 int ret;
2003
2004 if (!pool || ast_strlen_zero(topic_name)) {
2005 return NULL;
2006 }
2007
2008 /* Creator / waiter split:
2009 *
2010 * - The first thread to create/link an entry for topic_name becomes the
2011 * "creator" and is responsible for creating the underlying stasis
2012 * topic and wiring up forwarding.
2013 *
2014 * - Other threads that find the entry become "waiters"; they block on
2015 * entry->init_cond until either initialization succeeds or fails.
2016 */
2017
2018 /* --- Creator selection under pool container lock --- */
2019 ao2_lock(pool->pool_container);
2020
2021 entry = ao2_find(pool->pool_container, topic_name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
2022 if (!entry) {
2023 entry = topic_pool_entry_alloc(topic_name);
2024 if (!entry) {
2025 ao2_unlock(pool->pool_container);
2026 return NULL;
2027 }
2028
2029 if (!ao2_link_flags(pool->pool_container, entry, OBJ_NOLOCK)) {
2030 struct topic_pool_entry *other;
2031
2032 other = ao2_find(pool->pool_container, topic_name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
2033 if (other) {
2034 struct topic_pool_entry *tmp = entry;
2035
2036 entry = other;
2037 creator = 0;
2038 ao2_unlock(pool->pool_container);
2039 ao2_ref(tmp, -1);
2040 goto waiter_path;
2041 }
2042
2043 ao2_unlock(pool->pool_container);
2044 return NULL;
2045 }
2046
2047 creator = 1;
2048 }
2049
2050 ao2_unlock(pool->pool_container);
2051
2052 /* --- Waiter path: wait for creator to finish --- */
2053 waiter_path:
2054 if (!creator) {
2055 ast_mutex_lock(&entry->init_lock);
2056 while (!entry->initialized && !entry->failed) {
2057 ast_cond_wait(&entry->init_cond, &entry->init_lock);
2058 }
2059
2060 if (entry->initialized && !entry->failed) {
2061 struct stasis_topic *topic = entry->topic;
2062
2063 if (!topic) {
2064 ast_debug(1, "Pooled topic '%s' marked initialized but topic is NULL\n", entry->name);
2065 ast_mutex_unlock(&entry->init_lock);
2066 return NULL;
2067 }
2068 ast_mutex_unlock(&entry->init_lock);
2069 /* Borrowed reference: container owns the topic */
2070 return topic;
2071 }
2072
2073 ast_mutex_unlock(&entry->init_lock);
2074 return NULL;
2075 }
2076
2077 /* --- Creator path: perform topic creation without pool lock --- */
2078 ast_mutex_lock(&entry->init_lock);
2079 /* Defensive: entry may have been initialized/failed before we acquired init_lock. */
2080 if (entry->initialized || entry->failed) {
2081 struct stasis_topic *topic = entry->initialized ? entry->topic : NULL;
2082 ast_mutex_unlock(&entry->init_lock);
2083 return topic;
2084 }
2085
2086 ret = ast_asprintf(&fq, "%s/%s", stasis_topic_name(pool->pool_topic), topic_name);
2087 if (ret < 0) {
2088 entry->failed = 1;
2089 goto creator_fail;
2090 }
2091
2092 entry->topic = stasis_topic_create(fq);
2093 ast_free(fq);
2094 fq = NULL;
2095
2096 if (!entry->topic) {
2097 entry->failed = 1;
2098 goto creator_fail;
2099 }
2100
2101 entry->forward = stasis_forward_all(entry->topic, pool->pool_topic);
2102 if (!entry->forward) {
2103 ao2_cleanup(entry->topic);
2104 entry->topic = NULL;
2105 entry->failed = 1;
2106 goto creator_fail;
2107 }
2108
2109 entry->initialized = 1;
2110 ast_cond_broadcast(&entry->init_cond);
2111 ast_mutex_unlock(&entry->init_lock);
2112
2113 return entry->topic; /* borrowed ref */
2114
2115 creator_fail:
2116 ast_debug(1, "Failed to create pooled stasis topic '%s/%s'\n", stasis_topic_name(pool->pool_topic), entry->name);
2117 ast_cond_broadcast(&entry->init_cond);
2118 ast_mutex_unlock(&entry->init_lock);
2119
2120 /* Remove failed entry so future callers can retry */
2121 ao2_lock(pool->pool_container);
2122 ao2_unlink(pool->pool_container, entry);
2123 ao2_unlock(pool->pool_container);
2124
2125 return NULL;
2126 }
2127
2128 int stasis_topic_pool_topic_exists(const struct stasis_topic_pool *pool, const char *topic_name)
2129 {
2130 struct topic_pool_entry *topic_pool_entry;
2131
2132 topic_pool_entry = ao2_find(pool->pool_container, topic_name, OBJ_SEARCH_KEY);
2133 if (!topic_pool_entry) {
2134 return 0;
2135 }
2136
2137 ao2_ref(topic_pool_entry, -1);
2138 return 1;
2139 }
2140
2141 void stasis_log_bad_type_access(const char *name)
2142 {
2143 #ifdef AST_DEVMODE
2144 if (!stasis_message_type_declined(name)) {
2145 ast_log(LOG_ERROR, "Use of %s() before init/after destruction\n", name);
2146 }
2147 #endif
2148 }
2149
2150 /*! \brief A multi object blob data structure to carry user event stasis messages */
2151 struct ast_multi_object_blob {
2152 struct ast_json *blob; /*< A blob of JSON data */
2153 AST_VECTOR(, void *) snapshots[STASIS_UMOS_MAX]; /*< Vector of snapshots for each type */
2154 };
2155
2156 /*!
2157 * \internal
2158 * \brief Destructor for \ref ast_multi_object_blob objects
2159 */
2160 static void multi_object_blob_dtor(void *obj)
2161 {
2162 struct ast_multi_object_blob *multi = obj;
2163 int type;
2164 int i;
2165
2166 for (type = 0; type < STASIS_UMOS_MAX; ++type) {
2167 for (i = 0; i < AST_VECTOR_SIZE(&multi->snapshots[type]); ++i) {
2168 ao2_cleanup(AST_VECTOR_GET(&multi->snapshots[type], i));
2169 }
2170 AST_VECTOR_FREE(&multi->snapshots[type]);
2171 }
2172 ast_json_unref(multi->blob);
2173 }
2174
2175 /*! \brief Create a stasis user event multi object blob */
2176 struct ast_multi_object_blob *ast_multi_object_blob_create(struct ast_json *blob)
2177 {
2178 int type;
2179 struct ast_multi_object_blob *multi;
2180
2181 ast_assert(blob != NULL);
2182
2183 multi = ao2_alloc(sizeof(*multi), multi_object_blob_dtor);
2184 if (!multi) {
2185 return NULL;
2186 }
2187
2188 for (type = 0; type < STASIS_UMOS_MAX; ++type) {
2189 if (AST_VECTOR_INIT(&multi->snapshots[type], 0)) {
2190 ao2_ref(multi, -1);
2191
2192 return NULL;
2193 }
2194 }
2195
2196 multi->blob = ast_json_ref(blob);
2197
2198 return multi;
2199 }
2200
2201 /*! \brief Add an object (snapshot) to the blob */
2202 void ast_multi_object_blob_add(struct ast_multi_object_blob *multi,
2203 enum stasis_user_multi_object_snapshot_type type, void *object)
2204 {
2205 if (!multi || !object || AST_VECTOR_APPEND(&multi->snapshots[type], object)) {
2206 ao2_cleanup(object);
2207 }
2208 }
2209
2210 /*! \brief Publish single channel user event (for app_userevent compatibility) */
2211 void ast_multi_object_blob_single_channel_publish(struct ast_channel *chan,
2212 struct stasis_message_type *type, struct ast_json *blob)
2213 {
2214 struct stasis_message *message;
2215 struct ast_channel_snapshot *channel_snapshot;
2216 struct ast_multi_object_blob *multi;
2217
2218 if (!type) {
2219 return;
2220 }
2221
2222 multi = ast_multi_object_blob_create(blob);
2223 if (!multi) {
2224 return;
2225 }
2226
2227 channel_snapshot = ast_channel_snapshot_create(chan);
2228 if (!channel_snapshot) {
2229 ao2_ref(multi, -1);
2230 return;
2231 }
2232
2233 /* this call steals the channel_snapshot reference */
2234 ast_multi_object_blob_add(multi, STASIS_UMOS_CHANNEL, channel_snapshot);
2235
2236 message = stasis_message_create(type, multi);
2237 ao2_ref(multi, -1);
2238 if (message) {
2239 /* app_userevent still publishes to channel */
2240 stasis_publish(ast_channel_topic(chan), message);
2241 ao2_ref(message, -1);
2242 }
2243 }
2244
2245 /*! \internal \brief convert multi object blob to ari json */
2246 static struct ast_json *multi_user_event_to_json(
2247 struct stasis_message *message,
2248 const struct stasis_message_sanitizer *sanitize)
2249 {
2250 struct ast_json *out;
2251 struct ast_multi_object_blob *multi = stasis_message_data(message);
2252 struct ast_json *blob = multi->blob;
2253 const struct timeval *tv = stasis_message_timestamp(message);
2254 enum stasis_user_multi_object_snapshot_type type;
2255 int i;
2256
2257 out = ast_json_object_create();
2258 if (!out) {
2259 return NULL;
2260 }
2261
2262 ast_json_object_set(out, "type", ast_json_string_create("ChannelUserevent"));
2263 ast_json_object_set(out, "timestamp", ast_json_timeval(*tv, NULL));
2264 ast_json_object_set(out, "eventname", ast_json_ref(ast_json_object_get(blob, "eventname")));
2265 ast_json_object_set(out, "userevent", ast_json_ref(blob));
2266
2267 for (type = 0; type < STASIS_UMOS_MAX; ++type) {
2268 for (i = 0; i < AST_VECTOR_SIZE(&multi->snapshots[type]); ++i) {
2269 struct ast_json *json_object = NULL;
2270 char *name = NULL;
2271 void *snapshot = AST_VECTOR_GET(&multi->snapshots[type], i);
2272
2273 switch (type) {
2274 case STASIS_UMOS_CHANNEL:
2275 json_object = ast_channel_snapshot_to_json(snapshot, sanitize);
2276 name = "channel";
2277 break;
2278 case STASIS_UMOS_BRIDGE:
2279 json_object = ast_bridge_snapshot_to_json(snapshot, sanitize);
2280 name = "bridge";
2281 break;
2282 case STASIS_UMOS_ENDPOINT:
2283 json_object = ast_endpoint_snapshot_to_json(snapshot, sanitize);
2284 name = "endpoint";
2285 break;
2286 }
2287 if (json_object) {
2288 ast_json_object_set(out, name, json_object);
2289 }
2290 }
2291 }
2292
2293 return out;
2294 }
2295
2296 /*! \internal \brief convert multi object blob to ami string */
2297 static struct ast_str *multi_object_blob_to_ami(void *obj)
2298 {
2299 struct ast_str *ami_str=ast_str_create(1024);
2300 struct ast_str *ami_snapshot;
2301 const struct ast_multi_object_blob *multi = obj;
2302 enum stasis_user_multi_object_snapshot_type type;
2303 int i;
2304
2305 if (!ami_str) {
2306 return NULL;
2307 }
2308 if (!multi) {
2309 ast_free(ami_str);
2310 return NULL;
2311 }
2312
2313 for (type = 0; type < STASIS_UMOS_MAX; ++type) {
2314 for (i = 0; i < AST_VECTOR_SIZE(&multi->snapshots[type]); ++i) {
2315 char *name = NULL;
2316 void *snapshot = AST_VECTOR_GET(&multi->snapshots[type], i);
2317 ami_snapshot = NULL;
2318
2319 if (i > 0) {
2320 ast_asprintf(&name, "%d", i + 1);
2321 }
2322
2323 switch (type) {
2324 case STASIS_UMOS_CHANNEL:
2325 ami_snapshot = ast_manager_build_channel_state_string_prefix(snapshot, name ?: "");
2326 break;
2327
2328 case STASIS_UMOS_BRIDGE:
2329 ami_snapshot = ast_manager_build_bridge_state_string_prefix(snapshot, name ?: "");
2330 break;
2331
2332 case STASIS_UMOS_ENDPOINT:
2333 /* currently not sending endpoint snapshots to AMI */
2334 break;
2335 }
2336 if (ami_snapshot) {
2337 ast_str_append(&ami_str, 0, "%s", ast_str_buffer(ami_snapshot));
2338 ast_free(ami_snapshot);
2339 }
2340 ast_free(name);
2341 }
2342 }
2343
2344 return ami_str;
2345 }
2346
2347 /*! \internal \brief Callback to pass only user defined parameters from blob */
2348 static int userevent_exclusion_cb(const char *key)
2349 {
2350 if (!strcmp("eventname", key)) {
2351 return 1;
2352 }
2353 return 0;
2354 }
2355
2356 static struct ast_manager_event_blob *multi_user_event_to_ami(
2357 struct stasis_message *message)
2358 {
2359 RAII_VAR(struct ast_str *, object_string, NULL, ast_free);
2360 RAII_VAR(struct ast_str *, body, NULL, ast_free);
2361 struct ast_multi_object_blob *multi = stasis_message_data(message);
2362 const char *eventname;
2363
2364 eventname = ast_json_string_get(ast_json_object_get(multi->blob, "eventname"));
2365 body = ast_manager_str_from_json_object(multi->blob, userevent_exclusion_cb);
2366 object_string = multi_object_blob_to_ami(multi);
2367 if (!object_string || !body) {
2368 return NULL;
2369 }
2370
2371 return ast_manager_event_blob_create(EVENT_FLAG_USER, "UserEvent",
2372 "%s"
2373 "UserEvent: %s\r\n"
2374 "%s",
2375 ast_str_buffer(object_string),
2376 eventname,
2377 ast_str_buffer(body));
2378 }
2379
2380 /*! \brief A structure to hold global configuration-related options */
2381 struct stasis_declined_config {
2382 /*! The list of message types to decline */
2383 struct ao2_container *declined;
2384 };
2385
2386 /*! \brief Taskpool configuration options */
2387 struct stasis_taskpool_conf {
2388 /*! Minimum size of the taskpool */
2389 int minimum_size;
2390 /*! Initial size of the taskpool */
2391 int initial_size;
2392 /*! Time, in seconds, before we expire a taskprocessor */
2393 int idle_timeout_sec;
2394 /*! Maximum number of taskprocessors to allow */
2395 int max_size;
2396 };
2397
2398 struct stasis_config {
2399 /*! Taskpool configuration options */
2400 struct stasis_taskpool_conf *taskpool_options;
2401 /*! Declined message types */
2402 struct stasis_declined_config *declined_message_types;
2403 };
2404
2405 static struct aco_type threadpool_option = {
2406 .type = ACO_GLOBAL,
2407 .name = "threadpool",
2408 .item_offset = offsetof(struct stasis_config, taskpool_options),
2409 .category = "threadpool",
2410 .category_match = ACO_WHITELIST_EXACT,
2411 };
2412
2413 static struct aco_type taskpool_option = {
2414 .type = ACO_GLOBAL,
2415 .name = "taskpool",
2416 .item_offset = offsetof(struct stasis_config, taskpool_options),
2417 .category = "taskpool",
2418 .category_match = ACO_WHITELIST_EXACT,
2419 };
2420
2421 static struct aco_type *taskpool_options[] = ACO_TYPES(&threadpool_option, &taskpool_option);
2422
2423 /*! \brief An aco_type structure to link the "declined_message_types" category to the stasis_declined_config type */
2424 static struct aco_type declined_option = {
2425 .type = ACO_GLOBAL,
2426 .name = "declined_message_types",
2427 .item_offset = offsetof(struct stasis_config, declined_message_types),
2428 .category_match = ACO_WHITELIST_EXACT,
2429 .category = "declined_message_types",
2430 };
2431
2432 struct aco_type *declined_options[] = ACO_TYPES(&declined_option);
2433
2434 struct aco_file stasis_conf = {
2435 .filename = "stasis.conf",
2436 .types = ACO_TYPES(&declined_option, &threadpool_option, &taskpool_option),
2437 };
2438
2439 /*! \brief A global object container that will contain the stasis_config that gets swapped out on reloads */
2440 static AO2_GLOBAL_OBJ_STATIC(globals);
2441
2442 static void *stasis_config_alloc(void);
2443
2444 /*! \brief Register information about the configs being processed by this module */
2445 CONFIG_INFO_CORE("stasis", cfg_info, globals, stasis_config_alloc,
2446 .files = ACO_FILES(&stasis_conf),
2447 );
2448
2449 static void stasis_declined_config_destructor(void *obj)
2450 {
2451 struct stasis_declined_config *declined = obj;
2452
2453 ao2_cleanup(declined->declined);
2454 }
2455
2456 static void stasis_config_destructor(void *obj)
2457 {
2458 struct stasis_config *cfg = obj;
2459
2460 ao2_cleanup(cfg->declined_message_types);
2461 ast_free(cfg->taskpool_options);
2462 }
2463
2464 static void *stasis_config_alloc(void)
2465 {
2466 struct stasis_config *cfg;
2467
2468 if (!(cfg = ao2_alloc(sizeof(*cfg), stasis_config_destructor))) {
2469 return NULL;
2470 }
2471
2472 cfg->taskpool_options = ast_calloc(1, sizeof(*cfg->taskpool_options));
2473 if (!cfg->taskpool_options) {
2474 ao2_ref(cfg, -1);
2475 return NULL;
2476 }
2477
2478 cfg->declined_message_types = ao2_alloc(sizeof(*cfg->declined_message_types),
2479 stasis_declined_config_destructor);
2480 if (!cfg->declined_message_types) {
2481 ao2_ref(cfg, -1);
2482 return NULL;
2483 }
2484
2485 cfg->declined_message_types->declined = ast_str_container_alloc(13);
2486 if (!cfg->declined_message_types->declined) {
2487 ao2_ref(cfg, -1);
2488 return NULL;
2489 }
2490
2491 return cfg;
2492 }
2493
2494 int stasis_message_type_declined(const char *name)
2495 {
2496 struct stasis_config *cfg = ao2_global_obj_ref(globals);
2497 char *name_in_declined;
2498 int res;
2499
2500 if (!cfg || !cfg->declined_message_types) {
2501 ao2_cleanup(cfg);
2502 return 0;
2503 }
2504
2505 name_in_declined = ao2_find(cfg->declined_message_types->declined, name, OBJ_SEARCH_KEY);
2506 res = name_in_declined ? 1 : 0;
2507 ao2_cleanup(name_in_declined);
2508 ao2_ref(cfg, -1);
2509 if (res) {
2510 ast_debug(4, "Declining to allocate Stasis message type '%s' due to configuration\n", name);
2511 }
2512 return res;
2513 }
2514
2515 static int declined_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
2516 {
2517 struct stasis_declined_config *declined = obj;
2518
2519 if (ast_strlen_zero(var->value)) {
2520 return 0;
2521 }
2522
2523 if (ast_str_container_add(declined->declined, var->value)) {
2524 return -1;
2525 }
2526
2527 return 0;
2528 }
2529
2530 /*!
2531 * @{ \brief Define multi user event message type(s).
2532 */
2533
2534 STASIS_MESSAGE_TYPE_DEFN(ast_multi_user_event_type,
2535 .to_json = multi_user_event_to_json,
2536 .to_ami = multi_user_event_to_ami,
2537 );
2538
2539 /*! @} */
2540
2541 /*!
2542 * \internal
2543 * \brief CLI command implementation for 'stasis show topics'
2544 */
2545 static char *stasis_show_topics(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2546 {
2547 struct ao2_iterator iter;
2548 struct topic_proxy *topic;
2549 struct ao2_container *tmp_container;
2550 int count = 0;
2551 #define FMT_HEADERS "%-64s %-64s\n"
2552 #define FMT_FIELDS "%-64s %-64s\n"
2553
2554 switch (cmd) {
2555 case CLI_INIT:
2556 e->command = "stasis show topics";
2557 e->usage =
2558 "Usage: stasis show topics\n"
2559 " Shows a list of topics\n";
2560 return NULL;
2561 case CLI_GENERATE:
2562 return NULL;
2563 }
2564
2565 if (a->argc != e->args) {
2566 return CLI_SHOWUSAGE;
2567 }
2568
2569 ast_cli(a->fd, "\n" FMT_HEADERS, "Name", "Detail");
2570
2571 tmp_container = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
2572 topic_proxy_sort_fn, NULL);
2573
2574 if (!tmp_container || ao2_container_dup(tmp_container, topic_all, 0)) {
2575 ao2_cleanup(tmp_container);
2576
2577 return NULL;
2578 }
2579
2580 /* getting all topic in order */
2581 iter = ao2_iterator_init(tmp_container, AO2_ITERATOR_UNLINK);
2582 while ((topic = ao2_iterator_next(&iter))) {
2583 ast_cli(a->fd, FMT_FIELDS, topic->name, topic->detail);
2584 ao2_ref(topic, -1);
2585 ++count;
2586 }
2587 ao2_iterator_destroy(&iter);
2588 ao2_cleanup(tmp_container);
2589
2590 ast_cli(a->fd, "\n%d Total topics\n\n", count);
2591
2592 #undef FMT_HEADERS
2593 #undef FMT_FIELDS
2594
2595 return CLI_SUCCESS;
2596 }
2597
2598 /*!
2599 * \internal
2600 * \brief CLI tab completion for topic names
2601 */
2602 static char *topic_complete_name(const char *word)
2603 {
2604 struct topic_proxy *topic;
2605 struct ao2_iterator it;
2606 int wordlen = strlen(word);
2607 int ret;
2608
2609 it = ao2_iterator_init(topic_all, 0);
2610 while ((topic = ao2_iterator_next(&it))) {
2611 if (!strncasecmp(word, topic->name, wordlen)) {
2612 ret = ast_cli_completion_add(ast_strdup(topic->name));
2613 if (ret) {
2614 ao2_ref(topic, -1);
2615 break;
2616 }
2617 }
2618 ao2_ref(topic, -1);
2619 }
2620 ao2_iterator_destroy(&it);
2621 return NULL;
2622 }
2623
2624 /*!
2625 * \internal
2626 * \brief CLI command implementation for 'stasis show topic'
2627 */
2628 static char *stasis_show_topic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2629 {
2630 struct stasis_topic *topic;
2631 char print_time[32];
2632 int i;
2633
2634 switch (cmd) {
2635 case CLI_INIT:
2636 e->command = "stasis show topic";
2637 e->usage =
2638 "Usage: stasis show topic <name>\n"
2639 " Show stasis topic detail info.\n";
2640 return NULL;
2641 case CLI_GENERATE:
2642 if (a->pos == 3) {
2643 return topic_complete_name(a->word);
2644 } else {
2645 return NULL;
2646 }
2647 }
2648
2649 if (a->argc != 4) {
2650 return CLI_SHOWUSAGE;
2651 }
2652
2653 topic = stasis_topic_get(a->argv[3]);
2654 if (!topic) {
2655 ast_cli(a->fd, "Specified topic '%s' does not exist\n", a->argv[3]);
2656 return CLI_FAILURE;
2657 }
2658
2659 ast_cli(a->fd, "Name: %s\n", topic->name);
2660 ast_cli(a->fd, "Detail: %s\n", topic->detail);
2661 ast_cli(a->fd, "Subscribers count: %zu\n", AST_VECTOR_SIZE(&topic->subscribers));
2662 ast_cli(a->fd, "Forwarding topic count: %zu\n", AST_VECTOR_SIZE(&topic->upstream_topics));
2663 ast_format_duration_hh_mm_ss(ast_tvnow().tv_sec - topic->creationtime->tv_sec, print_time, sizeof(print_time));
2664 ast_cli(a->fd, "Duration time: %s\n", print_time);
2665
2666 ao2_lock(topic);
2667 ast_cli(a->fd, "\nSubscribers:\n");
2668 for (i = 0; i < AST_VECTOR_SIZE(&topic->subscribers); i++) {
2669 struct stasis_subscription *subscription_tmp = AST_VECTOR_GET(&topic->subscribers, i);
2670 ast_cli(a->fd, " UniqueID: %s, Topic: %s, Detail: %s\n",
2671 subscription_tmp->uniqueid, subscription_tmp->topic->name, subscription_tmp->topic->detail);
2672 }
2673
2674 ast_cli(a->fd, "\nForwarded topics:\n");
2675 for (i = 0; i < AST_VECTOR_SIZE(&topic->upstream_topics); i++) {
2676 struct stasis_topic *topic_tmp = AST_VECTOR_GET(&topic->upstream_topics, i);
2677 ast_cli(a->fd, " Topic: %s, Detail: %s\n", topic_tmp->name, topic_tmp->detail);
2678 }
2679 ao2_unlock(topic);
2680
2681 ao2_ref(topic, -1);
2682
2683 return CLI_SUCCESS;
2684 }
2685
2686
2687 static struct ast_cli_entry cli_stasis[] = {
2688 AST_CLI_DEFINE(stasis_show_topics, "Show all topics"),
2689 AST_CLI_DEFINE(stasis_show_topic, "Show topic"),
2690 };
2691
2692
2693 #ifdef AST_DEVMODE
2694
2695 AO2_STRING_FIELD_SORT_FN(stasis_subscription_statistics, uniqueid);
2696
2697 /*!
2698 * \internal
2699 * \brief CLI command implementation for 'stasis statistics show subscriptions'
2700 */
2701 static char *statistics_show_subscriptions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2702 {
2703 struct ao2_container *sorted_subscriptions;
2704 struct ao2_container *subscription_stats;
2705 struct ao2_iterator iter;
2706 struct stasis_subscription_statistics *statistics;
2707 int count = 0;
2708 int dropped = 0;
2709 int passed = 0;
2710 #define FMT_HEADERS "%-64s %10s %10s %16s %16s\n"
2711 #define FMT_FIELDS "%-64s %10d %10d %16ld %16ld\n"
2712 #define FMT_FIELDS2 "%-64s %10d %10d\n"
2713
2714 switch (cmd) {
2715 case CLI_INIT:
2716 e->command = "stasis statistics show subscriptions";
2717 e->usage =
2718 "Usage: stasis statistics show subscriptions\n"
2719 " Shows a list of subscriptions and their general statistics\n";
2720 return NULL;
2721 case CLI_GENERATE:
2722 return NULL;
2723 }
2724
2725 if (a->argc != e->args) {
2726 return CLI_SHOWUSAGE;
2727 }
2728
2729 subscription_stats = ao2_global_obj_ref(subscription_statistics);
2730 if (!subscription_stats) {
2731 ast_cli(a->fd, "Could not fetch subscription_statistics container\n");
2732 return CLI_FAILURE;
2733 }
2734
2735 sorted_subscriptions = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
2736 stasis_subscription_statistics_sort_fn, NULL);
2737 if (!sorted_subscriptions) {
2738 ao2_ref(subscription_stats, -1);
2739 ast_cli(a->fd, "Could not create container for sorting subscription statistics\n");
2740 return CLI_SUCCESS;
2741 }
2742
2743 if (ao2_container_dup(sorted_subscriptions, subscription_stats, 0)) {
2744 ao2_ref(sorted_subscriptions, -1);
2745 ao2_ref(subscription_stats, -1);
2746 ast_cli(a->fd, "Could not sort subscription statistics\n");
2747 return CLI_SUCCESS;
2748 }
2749
2750 ao2_ref(subscription_stats, -1);
2751
2752 ast_cli(a->fd, "\n" FMT_HEADERS, "Subscription", "Dropped", "Passed", "Lowest Invoke", "Highest Invoke");
2753
2754 iter = ao2_iterator_init(sorted_subscriptions, 0);
2755 while ((statistics = ao2_iterator_next(&iter))) {
2756 ast_cli(a->fd, FMT_FIELDS, statistics->uniqueid, statistics->messages_dropped, statistics->messages_passed,
2757 statistics->lowest_time_invoked, statistics->highest_time_invoked);
2758 dropped += statistics->messages_dropped;
2759 passed += statistics->messages_passed;
2760 ao2_ref(statistics, -1);
2761 ++count;
2762 }
2763 ao2_iterator_destroy(&iter);
2764
2765 ao2_ref(sorted_subscriptions, -1);
2766
2767 ast_cli(a->fd, FMT_FIELDS2, "Total", dropped, passed);
2768 ast_cli(a->fd, "\n%d subscriptions\n\n", count);
2769
2770 #undef FMT_HEADERS
2771 #undef FMT_FIELDS
2772 #undef FMT_FIELDS2
2773
2774 return CLI_SUCCESS;
2775 }
2776
2777 /*!
2778 * \internal
2779 * \brief CLI tab completion for subscription statistics names
2780 */
2781 static char *subscription_statistics_complete_name(const char *word, int state)
2782 {
2783 struct stasis_subscription_statistics *statistics;
2784 struct ao2_container *subscription_stats;
2785 struct ao2_iterator it_statistics;
2786 int wordlen = strlen(word);
2787 int which = 0;
2788 char *result = NULL;
2789
2790 subscription_stats = ao2_global_obj_ref(subscription_statistics);
2791 if (!subscription_stats) {
2792 return result;
2793 }
2794
2795 it_statistics = ao2_iterator_init(subscription_stats, 0);
2796 while ((statistics = ao2_iterator_next(&it_statistics))) {
2797 if (!strncasecmp(word, statistics->uniqueid, wordlen)
2798 && ++which > state) {
2799 result = ast_strdup(statistics->uniqueid);
2800 }
2801 ao2_ref(statistics, -1);
2802 if (result) {
2803 break;
2804 }
2805 }
2806 ao2_iterator_destroy(&it_statistics);
2807 ao2_ref(subscription_stats, -1);
2808 return result;
2809 }
2810
2811 /*!
2812 * \internal
2813 * \brief CLI command implementation for 'stasis statistics show subscription'
2814 */
2815 static char *statistics_show_subscription(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2816 {
2817 struct stasis_subscription_statistics *statistics;
2818 struct ao2_container *subscription_stats;
2819 struct ao2_iterator i;
2820 char *name;
2821
2822 switch (cmd) {
2823 case CLI_INIT:
2824 e->command = "stasis statistics show subscription";
2825 e->usage =
2826 "Usage: stasis statistics show subscription <uniqueid>\n"
2827 " Show stasis subscription statistics.\n";
2828 return NULL;
2829 case CLI_GENERATE:
2830 if (a->pos == 4) {
2831 return subscription_statistics_complete_name(a->word, a->n);
2832 } else {
2833 return NULL;
2834 }
2835 }
2836
2837 if (a->argc != 5) {
2838 return CLI_SHOWUSAGE;
2839 }
2840
2841 subscription_stats = ao2_global_obj_ref(subscription_statistics);
2842 if (!subscription_stats) {
2843 ast_cli(a->fd, "Could not fetch subscription_statistics container\n");
2844 return CLI_FAILURE;
2845 }
2846
2847 statistics = ao2_find(subscription_stats, a->argv[4], OBJ_SEARCH_KEY);
2848 if (!statistics) {
2849 ao2_ref(subscription_stats, -1);
2850 ast_cli(a->fd, "Specified subscription '%s' does not exist\n", a->argv[4]);
2851 return CLI_FAILURE;
2852 }
2853
2854 ao2_ref(subscription_stats, -1);
2855
2856 ast_cli(a->fd, "Subscription: %s\n", statistics->uniqueid);
2857 ast_cli(a->fd, "Pointer Address: %p\n", statistics->sub);
2858 ast_cli(a->fd, "Source filename: %s\n", S_OR(statistics->file, "<unavailable>"));
2859 ast_cli(a->fd, "Source line number: %d\n", statistics->lineno);
2860 ast_cli(a->fd, "Source function: %s\n", S_OR(statistics->func, "<unavailable>"));
2861 ast_cli(a->fd, "Number of messages dropped due to filtering: %d\n", statistics->messages_dropped);
2862 ast_cli(a->fd, "Number of messages passed to subscriber callback: %d\n", statistics->messages_passed);
2863 ast_cli(a->fd, "Using mailbox to queue messages: %s\n", statistics->uses_mailbox ? "Yes" : "No");
2864 ast_cli(a->fd, "Using stasis taskpool for handling messages: %s\n", statistics->uses_taskpool ? "Yes" : "No");
2865 ast_cli(a->fd, "Lowest amount of time (in milliseconds) spent invoking message: %ld\n", statistics->lowest_time_invoked);
2866 ast_cli(a->fd, "Highest amount of time (in milliseconds) spent invoking message: %ld\n", statistics->highest_time_invoked);
2867
2868 ao2_lock(statistics);
2869 if (statistics->highest_time_message_type) {
2870 ast_cli(a->fd, "Offender message type for highest invoking time: %s\n", stasis_message_type_name(statistics->highest_time_message_type));
2871 }
2872 ao2_unlock(statistics);
2873
2874 ast_cli(a->fd, "Number of topics: %d\n", ao2_container_count(statistics->topics));
2875
2876 ast_cli(a->fd, "Subscribed topics:\n");
2877 i = ao2_iterator_init(statistics->topics, 0);
2878 while ((name = ao2_iterator_next(&i))) {
2879 ast_cli(a->fd, "\t%s\n", name);
2880 ao2_ref(name, -1);
2881 }
2882 ao2_iterator_destroy(&i);
2883
2884 ao2_ref(statistics, -1);
2885
2886 return CLI_SUCCESS;
2887 }
2888
2889 AO2_STRING_FIELD_SORT_FN(stasis_topic_statistics, name);
2890
2891 /*!
2892 * \internal
2893 * \brief CLI command implementation for 'stasis statistics show topics'
2894 */
2895 static char *statistics_show_topics(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2896 {
2897 struct ao2_container *sorted_topics;
2898 struct ao2_container *topic_stats;
2899 struct ao2_iterator iter;
2900 struct stasis_topic_statistics *statistics;
2901 int count = 0;
2902 int not_dispatched = 0;
2903 int dispatched = 0;
2904 #define FMT_HEADERS "%-64s %10s %10s %10s %16s %16s\n"
2905 #define FMT_FIELDS "%-64s %10d %10d %10d %16ld %16ld\n"
2906 #define FMT_FIELDS2 "%-64s %10s %10d %10d\n"
2907
2908 switch (cmd) {
2909 case CLI_INIT:
2910 e->command = "stasis statistics show topics";
2911 e->usage =
2912 "Usage: stasis statistics show topics\n"
2913 " Shows a list of topics and their general statistics\n";
2914 return NULL;
2915 case CLI_GENERATE:
2916 return NULL;
2917 }
2918
2919 if (a->argc != e->args) {
2920 return CLI_SHOWUSAGE;
2921 }
2922
2923 topic_stats = ao2_global_obj_ref(topic_statistics);
2924 if (!topic_stats) {
2925 ast_cli(a->fd, "Could not fetch topic_statistics container\n");
2926 return CLI_FAILURE;
2927 }
2928
2929 sorted_topics = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
2930 stasis_topic_statistics_sort_fn, NULL);
2931 if (!sorted_topics) {
2932 ao2_ref(topic_stats, -1);
2933 ast_cli(a->fd, "Could not create container for sorting topic statistics\n");
2934 return CLI_SUCCESS;
2935 }
2936
2937 if (ao2_container_dup(sorted_topics, topic_stats, 0)) {
2938 ao2_ref(sorted_topics, -1);
2939 ao2_ref(topic_stats, -1);
2940 ast_cli(a->fd, "Could not sort topic statistics\n");
2941 return CLI_SUCCESS;
2942 }
2943
2944 ao2_ref(topic_stats, -1);
2945
2946 ast_cli(a->fd, "\n" FMT_HEADERS, "Topic", "Subscribers", "Dropped", "Dispatched", "Lowest Dispatch", "Highest Dispatch");
2947
2948 iter = ao2_iterator_init(sorted_topics, 0);
2949 while ((statistics = ao2_iterator_next(&iter))) {
2950 ast_cli(a->fd, FMT_FIELDS, statistics->name, ao2_container_count(statistics->subscribers),
2951 statistics->messages_not_dispatched, statistics->messages_dispatched,
2952 statistics->lowest_time_dispatched, statistics->highest_time_dispatched);
2953 not_dispatched += statistics->messages_not_dispatched;
2954 dispatched += statistics->messages_dispatched;
2955 ao2_ref(statistics, -1);
2956 ++count;
2957 }
2958 ao2_iterator_destroy(&iter);
2959
2960 ao2_ref(sorted_topics, -1);
2961
2962 ast_cli(a->fd, FMT_FIELDS2, "Total", "", not_dispatched, dispatched);
2963 ast_cli(a->fd, "\n%d topics\n\n", count);
2964
2965 #undef FMT_HEADERS
2966 #undef FMT_FIELDS
2967 #undef FMT_FIELDS2
2968
2969 return CLI_SUCCESS;
2970 }
2971
2972 /*!
2973 * \internal
2974 * \brief CLI tab completion for topic statistics names
2975 */
2976 static char *topic_statistics_complete_name(const char *word, int state)
2977 {
2978 struct stasis_topic_statistics *statistics;
2979 struct ao2_container *topic_stats;
2980 struct ao2_iterator it_statistics;
2981 int wordlen = strlen(word);
2982 int which = 0;
2983 char *result = NULL;
2984
2985 topic_stats = ao2_global_obj_ref(topic_statistics);
2986 if (!topic_stats) {
2987 return result;
2988 }
2989
2990 it_statistics = ao2_iterator_init(topic_stats, 0);
2991 while ((statistics = ao2_iterator_next(&it_statistics))) {
2992 if (!strncasecmp(word, statistics->name, wordlen)
2993 && ++which > state) {
2994 result = ast_strdup(statistics->name);
2995 }
2996 ao2_ref(statistics, -1);
2997 if (result) {
2998 break;
2999 }
3000 }
3001 ao2_iterator_destroy(&it_statistics);
3002 ao2_ref(topic_stats, -1);
3003 return result;
3004 }
3005
3006 /*!
3007 * \internal
3008 * \brief CLI command implementation for 'stasis statistics show topic'
3009 */
3010 static char *statistics_show_topic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3011 {
3012 struct stasis_topic_statistics *statistics;
3013 struct ao2_container *topic_stats;
3014 struct ao2_iterator i;
3015 char *uniqueid;
3016
3017 switch (cmd) {
3018 case CLI_INIT:
3019 e->command = "stasis statistics show topic";
3020 e->usage =
3021 "Usage: stasis statistics show topic <name>\n"
3022 " Show stasis topic statistics.\n";
3023 return NULL;
3024 case CLI_GENERATE:
3025 if (a->pos == 4) {
3026 return topic_statistics_complete_name(a->word, a->n);
3027 } else {
3028 return NULL;
3029 }
3030 }
3031
3032 if (a->argc != 5) {
3033 return CLI_SHOWUSAGE;
3034 }
3035
3036 topic_stats = ao2_global_obj_ref(topic_statistics);
3037 if (!topic_stats) {
3038 ast_cli(a->fd, "Could not fetch topic_statistics container\n");
3039 return CLI_FAILURE;
3040 }
3041
3042 statistics = ao2_find(topic_stats, a->argv[4], OBJ_SEARCH_KEY);
3043 if (!statistics) {
3044 ao2_ref(topic_stats, -1);
3045 ast_cli(a->fd, "Specified topic '%s' does not exist\n", a->argv[4]);
3046 return CLI_FAILURE;
3047 }
3048
3049 ao2_ref(topic_stats, -1);
3050
3051 ast_cli(a->fd, "Topic: %s\n", statistics->name);
3052 ast_cli(a->fd, "Pointer Address: %p\n", statistics->topic);
3053 ast_cli(a->fd, "Number of messages published that went to no subscriber: %d\n", statistics->messages_not_dispatched);
3054 ast_cli(a->fd, "Number of messages that went to at least one subscriber: %d\n", statistics->messages_dispatched);
3055 ast_cli(a->fd, "Lowest amount of time (in milliseconds) spent dispatching message: %ld\n", statistics->lowest_time_dispatched);
3056 ast_cli(a->fd, "Highest amount of time (in milliseconds) spent dispatching messages: %ld\n", statistics->highest_time_dispatched);
3057 ast_cli(a->fd, "Number of subscribers: %d\n", ao2_container_count(statistics->subscribers));
3058
3059 ast_cli(a->fd, "Subscribers:\n");
3060 i = ao2_iterator_init(statistics->subscribers, 0);
3061 while ((uniqueid = ao2_iterator_next(&i))) {
3062 ast_cli(a->fd, "\t%s\n", uniqueid);
3063 ao2_ref(uniqueid, -1);
3064 }
3065 ao2_iterator_destroy(&i);
3066
3067 ao2_ref(statistics, -1);
3068
3069 return CLI_SUCCESS;
3070 }
3071
3072 /*!
3073 * \internal
3074 * \brief CLI command implementation for 'stasis statistics show messages'
3075 */
3076 static char *statistics_show_messages(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3077 {
3078 int i;
3079 int count = 0;
3080 int published = 0;
3081 int unused = 0;
3082 #define FMT_HEADERS "%-64s %10s %10s\n"
3083 #define FMT_FIELDS "%-64s %10d %10d\n"
3084
3085 switch (cmd) {
3086 case CLI_INIT:
3087 e->command = "stasis statistics show messages";
3088 e->usage =
3089 "Usage: stasis statistics show messages\n"
3090 " Shows a list of message types and their general statistics\n";
3091 return NULL;
3092 case CLI_GENERATE:
3093 return NULL;
3094 }
3095
3096 if (a->argc != e->args) {
3097 return CLI_SHOWUSAGE;
3098 }
3099
3100 ast_cli(a->fd, "\n" FMT_HEADERS, "Message Type", "Published", "Unused");
3101
3102 ast_mutex_lock(&message_type_statistics_lock);
3103 for (i = 0; i < AST_VECTOR_SIZE(&message_type_statistics); ++i) {
3104 struct stasis_message_type_statistics *statistics = AST_VECTOR_GET_ADDR(&message_type_statistics, i);
3105
3106 if (!statistics->message_type) {
3107 continue;
3108 }
3109
3110 ast_cli(a->fd, FMT_FIELDS, stasis_message_type_name(statistics->message_type), statistics->published,
3111 statistics->unused);
3112 published += statistics->published;
3113 unused += statistics->unused;
3114 ++count;
3115 }
3116 ast_mutex_unlock(&message_type_statistics_lock);
3117
3118 ast_cli(a->fd, FMT_FIELDS, "Total", published, unused);
3119 ast_cli(a->fd, "\n%d seen message types\n\n", count);
3120
3121 #undef FMT_HEADERS
3122 #undef FMT_FIELDS
3123
3124 return CLI_SUCCESS;
3125 }
3126
3127 static struct ast_cli_entry cli_stasis_statistics[] = {
3128 AST_CLI_DEFINE(statistics_show_subscriptions, "Show subscriptions with general statistics"),
3129 AST_CLI_DEFINE(statistics_show_subscription, "Show subscription statistics"),
3130 AST_CLI_DEFINE(statistics_show_topics, "Show topics with general statistics"),
3131 AST_CLI_DEFINE(statistics_show_topic, "Show topic statistics"),
3132 AST_CLI_DEFINE(statistics_show_messages, "Show message types with general statistics"),
3133 };
3134
3135 static int subscription_statistics_hash(const void *obj, const int flags)
3136 {
3137 const struct stasis_subscription_statistics *object;
3138 const char *key;
3139
3140 switch (flags & OBJ_SEARCH_MASK) {
3141 case OBJ_SEARCH_KEY:
3142 key = obj;
3143 break;
3144 case OBJ_SEARCH_OBJECT:
3145 object = obj;
3146 key = object->uniqueid;
3147 break;
3148 default:
3149 /* Hash can only work on something with a full key. */
3150 ast_assert(0);
3151 return 0;
3152 }
3153 return ast_str_case_hash(key);
3154 }
3155
3156 static int subscription_statistics_cmp(void *obj, void *arg, int flags)
3157 {
3158 const struct stasis_subscription_statistics *object_left = obj;
3159 const struct stasis_subscription_statistics *object_right = arg;
3160 const char *right_key = arg;
3161 int cmp;
3162
3163 switch (flags & OBJ_SEARCH_MASK) {
3164 case OBJ_SEARCH_OBJECT:
3165 right_key = object_right->uniqueid;
3166 /* Fall through */
3167 case OBJ_SEARCH_KEY:
3168 cmp = strcasecmp(object_left->uniqueid, right_key);
3169 break;
3170 case OBJ_SEARCH_PARTIAL_KEY:
3171 /* Not supported by container */
3172 ast_assert(0);
3173 cmp = -1;
3174 break;
3175 default:
3176 /*
3177 * What arg points to is specific to this traversal callback
3178 * and has no special meaning to astobj2.
3179 */
3180 cmp = 0;
3181 break;
3182 }
3183 if (cmp) {
3184 return 0;
3185 }
3186 /*
3187 * At this point the traversal callback is identical to a sorted
3188 * container.
3189 */
3190 return CMP_MATCH;
3191 }
3192
3193 static int topic_statistics_hash(const void *obj, const int flags)
3194 {
3195 const struct stasis_topic_statistics *object;
3196 const char *key;
3197
3198 switch (flags & OBJ_SEARCH_MASK) {
3199 case OBJ_SEARCH_KEY:
3200 key = obj;
3201 break;
3202 case OBJ_SEARCH_OBJECT:
3203 object = obj;
3204 key = object->name;
3205 break;
3206 default:
3207 /* Hash can only work on something with a full key. */
3208 ast_assert(0);
3209 return 0;
3210 }
3211 return ast_str_case_hash(key);
3212 }
3213
3214 static int topic_statistics_cmp(void *obj, void *arg, int flags)
3215 {
3216 const struct stasis_topic_statistics *object_left = obj;
3217 const struct stasis_topic_statistics *object_right = arg;
3218 const char *right_key = arg;
3219 int cmp;
3220
3221 switch (flags & OBJ_SEARCH_MASK) {
3222 case OBJ_SEARCH_OBJECT:
3223 right_key = object_right->name;
3224 /* Fall through */
3225 case OBJ_SEARCH_KEY:
3226 cmp = strcasecmp(object_left->name, right_key);
3227 break;
3228 case OBJ_SEARCH_PARTIAL_KEY:
3229 /* Not supported by container */
3230 ast_assert(0);
3231 cmp = -1;
3232 break;
3233 default:
3234 /*
3235 * What arg points to is specific to this traversal callback
3236 * and has no special meaning to astobj2.
3237 */
3238 cmp = 0;
3239 break;
3240 }
3241 if (cmp) {
3242 return 0;
3243 }
3244 /*
3245 * At this point the traversal callback is identical to a sorted
3246 * container.
3247 */
3248 return CMP_MATCH;
3249 }
3250 #endif
3251
3252 /*! \brief Cleanup function for graceful shutdowns */
3253 static void stasis_cleanup(void)
3254 {
3255 #ifdef AST_DEVMODE
3256 ast_cli_unregister_multiple(cli_stasis_statistics, ARRAY_LEN(cli_stasis_statistics));
3257 AST_VECTOR_FREE(&message_type_statistics);
3258 ao2_global_obj_release(subscription_statistics);
3259 ao2_global_obj_release(topic_statistics);
3260 #endif
3261 ast_cli_unregister_multiple(cli_stasis, ARRAY_LEN(cli_stasis));
3262 ao2_cleanup(topic_all);
3263 topic_all = NULL;
3264 ast_taskpool_shutdown(taskpool);
3265 taskpool = NULL;
3266 STASIS_MESSAGE_TYPE_CLEANUP(stasis_subscription_change_type);
3267 STASIS_MESSAGE_TYPE_CLEANUP(ast_multi_user_event_type);
3268 aco_info_destroy(&cfg_info);
3269 ao2_global_obj_release(globals);
3270 }
3271
3272 int stasis_init(void)
3273 {
3274 struct stasis_config *cfg;
3275 int cache_init;
3276 struct ast_taskpool_options taskpool_opts = { 0, };
3277 #ifdef AST_DEVMODE
3278 struct ao2_container *subscription_stats;
3279 struct ao2_container *topic_stats;
3280 #endif
3281
3282 /* Be sure the types are cleaned up after the message bus */
3283 ast_register_cleanup(stasis_cleanup);
3284
3285 if (aco_info_init(&cfg_info)) {
3286 return -1;
3287 }
3288
3289 aco_option_register_custom(&cfg_info, "decline", ACO_EXACT,
3290 declined_options, "", declined_handler, 0);
3291 aco_option_register(&cfg_info, "minimum_size", ACO_EXACT,
3292 taskpool_options, "5", OPT_INT_T, PARSE_IN_RANGE,
3293 FLDSET(struct stasis_taskpool_conf, minimum_size), 0,
3294 INT_MAX);
3295 aco_option_register(&cfg_info, "initial_size", ACO_EXACT,
3296 taskpool_options, "5", OPT_INT_T, PARSE_IN_RANGE,
3297 FLDSET(struct stasis_taskpool_conf, initial_size), 0,
3298 INT_MAX);
3299 aco_option_register(&cfg_info, "idle_timeout_sec", ACO_EXACT,
3300 taskpool_options, "20", OPT_INT_T, PARSE_IN_RANGE,
3301 FLDSET(struct stasis_taskpool_conf, idle_timeout_sec), 0,
3302 INT_MAX);
3303 aco_option_register(&cfg_info, "max_size", ACO_EXACT,
3304 taskpool_options, "50", OPT_INT_T, PARSE_IN_RANGE,
3305 FLDSET(struct stasis_taskpool_conf, max_size), 0,
3306 INT_MAX);
3307
3308 if (aco_process_config(&cfg_info, 0) == ACO_PROCESS_ERROR) {
3309 struct stasis_config *default_cfg = stasis_config_alloc();
3310
3311 if (!default_cfg) {
3312 return -1;
3313 }
3314
3315 if (aco_set_defaults(&taskpool_option, "taskpool", default_cfg->taskpool_options)) {
3316 ast_log(LOG_ERROR, "Failed to initialize defaults on Stasis configuration object\n");
3317 ao2_ref(default_cfg, -1);
3318
3319 return -1;
3320 }
3321
3322 if (aco_set_defaults(&declined_option, "declined_message_types", default_cfg->declined_message_types)) {
3323 ast_log(LOG_ERROR, "Failed to load stasis.conf and failed to initialize defaults.\n");
3324 ao2_ref(default_cfg, -1);
3325
3326 return -1;
3327 }
3328
3329 ast_log(LOG_NOTICE, "Could not load Stasis configuration; using defaults\n");
3330 ao2_global_obj_replace_unref(globals, default_cfg);
3331 cfg = default_cfg;
3332 } else {
3333 cfg = ao2_global_obj_ref(globals);
3334 if (!cfg) {
3335 ast_log(LOG_ERROR, "Failed to obtain Stasis configuration object\n");
3336
3337 return -1;
3338 }
3339 }
3340
3341 taskpool_opts.version = AST_TASKPOOL_OPTIONS_VERSION;
3342 taskpool_opts.minimum_size = cfg->taskpool_options->minimum_size;
3343 taskpool_opts.initial_size = cfg->taskpool_options->initial_size;
3344 taskpool_opts.auto_increment = 1;
3345 taskpool_opts.max_size = cfg->taskpool_options->max_size;
3346 taskpool_opts.idle_timeout = cfg->taskpool_options->idle_timeout_sec;
3347 taskpool = ast_taskpool_create("stasis", &taskpool_opts);
3348 ao2_ref(cfg, -1);
3349 if (!taskpool) {
3350 ast_log(LOG_ERROR, "Failed to create 'stasis-core' taskpool\n");
3351
3352 return -1;
3353 }
3354
3355 cache_init = stasis_cache_init();
3356 if (cache_init != 0) {
3357 return -1;
3358 }
3359
3360 if (STASIS_MESSAGE_TYPE_INIT(stasis_subscription_change_type) != 0) {
3361 return -1;
3362 }
3363 if (STASIS_MESSAGE_TYPE_INIT(ast_multi_user_event_type) != 0) {
3364 return -1;
3365 }
3366
3367 topic_all = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, TOPIC_ALL_BUCKETS,
3368 topic_proxy_hash_fn, 0, topic_proxy_cmp_fn);
3369 if (!topic_all) {
3370 return -1;
3371 }
3372
3373 if (ast_cli_register_multiple(cli_stasis, ARRAY_LEN(cli_stasis))) {
3374 return -1;
3375 }
3376
3377 #ifdef AST_DEVMODE
3378 /* Statistics information is stored separately so that we don't alter or interrupt the lifetime of the underlying
3379 * topic or subscripton.
3380 */
3381 subscription_stats = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, SUBSCRIPTION_STATISTICS_BUCKETS,
3382 subscription_statistics_hash, 0, subscription_statistics_cmp);
3383 if (!subscription_stats) {
3384 return -1;
3385 }
3386 ao2_global_obj_replace_unref(subscription_statistics, subscription_stats);
3387 ao2_cleanup(subscription_stats);
3388
3389 topic_stats = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, TOPIC_STATISTICS_BUCKETS,
3390 topic_statistics_hash, 0, topic_statistics_cmp);
3391 if (!topic_stats) {
3392 return -1;
3393 }
3394 ao2_global_obj_replace_unref(topic_statistics, topic_stats);
3395 ao2_cleanup(topic_stats);
3396 if (!topic_stats) {
3397 return -1;
3398 }
3399
3400 AST_VECTOR_INIT(&message_type_statistics, 0);
3401
3402 if (ast_cli_register_multiple(cli_stasis_statistics, ARRAY_LEN(cli_stasis_statistics))) {
3403 return -1;
3404 }
3405 #endif
3406
3407 return 0;
3408 }