Fix a variety of ref counting issues
[asterisk/asterisk.git] / main / taskprocessor.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007-2008, Digium, Inc.
5  *
6  * Dwayne M. Hubbard <dhubbard@digium.com>
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 /*!
20  * \file
21  * \brief Maintain a container of uniquely-named taskprocessor threads that can be shared across modules.
22  *
23  * \author Dwayne Hubbard <dhubbard@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include "asterisk/_private.h"
35 #include "asterisk/module.h"
36 #include "asterisk/time.h"
37 #include "asterisk/astobj2.h"
38 #include "asterisk/cli.h"
39 #include "asterisk/taskprocessor.h"
40
41
42 /*!
43  * \brief tps_task structure is queued to a taskprocessor
44  *
45  * tps_tasks are processed in FIFO order and freed by the taskprocessing
46  * thread after the task handler returns.  The callback function that is assigned
47  * to the execute() function pointer is responsible for releasing datap resources if necessary.
48  */
49 struct tps_task {
50         /*! \brief The execute() task callback function pointer */
51         int (*execute)(void *datap);
52         /*! \brief The data pointer for the task execute() function */
53         void *datap;
54         /*! \brief AST_LIST_ENTRY overhead */
55         AST_LIST_ENTRY(tps_task) list;
56 };
57
58 /*! \brief tps_taskprocessor_stats maintain statistics for a taskprocessor. */
59 struct tps_taskprocessor_stats {
60         /*! \brief This is the maximum number of tasks queued at any one time */
61         unsigned long max_qsize;
62         /*! \brief This is the current number of tasks processed */
63         unsigned long _tasks_processed_count;
64 };
65
66 /*! \brief A ast_taskprocessor structure is a singleton by name */
67 struct ast_taskprocessor {
68         /*! \brief Friendly name of the taskprocessor */
69         const char *name;
70         /*! \brief Thread poll condition */
71         ast_cond_t poll_cond;
72         /*! \brief Taskprocessor thread */
73         pthread_t poll_thread;
74         /*! \brief Taskprocessor lock */
75         ast_mutex_t taskprocessor_lock;
76         /*! \brief Taskprocesor thread run flag */
77         unsigned char poll_thread_run;
78         /*! \brief Taskprocessor statistics */
79         struct tps_taskprocessor_stats *stats;
80         /*! \brief Taskprocessor current queue size */
81         long tps_queue_size;
82         /*! \brief Taskprocessor queue */
83         AST_LIST_HEAD_NOLOCK(tps_queue, tps_task) tps_queue;
84         /*! \brief Taskprocessor singleton list entry */
85         AST_LIST_ENTRY(ast_taskprocessor) list;
86 };
87 #define TPS_MAX_BUCKETS 7
88 /*! \brief tps_singletons is the astobj2 container for taskprocessor singletons */
89 static struct ao2_container *tps_singletons;
90
91 /*! \brief CLI <example>taskprocessor ping &lt;blah&gt;</example> operation requires a ping condition */
92 static ast_cond_t cli_ping_cond;
93
94 /*! \brief CLI <example>taskprocessor ping &lt;blah&gt;</example> operation requires a ping condition lock */
95 AST_MUTEX_DEFINE_STATIC(cli_ping_cond_lock);
96
97 /*! \brief The astobj2 hash callback for taskprocessors */
98 static int tps_hash_cb(const void *obj, const int flags);
99 /*! \brief The astobj2 compare callback for taskprocessors */
100 static int tps_cmp_cb(void *obj, void *arg, int flags);
101
102 /*! \brief The task processing function executed by a taskprocessor */
103 static void *tps_processing_function(void *data);
104
105 /*! \brief Destroy the taskprocessor when its refcount reaches zero */
106 static void tps_taskprocessor_destroy(void *tps);
107
108 /*! \brief CLI <example>taskprocessor ping &lt;blah&gt;</example> handler function */
109 static int tps_ping_handler(void *datap);
110
111 /*! \brief Remove the front task off the taskprocessor queue */
112 static struct tps_task *tps_taskprocessor_pop(struct ast_taskprocessor *tps);
113
114 /*! \brief Return the size of the taskprocessor queue */
115 static int tps_taskprocessor_depth(struct ast_taskprocessor *tps);
116
117 static char *cli_tps_ping(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
118 static char *cli_tps_report(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
119
120 static struct ast_cli_entry taskprocessor_clis[] = {
121         AST_CLI_DEFINE(cli_tps_ping, "Ping a named task processor"),
122         AST_CLI_DEFINE(cli_tps_report, "List instantiated task processors and statistics"),
123 };
124
125 /*! \internal \brief Clean up resources on Asterisk shutdown */
126 static void tps_shutdown(void)
127 {
128         ao2_t_ref(tps_singletons, -1, "Unref tps_singletons in shutdown");
129 }
130
131 /* initialize the taskprocessor container and register CLI operations */
132 int ast_tps_init(void)
133 {
134         if (!(tps_singletons = ao2_container_alloc(TPS_MAX_BUCKETS, tps_hash_cb, tps_cmp_cb))) {
135                 ast_log(LOG_ERROR, "taskprocessor container failed to initialize!\n");
136                 return -1;
137         }
138
139         ast_cond_init(&cli_ping_cond, NULL);
140
141         ast_cli_register_multiple(taskprocessor_clis, ARRAY_LEN(taskprocessor_clis));
142
143         ast_register_atexit(tps_shutdown);
144
145         return 0;
146 }
147
148 /* allocate resources for the task */
149 static struct tps_task *tps_task_alloc(int (*task_exe)(void *datap), void *datap)
150 {
151         struct tps_task *t;
152         if ((t = ast_calloc(1, sizeof(*t)))) {
153                 t->execute = task_exe;
154                 t->datap = datap;
155         }
156         return t;
157 }
158
159 /* release task resources */
160 static void *tps_task_free(struct tps_task *task)
161 {
162         if (task) {
163                 ast_free(task);
164         }
165         return NULL;
166 }
167
168 /* taskprocessor tab completion */
169 static char *tps_taskprocessor_tab_complete(struct ast_taskprocessor *p, struct ast_cli_args *a)
170 {
171         int tklen;
172         int wordnum = 0;
173         char *name = NULL;
174         struct ao2_iterator i;
175
176         if (a->pos != 3)
177                 return NULL;
178
179         tklen = strlen(a->word);
180         i = ao2_iterator_init(tps_singletons, 0);
181         while ((p = ao2_iterator_next(&i))) {
182                 if (!strncasecmp(a->word, p->name, tklen) && ++wordnum > a->n) {
183                         name = ast_strdup(p->name);
184                         ao2_ref(p, -1);
185                         break;
186                 }
187                 ao2_ref(p, -1);
188         }
189         ao2_iterator_destroy(&i);
190         return name;
191 }
192
193 /* ping task handling function */
194 static int tps_ping_handler(void *datap)
195 {
196         ast_mutex_lock(&cli_ping_cond_lock);
197         ast_cond_signal(&cli_ping_cond);
198         ast_mutex_unlock(&cli_ping_cond_lock);
199         return 0;
200 }
201
202 /* ping the specified taskprocessor and display the ping time on the CLI */
203 static char *cli_tps_ping(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
204 {
205         struct timeval begin, end, delta;
206         const char *name;
207         struct timeval when;
208         struct timespec ts;
209         struct ast_taskprocessor *tps = NULL;
210
211         switch (cmd) {
212         case CLI_INIT:
213                 e->command = "core ping taskprocessor";
214                 e->usage =
215                         "Usage: core ping taskprocessor <taskprocessor>\n"
216                         "       Displays the time required for a task to be processed\n";
217                 return NULL;
218         case CLI_GENERATE:
219                 return tps_taskprocessor_tab_complete(tps, a);
220         }
221
222         if (a->argc != 4)
223                 return CLI_SHOWUSAGE;
224
225         name = a->argv[3];
226         if (!(tps = ast_taskprocessor_get(name, TPS_REF_IF_EXISTS))) {
227                 ast_cli(a->fd, "\nping failed: %s not found\n\n", name);
228                 return CLI_SUCCESS;
229         }
230         ast_cli(a->fd, "\npinging %s ...", name);
231         when = ast_tvadd((begin = ast_tvnow()), ast_samp2tv(1000, 1000));
232         ts.tv_sec = when.tv_sec;
233         ts.tv_nsec = when.tv_usec * 1000;
234         ast_mutex_lock(&cli_ping_cond_lock);
235         if (ast_taskprocessor_push(tps, tps_ping_handler, 0) < 0) {
236                 ast_cli(a->fd, "\nping failed: could not push task to %s\n\n", name);
237                 ao2_ref(tps, -1);
238                 return CLI_FAILURE;
239         }
240         ast_cond_timedwait(&cli_ping_cond, &cli_ping_cond_lock, &ts);
241         ast_mutex_unlock(&cli_ping_cond_lock);
242         end = ast_tvnow();
243         delta = ast_tvsub(end, begin);
244         ast_cli(a->fd, "\n\t%24s ping time: %.1ld.%.6ld sec\n\n", name, (long)delta.tv_sec, (long int)delta.tv_usec);
245         ao2_ref(tps, -1);
246         return CLI_SUCCESS;
247 }
248
249 static char *cli_tps_report(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
250 {
251         char name[256];
252         int tcount;
253         unsigned long qsize;
254         unsigned long maxqsize;
255         unsigned long processed;
256         struct ast_taskprocessor *p;
257         struct ao2_iterator i;
258
259         switch (cmd) {
260         case CLI_INIT:
261                 e->command = "core show taskprocessors";
262                 e->usage =
263                         "Usage: core show taskprocessors\n"
264                         "       Shows a list of instantiated task processors and their statistics\n";
265                 return NULL;
266         case CLI_GENERATE:
267                 return NULL;
268         }
269
270         if (a->argc != e->args)
271                 return CLI_SHOWUSAGE;
272
273         ast_cli(a->fd, "\n\t+----- Processor -----+--- Processed ---+- In Queue -+- Max Depth -+");
274         i = ao2_iterator_init(tps_singletons, 0);
275         while ((p = ao2_iterator_next(&i))) {
276                 ast_copy_string(name, p->name, sizeof(name));
277                 qsize = p->tps_queue_size;
278                 maxqsize = p->stats->max_qsize;
279                 processed = p->stats->_tasks_processed_count;
280                 ast_cli(a->fd, "\n%24s   %17ld %12ld %12ld", name, processed, qsize, maxqsize);
281                 ao2_ref(p, -1);
282         }
283         ao2_iterator_destroy(&i);
284         tcount = ao2_container_count(tps_singletons);
285         ast_cli(a->fd, "\n\t+---------------------+-----------------+------------+-------------+\n\t%d taskprocessors\n\n", tcount);
286         return CLI_SUCCESS;
287 }
288
289 /* this is the task processing worker function */
290 static void *tps_processing_function(void *data)
291 {
292         struct ast_taskprocessor *i = data;
293         struct tps_task *t;
294         int size;
295
296         if (!i) {
297                 ast_log(LOG_ERROR, "cannot start thread_function loop without a ast_taskprocessor structure.\n");
298                 return NULL;
299         }
300
301         while (i->poll_thread_run) {
302                 ast_mutex_lock(&i->taskprocessor_lock);
303                 if (!i->poll_thread_run) {
304                         ast_mutex_unlock(&i->taskprocessor_lock);
305                         break;
306                 }
307                 if (!(size = tps_taskprocessor_depth(i))) {
308                         ast_cond_wait(&i->poll_cond, &i->taskprocessor_lock);
309                         if (!i->poll_thread_run) {
310                                 ast_mutex_unlock(&i->taskprocessor_lock);
311                                 break;
312                         }
313                 }
314                 ast_mutex_unlock(&i->taskprocessor_lock);
315                 /* stuff is in the queue */
316                 if (!(t = tps_taskprocessor_pop(i))) {
317                         ast_log(LOG_ERROR, "Wtf?? %d tasks in the queue, but we're popping blanks!\n", size);
318                         continue;
319                 }
320                 if (!t->execute) {
321                         ast_log(LOG_WARNING, "Task is missing a function to execute!\n");
322                         tps_task_free(t);
323                         continue;
324                 }
325                 t->execute(t->datap);
326
327                 ast_mutex_lock(&i->taskprocessor_lock);
328                 if (i->stats) {
329                         i->stats->_tasks_processed_count++;
330                         if (size > i->stats->max_qsize) {
331                                 i->stats->max_qsize = size;
332                         }
333                 }
334                 ast_mutex_unlock(&i->taskprocessor_lock);
335
336                 tps_task_free(t);
337         }
338         while ((t = tps_taskprocessor_pop(i))) {
339                 tps_task_free(t);
340         }
341         return NULL;
342 }
343
344 /* hash callback for astobj2 */
345 static int tps_hash_cb(const void *obj, const int flags)
346 {
347         const struct ast_taskprocessor *tps = obj;
348
349         return ast_str_case_hash(tps->name);
350 }
351
352 /* compare callback for astobj2 */
353 static int tps_cmp_cb(void *obj, void *arg, int flags)
354 {
355         struct ast_taskprocessor *lhs = obj, *rhs = arg;
356
357         return !strcasecmp(lhs->name, rhs->name) ? CMP_MATCH | CMP_STOP : 0;
358 }
359
360 /* destroy the taskprocessor */
361 static void tps_taskprocessor_destroy(void *tps)
362 {
363         struct ast_taskprocessor *t = tps;
364
365         if (!tps) {
366                 ast_log(LOG_ERROR, "missing taskprocessor\n");
367                 return;
368         }
369         ast_debug(1, "destroying taskprocessor '%s'\n", t->name);
370         /* kill it */
371         ast_mutex_lock(&t->taskprocessor_lock);
372         t->poll_thread_run = 0;
373         ast_cond_signal(&t->poll_cond);
374         ast_mutex_unlock(&t->taskprocessor_lock);
375         pthread_join(t->poll_thread, NULL);
376         t->poll_thread = AST_PTHREADT_NULL;
377         ast_mutex_destroy(&t->taskprocessor_lock);
378         ast_cond_destroy(&t->poll_cond);
379         /* free it */
380         if (t->stats) {
381                 ast_free(t->stats);
382                 t->stats = NULL;
383         }
384         ast_free((char *) t->name);
385 }
386
387 /* pop the front task and return it */
388 static struct tps_task *tps_taskprocessor_pop(struct ast_taskprocessor *tps)
389 {
390         struct tps_task *task;
391
392         if (!tps) {
393                 ast_log(LOG_ERROR, "missing taskprocessor\n");
394                 return NULL;
395         }
396         ast_mutex_lock(&tps->taskprocessor_lock);
397         if ((task = AST_LIST_REMOVE_HEAD(&tps->tps_queue, list))) {
398                 tps->tps_queue_size--;
399         }
400         ast_mutex_unlock(&tps->taskprocessor_lock);
401         return task;
402 }
403
404 static int tps_taskprocessor_depth(struct ast_taskprocessor *tps)
405 {
406         return (tps) ? tps->tps_queue_size : -1;
407 }
408
409 /* taskprocessor name accessor */
410 const char *ast_taskprocessor_name(struct ast_taskprocessor *tps)
411 {
412         if (!tps) {
413                 ast_log(LOG_ERROR, "no taskprocessor specified!\n");
414                 return NULL;
415         }
416         return tps->name;
417 }
418
419 /* Provide a reference to a taskprocessor.  Create the taskprocessor if necessary, but don't
420  * create the taskprocessor if we were told via ast_tps_options to return a reference only
421  * if it already exists */
422 struct ast_taskprocessor *ast_taskprocessor_get(const char *name, enum ast_tps_options create)
423 {
424         struct ast_taskprocessor *p, tmp_tps = {
425                 .name = name,
426         };
427
428         if (ast_strlen_zero(name)) {
429                 ast_log(LOG_ERROR, "requesting a nameless taskprocessor!!!\n");
430                 return NULL;
431         }
432         ao2_lock(tps_singletons);
433         p = ao2_find(tps_singletons, &tmp_tps, OBJ_POINTER);
434         if (p) {
435                 ao2_unlock(tps_singletons);
436                 return p;
437         }
438         if (create & TPS_REF_IF_EXISTS) {
439                 /* calling function does not want a new taskprocessor to be created if it doesn't already exist */
440                 ao2_unlock(tps_singletons);
441                 return NULL;
442         }
443         /* create a new taskprocessor */
444         if (!(p = ao2_alloc(sizeof(*p), tps_taskprocessor_destroy))) {
445                 ao2_unlock(tps_singletons);
446                 ast_log(LOG_WARNING, "failed to create taskprocessor '%s'\n", name);
447                 return NULL;
448         }
449
450         ast_cond_init(&p->poll_cond, NULL);
451         ast_mutex_init(&p->taskprocessor_lock);
452
453         if (!(p->stats = ast_calloc(1, sizeof(*p->stats)))) {
454                 ao2_unlock(tps_singletons);
455                 ast_log(LOG_WARNING, "failed to create taskprocessor stats for '%s'\n", name);
456                 ao2_ref(p, -1);
457                 return NULL;
458         }
459         if (!(p->name = ast_strdup(name))) {
460                 ao2_unlock(tps_singletons);
461                 ao2_ref(p, -1);
462                 return NULL;
463         }
464         p->poll_thread_run = 1;
465         p->poll_thread = AST_PTHREADT_NULL;
466         if (ast_pthread_create(&p->poll_thread, NULL, tps_processing_function, p) < 0) {
467                 ao2_unlock(tps_singletons);
468                 ast_log(LOG_ERROR, "Taskprocessor '%s' failed to create the processing thread.\n", p->name);
469                 ao2_ref(p, -1);
470                 return NULL;
471         }
472         if (!(ao2_link(tps_singletons, p))) {
473                 ao2_unlock(tps_singletons);
474                 ast_log(LOG_ERROR, "Failed to add taskprocessor '%s' to container\n", p->name);
475                 ao2_ref(p, -1);
476                 return NULL;
477         }
478         ao2_unlock(tps_singletons);
479         return p;
480 }
481
482 /* decrement the taskprocessor reference count and unlink from the container if necessary */
483 void *ast_taskprocessor_unreference(struct ast_taskprocessor *tps)
484 {
485         if (tps) {
486                 ao2_lock(tps_singletons);
487                 ao2_unlink(tps_singletons, tps);
488                 if (ao2_ref(tps, -1) > 1) {
489                         ao2_link(tps_singletons, tps);
490                 }
491                 ao2_unlock(tps_singletons);
492         }
493         return NULL;
494 }
495
496 /* push the task into the taskprocessor queue */
497 int ast_taskprocessor_push(struct ast_taskprocessor *tps, int (*task_exe)(void *datap), void *datap)
498 {
499         struct tps_task *t;
500
501         if (!tps || !task_exe) {
502                 ast_log(LOG_ERROR, "%s is missing!!\n", (tps) ? "task callback" : "taskprocessor");
503                 return -1;
504         }
505         if (!(t = tps_task_alloc(task_exe, datap))) {
506                 ast_log(LOG_ERROR, "failed to allocate task!  Can't push to '%s'\n", tps->name);
507                 return -1;
508         }
509         ast_mutex_lock(&tps->taskprocessor_lock);
510         AST_LIST_INSERT_TAIL(&tps->tps_queue, t, list);
511         tps->tps_queue_size++;
512         ast_cond_signal(&tps->poll_cond);
513         ast_mutex_unlock(&tps->taskprocessor_lock);
514         return 0;
515 }
516