/
agent_manager.erl
2013 lines (1863 loc) · 71.4 KB
/
agent_manager.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%% The contents of this file are subject to the Common Public Attribution
%% License Version 1.0 (the “License”); you may not use this file except
%% in compliance with the License. You may obtain a copy of the License at
%% http://opensource.org/licenses/cpal_1.0. The License is based on the
%% Mozilla Public License Version 1.1 but Sections 14 and 15 have been
%% added to cover use of software over a computer network and provide for
%% limited attribution for the Original Developer. In addition, Exhibit A
%% has been modified to be consistent with Exhibit B.
%%
%% Software distributed under the License is distributed on an “AS IS”
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%% License for the specific language governing rights and limitations
%% under the License.
%%
%% The Original Code is OpenACD.
%%
%% The Initial Developers of the Original Code is
%% Andrew Thompson and Micah Warren.
%%
%% All portions of the code written by the Initial Developers are Copyright
%% (c) 2008-2009 SpiceCSM.
%% All Rights Reserved.
%%
%% Contributor(s):
%%
%% Andrew Thompson <andrew at hijacked dot us>
%% Micah Warren <micahw at lordnull dot com>
%%
%% @doc Centralized authority on where agent_fsm's are and starting them.
%% Similar in function to the {@link queue_manager}, just oriented towards
%% agents. There can be only one `agent_manager' per node.
-module(agent_manager).
-author(micahw).
-behaviour(gen_leader).
-ifdef(TEST).
-define(STANDARD_TEST, true).
-include_lib("eunit/include/eunit.hrl").
-endif.
-ifdef(PROFILE).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("log.hrl").
-include("call.hrl").
-include("agent.hrl").
-type(agent_pid() :: pid()).
-type(agent_id() :: string()).
-type(time_avail() :: integer()).
-type(channels() :: [channel_category()]).
-type(endpoints() :: [atom()]). % list of media modules.
-type(skills() :: skill_list()).
-type(agent_cache() :: {agent_pid(), agent_id(), time_avail(), skills(),
channels(), endpoints()}).
-type(agent_entry() :: {#agent_key{}, #agent_cache{}}).
%-type(rotations() :: non_neg_integer()).
%-type(all_skill_flag() :: 'a' | 'z'). % a < z, a meaning it has the all flag,
% z lacking. So, the gb tree will sort the a's first.
%-type(skill_list_length() :: non_neg_integer()).
%-type(went_avail_at() :: {pos_integer(), non_neg_integer(), non_neg_integer()}).
%-type(sort_key() :: {rotations(), all_skill_flag(), skill_list_length(), went_avail_at()}).
-record(state, {
agents = dict:new() :: dict(),
route_list = gb_trees:empty() :: gb_tree(),
lists_requested = 0 :: integer()
}).
-type(state() :: #state{}).
-define(GEN_LEADER, true).
-include("gen_spec.hrl").
-define(has_all(Skills), case lists:member('_all', Skills) of true -> a; false -> z end).
% API exports
-export([
start_link/1,
start_link/2,
start/1,
start/2,
stop/0,
start_agent/1,
query_agent/1,
update_skill_list/2,
find_by_skill/1,
find_avail_agents_by_skill/1,
sort_agents_by_elegibility/1,
filtered_route_list/1,
filtered_route_list/3,
find_by_pid/1,
blab/2,
get_leader/0,
list/0,
notify/5,
set_avail/2,
set_ends/2,route_list/0
]).
% gen_leader callbacks
-export([init/1,
elected/3,
surrendered/3,
handle_DOWN/3,
handle_leader_call/4,
handle_leader_cast/3,
from_leader/3,
handle_call/4,
handle_cast/3,
handle_info/2,
terminate/2,
code_change/4]).
%% API
%% @doc Starts the `agent_manger' linked to the calling process.
-spec(start_link/1 :: (Nodes :: [atom()]) -> {'ok', pid()}).
start_link(Nodes) ->
gen_leader:start_link(?MODULE, Nodes, [{heartbeat, 1}, {vardir, util:run_dir()}], ?MODULE, [], []).
-spec(start_link/2 :: (Nodes :: [atom()], Opts :: [any()]) -> {'ok', pid()}).
start_link(Nodes, Opts) ->
gen_leader:start_link(?MODULE, Nodes, [{heartbeat, 1}, {vardir, util:run_dir()}], ?MODULE, Opts, []).
%% @doc Starts the `agent_manager' without linking to the calling process.
-spec(start/1 :: (Nodes :: [atom()]) -> {'ok', pid()}).
start(Nodes) ->
gen_leader:start(?MODULE, Nodes, [{heartbeat, 1}, {vardir, util:run_dir()}], ?MODULE, [], []).
-spec(start/2 :: (Nodes :: [atom()], Opts :: [any()]) -> {'ok', pid()}).
start(Nodes, Opts) ->
gen_leader:start(?MODULE, Nodes, [{heartbeat, 1}, {vardir, util:run_dir()}], ?MODULE, Opts, []).
%% @doc stops the `agent_manager'.
-spec(stop/0 :: () -> {'ok', pid()}).
stop() ->
gen_leader:call(?MODULE, stop).
%% @doc starts a new agent_fsm for `Agent'. Returns `{ok, pid()}', where `Pid' is the new agent_fsm pid.
-spec(start_agent/1 :: (Agent :: #agent{}) -> {'ok', pid()} | {'exists', pid()}).
start_agent(#agent{login = ALogin} = Agent) ->
case query_agent(ALogin) of
false ->
gen_leader:call(?MODULE, {start_agent, Agent}, infinity);
{true, Apid} ->
{exists, Apid}
end.
%% @doc updates the skill-list cached here. 'Tis a case to prevent blockage.
-spec(update_skill_list/2 :: (Login :: string(), Skills :: skills()) -> 'ok').
update_skill_list(Login, Skills) ->
gen_leader:cast(?MODULE, {update_skill_list, Login, Skills}).
%% @doc Locally find all available agents with a particular skillset that contains the subset `Skills'.
-spec(find_avail_agents_by_skill/1 :: (Skills :: [atom()]) -> [{string(), pid(), #agent{}}]).
find_avail_agents_by_skill(Skills) ->
%?DEBUG("skills passed: ~p.", [Skills]),
List = list_avail(),
filter_avail_agents_by_skill(List, Skills).
%% @doc Locally find all available agents with a particular skillset, and
%% makes sure the server knows it's for routing. Depricated in favor of
%% {@link filtered_route_list/3}
-spec(filtered_route_list/1 :: (Skills :: [atom()]) ->
[agent_entry()]).
filtered_route_list(Skills) ->
Agents = route_list(),
filter_avail_agents_by_skill(Agents, Skills).
%% @doc Locally find all available agents with a particular skillset,
%% media channel, and media callback module. Also makes sure the server
%% knows it's for routing.
-spec(filtered_route_list/3 :: (
Skills :: [atom()],
Chan :: atom(),
Endpoint :: atom()) ->
[agent_entry()]).
filtered_route_list(Skills, Chan, Endpoint) ->
Agents = route_list(),
[ O ||
{_K, #agent_cache{skills = AgSkills, channels = AgChans, endpoints = AgEndpoints}} = O <- Agents,
length(AgChans) > 0,
(lists:member('_all', AgSkills) orelse lists:member('_all', Skills) )
orelse
util:list_contains_all(AgSkills, Skills),
lists:member(Chan, AgChans),
lists:member(Endpoint, AgEndpoints)
].
%% @doc Filter the agents based on the skill list and availability.
-spec(filter_avail_agents_by_skill/2 :: (Agents :: [agent_entry()], Skills :: [atom()]) -> [agent_entry()]).
filter_avail_agents_by_skill(Agents, Skills) ->
[O ||
{_K, #agent_cache{skills = AgSkills} = AgCache} = O <- Agents,
length(AgCache#agent_cache.channels) > 0,
( % check if either the call or the agent has the _all skill
lists:member('_all', AgSkills) orelse
lists:member('_all', Skills)
% if there's no _all skill, make sure the agent has all the required skills
) orelse util:list_contains_all(AgSkills, Skills)].
%% @doc Sorted by idle time, then the length of the list of skills the agent has; this means idle time is less important.
%% No un-idle agents should be in the list, otherwise it is fail.
-spec(sort_agents_by_elegibility/1 :: (Agents :: [agent_cache()]) -> [agent_cache()]).
sort_agents_by_elegibility(AvailSkilledAgents) ->
lists:keysort(1, AvailSkilledAgents).
%help_sort(E1, E2) when size(E1) == 4, size(E2) == 4 ->
% help_sort(erlang:append_element(E1, ignored), erlang:append_element(E2, ignored));
%help_sort({_K1, _V1, Time1, Skills1, _}, {_K2, _V2, Time2, Skills2, _}) ->
% case {lists:member('_all', Skills1), lists:member('_all', Skills2)} of
% {true, false} ->
% false;
% {false, true} ->
% true;
% _Else ->
% if
% length(Skills1) == length(Skills2) ->
% Time1 =< Time2;
% true ->
% length(Skills1) =< length(Skills2)
% end
% end.
%% @doc Gets all the agents have have the given `[atom()] Skills'.
% TODO This is wrong, should use agent cache
-spec(find_by_skill/1 :: (Skills :: [atom()]) -> [#agent{}]).
find_by_skill(Skills) ->
[{K, V, Timeavail, AgSkills} ||
{K, {V, _Id, Timeavail, AgSkills, _Chan, _Ends}} <- gen_leader:call(?MODULE, list_agents),
lists:member('_all', AgSkills) orelse util:list_contains_all(AgSkills, Skills)].
%% @doc Gets the login associated with the passed pid().
-spec(find_by_pid/1 :: (Apid :: pid()) -> string() | 'notfound').
find_by_pid(Apid) ->
gen_leader:leader_call(?MODULE, {get_login, Apid}).
%% @doc Get a list of agents at the node this `agent_manager' is running on.
-spec(list/0 :: () -> [agent_entry()]).
list() ->
gen_leader:call(?MODULE, list_agents).
%% @doc List the available agents on this node.
-spec(list_avail/0 :: () -> [agent_entry()]).
list_avail() ->
List = gen_leader:call(?MODULE, list_avail_agents),
[X || {_, #agent_cache{channels = Chans}} = X <- List, length(Chans) > 0].
%% @doc Get a list of agents, tagged for how many requests of this type
%% have been made without the agent list changing in any way. A change is
%% either an agent added, dropped, or skill list change.
-spec(route_list/0 :: () -> [agent_entry()]).
route_list() ->
gen_leader:call(?MODULE, route_list_agents).
%% @doc Check if an agent idetified by agent record or login name string of `Login' exists
-spec(query_agent/1 :: (Agent :: #agent{}) -> {'true', pid()} | 'false';
(Login :: string()) -> {'true', pid()} | 'false').
query_agent(#agent{login=Login}) ->
query_agent(Login);
query_agent(Login) ->
gen_leader:leader_call(?MODULE, {exists, Login}).
%% @doc Notify the agent_manager of a local agent after an agent manager restart.
%% TODO update to take channels and endpoints too
-spec(notify/5 :: (Login :: string(), Id :: string(), Pid :: pid(), TimeAvail :: non_neg_integer(), Skills :: [atom()]) -> 'ok').
notify(Login, Id, Pid, TimeAvail, Skills) ->
case gen_leader:call(?MODULE, {exists, Login}) of
false ->
gen_leader:call(?MODULE, {notify, Login, Id, Pid, TimeAvail, Skills});
{true, Pid} ->
ok;
{true, _OtherPid} ->
erlang:error({duplicate_registration, Login})
end.
%% @doc Returns `{ok, pid()}' where `pid()' is the pid of the leader process.
-spec(get_leader/0 :: () -> {'ok', pid()}).
get_leader() ->
gen_leader:leader_call(?MODULE, get_pid).
%% @doc Send the message `string() Text' to all agents that match the given filter.
-spec(blab/2 :: (Text :: string(), {Key :: 'agent' | 'node' | 'profile', Value :: string() | atom()}) -> 'ok').
blab(Text, all) ->
gen_leader:leader_cast(?MODULE, {blab, Text, all});
blab(Text, {Key, Value}) ->
gen_leader:leader_cast(?MODULE, {blab, Text, {Key, Value}}).
-spec(set_avail/2 :: (AgentLogin :: string(), Channels :: [atom()]) -> 'ok').
set_avail(AgentLogin, Channels) ->
gen_leader:cast(?MODULE, {set_avail, AgentLogin, Channels}).
-spec(set_ends/2 :: (AgentLogin :: string(), Endpoints :: [atom()]) -> 'ok').
set_ends(AgentLogin, Endpoints) ->
gen_leader:cast(?MODULE, {set_ends, AgentLogin, Endpoints}).
%% =================================================================
%% gen_leader callbacks
%% =================================================================
%% @hidden
init(_Opts) ->
?DEBUG("~p starting at ~p", [?MODULE, node()]),
process_flag(trap_exit, true),
try agent_auth:start() of
Whatever ->
?DEBUG("building agent_state table: ~p", [Whatever]),
ok
catch
What:Why ->
?WARNING("What: ~w; Why: ~p", [What, Why]),
ok
end,
{ok, #state{}}.
%% @hidden
elected(State, _Election, Node) ->
?INFO("elected by ~w", [Node]),
mnesia:subscribe(system),
{ok, ok, State}.
%% @hidden
%% if an agent is started at two locations, the 2nd notify will be told that
%% the register failed, allowing the agent to hagurk at that point.
surrendered(#state{agents = Agents} = State, _LeaderState, _Election) ->
?INFO("surrendered", []),
mnesia:unsubscribe(system),
% clean out non-local pids
F = fun(_Login, #agent_cache{pid = Apid}) ->
node() =:= node(Apid)
end,
Locals = dict:filter(F, Agents),
% and tell the leader about local pids
Notify = fun({Login, V}) ->
gen_leader:leader_cast(?MODULE, {update_notify, Login, V})
end,
Dictlist= dict:to_list(Locals),
lists:foreach(Notify, Dictlist),
RoutlistFilter = fun({_Key, #agent_cache{pid = Pid}}) ->
node() =:= node(Pid)
end,
Routelist = gb_trees_filter(RoutlistFilter, State#state.route_list),
{ok, State#state{agents=Locals, route_list = Routelist}}.
%% @hidden
handle_DOWN(Node, #state{agents = Agents} = State, _Election) ->
?INFO("Node ~p died", [Node]),
% clean out the pids associated w/ the dead node
F = fun(_Login, #agent_cache{pid = Apid}) ->
Node =/= node(Apid)
end,
Agents2 = dict:filter(F, Agents),
Routelist = gb_trees_filter(fun({_Key, #agent_cache{pid = Pid}}) ->
Node =/= node(Pid)
end, State#state.route_list),
{ok, State#state{agents = Agents2, route_list = Routelist}}.
%% @hidden
handle_leader_call({exists, Agent}, From, #state{agents = _Agents} = State, Election) when is_list(Agent) ->
?DEBUG("Trying to determine if ~p exists", [Agent]),
case handle_leader_call({full_data, Agent}, From, State, Election) of
{reply, false, _State} = O ->
O;
{reply, #agent_cache{pid = Apid}, NewState} ->
{reply, {true, Apid}, NewState}
end;
handle_leader_call({full_data, Agent}, _From, #state{agents = Agents} = State, _Election) when is_list(Agent) ->
case dict:find(Agent, Agents) of
error ->
%% TODO - a nasty hack for when the agent has a @ sign in their username
case dict:find(re:replace(Agent, "_", "@", [{return, list}]), Agents) of
error ->
{reply, false, State};
{ok, Value} ->
{reply, Value, State}
end;
{ok, Value} ->
{reply, Value, State}
end;
handle_leader_call(get_pid, _From, State, _Election) ->
{reply, {ok, self()}, State};
handle_leader_call({get_login, Apid}, _From, #state{agents = Agents} = State, _Election) when is_pid(Apid) ->
List = dict:to_list(Agents),
Out = find_via_pid(Apid, List),
{reply, Out, State};
handle_leader_call({get_login, Id}, _From, #state{agents = Agents} = State, _Election) ->
List = dict:to_list(Agents),
Out = find_via_id(Id, List),
{reply, Out, State};
handle_leader_call(Message, From, State, _Election) ->
?WARNING("received unexpected leader_call ~p from ~p", [Message, From]),
{reply, ok, State}.
%% @hidden
handle_leader_cast({notify, Agent, AgentCache}, #state{agents = Agents} = State, _Election) ->
?INFO("Notified of ~p (~p)", [Agent, AgentCache]),
Apid = AgentCache#agent_cache.pid,
case dict:find(Agent, Agents) of
error ->
?DEBUG("Adding agent ~p", [Agent]),
Agents2 = dict:store(Agent, AgentCache, Agents),
Routelist = gb_trees:enter(#agent_key{
rotations = 0,
has_all = ?has_all(AgentCache#agent_cache.skills),
skill_count = length(AgentCache#agent_cache.skills),
idle_time = AgentCache#agent_cache.time_avail},
AgentCache, State#state.route_list),
{noreply, State#state{agents = Agents2, route_list = Routelist}};
{ok, #agent_cache{pid = Apid}} ->
?DEBUG("Agent ~p already know", [Agent]),
{noreply, State};
_Else ->
?DEBUG("agent pid mismatch, telling imposter", []),
agent:register_rejected(AgentCache#agent_cache.pid),
{noreply, State}
end;
handle_leader_cast({update_notify, Login, #agent_cache{pid = Pid} = Value}, #state{agents = Agents} = State, _Election) ->
NewAgents = dict:update(Login, fun(_Old) -> Value end, Value, Agents),
Midroutelist = gb_trees_filter(fun({_Key, #agent_cache{pid = Apid}}) ->
Apid =/= Pid
end, State#state.route_list),
Skills = Value#agent_cache.skills,
Time = Value#agent_cache.time_avail,
Routelist = gb_trees:enter(#agent_key{ rotations = 0,
has_all = ?has_all(Skills), skill_count = length(Skills),
idle_time = Time}, Value, Midroutelist),
{noreply, State#state{agents = NewAgents, route_list = Routelist}};
handle_leader_cast({notify_down, Agent}, #state{agents = Agents} = State, _Election) ->
?NOTICE("leader notified of ~p exiting", [Agent]),
Routelist = case dict:find(Agent, Agents) of
error ->
State#state.route_list;
{ok, #agent_cache{pid = Pid}} ->
gb_trees_filter(fun({_Key, #agent_cache{pid = Apid}}) ->
Apid =/= Pid
end, State#state.route_list)
end,
{noreply, State#state{agents = dict:erase(Agent, Agents), route_list = Routelist}};
handle_leader_cast({blab, Text, {agent, Value}}, #state{agents = Agents} = State, _Election) ->
case dict:find(Value, Agents) of
error ->
% /shrug. Meh.
{noreply, State};
{ok, #agent_cache{pid = Apid}} ->
agent:blab(Apid, Text),
{noreply, State}
end;
handle_leader_cast({blab, Text, {node, Value}}, #state{agents = Agents} = State, _Election) ->
Alist = dict:to_list(Agents),
F = fun({_Aname, #agent_cache{pid = Apid}}) ->
case node(Apid) of
Value ->
agent:blab(Apid, Text);
_Else -> ok
end
end,
spawn(fun() -> lists:foreach(F, Alist) end),
{noreply, State};
handle_leader_cast({blab, Text, {profile, Value}}, #state{agents = Agents} = State, _Election) ->
Alist = dict:to_list(Agents),
Foreach = fun({_Aname, #agent_cache{pid = Apid}}) ->
try agent:dump_state(Apid) of
#agent{profile = Value} ->
agent:blab(Apid, Text);
_Else ->
ok
catch
What:Why ->
?WARNING("could not blab to ~p. ~p:~p", [Apid, What, Why]),
ok
end
end,
F = fun() ->
lists:foreach(Foreach, Alist)
end,
spawn(F),
{noreply, State};
handle_leader_cast({blab, Text, all}, #state{agents = Agents} = State, _Election) ->
F = fun(_, #agent_cache{pid = Pid}) ->
agent:blab(Pid, Text)
end,
spawn(fun() -> dict:map(F, Agents) end),
{noreply, State};
handle_leader_cast(dump_election, State, Election) ->
?DEBUG("Dumping leader election.~nSelf: ~p~nDump: ~p", [self(), Election]),
{noreply, State};
handle_leader_cast(Message, State, _Election) ->
?WARNING("received unexpected leader_cast ~p", [Message]),
{noreply, State}.
%% @hidden
from_leader(_Msg, State, _Election) ->
?DEBUG("Stub from leader.", []),
{ok, State}.
%% @hidden
handle_call(list_agents, _From, #state{agents = Agents} = State, _Election) ->
{reply, dict:to_list(Agents), State};
handle_call(list_avail_agents, _From, State, _Election) ->
{reply, gb_trees:to_list(State#state.route_list), State};
handle_call(route_list_agents, _From, #state{agents = _Agents, lists_requested = Count, route_list = Routelist} = State, _Election) ->
List = gb_trees:to_list(Routelist),
NewRoutelist = case gb_trees:is_empty(Routelist) of
true ->
Routelist;
false ->
{#agent_key{rotations = OldCount} = Key, Val, Midroutelist} =
gb_trees:take_smallest(Routelist),
gb_trees:enter(Key#agent_key{rotations = OldCount + 1}, Val, Midroutelist)
end,
{reply, List, State#state{lists_requested = Count + 1, route_list = NewRoutelist}};
handle_call(stop, _From, State, _Election) ->
{stop, normal, ok, State};
handle_call({start_agent, #agent{login = ALogin, id=Aid} = InAgent}, _From, #state{agents = Agents} = State, Election) ->
% This should not be called directly! use the wrapper start_agent/1
Agent = InAgent#agent{release_data = ?DEFAULT_RELEASE},
?INFO("Starting new agent ~p", [Agent]),
{ok, Apid} = agent:start(Agent, [logging, gen_leader:candidates(Election)]),
link(Apid),
Value = #agent_cache{
pid = Apid,
id = Aid,
time_avail = os:timestamp(),
skills = Agent#agent.skills,
channels = [],
endpoints = dict:fetch_keys(Agent#agent.endpoints)
},
Leader = gen_leader:leader_node(Election),
case node() of
Leader ->
ok;
_ ->
gen_leader:leader_cast(?MODULE, {update_notify, ALogin, Value})
end,
Agents2 = dict:store(ALogin, Value, Agents),
dispatch_manager:end_avail(Apid),
Key = #agent_key{
has_all = ?has_all(Agent#agent.skills),
skill_count = length(Agent#agent.skills),
idle_time = os:timestamp()
},
RouteList = gb_trees:enter(Key, Value, State#state.route_list),
{reply, {ok, Apid}, State#state{agents = Agents2, route_list = RouteList}};
handle_call({exists, Login}, _From, #state{agents = Agents} = State, Election) ->
Leader = gen_leader:leader_node(Election),
case dict:find(Login, Agents) of
error when Leader =/= node() ->
case gen_leader:leader_call(?MODULE, {full_data, Login}) of
false ->
{reply, false, State};
#agent_cache{pid = Pid} = V when node(Pid) =:= node() ->
% leader knows about a local agent, but we didn't!
% So we update the local dict
Agents2 = dict:store(Login, V, Agents),
{reply, {true, Pid}, State#state{agents = Agents2}};
#agent_cache{pid = OtherPid} ->
{reply, {true, OtherPid}, State}
end;
error -> % we're the leader
{reply, false, State};
{ok, #agent_cache{pid = Pid}} ->
{reply, {true, Pid}, State}
end;
handle_call({notify, Login, #agent_cache{pid = Pid} = AgentCache}, _From, #state{agents = Agents} = State, Election) when is_pid(Pid) andalso node(Pid) =:= node() ->
case dict:find(Login, Agents) of
error ->
link(Pid),
case gen_leader:leader_node(Election) =:= node() of
false ->
gen_leader:leader_cast(?MODULE, {notify, Login, AgentCache});
_Else ->
ok
end,
Agents2 = dict:store(Login, AgentCache, Agents),
#agent_cache{skills = Skills, time_avail = TimeAvail} = AgentCache,
Midroutelist = gb_trees:enter(#agent_key{rotations = 0,
has_all = ?has_all(Skills), skill_count = length(Skills),
idle_time = TimeAvail}, AgentCache, State#state.route_list),
{reply, ok, State#state{agents = Agents2, lists_requested = 0, route_list = clear_rotates(Midroutelist)}};
{ok, {Pid, _Id}} ->
{reply, ok, State};
{ok, _OtherPid} ->
% TODO - wait, so we get notified about an agent, we have a record of the an agent with that login already,
% and we just say 'ok'?
{reply, ok, State}
end;
handle_call(Message, From, State, _Election) ->
?WARNING("received unexpected call ~p from ~p", [Message, From]),
{reply, ok, State}.
%% @hidden
handle_cast({set_avail, Nom, Chans}, #state{agents = Agents} = State, Election) ->
Node = node(),
#agent_cache{pid = Pid} = AgentCache = dict:fetch(Nom, Agents),
Midroutelist = gb_trees_filter(fun({_Key, #agent_cache{pid = Apid}}) ->
Apid =/= Pid
end, State#state.route_list),
%% If the new channel list is shorter, they likely went on call
%% if so, we can consider the 'time they have been idle' as how long
%% it's been since they took a call.
% TODO This can be gamed by agents by bouncing idle and released
Time = case length(AgentCache#agent_cache.channels) > length(Chans) of
true -> os:timestamp();
false -> AgentCache#agent_cache.time_avail
end,
#agent_cache{skills = Skills} = Out = AgentCache#agent_cache{time_avail = Time, channels = Chans},
Key = #agent_key{
rotations = 0,
has_all = ?has_all(Skills),
skill_count = length(Skills),
idle_time = Time
},
Routelist = gb_trees:enter(Key, Out, Midroutelist),
F = fun(_) ->
case gen_leader:leader_node(Election) of
Node ->
ok;
_ ->
gen_leader:leader_cast(?MODULE, {update_notify, Nom, Out})
end,
Out
end,
NewAgents = dict:update(Nom, F, Agents),
%?INFO("Updated key ~p to ~p", [Key, Out]),
%?DEBUG("rl: ~p", [Routelist]),
{noreply, State#state{agents = NewAgents, lists_requested = 0, route_list = clear_rotates(Routelist)}};
handle_cast({set_ends, Nom, Ends}, #state{agents = Agents} = State, Election) ->
Node = node(),
#agent_cache{ pid = Pid, id = Id, time_avail = Time, skills = Skills,
channels = Chans} = dict:fetch(Nom, Agents),
Midroutelist = gb_trees_filter(fun({_Key, #agent_cache{pid = Apid}}) ->
Apid =/= Pid
end, State#state.route_list),
Out = #agent_cache{pid = Pid, id = Id, time_avail = Time,
skills = Skills, channels = Chans, endpoints = Ends},
Routelist = gb_trees:enter(#agent_key{ rotations = 0,
has_all = ?has_all(Skills), skill_count = length(Skills),
idle_time = Time}, Out, Midroutelist),
F = fun(_) ->
case gen_leader:leader_node(Election) of
Node ->
ok;
_ ->
gen_leader:leader_cast(?MODULE, {update_notify, Nom, Out})
end,
Out
end,
NewAgents = dict:update(Nom, F, Agents),
{noreply, State#state{agents = NewAgents, lists_requested = 0, route_list = clear_rotates(Routelist)}};
%handle_cast({end_avail, Nom}, #state{agents = Agents} = State, Election) ->
% Node = node(),
% {Pid, Id, _, Skills} = dict:fetch(Nom, Agents),
% Routelist = gb_trees_filter(fun({_, {Apid, _, _}}) ->
% Apid =/= Pid
% end, State#state.route_list),
% NewAgents = dict:store(Nom, {Pid, Id, 0, Skills}, Agents),
% case gen_leader:leader_node(Election) of
% Node ->
% ok;
% _ ->
% gen_leader:leader_cast(?MODULE, {update_notify, Nom, {Pid, Id, 0, Skills}})
% end,
% {noreply, State#state{agents = NewAgents, lists_requested = 0, route_list = Routelist}};
handle_cast({update_skill_list, Login, Skills}, #state{agents = Agents} = State, Election) ->
Node = node(),
#agent_cache{pid = Pid, time_avail = Time} = AgentCache = dict:fetch(Login, Agents),
Out = AgentCache#agent_cache{skills = Skills},
Midroutelist = clear_rotates(gb_trees_filter(fun({_, #agent_cache{pid = Apid}}) ->
Apid =/= Pid
end, State#state.route_list)),
Routelist = gb_trees:enter(#agent_key{ rotations = 0,
has_all = ?has_all(Skills), skill_count = length(Skills),
idle_time = Time}, Out, Midroutelist),
F = fun(_) ->
case gen_leader:leader_node(Election) of
Node ->
ok;
_ ->
gen_leader:leader_cast(?MODULE, {update_notify, Login, Out})
end,
Out
end,
NewAgents = dict:update(Login, F, Agents),
{noreply, State#state{agents = NewAgents, lists_requested = 0, route_list = Routelist}};
handle_cast(_Request, State, _Election) ->
?DEBUG("Stub handle_cast", []),
{noreply, State}.
%% @hidden
handle_info({'EXIT', Pid, Reason}, #state{agents=Agents} = State) ->
?NOTICE("Caught exit for ~p with reason ~p", [Pid, Reason]),
F = fun(Key, #agent_cache{ pid = Value, id = Id}) ->
case Value =/= Pid of
true -> true;
false ->
?NOTICE("notifying leader of ~p exit", [{Key, Id}]),
cpx_monitor:drop({agent, Id}),
gen_leader:leader_cast(?MODULE, {notify_down, Key}),
false
end
end,
Routelist = clear_rotates(gb_trees_filter(fun({_, #agent_cache{pid = Apid}}) ->
Apid =/= Pid
end, State#state.route_list)),
{noreply, State#state{agents=dict:filter(F, Agents), lists_requested = 0, route_list = Routelist}};
handle_info({mnesia_system_event, {mnesia_down, Node}}, State) ->
?WARNING("mnesia down at ~w", [Node]),
{noreply, State};
handle_info(Msg, State) ->
?DEBUG("Stub handle_info for ~p", [Msg]),
{noreply, State}.
%% @hidden
terminate(Reason, _State) ->
?NOTICE("Terminating: ~p", [Reason]),
ok.
%% @hidden
code_change(_OldVsn, State, _Election, _Extra) ->
{ok, State}.
%% @private
find_via_pid(_Needle, []) ->
notfound;
find_via_pid(Needle, [{Key, #agent_cache{pid = Needle}} | _Tail]) ->
Key;
find_via_pid(Needle, [{_Key, _NotNeedle} | Tail]) ->
find_via_pid(Needle, Tail).
%% @private
find_via_id(_Needle, []) ->
notfound;
find_via_id(Needle, [{Key, #agent_cache{id = Needle}} | _Tail]) ->
Key;
find_via_id(Needle, [_Head | Tail]) ->
find_via_id(Needle, Tail).
%% @doc returns a new tree which contians only entrys where Fun({Key, Val}) = true.
gb_trees_filter(Fun, Tree) ->
Itor = gb_trees:iterator(Tree),
gb_trees_filter(Fun, gb_trees:next(Itor), Tree).
gb_trees_filter(_Fun, none, Tree) ->
Tree;
gb_trees_filter(Fun, {Key, Val, Itor}, Tree) ->
case Fun({Key, Val}) of
true ->
gb_trees_filter(Fun, gb_trees:next(Itor), Tree);
false ->
Newtree = gb_trees:delete_any(Key, Tree),
gb_trees_filter(Fun, gb_trees:next(Itor), Newtree)
end.
clear_rotates({#agent_key{rotations = 0} = Key, Val, Tree}) ->
gb_trees:enter(Key, Val, Tree);
clear_rotates({Key, Val, Tree}) ->
Newtree = gb_trees:enter(Key#agent_key{rotations = 0}, Val, Tree),
clear_rotates(gb_trees:take_largest(Newtree));
clear_rotates(Tree) ->
case gb_trees:is_empty(Tree) of
true ->
Tree;
false ->
clear_rotates(gb_trees:take_largest(Tree))
end.
-ifdef(STANDARD_TEST).
ds() ->
spawn(fun() -> ok end).
filter_avail_agents_by_skill_test_() ->
[{"one in, one out",
fun() ->
Agents = [{{agent_key, 0, z, 1, {100, 100, 100}}, {agent_cache, ds(), "agent", 0, [skill], [dummy], []}}],
?assertEqual(Agents, filter_avail_agents_by_skill(Agents, [skill]))
end},
{"two in, one out",
fun() ->
[Out | _] = Agents = [
{{agent_key, 0, z, 1, {100, 100, 100}}, {agent_cache, ds(), "agent1", 0, [skill], [voice], []}},
{{agent_key, 0, z, 0, {100, 100, 100}}, {agent_cache, ds(), "agent2", 0, [], [voice], []}}
],
?assertEqual([Out], filter_avail_agents_by_skill(Agents, [skill]))
end},
{"agent with all gets in",
fun() ->
Agents = [{{agent_key, 0, z, 1, {100, 100, 100}}, {agent_cache, ds(), "agent", 0, ['_all'], [dummy], []}}],
?assertEqual(Agents, filter_avail_agents_by_skill(Agents, [skill]))
end},
{"agents get through when all passed in",
fun() ->
Agents = [
{{agent_key, 0, z, 1, {100, 100, 100}}, {agent_cache, ds(), "agent1", 0, [skill], [dummy], []}},
{{agent_key, 0, z, 0, {100, 100, 100}}, {agent_cache, ds(), "agent2", 0, [], [dummy], []}}
],
?assertEqual(Agents, filter_avail_agents_by_skill(Agents, ['_all']))
end}].
-record(election, {
leader = none,
name,
leadernode = none,
candidate_nodes = [],
worker_nodes = [],
alive = [],
down = [],
monitored = [],
buffered = [],
status,
elid,
acks = [],
work_down = [],
cand_timer_int,
cand_timer,
pendack,
incarn,
nextel,
bcast_type %% all | one. When `all' each election event
%% will be broadcast to all candidate nodes.
}).
handle_cast_test_() ->
{setup,
fun() ->
Election = #election{
leader = node(),
leadernode = node()
},
State = #state{},
{State, Election}
end,
fun(_) ->
ok
end,
fun({Seedstate, Election}) ->
[{"basic now availalble",
fun() ->
Agents = dict:from_list([{"agent", {agent_cache, ds(), "agent", 0, [], [], []}}]),
State = #state{agents = Agents},
{noreply, Newstate} = handle_cast({set_avail, "agent", [voice]}, State, Election),
?assertNot(gb_trees:is_empty(Newstate#state.route_list)),
?assertMatch([{{agent_key, 0, z, 0, _}, {agent_cache, _, "agent", _, [], [voice], []}}], gb_trees:to_list(Newstate#state.route_list))
end},
{"basic end avail",
fun() ->
Time = os:timestamp(),
Pid = ds(),
Agents = dict:from_list([{"agent", {agent_cache, Pid, "agent", Time, [], [voice], []}}]),
Routelist = gb_trees:enter({agent_key, 0, z, 0, Time}, {agent_cache, Pid, "agent", Time, [], [voice], []}, gb_trees:empty()),
State = Seedstate#state{agents = Agents, route_list = Routelist},
{noreply, Newstate} = handle_cast({set_avail, "agent", []}, State, Election),
?assertMatch([{{agent_key, 0, z, 0, _}, {agent_cache, _, "agent", _, [], [], []}}], gb_trees:to_list(Newstate#state.route_list))
end},
{"updatin' a skill list of an idle agent",
fun() ->
Pid = ds(),
Time = os:timestamp(),
Agents = dict:from_list([{"agent", {agent_cache, Pid, "agent", Time, [], [dummy], [dummy]}}]),
Routelist = gb_trees:enter({agent_key, 0, z, 0, Time}, {agent_cache, Pid, "agent", Time, [], [dummy], [dummy]}, gb_trees:empty()),
State = #state{agents = Agents, route_list = Routelist},
{noreply, NewState} = handle_cast({update_skill_list, "agent", [skill]}, State, Election),
?assertNot(gb_trees:is_empty(NewState#state.route_list)),
?assertMatch([{{agent_key, 0, z, 1, _}, {agent_cache, Pid, "agent", _, [skill], [dummy], [dummy]}}], gb_trees:to_list(NewState#state.route_list))
end}]
end}.
external_api_test_() ->
{setup, fun() ->
meck:new(gen_leader)
end,
fun(_) ->
meck:validate(gen_leader),
meck:unload(gen_leader)
end,
fun(_) -> [
{"start_link/1", fun() ->
meck:expect(gen_leader, start_link, fun(?MODULE, [Node], [{heartbeat, 1}, {vardir, _RunDir}], ?MODULE, [], []) ->
?assertEqual(node(), Node),
{ok, util:zombie()}
end),
?assertMatch({ok, _Pid}, start_link([node()]))
end},
{"start_link/2", fun() ->
meck:expect(gen_leader, start_link, fun(?MODULE, [Node], [{heartbeat, 1}, {vardir, _Rundir}], ?MODULE, opts, []) ->
?assertEqual(node(), Node),
{ok, util:zombie()}
end),
?assertMatch({ok, _Pid}, start_link([node()], opts))
end},
{"start/1", fun() ->
meck:expect(gen_leader, start, fun(?MODULE, [Node], [{heartbeat, 1}, {vardir, _Rundir}], ?MODULE, [], []) ->
?assertEqual(node(), Node),
{ok, util:zombie()}
end),
?assertMatch({ok, _Pid}, start([node()]))
end},
{"start/2", fun() ->
meck:expect(gen_leader, start, fun(?MODULE, [Node], [{heartbeat, 1}, {vardir, _Rundir}], ?MODULE, opts, []) ->
?assertEqual(node(), Node),
{ok, util:zombie()}
end),
?assertMatch({ok, _Pid}, start([node()], opts))
end},
{"stop/0", fun() ->
meck:expect(gen_leader, call, fun(?MODULE, stop) ->
ok
end),
?assertEqual(ok, stop())
end},
{"start_agent/1, agent exists", fun() ->
meck:expect(gen_leader, leader_call, fun(?MODULE, {exists, "testagent"}) ->
{true, util:zombie()}
end),
Agent = #agent{login = "testagent"},
?assertMatch({exists, _Pid}, start_agent(Agent))
end},
{"start_agent/1, agent doesn't exist", fun() ->
Agent = #agent{login = "testagent"},
meck:expect(gen_leader, leader_call, fun(?MODULE, {exists, "testagent"}) ->
false
end),
meck:expect(gen_leader, call, fun(?MODULE, {start_agent, InAgent}, infinity) ->
?assertEqual(Agent, InAgent),
{'ok', util:zombie()}
end),
?assertMatch({ok, _Pid}, start_agent(Agent))
end},
{"query_agent/1, given record", fun() ->
meck:expect(gen_leader, leader_call, fun(?MODULE, {exists, "testagent"}) ->
ok
end),
Agent = #agent{login = "testagent"},
?assertEqual(ok, query_agent(Agent))
end},
{"query_agent/1, given login", fun() ->
meck:expect(gen_leader, leader_call, fun(?MODULE, {exists, "testagent"}) ->
ok
end),
?assertEqual(ok, query_agent("testagent"))
end},
{"update_skill_list/2", fun() ->
meck:expect(gen_leader, cast, fun(?MODULE, {update_skill_list, "testagent", [english, awesome]}) ->
ok
end),
?assertEqual(ok, update_skill_list("testagent", [english, awesome]))
end},
{"find_avail_agents_by_skill/1, 'english' skill given", fun() ->
AgentCaches = [
{"key1", #agent_cache{channels = [voice], skills = [], id = "skip1"}},
{"key2", #agent_cache{channels = [], skills = [english], id = "skip2"}},
{"key3", #agent_cache{time_avail = 1, channels = [voice], skills = [english], id = "gotit1"}},
{"key4", #agent_cache{time_avail = 1, channels = [voice], skills = ['_all'], id = "gotit2"}}
],
meck:expect(gen_leader, call, fun(?MODULE, list_avail_agents) ->
AgentCaches
end),
Expected = [
{"key3", #agent_cache{time_avail = 1, channels = [voice], skills = [english], id = "gotit1"}},
{"key4", #agent_cache{time_avail = 1, channels = [voice], skills = ['_all'], id = "gotit2"}}
],
?assertEqual(Expected, find_avail_agents_by_skill([english]))
end},
{"find_avail_agents_by_skill/1, '_all' skill given", fun() ->
AgentCaches = [
{"key1", #agent_cache{time_avail = 1, channels = [voice], skills = [], id = "skip1"}},
{"key2", #agent_cache{time_avail = 1, channels = [], skills = [english], id = "skip2"}},
{"key3", #agent_cache{time_avail = 1, channels = [voice], skills = [english], id = "gotit1"}},
{"key4", #agent_cache{time_avail = 1, channels = [voice], skills = ['_all'], id = "gotit2"}}
],
meck:expect(gen_leader, call, fun(?MODULE, list_avail_agents) ->
AgentCaches
end),
Expected = [
{"key1", #agent_cache{time_avail = 1, channels = [voice], skills = [], id = "skip1"}},
{"key3", #agent_cache{time_avail = 1, channels = [voice], skills = [english], id = "gotit1"}},
{"key4", #agent_cache{time_avail = 1, channels = [voice], skills = ['_all'], id = "gotit2"}}
],
?assertEqual(Expected, find_avail_agents_by_skill(['_all']))
end},