2 * Asterisk -- A telephony toolkit for Linux.
4 * True call queues with optional send URL on answer
6 * Copyright (C) 1999-2004, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * 2004-11-25: Persistent Dynamic Members added by:
11 * NetNation Communications (www.netnation.com)
12 * Kevin Lindsay <kevinl@netnation.com>
14 * Each dynamic agent in each queue is now stored in the astdb.
15 * When asterisk is restarted, each agent will be automatically
16 * readded into their recorded queues. This feature can be
17 * configured with the 'peristent_members=<1|0>' KVP under the
18 * '[general]' group in queues.conf. The default is on.
20 * 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
22 * These features added by David C. Troy <dave@toad.net>:
23 * - Per-queue holdtime calculation
24 * - Estimated holdtime announcement
25 * - Position announcement
26 * - Abandoned/completed call counters
27 * - Failout timer passed as optional app parameter
28 * - Optional monitoring of calls, started when call is answered
30 * Patch Version 1.07 2003-12-24 01
32 * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
33 * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
35 * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
36 * by Matthew Enger <m.enger@xi.com.au>
38 * This program is free software, distributed under the terms of
39 * the GNU General Public License
42 #include <asterisk/lock.h>
43 #include <asterisk/file.h>
44 #include <asterisk/logger.h>
45 #include <asterisk/channel.h>
46 #include <asterisk/pbx.h>
47 #include <asterisk/options.h>
48 #include <asterisk/module.h>
49 #include <asterisk/translate.h>
50 #include <asterisk/say.h>
51 #include <asterisk/features.h>
52 #include <asterisk/musiconhold.h>
53 #include <asterisk/cli.h>
54 #include <asterisk/manager.h>
55 #include <asterisk/config.h>
56 #include <asterisk/monitor.h>
57 #include <asterisk/utils.h>
58 #include <asterisk/causes.h>
59 #include <asterisk/astdb.h>
67 #include <sys/signal.h>
68 #include <netinet/in.h>
70 #include "../astconf.h"
72 #define QUEUE_STRATEGY_RINGALL 0
73 #define QUEUE_STRATEGY_ROUNDROBIN 1
74 #define QUEUE_STRATEGY_LEASTRECENT 2
75 #define QUEUE_STRATEGY_FEWESTCALLS 3
76 #define QUEUE_STRATEGY_RANDOM 4
77 #define QUEUE_STRATEGY_RRMEMORY 5
79 static struct strategy {
83 { QUEUE_STRATEGY_RINGALL, "ringall" },
84 { QUEUE_STRATEGY_ROUNDROBIN, "roundrobin" },
85 { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
86 { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
87 { QUEUE_STRATEGY_RANDOM, "random" },
88 { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
91 #define DEFAULT_RETRY 5
92 #define DEFAULT_TIMEOUT 15
93 #define RECHECK 1 /* Recheck every second to see we we're at the top yet */
95 #define RES_OKAY 0 /* Action completed */
96 #define RES_EXISTS (-1) /* Entry already exists */
97 #define RES_OUTOFMEMORY (-2) /* Out of memory */
98 #define RES_NOSUCHQUEUE (-3) /* No such queue */
100 static char *tdesc = "True Call Queueing";
102 static char *app = "Queue";
104 static char *synopsis = "Queue a call for a call queue";
106 static char *descrip =
107 " Queue(queuename[|options[|URL][|announceoverride][|timeout]]):\n"
108 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
109 " This application returns -1 if the originating channel hangs up, or if the\n"
110 "call is bridged and either of the parties in the bridge terminate the call.\n"
111 "Returns 0 if the queue is full, nonexistant, or has no members.\n"
112 "The option string may contain zero or more of the following characters:\n"
113 " 't' -- allow the called user transfer the calling user\n"
114 " 'T' -- to allow the calling user to transfer the call.\n"
115 " 'd' -- data-quality (modem) call (minimum delay).\n"
116 " 'h' -- allow callee to hang up by hitting *.\n"
117 " 'H' -- allow caller to hang up by hitting *.\n"
118 " 'n' -- no retries on the timeout; will exit this application and go to the next step.\n"
119 " 'r' -- ring instead of playing MOH\n"
120 " In addition to transferring the call, a call may be parked and then picked\n"
121 "up by another user.\n"
122 " The optional URL will be sent to the called party if the channel supports\n"
124 " The timeout will cause the queue to fail out after a specified number of\n"
125 "seconds, checked between each queues.conf 'timeout' and 'retry' cycle.\n";
128 static char *app_aqm = "AddQueueMember" ;
129 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
130 static char *app_aqm_descrip =
131 " AddQueueMember(queuename[|interface[|penalty]]):\n"
132 "Dynamically adds interface to an existing queue.\n"
133 "If the interface is already in the queue and there exists an n+101 priority\n"
134 "then it will then jump to this priority. Otherwise it will return an error\n"
135 "Returns -1 if there is an error.\n"
136 "Example: AddQueueMember(techsupport|SIP/3000)\n"
139 static char *app_rqm = "RemoveQueueMember" ;
140 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
141 static char *app_rqm_descrip =
142 " RemoveQueueMember(queuename[|interface]):\n"
143 "Dynamically removes interface to an existing queue\n"
144 "If the interface is NOT in the queue and there exists an n+101 priority\n"
145 "then it will then jump to this priority. Otherwise it will return an error\n"
146 "Returns -1 if there is an error.\n"
147 "Example: RemoveQueueMember(techsupport|SIP/3000)\n"
150 /* Persistent Members astdb family */
151 static const char *pm_family = "/Queue/PersistentMembers";
152 /* The maximum lengh of each persistent member queue database entry */
153 #define PM_MAX_LEN 2048
154 /* queues.conf [general] option */
155 static int queue_persistent_members = 0;
157 /* We define a customer "local user" structure because we
158 use it not only for keeping track of what is in use but
159 also for keeping track of who we're dialing. */
162 struct ast_channel *chan;
167 int allowredirect_in;
168 int allowredirect_out;
172 int allowdisconnect_in;
173 int allowdisconnect_out;
175 struct member *member;
176 struct localuser *next;
182 struct ast_call_queue *parent; /* What queue is our parent */
183 char moh[80]; /* Name of musiconhold to be used */
184 char announce[80]; /* Announcement to play for member when call is answered */
185 char context[80]; /* Context when user exits queue */
186 int pos; /* Where we are in the queue */
187 int prio; /* Our priority */
188 int last_pos_said; /* Last position we told the user */
189 time_t last_pos; /* Last time we told the user their position */
190 int opos; /* Where we started in the queue */
191 int handled; /* Whether our call was handled */
192 time_t start; /* When we started holding */
193 time_t expire; /* When this entry should expire (time out of queue) */
194 struct ast_channel *chan; /* Our channel */
195 struct queue_ent *next; /* The next queue entry */
199 char interface[80]; /* Technology/Location */
200 int penalty; /* Are we a last resort? */
201 int calls; /* Number of calls serviced by this member */
202 int dynamic; /* Are we dynamically added? */
203 int status; /* Status of queue member */
204 time_t lastcall; /* When last successful call was hungup */
205 struct member *next; /* Next member */
208 struct ast_call_queue {
210 char name[80]; /* Name of the queue */
211 char moh[80]; /* Name of musiconhold to be used */
212 char announce[80]; /* Announcement to play when call is answered */
213 char context[80]; /* Context for this queue */
214 int strategy; /* Queueing strategy */
215 int announcefrequency; /* How often to announce their position */
216 int roundingseconds; /* How many seconds do we round to? */
217 int announceholdtime; /* When to announce holdtime: 0 = never, -1 = every announcement, 1 = only once */
218 int holdtime; /* Current avg holdtime for this queue, based on recursive boxcar filter */
219 int callscompleted; /* Number of queue calls completed */
220 int callsabandoned; /* Number of queue calls abandoned */
221 int servicelevel; /* seconds setting for servicelevel*/
222 int callscompletedinsl; /* Number of queue calls answererd with servicelevel*/
223 char monfmt[8]; /* Format to use when recording calls */
224 int monjoin; /* Should we join the two files when we are done with the call */
225 char sound_next[80]; /* Sound file: "Your call is now first in line" (def. queue-youarenext) */
226 char sound_thereare[80]; /* Sound file: "There are currently" (def. queue-thereare) */
227 char sound_calls[80]; /* Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting)*/
228 char sound_holdtime[80]; /* Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
229 char sound_minutes[80]; /* Sound file: "minutes." (def. queue-minutes) */
230 char sound_lessthan[80]; /* Sound file: "less-than" (def. queue-lessthan) */
231 char sound_seconds[80]; /* Sound file: "seconds." (def. queue-seconds) */
232 char sound_thanks[80]; /* Sound file: "Thank you for your patience." (def. queue-thankyou) */
233 char sound_reporthold[80]; /* Sound file: "Hold time" (def. queue-reporthold) */
235 int count; /* How many entries are in the queue */
236 int maxlen; /* Max number of entries in queue */
237 int wrapuptime; /* Wrapup Time */
239 int dead; /* Whether this queue is dead or not */
240 int retry; /* Retry calling everyone after this amount of time */
241 int timeout; /* How long to wait for an answer */
243 /* Queue strategy things */
245 int rrpos; /* Round Robin - position */
246 int wrapped; /* Round Robin - wrapped around? */
247 int joinempty; /* Do we care if the queue has no members? */
248 int eventwhencalled; /* Generate an event when the agent is called (before pickup) */
249 int leavewhenempty; /* If all agents leave the queue, remove callers from the queue */
250 int reportholdtime; /* Should we report caller hold time to member? */
251 int memberdelay; /* Seconds to delay connecting member to caller */
253 struct member *members; /* Member channels to be tried */
254 struct queue_ent *head; /* Start of the actual queue */
255 struct ast_call_queue *next; /* Next call queue */
258 static struct ast_call_queue *queues = NULL;
259 AST_MUTEX_DEFINE_STATIC(qlock);
261 static char *int2strat(int strategy)
264 for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
265 if (strategy == strategies[x].strategy)
266 return strategies[x].name;
271 static int strat2int(char *strategy)
274 for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
275 if (!strcasecmp(strategy, strategies[x].name))
276 return strategies[x].strategy;
281 /* Insert the 'new' entry after the 'prev' entry of queue 'q' */
282 static inline void insert_entry(struct ast_call_queue *q,
283 struct queue_ent *prev, struct queue_ent *new, int *pos)
285 struct queue_ent *cur;
302 static int has_no_members(struct ast_call_queue *q)
304 struct member *member;
307 while(empty && member) {
308 switch(member->status) {
309 case AST_DEVICE_UNAVAILABLE:
310 case AST_DEVICE_INVALID:
311 /* Not logged on, etc */
317 member = member->next;
327 static void *changethread(void *data)
329 struct ast_call_queue *q;
330 struct statechange *sc = data;
333 loc = strchr(sc->dev, '/');
338 ast_log(LOG_WARNING, "Can't change device with no technology!\n");
343 ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d'\n", sc->dev, loc, sc->state);
344 ast_mutex_lock(&qlock);
345 for (q = queues; q; q = q->next) {
346 ast_mutex_lock(&q->lock);
349 if (!strcasecmp(sc->dev, cur->interface)) {
350 if (cur->status != sc->state) {
351 cur->status = sc->state;
352 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
360 q->name, cur->interface, cur->dynamic ? "dynamic" : "static",
361 cur->penalty, cur->calls, cur->lastcall, cur->status);
366 ast_mutex_unlock(&q->lock);
368 ast_mutex_unlock(&qlock);
369 ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d'\n", sc->dev, loc, sc->state);
374 static int statechange_queue(const char *dev, int state, void *ign)
376 /* Avoid potential for deadlocks by spawning a new thread to handle
378 struct statechange *sc;
381 sc = malloc(sizeof(struct statechange) + strlen(dev) + 1);
384 strcpy(sc->dev, dev);
385 pthread_attr_init(&attr);
386 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
387 if (ast_pthread_create(&t, &attr, changethread, sc)) {
388 ast_log(LOG_WARNING, "Failed to create update thread!\n");
395 static int join_queue(char *queuename, struct queue_ent *qe)
397 struct ast_call_queue *q;
398 struct queue_ent *cur, *prev = NULL;
403 ast_mutex_lock(&qlock);
404 for (q = queues; q; q = q->next) {
405 if (!strcasecmp(q->name, queuename)) {
406 /* This is our one */
407 ast_mutex_lock(&q->lock);
408 if ((!has_no_members(q) || q->joinempty) && (!q->maxlen || (q->count < q->maxlen))) {
409 /* There's space for us, put us at the right position inside
411 * Take into account the priority of the calling user */
416 /* We have higher priority than the current user, enter
417 * before him, after all the other users with priority
418 * higher or equal to our priority. */
419 if ((!inserted) && (qe->prio > cur->prio)) {
420 insert_entry(q, prev, qe, &pos);
427 /* No luck, join at the end of the queue */
429 insert_entry(q, prev, qe, &pos);
430 strncpy(qe->moh, q->moh, sizeof(qe->moh) - 1);
431 strncpy(qe->announce, q->announce, sizeof(qe->announce) - 1);
432 strncpy(qe->context, q->context, sizeof(qe->context) - 1);
435 manager_event(EVENT_FLAG_CALL, "Join",
436 "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\n",
438 qe->chan->cid.cid_num ? qe->chan->cid.cid_num : "unknown",
439 qe->chan->cid.cid_name ? qe->chan->cid.cid_name : "unknown",
440 q->name, qe->pos, q->count );
442 ast_log(LOG_NOTICE, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
445 ast_mutex_unlock(&q->lock);
449 ast_mutex_unlock(&qlock);
453 static void free_members(struct ast_call_queue *q, int all)
455 /* Free non-dynamic members */
456 struct member *curm, *next, *prev;
461 if (all || !curm->dynamic) {
473 static void destroy_queue(struct ast_call_queue *q)
475 struct ast_call_queue *cur, *prev = NULL;
476 ast_mutex_lock(&qlock);
477 for (cur = queues; cur; cur = cur->next) {
480 prev->next = cur->next;
487 ast_mutex_unlock(&qlock);
489 ast_mutex_destroy(&q->lock);
493 static int play_file(struct ast_channel *chan, char *filename)
497 ast_stopstream(chan);
498 res = ast_streamfile(chan, filename, chan->language);
501 res = ast_waitstream(chan, "");
506 ast_log(LOG_WARNING, "ast_streamfile failed on %s \n", chan->name);
509 ast_stopstream(chan);
514 static int say_position(struct queue_ent *qe)
516 int res = 0, avgholdmins, avgholdsecs;
519 /* Check to see if this is ludicrous -- if we just announced position, don't do it again*/
521 if ( (now - qe->last_pos) < 15 )
524 /* If either our position has changed, or we are over the freq timer, say position */
525 if ( (qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency) )
528 ast_moh_stop(qe->chan);
529 /* Say we're next, if we are */
531 res += play_file(qe->chan, qe->parent->sound_next);
534 res += play_file(qe->chan, qe->parent->sound_thereare);
535 res += ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
536 res += play_file(qe->chan, qe->parent->sound_calls);
538 /* Round hold time to nearest minute */
539 avgholdmins = abs(( (qe->parent->holdtime + 30) - (now - qe->start) ) / 60);
541 /* If they have specified a rounding then round the seconds as well */
542 if(qe->parent->roundingseconds) {
543 avgholdsecs = (abs(( (qe->parent->holdtime + 30) - (now - qe->start) )) - 60 * avgholdmins) / qe->parent->roundingseconds;
544 avgholdsecs*= qe->parent->roundingseconds;
549 if (option_verbose > 2)
550 ast_verbose(VERBOSE_PREFIX_3 "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
552 /* If the hold time is >1 min, if it's enabled, and if it's not
553 supposed to be only once and we have already said it, say it */
554 if ((avgholdmins+avgholdsecs) > 0 && (qe->parent->announceholdtime) && (!(qe->parent->announceholdtime==1 && qe->last_pos)) ) {
555 res += play_file(qe->chan, qe->parent->sound_holdtime);
557 if (avgholdmins < 2) {
558 res += play_file(qe->chan, qe->parent->sound_lessthan);
559 res += ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, (char *)NULL);
561 res += ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, (char*) NULL);
562 res += play_file(qe->chan, qe->parent->sound_minutes);
565 res += ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, (char*) NULL);
566 res += play_file(qe->chan, qe->parent->sound_seconds);
572 /* Set our last_pos indicators */
574 qe->last_pos_said = qe->pos;
576 if (option_verbose > 2)
577 ast_verbose(VERBOSE_PREFIX_3 "Told %s in %s their queue position (which was %d)\n", qe->chan->name, qe->parent->name, qe->pos);
578 res += play_file(qe->chan, qe->parent->sound_thanks);
579 ast_moh_start(qe->chan, qe->moh);
584 static void record_abandoned(struct queue_ent *qe)
586 ast_mutex_lock(&qe->parent->lock);
587 qe->parent->callsabandoned++;
588 ast_mutex_unlock(&qe->parent->lock);
591 static void recalc_holdtime(struct queue_ent *qe)
593 int oldvalue, newvalue;
595 /* Calculate holdtime using a recursive boxcar filter */
596 /* Thanks to SRT for this contribution */
597 /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
599 newvalue = time(NULL) - qe->start;
601 ast_mutex_lock(&qe->parent->lock);
602 if (newvalue <= qe->parent->servicelevel)
603 qe->parent->callscompletedinsl++;
604 oldvalue = qe->parent->holdtime;
605 qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newvalue) >> 2;
606 ast_mutex_unlock(&qe->parent->lock);
610 static void leave_queue(struct queue_ent *qe)
612 struct ast_call_queue *q;
613 struct queue_ent *cur, *prev = NULL;
618 ast_mutex_lock(&q->lock);
626 /* Take us out of the queue */
627 manager_event(EVENT_FLAG_CALL, "Leave",
628 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\n",
629 qe->chan->name, q->name, q->count);
631 ast_log(LOG_NOTICE, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
633 /* Take us out of the queue */
635 prev->next = cur->next;
639 /* Renumber the people after us in the queue based on a new count */
645 ast_mutex_unlock(&q->lock);
646 if (q->dead && !q->count) {
647 /* It's dead and nobody is in it, so kill it */
652 static void hanguptree(struct localuser *outgoing, struct ast_channel *exception)
654 /* Hang up a tree of stuff */
655 struct localuser *oo;
657 /* Hangup any existing lines we have open */
658 if (outgoing->chan && (outgoing->chan != exception))
659 ast_hangup(outgoing->chan);
661 outgoing=outgoing->next;
666 static int update_status(struct ast_call_queue *q, struct member *member, int status)
669 /* Since a reload could have taken place, we have to traverse the list to
670 be sure it's still valid */
671 ast_mutex_lock(&q->lock);
675 cur->status = status;
676 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
684 q->name, cur->interface, cur->dynamic ? "dynamic" : "static",
685 cur->penalty, cur->calls, cur->lastcall, cur->status);
691 ast_mutex_unlock(&q->lock);
695 static int update_dial_status(struct ast_call_queue *q, struct member *member, int status)
697 if (status == AST_CAUSE_BUSY)
698 status = AST_DEVICE_BUSY;
699 else if (status == AST_CAUSE_UNREGISTERED)
700 status = AST_DEVICE_UNAVAILABLE;
701 else if (status == AST_CAUSE_NOSUCHDRIVER)
702 status = AST_DEVICE_INVALID;
704 status = AST_DEVICE_UNKNOWN;
705 return update_status(q, member, status);
708 static int ring_entry(struct queue_ent *qe, struct localuser *tmp)
715 if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
716 ast_log(LOG_DEBUG, "Wrapuptime not yet expired for %s\n", tmp->interface);
718 ast_cdr_busy(qe->chan->cdr);
723 strncpy(tech, tmp->interface, sizeof(tech) - 1);
724 if ((location = strchr(tech, '/')))
729 /* Request the peer */
730 tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
731 if (!tmp->chan) { /* If we can't, just go on to the next call */
733 ast_log(LOG_NOTICE, "Unable to create channel of type '%s'\n", cur->tech);
736 ast_cdr_busy(qe->chan->cdr);
738 update_dial_status(qe->parent, tmp->member, status);
740 } else if (status != tmp->oldstatus)
741 update_dial_status(qe->parent, tmp->member, status);
743 tmp->chan->appl = "AppQueue";
744 tmp->chan->data = "(Outgoing Line)";
745 tmp->chan->whentohangup = 0;
746 if (tmp->chan->cid.cid_num)
747 free(tmp->chan->cid.cid_num);
748 tmp->chan->cid.cid_num = NULL;
749 if (tmp->chan->cid.cid_name)
750 free(tmp->chan->cid.cid_name);
751 tmp->chan->cid.cid_name = NULL;
752 if (tmp->chan->cid.cid_ani)
753 free(tmp->chan->cid.cid_ani);
754 tmp->chan->cid.cid_ani = NULL;
755 if (qe->chan->cid.cid_num)
756 tmp->chan->cid.cid_num = strdup(qe->chan->cid.cid_num);
757 if (qe->chan->cid.cid_name)
758 tmp->chan->cid.cid_name = strdup(qe->chan->cid.cid_name);
759 if (qe->chan->cid.cid_ani)
760 tmp->chan->cid.cid_ani = strdup(qe->chan->cid.cid_ani);
761 /* Presense of ADSI CPE on outgoing channel follows ours */
762 tmp->chan->adsicpe = qe->chan->adsicpe;
763 /* Place the call, but don't wait on the answer */
764 res = ast_call(tmp->chan, location, 0);
766 /* Again, keep going even if there's an error */
768 ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
769 else if (option_verbose > 2)
770 ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->interface);
771 ast_hangup(tmp->chan);
776 if (qe->parent->eventwhencalled) {
777 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
778 "AgentCalled: %s\r\n"
779 "ChannelCalling: %s\r\n"
781 "CallerIDName: %s\r\n"
785 tmp->interface, qe->chan->name,
786 tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
787 tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
788 qe->chan->context, qe->chan->exten, qe->chan->priority);
790 if (option_verbose > 2)
791 ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->interface);
796 static int ring_one(struct queue_ent *qe, struct localuser *outgoing)
798 struct localuser *cur;
799 struct localuser *best;
805 if (cur->stillgoing && /* Not already done */
806 !cur->chan && /* Isn't already going */
807 (!best || (cur->metric < bestmetric))) { /* We haven't found one yet, or it's better */
808 bestmetric = cur->metric;
814 if (!qe->parent->strategy) {
815 /* Ring everyone who shares this best metric (for ringall) */
818 if (cur->stillgoing && !cur->chan && (cur->metric == bestmetric)) {
819 ast_log(LOG_DEBUG, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
825 /* Ring just the best channel */
827 ast_log(LOG_DEBUG, "Trying '%s' with metric %d\n", best->interface, best->metric);
828 ring_entry(qe, best);
831 } while (best && !best->chan);
834 ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
840 static int store_next(struct queue_ent *qe, struct localuser *outgoing)
842 struct localuser *cur;
843 struct localuser *best;
848 if (cur->stillgoing && /* Not already done */
849 !cur->chan && /* Isn't already going */
850 (!best || (cur->metric < bestmetric))) { /* We haven't found one yet, or it's better */
851 bestmetric = cur->metric;
857 /* Ring just the best channel */
858 ast_log(LOG_DEBUG, "Next is '%s' with metric %d\n", best->interface, best->metric);
859 qe->parent->rrpos = best->metric % 1000;
861 /* Just increment rrpos */
862 if (!qe->parent->wrapped) {
863 /* No more channels, start over */
864 qe->parent->rrpos = 0;
866 /* Prioritize next entry */
870 qe->parent->wrapped = 0;
874 static int valid_exit(struct queue_ent *qe, char digit)
877 if (ast_strlen_zero(qe->context))
881 if (ast_exists_extension(qe->chan, qe->context, tmp, 1, qe->chan->cid.cid_num)) {
882 strncpy(qe->chan->context, qe->context, sizeof(qe->chan->context) - 1);
883 strncpy(qe->chan->exten, tmp, sizeof(qe->chan->exten) - 1);
884 qe->chan->priority = 0;
890 #define AST_MAX_WATCHERS 256
892 static struct localuser *wait_for_answer(struct queue_ent *qe, struct localuser *outgoing, int *to, int *allowredir_in, int *allowredir_out, int *allowdisconnect_in, int *allowdisconnect_out, char *digit)
894 char *queue = qe->parent->name;
904 struct localuser *peer = NULL;
905 struct ast_channel *watchers[AST_MAX_WATCHERS];
907 struct ast_channel *winner;
908 struct ast_channel *in = qe->chan;
910 while(*to && !peer) {
917 /* Keep track of important channels */
918 if (o->stillgoing && o->chan) {
919 watchers[pos++] = o->chan;
926 if (numlines == (numbusies + numnochan)) {
927 ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
929 ast_log(LOG_NOTICE, "No one is answering queue '%s'\n", queue);
934 winner = ast_waitfor_n(watchers, pos, to);
937 if (o->stillgoing && (o->chan) && (o->chan->_state == AST_STATE_UP)) {
939 if (option_verbose > 2)
940 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
942 *allowredir_in = o->allowredirect_in;
943 *allowredir_out = o->allowredirect_out;
944 *allowdisconnect_in = o->allowdisconnect_in;
945 *allowdisconnect_out = o->allowdisconnect_out;
947 } else if (o->chan && (o->chan == winner)) {
948 if (!ast_strlen_zero(o->chan->call_forward)) {
949 char tmpchan[256]="";
952 strncpy(tmpchan, o->chan->call_forward, sizeof(tmpchan) - 1);
953 if ((stuff = strchr(tmpchan, '/'))) {
958 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
962 /* Before processing channel, go ahead and check for forwarding */
963 if (option_verbose > 2)
964 ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
965 /* Setup parameters */
966 o->chan = ast_request(tech, in->nativeformats, stuff, &status);
967 if (status != o->oldstatus)
968 update_dial_status(qe->parent, o->member, status);
970 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
974 if (o->chan->cid.cid_num)
975 free(o->chan->cid.cid_num);
976 o->chan->cid.cid_num = NULL;
977 if (o->chan->cid.cid_name)
978 free(o->chan->cid.cid_name);
979 o->chan->cid.cid_name = NULL;
981 if (in->cid.cid_num) {
982 o->chan->cid.cid_num = strdup(in->cid.cid_num);
983 if (!o->chan->cid.cid_num)
984 ast_log(LOG_WARNING, "Out of memory\n");
986 if (in->cid.cid_name) {
987 o->chan->cid.cid_name = strdup(in->cid.cid_name);
988 if (!o->chan->cid.cid_name)
989 ast_log(LOG_WARNING, "Out of memory\n");
991 strncpy(o->chan->accountcode, in->accountcode, sizeof(o->chan->accountcode) - 1);
992 o->chan->cdrflags = in->cdrflags;
994 if (in->cid.cid_ani) {
995 if (o->chan->cid.cid_ani)
996 free(o->chan->cid.cid_ani);
997 o->chan->cid.cid_ani = malloc(strlen(in->cid.cid_ani) + 1);
998 if (o->chan->cid.cid_ani)
999 strncpy(o->chan->cid.cid_ani, in->cid.cid_ani, strlen(in->cid.cid_ani) + 1);
1001 ast_log(LOG_WARNING, "Out of memory\n");
1003 if (o->chan->cid.cid_rdnis)
1004 free(o->chan->cid.cid_rdnis);
1005 if (!ast_strlen_zero(in->macroexten))
1006 o->chan->cid.cid_rdnis = strdup(in->macroexten);
1008 o->chan->cid.cid_rdnis = strdup(in->exten);
1009 if (ast_call(o->chan, tmpchan, 0)) {
1010 ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
1012 ast_hangup(o->chan);
1017 /* Hangup the original channel now, in case we needed it */
1021 f = ast_read(winner);
1023 if (f->frametype == AST_FRAME_CONTROL) {
1024 switch(f->subclass) {
1025 case AST_CONTROL_ANSWER:
1026 /* This is our guy if someone answered. */
1028 if (option_verbose > 2)
1029 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
1031 *allowredir_in = o->allowredirect_in;
1032 *allowredir_out = o->allowredirect_out;
1033 *allowdisconnect_in = o->allowdisconnect_out;
1034 *allowdisconnect_out = o->allowdisconnect_out;
1037 case AST_CONTROL_BUSY:
1038 if (option_verbose > 2)
1039 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
1042 ast_cdr_busy(in->cdr);
1043 ast_hangup(o->chan);
1045 if (qe->parent->strategy)
1046 ring_one(qe, outgoing);
1049 case AST_CONTROL_CONGESTION:
1050 if (option_verbose > 2)
1051 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
1054 ast_cdr_busy(in->cdr);
1055 ast_hangup(o->chan);
1057 if (qe->parent->strategy)
1058 ring_one(qe, outgoing);
1061 case AST_CONTROL_RINGING:
1062 if (option_verbose > 2)
1063 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
1066 ast_indicate(in, AST_CONTROL_RINGING);
1071 case AST_CONTROL_OFFHOOK:
1072 /* Ignore going off hook */
1075 ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
1081 ast_hangup(o->chan);
1083 if (qe->parent->strategy)
1084 ring_one(qe, outgoing);
1092 if (f && (f->frametype != AST_FRAME_VOICE))
1093 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1094 else if (!f || (f->frametype != AST_FRAME_VOICE))
1095 printf("Hangup received on %s\n", in->name);
1097 if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
1102 if (f && (f->frametype == AST_FRAME_DTMF) && allowdisconnect_out && (f->subclass == '*')) {
1103 if (option_verbose > 3)
1104 ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
1108 if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass != '*') && valid_exit(qe, f->subclass)) {
1109 if (option_verbose > 3)
1110 ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c", f->subclass);
1116 if (!*to && (option_verbose > 2))
1117 ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
1124 static int is_our_turn(struct queue_ent *qe)
1126 struct queue_ent *ch;
1129 /* Atomically read the parent head -- does not need a lock */
1130 ch = qe->parent->head;
1131 /* If we are now at the top of the head, break out */
1134 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
1138 ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
1144 static int wait_our_turn(struct queue_ent *qe, int ringing)
1146 struct queue_ent *ch;
1149 /* This is the holding pen for callers 2 through maxlen */
1151 /* Atomically read the parent head -- does not need a lock */
1152 ch = qe->parent->head;
1154 /* If we are now at the top of the head, break out */
1157 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
1161 /* If we have timed out, break out */
1162 if (qe->expire && (time(NULL) > qe->expire))
1165 /* leave the queue if no agents, if enabled */
1166 if (has_no_members(qe->parent) && qe->parent->leavewhenempty) {
1171 /* Make a position announcement, if enabled */
1172 if (qe->parent->announcefrequency && !ringing)
1175 /* Wait a second before checking again */
1176 res = ast_waitfordigit(qe->chan, RECHECK * 1000);
1183 static int update_queue(struct ast_call_queue *q, struct member *member)
1186 /* Since a reload could have taken place, we have to traverse the list to
1187 be sure it's still valid */
1188 ast_mutex_lock(&q->lock);
1191 if (member == cur) {
1192 time(&cur->lastcall);
1198 q->callscompleted++;
1199 ast_mutex_unlock(&q->lock);
1203 static int calc_metric(struct ast_call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct localuser *tmp)
1205 switch (q->strategy) {
1206 case QUEUE_STRATEGY_RINGALL:
1207 /* Everyone equal, except for penalty */
1208 tmp->metric = mem->penalty * 1000000;
1210 case QUEUE_STRATEGY_ROUNDROBIN:
1213 /* No more channels, start over */
1216 /* Prioritize next entry */
1222 case QUEUE_STRATEGY_RRMEMORY:
1223 if (pos < q->rrpos) {
1224 tmp->metric = 1000 + pos;
1226 if (pos > q->rrpos) {
1227 /* Indicate there is another priority */
1232 tmp->metric += mem->penalty * 1000000;
1234 case QUEUE_STRATEGY_RANDOM:
1235 tmp->metric = rand() % 1000;
1236 tmp->metric += mem->penalty * 1000000;
1238 case QUEUE_STRATEGY_FEWESTCALLS:
1239 tmp->metric = mem->calls;
1240 tmp->metric += mem->penalty * 1000000;
1242 case QUEUE_STRATEGY_LEASTRECENT:
1246 tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
1247 tmp->metric += mem->penalty * 1000000;
1250 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
1256 static int try_calling(struct queue_ent *qe, char *options, char *announceoverride, char *url, int *go_on)
1259 struct localuser *outgoing=NULL, *tmp = NULL;
1261 int allowredir_in=0;
1262 int allowredir_out=0;
1263 int allowdisconnect_in=0;
1264 int allowdisconnect_out=0;
1265 char restofit[AST_MAX_EXTENSION];
1266 char oldexten[AST_MAX_EXTENSION]="";
1267 char oldcontext[AST_MAX_EXTENSION]="";
1268 char queuename[256]="";
1270 char *monitorfilename;
1271 struct ast_channel *peer;
1272 struct localuser *lpeer;
1273 struct member *member;
1274 int res = 0, bridge = 0;
1277 char *announce = NULL;
1281 struct ast_bridge_config config;
1282 /* Hold the lock while we setup the outgoing calls */
1283 ast_mutex_lock(&qe->parent->lock);
1285 ast_log(LOG_DEBUG, "%s is trying to call a queue member.\n",
1287 strncpy(queuename, qe->parent->name, sizeof(queuename) - 1);
1289 cur = qe->parent->members;
1290 if (!ast_strlen_zero(qe->announce))
1291 announce = qe->announce;
1292 if (announceoverride && !ast_strlen_zero(announceoverride))
1293 announce = announceoverride;
1295 /* Get a technology/[device:]number pair */
1296 tmp = malloc(sizeof(struct localuser));
1298 ast_mutex_unlock(&qe->parent->lock);
1299 ast_log(LOG_WARNING, "Out of memory\n");
1302 memset(tmp, 0, sizeof(struct localuser));
1303 tmp->stillgoing = -1;
1305 if (strchr(options, 't'))
1306 tmp->allowredirect_in = 1;
1307 if (strchr(options, 'T'))
1308 tmp->allowredirect_out = 1;
1309 if (strchr(options, 'r'))
1310 tmp->ringbackonly = 1;
1311 if (strchr(options, 'm'))
1312 tmp->musiconhold = 1;
1313 if (strchr(options, 'd'))
1314 tmp->dataquality = 1;
1315 if (strchr(options, 'h'))
1316 tmp->allowdisconnect_in = 1;
1317 if (strchr(options, 'H'))
1318 tmp->allowdisconnect_out = 1;
1319 if ((strchr(options, 'n')) && (now - qe->start >= qe->parent->timeout))
1324 ast_log(LOG_DEBUG, "Queue with URL=%s_\n", url);
1326 ast_log(LOG_DEBUG, "Simple queue (no URL)\n");
1329 tmp->member = cur; /* Never directly dereference! Could change on reload */
1330 tmp->oldstatus = cur->status;
1331 tmp->lastcall = cur->lastcall;
1332 strncpy(tmp->interface, cur->interface, sizeof(tmp->interface)-1);
1333 /* If we're dialing by extension, look at the extension to know what to dial */
1334 if ((newnum = strstr(tmp->interface, "/BYEXTENSION"))) {
1336 strncpy(restofit, newnum + strlen("BYEXTENSION"), sizeof(restofit) - 1);
1337 snprintf(newnum, sizeof(tmp->interface) - (newnum - tmp->interface), "%s%s", qe->chan->exten, restofit);
1339 ast_log(LOG_DEBUG, "Dialing by extension %s\n", tmp->interface);
1341 /* Special case: If we ring everyone, go ahead and ring them, otherwise
1342 just calculate their metric for the appropriate strategy */
1343 calc_metric(qe->parent, cur, x++, qe, tmp);
1344 /* Put them in the list of outgoing thingies... We're ready now.
1345 XXX If we're forcibly removed, these outgoing calls won't get
1347 tmp->next = outgoing;
1349 /* If this line is up, don't try anybody else */
1350 if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
1355 if (qe->parent->timeout)
1356 to = qe->parent->timeout * 1000;
1359 ring_one(qe, outgoing);
1360 ast_mutex_unlock(&qe->parent->lock);
1361 lpeer = wait_for_answer(qe, outgoing, &to, &allowredir_in, &allowredir_out, &allowdisconnect_in, &allowdisconnect_out, &digit);
1362 ast_mutex_lock(&qe->parent->lock);
1363 if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
1364 store_next(qe, outgoing);
1366 ast_mutex_unlock(&qe->parent->lock);
1373 /* Musta gotten hung up */
1374 record_abandoned(qe);
1377 if (digit && valid_exit(qe, digit))
1380 /* Nobody answered, next please? */
1384 ast_log(LOG_DEBUG, "%s: Nobody answered.\n", qe->chan->name);
1388 /* Ah ha! Someone answered within the desired timeframe. Of course after this
1389 we will always return with -1 so that it is hung up properly after the
1392 if (!strcmp(qe->chan->type,"Zap")) {
1393 if (tmp->dataquality) zapx = 0;
1394 ast_channel_setoption(qe->chan,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1396 if (!strcmp(peer->type,"Zap")) {
1397 if (tmp->dataquality) zapx = 0;
1398 ast_channel_setoption(peer,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1400 /* Update parameters for the queue */
1401 recalc_holdtime(qe);
1402 member = lpeer->member;
1403 hanguptree(outgoing, peer);
1405 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
1407 res2 = ast_autoservice_start(qe->chan);
1409 if (qe->parent->memberdelay) {
1410 ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
1411 res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
1413 if (!res2 && announce) {
1414 if (play_file(peer, announce))
1415 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
1417 if (!res2 && qe->parent->reportholdtime) {
1418 if (!play_file(peer, qe->parent->sound_reporthold)) {
1423 holdtime = abs((now - qe->start) / 60);
1425 play_file(peer, qe->parent->sound_lessthan);
1426 ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
1428 ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
1429 play_file(peer, qe->parent->sound_minutes);
1433 res2 |= ast_autoservice_stop(qe->chan);
1435 /* Agent must have hung up */
1436 ast_log(LOG_WARNING, "Agent on %s hungup on the customer. They're going to be pissed.\n", peer->name);
1437 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "AGENTDUMP", "%s", "");
1442 /* Stop music on hold */
1443 ast_moh_stop(qe->chan);
1444 /* If appropriate, log that we have a destination channel */
1446 ast_cdr_setdestchan(qe->chan->cdr, peer->name);
1447 /* Make sure channels are compatible */
1448 res = ast_channel_make_compatible(qe->chan, peer);
1450 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "SYSCOMPAT", "%s", "");
1451 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
1455 /* Begin Monitoring */
1456 if (qe->parent->monfmt && *qe->parent->monfmt) {
1457 monitorfilename = pbx_builtin_getvar_helper( qe->chan, "MONITOR_FILENAME");
1458 if(monitorfilename) {
1459 ast_monitor_start( peer, qe->parent->monfmt, monitorfilename, 1 );
1461 ast_monitor_start( peer, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1 );
1463 if(qe->parent->monjoin) {
1464 ast_monitor_setjoinfiles( peer, 1);
1467 /* Drop out of the queue at this point, to prepare for next caller */
1469 if( url && !ast_strlen_zero(url) && ast_channel_supports_html(peer) ) {
1471 ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
1472 ast_channel_sendurl( peer, url );
1474 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "CONNECT", "%ld", (long)time(NULL) - qe->start);
1475 strncpy(oldcontext, qe->chan->context, sizeof(oldcontext) - 1);
1476 strncpy(oldexten, qe->chan->exten, sizeof(oldexten) - 1);
1479 memset(&config,0,sizeof(struct ast_bridge_config));
1480 config.allowredirect_in = allowredir_in;
1481 config.allowredirect_out = allowredir_out;
1482 config.allowdisconnect_in = allowdisconnect_in;
1483 config.allowdisconnect_out = allowdisconnect_out;
1484 bridge = ast_bridge_call(qe->chan,peer,&config);
1486 if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
1487 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "TRANSFER", "%s|%s", qe->chan->exten, qe->chan->context);
1488 } else if (qe->chan->_softhangup) {
1489 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETECALLER", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1491 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETEAGENT", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1494 if(bridge != AST_PBX_NO_HANGUP_PEER)
1496 update_queue(qe->parent, member);
1497 if( bridge == 0 ) res=1; /* JDG: bridge successfull, leave app_queue */
1498 else res = bridge; /* bridge error, stay in the queue */
1501 hanguptree(outgoing, NULL);
1505 static int wait_a_bit(struct queue_ent *qe)
1507 /* Don't need to hold the lock while we setup the outgoing calls */
1508 int retrywait = qe->parent->retry * 1000;
1509 return ast_waitfordigit(qe->chan, retrywait);
1512 /* [PHM 06/26/03] */
1514 static struct member * interface_exists(struct ast_call_queue *q, char *interface)
1519 for (mem = q->members; mem; mem = mem->next)
1520 if (!strcmp(interface, mem->interface))
1527 static struct member *create_queue_node(char *interface, int penalty)
1531 /* Add a new member */
1533 cur = malloc(sizeof(struct member));
1536 memset(cur, 0, sizeof(struct member));
1537 cur->penalty = penalty;
1538 strncpy(cur->interface, interface, sizeof(cur->interface) - 1);
1539 if (!strchr(cur->interface, '/'))
1540 ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1541 cur->status = ast_device_state(interface);
1547 /* Dump all members in a specific queue to the databse
1549 * <pm_family>/<queuename> = <interface>;<penalty>;...
1552 static void dump_queue_members(struct ast_call_queue *pm_queue)
1554 struct member *cur_member = NULL;
1555 char value[PM_MAX_LEN];
1559 memset(value, 0, sizeof(value));
1562 cur_member = pm_queue->members;
1563 while (cur_member) {
1564 if (cur_member->dynamic) {
1565 value_len = strlen(value);
1566 res = snprintf(value+value_len, sizeof(value)-value_len, "%s;%d;", cur_member->interface, cur_member->penalty);
1567 if (res != strlen(value + value_len)) {
1568 ast_log(LOG_WARNING, "Could not create persistent member string, out of space\n");
1572 cur_member = cur_member->next;
1575 if (!ast_strlen_zero(value) && !cur_member) {
1576 if (ast_db_put(pm_family, pm_queue->name, value))
1577 ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
1579 /* Delete the entry if the queue is empty or there is an error */
1580 ast_db_del(pm_family, pm_queue->name);
1587 static int remove_from_queue(char *queuename, char *interface)
1589 struct ast_call_queue *q;
1590 struct member *last_member, *look;
1591 int res = RES_NOSUCHQUEUE;
1593 ast_mutex_lock(&qlock);
1594 for (q = queues ; q ; q = q->next) {
1595 ast_mutex_lock(&q->lock);
1596 if (!strcmp(q->name, queuename)) {
1597 if ((last_member = interface_exists(q, interface))) {
1598 if ((look = q->members) == last_member) {
1599 q->members = last_member->next;
1601 while (look != NULL) {
1602 if (look->next == last_member) {
1603 look->next = last_member->next;
1610 manager_event(EVENT_FLAG_AGENT, "QueueMemberRemoved",
1613 q->name, last_member->interface);
1616 if (queue_persistent_members)
1617 dump_queue_members(q);
1623 ast_mutex_unlock(&q->lock);
1626 ast_mutex_unlock(&q->lock);
1628 ast_mutex_unlock(&qlock);
1632 static int add_to_queue(char *queuename, char *interface, int penalty)
1634 struct ast_call_queue *q;
1635 struct member *new_member;
1636 int res = RES_NOSUCHQUEUE;
1638 ast_mutex_lock(&qlock);
1639 for (q = queues ; q ; q = q->next) {
1640 ast_mutex_lock(&q->lock);
1641 if (!strcmp(q->name, queuename)) {
1642 if (interface_exists(q, interface) == NULL) {
1643 new_member = create_queue_node(interface, penalty);
1645 if (new_member != NULL) {
1646 new_member->dynamic = 1;
1647 new_member->next = q->members;
1648 q->members = new_member;
1649 manager_event(EVENT_FLAG_AGENT, "QueueMemberAdded",
1652 "Membership: %s\r\n"
1654 "CallsTaken: %d\r\n"
1657 q->name, new_member->interface, new_member->dynamic ? "dynamic" : "static",
1658 new_member->penalty, new_member->calls, new_member->lastcall, new_member->status);
1660 if (queue_persistent_members)
1661 dump_queue_members(q);
1665 res = RES_OUTOFMEMORY;
1670 ast_mutex_unlock(&q->lock);
1673 ast_mutex_unlock(&q->lock);
1675 ast_mutex_unlock(&qlock);
1679 /* Add members saved in the queue members DB file saves
1680 * created by dump_queue_members(), back into the queues */
1681 static void reload_queue_members(void)
1684 char *pm_queue_name;
1686 char *pm_penalty_tok;
1688 struct ast_db_entry *pm_db_tree = NULL;
1689 int pm_family_len = 0;
1690 struct ast_call_queue *cur_queue = NULL;
1691 char queue_data[PM_MAX_LEN];
1693 pm_db_tree = ast_db_gettree(pm_family, NULL);
1695 pm_family_len = strlen(pm_family);
1696 ast_mutex_lock(&qlock);
1697 /* Each key in 'pm_family' is the name of a specific queue in which
1698 * we will reload members into. */
1699 while (pm_db_tree) {
1700 pm_queue_name = pm_db_tree->key+pm_family_len+2;
1704 ast_mutex_lock(&cur_queue->lock);
1706 if (strcmp(pm_queue_name, cur_queue->name) == 0)
1709 ast_mutex_unlock(&cur_queue->lock);
1711 cur_queue = cur_queue->next;
1715 /* If the queue no longer exists, remove it from the
1717 ast_db_del(pm_family, pm_queue_name);
1718 pm_db_tree = pm_db_tree->next;
1721 ast_mutex_unlock(&cur_queue->lock);
1723 if (!ast_db_get(pm_family, pm_queue_name, queue_data, PM_MAX_LEN)) {
1724 /* Parse each <interface>;<penalty>; from the value of the
1725 * queuename key and add it to the respective queue */
1726 cur_pm_ptr = queue_data;
1727 while ((pm_interface = strsep(&cur_pm_ptr, ";"))) {
1728 if (!(pm_penalty_tok = strsep(&cur_pm_ptr, ";"))) {
1729 ast_log(LOG_WARNING, "Error parsing corrupted Queue DB string for '%s'\n", pm_queue_name);
1732 pm_penalty = strtol(pm_penalty_tok, NULL, 10);
1733 if (errno == ERANGE) {
1734 ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", pm_penalty_tok);
1739 ast_log(LOG_DEBUG, "Reload Members: Queue: %s Member: %s Penalty: %d\n", pm_queue_name, pm_interface, pm_penalty);
1741 if (add_to_queue(pm_queue_name, pm_interface, pm_penalty) == RES_OUTOFMEMORY) {
1742 ast_log(LOG_ERROR, "Out of Memory\n");
1748 pm_db_tree = pm_db_tree->next;
1751 ast_log(LOG_NOTICE, "Queue members sucessfully reloaded from database.\n");
1752 ast_mutex_unlock(&qlock);
1754 ast_db_freetree(pm_db_tree);
1759 static int rqm_exec(struct ast_channel *chan, void *data)
1762 struct localuser *u;
1763 char *info, *queuename;
1764 char tmpchan[256]="";
1765 char *interface = NULL;
1768 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[|interface])\n");
1772 info = ast_strdupa((char *)data);
1774 ast_log(LOG_ERROR, "Out of memory\n");
1782 interface = strchr(queuename, '|');
1788 strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1789 interface = strrchr(tmpchan, '-');
1792 interface = tmpchan;
1796 switch (remove_from_queue(queuename, interface)) {
1798 ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", interface, queuename);
1802 ast_log(LOG_WARNING, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
1803 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
1804 chan->priority += 100;
1808 case RES_NOSUCHQUEUE:
1809 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", queuename);
1812 case RES_OUTOFMEMORY:
1813 ast_log(LOG_ERROR, "Out of memory\n");
1817 LOCAL_USER_REMOVE(u);
1821 static int aqm_exec(struct ast_channel *chan, void *data)
1824 struct localuser *u;
1827 char tmpchan[512]="";
1828 char *interface=NULL;
1829 char *penaltys=NULL;
1833 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[|[interface][|penalty]])\n");
1837 info = ast_strdupa((char *)data);
1839 ast_log(LOG_ERROR, "Out of memory\n");
1846 interface = strchr(queuename, '|');
1852 penaltys = strchr(interface, '|');
1858 if (!interface || ast_strlen_zero(interface)) {
1859 strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1860 interface = strrchr(tmpchan, '-');
1863 interface = tmpchan;
1865 if (penaltys && strlen(penaltys)) {
1866 if ((sscanf(penaltys, "%d", &penalty) != 1) || penalty < 0) {
1867 ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", penaltys);
1873 switch (add_to_queue(queuename, interface, penalty)) {
1875 ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", interface, queuename);
1879 ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
1880 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
1881 chan->priority += 100;
1885 case RES_NOSUCHQUEUE:
1886 ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", queuename);
1889 case RES_OUTOFMEMORY:
1890 ast_log(LOG_ERROR, "Out of memory\n");
1894 LOCAL_USER_REMOVE(u);
1898 static int queue_exec(struct ast_channel *chan, void *data)
1902 struct localuser *u;
1905 char *info_ptr = info;
1906 char *options = NULL;
1908 char *announceoverride = NULL;
1909 char *user_priority;
1911 char *queuetimeoutstr = NULL;
1913 /* whether to exit Queue application after the timeout hits */
1916 /* Our queue entry */
1917 struct queue_ent qe;
1920 ast_log(LOG_WARNING, "Queue requires an argument (queuename[|[timeout][|URL]])\n");
1926 /* Setup our queue entry */
1927 memset(&qe, 0, sizeof(qe));
1928 qe.start = time(NULL);
1930 /* Parse our arguments XXX Check for failure XXX */
1931 strncpy(info, (char *) data, sizeof(info) - 1);
1932 queuename = strsep(&info_ptr, "|");
1933 options = strsep(&info_ptr, "|");
1934 url = strsep(&info_ptr, "|");
1935 announceoverride = strsep(&info_ptr, "|");
1936 queuetimeoutstr = info_ptr;
1938 /* set the expire time based on the supplied timeout; */
1939 if (queuetimeoutstr)
1940 qe.expire = qe.start + atoi(queuetimeoutstr);
1944 /* Get the priority from the variable ${QUEUE_PRIO} */
1945 user_priority = pbx_builtin_getvar_helper(chan, "QUEUE_PRIO");
1946 if (user_priority) {
1947 if (sscanf(user_priority, "%d", &prio) == 1) {
1949 ast_log(LOG_DEBUG, "%s: Got priority %d from ${QUEUE_PRIO}.\n",
1952 ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
1953 user_priority, chan->name);
1958 ast_log(LOG_DEBUG, "NO QUEUE_PRIO variable found. Using default.\n");
1963 if (strchr(options, 'r')) {
1968 /* if (option_debug) */
1969 ast_log(LOG_DEBUG, "queue: %s, options: %s, url: %s, announce: %s, expires: %ld, priority: %d\n",
1970 queuename, options, url, announceoverride, (long)qe.expire, (int)prio);
1973 qe.prio = (int)prio;
1974 qe.last_pos_said = 0;
1976 if (!join_queue(queuename, &qe)) {
1977 ast_queue_log(queuename, chan->uniqueid, "NONE", "ENTERQUEUE", "%s|%s", url ? url : "", chan->cid.cid_num ? chan->cid.cid_num : "");
1978 /* Start music on hold */
1981 ast_indicate(chan, AST_CONTROL_RINGING);
1983 ast_moh_start(chan, qe.moh);
1986 /* This is the wait loop for callers 2 through maxlen */
1988 res = wait_our_turn(&qe, ringing);
1989 /* If they hungup, return immediately */
1991 /* Record this abandoned call */
1992 record_abandoned(&qe);
1993 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
1994 if (option_verbose > 2) {
1995 ast_verbose(VERBOSE_PREFIX_3 "User disconnected while waiting their turn\n");
2002 if (valid_exit(&qe, res)) {
2003 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2008 int makeannouncement = 0;
2010 /* This is the wait loop for the head caller*/
2011 /* To exit, they may get their call answered; */
2012 /* they may dial a digit from the queue context; */
2013 /* or, they may timeout. */
2015 /* Leave if we have exceeded our queuetimeout */
2016 if (qe.expire && (time(NULL) > qe.expire)) {
2021 if (makeannouncement) {
2022 /* Make a position announcement, if enabled */
2023 if (qe.parent->announcefrequency && !ringing)
2026 makeannouncement = 1;
2028 /* Try calling all queue members for 'timeout' seconds */
2029 res = try_calling(&qe, options, announceoverride, url, &go_on);
2033 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2035 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2039 /* leave the queue if no agents, if enabled */
2040 if (has_no_members(qe.parent) && (qe.parent->leavewhenempty)) {
2045 /* Leave if we have exceeded our queuetimeout */
2046 if (qe.expire && (time(NULL) > qe.expire)) {
2051 /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
2052 res = wait_a_bit(&qe);
2054 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2055 if (option_verbose > 2) {
2056 ast_verbose(VERBOSE_PREFIX_3 "User disconnected when they almost made it\n");
2061 if (res && valid_exit(&qe, res)) {
2062 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2065 /* exit after 'timeout' cycle if 'n' option enabled */
2067 if (option_verbose > 2) {
2068 ast_verbose(VERBOSE_PREFIX_3 "Exiting on time-out cycle\n");
2071 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
2075 /* Since this is a priority queue and
2076 * it is not sure that we are still at the head
2077 * of the queue, go and check for our turn again.
2079 if (!is_our_turn(&qe)) {
2080 ast_log(LOG_DEBUG, "Darn priorities, going back in queue (%s)!\n",
2086 /* Don't allow return code > 0 */
2087 if (res >= 0 && res != AST_PBX_KEEPALIVE) {
2090 ast_indicate(chan, -1);
2094 ast_stopstream(chan);
2098 ast_log(LOG_WARNING, "Unable to join queue '%s'\n", queuename);
2101 LOCAL_USER_REMOVE(u);
2105 static void reload_queues(void)
2107 struct ast_call_queue *q, *ql, *qn;
2108 struct ast_config *cfg;
2110 struct ast_variable *var;
2111 struct member *prev, *cur;
2113 char *general_val = NULL;
2115 cfg = ast_load("queues.conf");
2117 ast_log(LOG_NOTICE, "No call queueing config file, so no call queues\n");
2120 ast_mutex_lock(&qlock);
2121 /* Mark all queues as dead for the moment */
2127 /* Chug through config file */
2128 cat = ast_category_browse(cfg, NULL);
2130 if (strcasecmp(cat, "general")) {
2131 /* Look for an existing one */
2134 if (!strcmp(q->name, cat))
2140 q = malloc(sizeof(struct ast_call_queue));
2143 memset(q, 0, sizeof(struct ast_call_queue));
2144 ast_mutex_init(&q->lock);
2145 strncpy(q->name, cat, sizeof(q->name) - 1);
2152 ast_mutex_lock(&q->lock);
2153 /* Re-initialize the queue */
2158 q->announcefrequency = 0;
2159 q->announceholdtime = 0;
2160 q->roundingseconds = 0; /* Default - don't announce seconds */
2162 q->callscompleted = 0;
2163 q->callsabandoned = 0;
2164 q->callscompletedinsl = 0;
2165 q->servicelevel = 0;
2169 q->announce[0] = '\0';
2170 q->context[0] = '\0';
2171 q->monfmt[0] = '\0';
2172 strncpy(q->sound_next, "queue-youarenext", sizeof(q->sound_next) - 1);
2173 strncpy(q->sound_thereare, "queue-thereare", sizeof(q->sound_thereare) - 1);
2174 strncpy(q->sound_calls, "queue-callswaiting", sizeof(q->sound_calls) - 1);
2175 strncpy(q->sound_holdtime, "queue-holdtime", sizeof(q->sound_holdtime) - 1);
2176 strncpy(q->sound_minutes, "queue-minutes", sizeof(q->sound_minutes) - 1);
2177 strncpy(q->sound_seconds, "queue-seconds", sizeof(q->sound_seconds) - 1);
2178 strncpy(q->sound_thanks, "queue-thankyou", sizeof(q->sound_thanks) - 1);
2179 strncpy(q->sound_lessthan, "queue-less-than", sizeof(q->sound_lessthan) - 1);
2180 strncpy(q->sound_reporthold, "queue-reporthold", sizeof(q->sound_reporthold) - 1);
2183 /* find the end of any dynamic members */
2187 var = ast_variable_browse(cfg, cat);
2189 if (!strcasecmp(var->name, "member")) {
2190 /* Add a new member */
2191 cur = malloc(sizeof(struct member));
2193 memset(cur, 0, sizeof(struct member));
2194 strncpy(cur->interface, var->value, sizeof(cur->interface) - 1);
2195 if ((tmp = strchr(cur->interface, ','))) {
2198 cur->penalty = atoi(tmp);
2199 if (cur->penalty < 0)
2202 if (!strchr(cur->interface, '/'))
2203 ast_log(LOG_WARNING, "No location at line %d of queue.conf\n", var->lineno);
2210 } else if (!strcasecmp(var->name, "music")) {
2211 strncpy(q->moh, var->value, sizeof(q->moh) - 1);
2212 } else if (!strcasecmp(var->name, "announce")) {
2213 strncpy(q->announce, var->value, sizeof(q->announce) - 1);
2214 } else if (!strcasecmp(var->name, "context")) {
2215 strncpy(q->context, var->value, sizeof(q->context) - 1);
2216 } else if (!strcasecmp(var->name, "timeout")) {
2217 q->timeout = atoi(var->value);
2218 } else if (!strcasecmp(var->name, "monitor-join")) {
2219 q->monjoin = ast_true(var->value);
2220 } else if (!strcasecmp(var->name, "monitor-format")) {
2221 strncpy(q->monfmt, var->value, sizeof(q->monfmt) - 1);
2222 } else if (!strcasecmp(var->name, "queue-youarenext")) {
2223 strncpy(q->sound_next, var->value, sizeof(q->sound_next) - 1);
2224 } else if (!strcasecmp(var->name, "queue-thereare")) {
2225 strncpy(q->sound_thereare, var->value, sizeof(q->sound_thereare) - 1);
2226 } else if (!strcasecmp(var->name, "queue-callswaiting")) {
2227 strncpy(q->sound_calls, var->value, sizeof(q->sound_calls) - 1);
2228 } else if (!strcasecmp(var->name, "queue-holdtime")) {
2229 strncpy(q->sound_holdtime, var->value, sizeof(q->sound_holdtime) - 1);
2230 } else if (!strcasecmp(var->name, "queue-minutes")) {
2231 strncpy(q->sound_minutes, var->value, sizeof(q->sound_minutes) - 1);
2232 } else if (!strcasecmp(var->name, "queue-seconds")) {
2233 strncpy(q->sound_seconds, var->value, sizeof(q->sound_seconds) - 1);
2234 } else if (!strcasecmp(var->name, "queue-lessthan")) {
2235 strncpy(q->sound_lessthan, var->value, sizeof(q->sound_lessthan) - 1);
2236 } else if (!strcasecmp(var->name, "queue-thankyou")) {
2237 strncpy(q->sound_thanks, var->value, sizeof(q->sound_thanks) - 1);
2238 } else if (!strcasecmp(var->name, "queue-reporthold")) {
2239 strncpy(q->sound_reporthold, var->value, sizeof(q->sound_reporthold) - 1);
2240 } else if (!strcasecmp(var->name, "announce-frequency")) {
2241 q->announcefrequency = atoi(var->value);
2242 } else if (!strcasecmp(var->name, "announce-round-seconds")) {
2243 q->roundingseconds = atoi(var->value);
2244 if(q->roundingseconds>60 || q->roundingseconds<0) {
2245 ast_log(LOG_WARNING, "'%s' isn't a valid value for queue-rounding-seconds using 0 instead at line %d of queue.conf\n", var->value, var->lineno);
2246 q->roundingseconds=0;
2248 } else if (!strcasecmp(var->name, "announce-holdtime")) {
2249 q->announceholdtime = (!strcasecmp(var->value,"once")) ? 1 : ast_true(var->value);
2250 } else if (!strcasecmp(var->name, "retry")) {
2251 q->retry = atoi(var->value);
2252 } else if (!strcasecmp(var->name, "wrapuptime")) {
2253 q->wrapuptime = atoi(var->value);
2254 } else if (!strcasecmp(var->name, "maxlen")) {
2255 q->maxlen = atoi(var->value);
2256 } else if (!strcasecmp(var->name, "servicelevel")) {
2257 q->servicelevel= atoi(var->value);
2258 } else if (!strcasecmp(var->name, "strategy")) {
2259 q->strategy = strat2int(var->value);
2260 if (q->strategy < 0) {
2261 ast_log(LOG_WARNING, "'%s' isn't a valid strategy, using ringall instead\n", var->value);
2264 } else if (!strcasecmp(var->name, "joinempty")) {
2265 q->joinempty = ast_true(var->value);
2266 } else if (!strcasecmp(var->name, "leavewhenempty")) {
2267 q->leavewhenempty = ast_true(var->value);
2268 } else if (!strcasecmp(var->name, "eventwhencalled")) {
2269 q->eventwhencalled = ast_true(var->value);
2270 } else if (!strcasecmp(var->name, "reportholdtime")) {
2271 q->reportholdtime = ast_true(var->value);
2272 } else if (!strcasecmp(var->name, "memberdelay")) {
2273 q->memberdelay = atoi(var->value);
2275 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queue.conf\n", cat, var->name, var->lineno);
2280 q->retry = DEFAULT_RETRY;
2282 q->timeout = DEFAULT_TIMEOUT;
2286 ast_mutex_unlock(&q->lock);
2293 /* Initialize global settings */
2294 queue_persistent_members = 0;
2295 if ((general_val = ast_variable_retrieve(cfg, "general", "persistentmembers")))
2296 queue_persistent_members = ast_true(general_val);
2298 cat = ast_category_browse(cfg, cat);
2313 ast_log(LOG_WARNING, "XXX Leaking a little memory :( XXX\n");
2315 for (cur = q->members; cur; cur = cur->next)
2316 cur->status = ast_device_state(cur->interface);
2321 ast_mutex_unlock(&qlock);
2324 static char *status2str(int status, char *buf, int buflen)
2327 case AST_DEVICE_UNKNOWN:
2328 strncpy(buf, "unknown", buflen - 1);
2330 case AST_DEVICE_NOT_INUSE:
2331 strncpy(buf, "notinuse", buflen - 1);
2333 case AST_DEVICE_INUSE:
2334 strncpy(buf, "inuse", buflen - 1);
2336 case AST_DEVICE_BUSY:
2337 strncpy(buf, "busy", buflen - 1);
2339 case AST_DEVICE_INVALID:
2340 strncpy(buf, "invalid", buflen - 1);
2342 case AST_DEVICE_UNAVAILABLE:
2343 strncpy(buf, "unavailable", buflen - 1);
2346 snprintf(buf, buflen, "unknown status %d", status);
2351 static int __queues_show(int fd, int argc, char **argv, int queue_show)
2353 struct ast_call_queue *q;
2354 struct queue_ent *qe;
2359 char calls[80] = "";
2360 char tmpbuf[80] = "";
2364 if ((!queue_show && argc != 2) || (queue_show && argc != 3))
2365 return RESULT_SHOWUSAGE;
2366 ast_mutex_lock(&qlock);
2369 ast_mutex_unlock(&qlock);
2371 ast_cli(fd, "No such queue: %s.\n",argv[2]);
2373 ast_cli(fd, "No queues.\n");
2374 return RESULT_SUCCESS;
2377 ast_mutex_lock(&q->lock);
2379 if (strcasecmp(q->name, argv[2]) != 0) {
2380 ast_mutex_unlock(&q->lock);
2383 ast_cli(fd, "No such queue: %s.\n",argv[2]);
2390 snprintf(max, sizeof(max), "%d", q->maxlen);
2392 strncpy(max, "unlimited", sizeof(max) - 1);
2394 if(q->callscompleted > 0)
2395 sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
2396 ast_cli(fd, "%-12.12s has %d calls (max %s) in '%s' strategy (%ds holdtime), C:%d, A:%d, SL:%2.1f%% within %ds\n",
2397 q->name, q->count, max, int2strat(q->strategy), q->holdtime, q->callscompleted, q->callsabandoned,sl,q->servicelevel);
2399 ast_cli(fd, " Members: \n");
2400 for (mem = q->members; mem; mem = mem->next) {
2402 snprintf(max, sizeof(max) - 20, " with penalty %d", mem->penalty);
2406 strncat(max, " (dynamic)", sizeof(max) - strlen(max) - 1);
2408 snprintf(max + strlen(max), sizeof(max) - strlen(max), " (%s)", status2str(mem->status, tmpbuf, sizeof(tmpbuf)));
2410 snprintf(calls, sizeof(calls), " has taken %d calls (last was %ld secs ago)",
2411 mem->calls, (long)(time(NULL) - mem->lastcall));
2413 strncpy(calls, " has taken no calls yet", sizeof(calls) - 1);
2414 ast_cli(fd, " %s%s%s\n", mem->interface, max, calls);
2417 ast_cli(fd, " No Members\n");
2420 ast_cli(fd, " Callers: \n");
2421 for (qe = q->head; qe; qe = qe->next)
2422 ast_cli(fd, " %d. %s (wait: %ld:%2.2ld, prio: %d)\n", pos++, qe->chan->name,
2423 (long)(now - qe->start) / 60, (long)(now - qe->start) % 60, qe->prio);
2425 ast_cli(fd, " No Callers\n");
2427 ast_mutex_unlock(&q->lock);
2432 ast_mutex_unlock(&qlock);
2433 return RESULT_SUCCESS;
2436 static int queues_show(int fd, int argc, char **argv)
2438 return __queues_show(fd, argc, argv, 0);
2441 static int queue_show(int fd, int argc, char **argv)
2443 return __queues_show(fd, argc, argv, 1);
2446 static char *complete_queue(char *line, char *word, int pos, int state)
2448 struct ast_call_queue *q;
2451 ast_mutex_lock(&qlock);
2452 for (q = queues; q; q = q->next) {
2453 if (!strncasecmp(word, q->name, strlen(word))) {
2454 if (++which > state)
2458 ast_mutex_unlock(&qlock);
2459 return q ? strdup(q->name) : NULL;
2462 /* JDG: callback to display queues status in manager */
2463 static int manager_queues_show( struct mansession *s, struct message *m )
2465 char *a[] = { "show", "queues" };
2466 return queues_show( s->fd, 2, a );
2470 /* Dump queue status */
2471 static int manager_queues_status( struct mansession *s, struct message *m )
2475 char *id = astman_get_header(m,"ActionID");
2476 char idText[256] = "";
2477 struct ast_call_queue *q;
2478 struct queue_ent *qe;
2481 astman_send_ack(s, m, "Queue status will follow");
2483 ast_mutex_lock(&qlock);
2484 if (!ast_strlen_zero(id)) {
2485 snprintf(idText,256,"ActionID: %s\r\n",id);
2487 for (q = queues; q; q = q->next) {
2488 ast_mutex_lock(&q->lock);
2490 /* List queue properties */
2491 if(q->callscompleted > 0)
2492 sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
2493 ast_mutex_lock(&s->lock);
2494 ast_cli(s->fd, "Event: QueueParams\r\n"
2501 "ServiceLevel: %d\r\n"
2502 "ServicelevelPerf: %2.1f\r\n"
2505 q->name, q->maxlen, q->count, q->holdtime, q->callscompleted,
2506 q->callsabandoned, q->servicelevel, sl, idText);
2508 /* List Queue Members */
2509 for (mem = q->members; mem; mem = mem->next)
2510 ast_cli(s->fd, "Event: QueueMember\r\n"
2513 "Membership: %s\r\n"
2515 "CallsTaken: %d\r\n"
2520 q->name, mem->interface, mem->dynamic ? "dynamic" : "static",
2521 mem->penalty, mem->calls, mem->lastcall, mem->status, idText);
2523 /* List Queue Entries */
2526 for (qe = q->head; qe; qe = qe->next)
2527 ast_cli(s->fd, "Event: QueueEntry\r\n"
2532 "CallerIDName: %s\r\n"
2536 q->name, pos++, qe->chan->name,
2537 qe->chan->cid.cid_num ? qe->chan->cid.cid_num : "unknown",
2538 qe->chan->cid.cid_name ? qe->chan->cid.cid_name : "unknown",
2539 (long)(now - qe->start), idText);
2540 ast_mutex_unlock(&s->lock);
2541 ast_mutex_unlock(&q->lock);
2543 ast_mutex_unlock(&qlock);
2544 return RESULT_SUCCESS;
2547 static int manager_add_queue_member(struct mansession *s, struct message *m)
2549 char *queuename, *interface, *penalty_s;
2552 queuename = astman_get_header(m, "Queue");
2553 interface = astman_get_header(m, "Interface");
2554 penalty_s = astman_get_header(m, "Penalty");
2556 if (ast_strlen_zero(queuename)) {
2557 astman_send_error(s, m, "'Queue' not specified.");
2561 if (ast_strlen_zero(interface)) {
2562 astman_send_error(s, m, "'Interface' not specified.");
2566 if (ast_strlen_zero(penalty_s))
2568 else if (sscanf(penalty_s, "%d", &penalty) != 1) {
2572 switch (add_to_queue(queuename, interface, penalty)) {
2574 astman_send_ack(s, m, "Added interface to queue");
2577 astman_send_error(s, m, "Unable to add interface: Already there");
2579 case RES_NOSUCHQUEUE:
2580 astman_send_error(s, m, "Unable to add interface to queue: No such queue");
2582 case RES_OUTOFMEMORY:
2583 astman_send_error(s, m, "Out of memory");
2589 static int manager_remove_queue_member(struct mansession *s, struct message *m)
2591 char *queuename, *interface;
2593 queuename = astman_get_header(m, "Queue");
2594 interface = astman_get_header(m, "Interface");
2596 if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
2597 astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
2601 switch (remove_from_queue(queuename, interface)) {
2603 astman_send_ack(s, m, "Removed interface from queue");
2606 astman_send_error(s, m, "Unable to remove interface: Not there");
2608 case RES_NOSUCHQUEUE:
2609 astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
2611 case RES_OUTOFMEMORY:
2612 astman_send_error(s, m, "Out of memory");
2618 static int handle_add_queue_member(int fd, int argc, char *argv[])
2620 char *queuename, *interface;
2623 if ((argc != 6) && (argc != 8)) {
2624 return RESULT_SHOWUSAGE;
2625 } else if (strcmp(argv[4], "to")) {
2626 return RESULT_SHOWUSAGE;
2627 } else if ((argc == 8) && strcmp(argv[6], "penalty")) {
2628 return RESULT_SHOWUSAGE;
2631 queuename = argv[5];
2632 interface = argv[3];
2634 if (sscanf(argv[7], "%d", &penalty) == 1) {
2636 ast_cli(fd, "Penalty must be >= 0\n");
2640 ast_cli(fd, "Penalty must be an integer >= 0\n");
2647 switch (add_to_queue(queuename, interface, penalty)) {
2649 ast_cli(fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
2650 return RESULT_SUCCESS;
2652 ast_cli(fd, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
2653 return RESULT_FAILURE;
2654 case RES_NOSUCHQUEUE:
2655 ast_cli(fd, "Unable to add interface to queue '%s': No such queue\n", queuename);
2656 return RESULT_FAILURE;
2657 case RES_OUTOFMEMORY:
2658 ast_cli(fd, "Out of memory\n");
2659 return RESULT_FAILURE;
2661 return RESULT_FAILURE;
2665 static char *complete_add_queue_member(char *line, char *word, int pos, int state)
2667 /* 0 - add; 1 - queue; 2 - member; 3 - <member>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty> */
2670 /* Don't attempt to complete name of member (infinite possibilities) */
2674 return strdup("to");
2679 /* No need to duplicate code */
2680 return complete_queue(line, word, pos, state);
2683 return strdup("penalty");
2688 if (state < 100) { /* 0-99 */
2689 char *num = malloc(3);
2691 sprintf(num, "%d", state);
2702 static int handle_remove_queue_member(int fd, int argc, char *argv[])
2704 char *queuename, *interface;
2707 return RESULT_SHOWUSAGE;
2708 } else if (strcmp(argv[4], "from")) {
2709 return RESULT_SHOWUSAGE;
2712 queuename = argv[5];
2713 interface = argv[3];
2715 switch (remove_from_queue(queuename, interface)) {
2717 ast_cli(fd, "Removed interface '%s' from queue '%s'\n", interface, queuename);
2718 return RESULT_SUCCESS;
2720 ast_cli(fd, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
2721 return RESULT_FAILURE;
2722 case RES_NOSUCHQUEUE:
2723 ast_cli(fd, "Unable to remove interface from queue '%s': No such queue\n", queuename);
2724 return RESULT_FAILURE;
2725 case RES_OUTOFMEMORY:
2726 ast_cli(fd, "Out of memory\n");
2727 return RESULT_FAILURE;
2729 return RESULT_FAILURE;
2733 static char *complete_remove_queue_member(char *line, char *word, int pos, int state)
2736 struct ast_call_queue *q;
2739 /* 0 - add; 1 - queue; 2 - member; 3 - <member>; 4 - to; 5 - <queue> */
2740 if ((pos > 5) || (pos < 3)) {
2745 return strdup("from");
2752 /* No need to duplicate code */
2753 return complete_queue(line, word, pos, state);
2756 if (queues != NULL) {
2757 for (q = queues ; q ; q = q->next) {
2758 ast_mutex_lock(&q->lock);
2759 for (m = q->members ; m ; m = m->next) {
2760 if (++which > state) {
2761 ast_mutex_unlock(&q->lock);
2762 return strdup(m->interface);
2765 ast_mutex_unlock(&q->lock);
2771 static char show_queues_usage[] =
2772 "Usage: show queues\n"
2773 " Provides summary information on call queues.\n";
2775 static struct ast_cli_entry cli_show_queues = {
2776 { "show", "queues", NULL }, queues_show,
2777 "Show status of queues", show_queues_usage, NULL };
2779 static char show_queue_usage[] =
2780 "Usage: show queue\n"
2781 " Provides summary information on a specified queue.\n";
2783 static struct ast_cli_entry cli_show_queue = {
2784 { "show", "queue", NULL }, queue_show,
2785 "Show status of a specified queue", show_queue_usage, complete_queue };
2787 static char aqm_cmd_usage[] =
2788 "Usage: add queue member <channel> to <queue> [penalty <penalty>]\n";
2790 static struct ast_cli_entry cli_add_queue_member = {