1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 2003-2020. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20
21%%----------------------------------------------------------------------
22%% Purpose:
23%%
24%% Test:    ts:run(snmp, snmp_manager_SUITE, [batch]).
25%% Test:    ts:run(snmp, snmp_manager_SUITE, event_tests, [batch]).
26%% Test:    ts:run(snmp, snmp_manager_SUITE, inform_swarm, [batch]).
27%%
28%%----------------------------------------------------------------------
29-module(snmp_manager_SUITE).
30
31%%----------------------------------------------------------------------
32%% Include files
33%%----------------------------------------------------------------------
34
35-include_lib("common_test/include/ct.hrl").
36-include("snmp_test_lib.hrl").
37-include("snmp_test_data/Test2.hrl").
38
39-include_lib("snmp/include/snmp_types.hrl").
40-include_lib("snmp/include/STANDARD-MIB.hrl").
41-include_lib("snmp/src/manager/snmpm_internal.hrl").
42
43
44%%----------------------------------------------------------------------
45%% External exports
46%%----------------------------------------------------------------------
47-export([
48         suite/0, all/0, groups/0,
49	 init_per_suite/1,    end_per_suite/1,
50	 init_per_group/2,    end_per_group/2,
51	 init_per_testcase/2, end_per_testcase/2,
52
53
54	 simple_start_and_stop1/1,
55	 simple_start_and_stop2/1,
56	 simple_start_and_stop3/1,
57	 simple_start_and_monitor_crash1/1,
58	 simple_start_and_monitor_crash2/1,
59	 notify_started01/1,
60	 notify_started02/1,
61
62	 register_user1/1,
63
64	 register_agent_old/1,
65	 register_agent2/1,
66	 register_agent3/1,
67
68	 info/1,
69         usm_priv_aes/1,
70
71	 simple_sync_get2/1,
72	 simple_sync_get3/1,
73	 simple_async_get2/1,
74	 simple_async_get3/1,
75
76  	 simple_sync_get_next2/1,
77  	 simple_sync_get_next3/1,
78  	 simple_async_get_next2/1,
79         simple_async_get_next3_cbp_def/1,
80         simple_async_get_next3_cbp_temp/1,
81         simple_async_get_next3_cbp_perm/1,
82
83	 simple_sync_set2/1,
84	 simple_sync_set3/1,
85	 simple_async_set2/1,
86         simple_async_set3_cbp_def/1,
87         simple_async_set3_cbp_temp/1,
88         simple_async_set3_cbp_perm/1,
89
90  	 simple_sync_get_bulk2/1,
91  	 simple_sync_get_bulk3/1,
92  	 simple_async_get_bulk2/1,
93         simple_async_get_bulk3_cbp_def/1,
94         simple_async_get_bulk3_cbp_temp/1,
95         simple_async_get_bulk3_cbp_perm/1,
96
97  	 misc_async2/1,
98
99	 discovery/1,
100
101	 trap1/1,
102	 trap2/1,
103
104	 inform1/1,
105	 inform2/1,
106	 inform3/1,
107	 inform4/1,
108	 inform_swarm_cbp_def/1,
109         inform_swarm_cbp_temp/1,
110         inform_swarm_cbp_perm/1,
111
112	 report/1,
113
114	 otp8015_1/1,
115
116	 otp8395_1/1
117
118	]).
119
120
121%%----------------------------------------------------------------------
122%% Internal exports
123%%----------------------------------------------------------------------
124
125%% -export([async_exec/2]).
126
127
128%%----------------------------------------------------------------------
129%% Macros and constants
130%%----------------------------------------------------------------------
131
132-define(AGENT_PORT,       4000).
133-define(AGENT_MMS,        1024).
134-define(AGENT_ENGINE_ID,  "agentEngine").
135
136-define(MGR_PORT,       5000).
137-define(MGR_MMS,        1024).
138-define(MGR_ENGINE_ID,  "mgrEngine").
139
140-define(NS_TIMEOUT,     10000).
141
142-define(DEFAULT_MNESIA_DEBUG, none).
143
144
145%%----------------------------------------------------------------------
146%% Records
147%%----------------------------------------------------------------------
148
149%%======================================================================
150%% Common Test interface functions
151%%======================================================================
152
153suite() ->
154    [{ct_hooks, [ts_install_cth]}].
155
156
157all() ->
158    [
159     {group, start_and_stop_tests},
160     {group, misc_tests},
161     {group, user_tests},
162     {group, agent_tests},
163     {group, request_tests},
164     {group, request_tests_mt},
165     {group, event_tests},
166     {group, event_tests_mt},
167     discovery,
168     {group, tickets},
169     {group, ipv6},
170     {group, ipv6_mt}
171    ].
172
173groups() ->
174    [
175     {start_and_stop_tests, [],
176      [
177       simple_start_and_stop1,
178       simple_start_and_stop2,
179       simple_start_and_stop3,
180       simple_start_and_monitor_crash1,
181       simple_start_and_monitor_crash2,
182       notify_started01,
183       notify_started02
184      ]
185     },
186     {misc_tests, [],
187      [
188       info,
189       usm_priv_aes
190      ]
191     },
192     {user_tests, [],
193      [
194       register_user1
195      ]
196     },
197     {agent_tests, [],
198      [
199       register_agent_old,
200       register_agent2,
201       register_agent3
202      ]
203     },
204     {request_tests, [],
205      [
206       {group, get_tests},
207       {group, get_next_tests},
208       {group, set_tests},
209       {group, bulk_tests},
210       {group, misc_request_tests}
211      ]
212     },
213     {request_tests_mt, [],
214      [
215       {group, get_tests},
216       {group, get_next_tests},
217       {group, set_tests},
218       {group, bulk_tests},
219       {group, misc_request_tests}
220      ]
221     },
222     {get_tests, [],
223      [
224       simple_sync_get2,
225       simple_sync_get3,
226       simple_async_get2,
227       simple_async_get3
228      ]
229     },
230     {get_next_tests, [],
231      [
232       simple_sync_get_next2,
233       simple_sync_get_next3,
234       simple_async_get_next2,
235       simple_async_get_next3_cbp_def,
236       simple_async_get_next3_cbp_temp,
237       simple_async_get_next3_cbp_perm
238      ]
239     },
240     {set_tests, [],
241      [
242       simple_sync_set2,
243       simple_sync_set3,
244       simple_async_set2,
245       simple_async_set3_cbp_def,
246       simple_async_set3_cbp_temp,
247       simple_async_set3_cbp_perm
248      ]
249     },
250     {bulk_tests, [],
251      [
252       simple_sync_get_bulk2,
253       simple_sync_get_bulk3,
254       simple_async_get_bulk2,
255       simple_async_get_bulk3_cbp_def,
256       simple_async_get_bulk3_cbp_temp,
257       simple_async_get_bulk3_cbp_perm
258      ]
259     },
260     {misc_request_tests, [],
261      [
262       misc_async2
263      ]
264     },
265     {event_tests, [],
266      [
267       trap1,
268       trap2,
269       inform1,
270       inform2,
271       inform3,
272       inform4,
273       inform_swarm_cbp_def,
274       inform_swarm_cbp_temp,
275       inform_swarm_cbp_perm,
276       report
277      ]
278     },
279     {event_tests_mt, [],
280      [
281       trap1,
282       trap2,
283       inform1,
284       inform2,
285       inform3,
286       inform4,
287       inform_swarm_cbp_def,
288       inform_swarm_cbp_temp,
289       inform_swarm_cbp_perm,
290       report
291      ]
292     },
293     {tickets, [],
294      [
295       {group, otp8015},
296       {group, otp8395}
297      ]
298     },
299     {otp8015, [],
300      [
301       otp8015_1
302      ]
303     },
304     {otp8395, [],
305      [
306       otp8395_1
307      ]
308     },
309     {ipv6, [], ipv6_tests()},
310     {ipv6_mt, [], ipv6_tests()}
311
312    ].
313
314ipv6_tests() ->
315    [
316     register_agent_old,
317     simple_sync_get_next3,
318     simple_async_get2,
319     simple_sync_get3,
320     simple_async_get_next2,
321     simple_sync_set3,
322     simple_async_set2,
323     simple_sync_get_bulk2,
324     simple_async_get_bulk3_cbp_def,
325     simple_async_get_bulk3_cbp_temp,
326     simple_async_get_bulk3_cbp_perm,
327     misc_async2,
328     inform1,
329     inform_swarm_cbp_def,
330     inform_swarm_cbp_temp,
331     inform_swarm_cbp_perm
332    ].
333
334
335
336%%
337%% -----
338%%
339
340init_per_suite(Config0) when is_list(Config0) ->
341
342    ?IPRINT("init_per_suite -> entry with"
343            "~n      Config0: ~p", [Config0]),
344
345    case ?LIB:init_per_suite(Config0) of
346        {skip, _} = SKIP ->
347            SKIP;
348
349        Config1 ->
350
351            ?IPRINT("init_per_suite -> common init done"
352                    "~n      Config1: ~p", [Config1]),
353
354            %% Preferably this test SUITE should be divided into groups
355            %% so that if crypto does not work only v3 tests that
356            %% need crypto will be skipped, but as this is only a
357            %% problem with one legacy test machine, we will procrastinate
358            %% until we have a more important reason to fix this.
359            case ?LIB:crypto_start() of
360                ok ->
361                    %% We need one on this node also
362                    snmp_test_sys_monitor:start(),
363
364                    Config2   = ?LIB:init_suite_top_dir(?MODULE, Config1),
365                    Config3   = ?LIB:fix_data_dir(Config2),
366                    %% Mib-dirs
367                    %% data_dir is trashed by the test-server / common-test
368                    %% so there is no point in fixing it...
369                    MibDir    = ?LIB:lookup(data_dir, Config3),
370                    StdMibDir = filename:join([code:priv_dir(snmp), "mibs"]),
371                    [{mib_dir, MibDir}, {std_mib_dir, StdMibDir} | Config3];
372
373                _ ->
374                    {skip, "Crypto did not start"}
375            end
376    end.
377
378end_per_suite(Config0) when is_list(Config0) ->
379
380    ?IPRINT("end_per_suite -> entry with"
381            "~n      Config0: ~p"
382            "~n      Nodes:  ~p", [Config0, erlang:nodes()]),
383
384    snmp_test_sys_monitor:stop(),
385    Config1 = ?LIB:end_per_suite(Config0),
386
387    ?IPRINT("end_per_suite -> end when"
388            "~n      Nodes:  ~p", [erlang:nodes()]),
389    Config1.
390
391
392%%
393%% -----
394%%
395
396init_per_group(request_tests_mt = GroupName, Config) ->
397    ?LIB:init_group_top_dir(
398      GroupName,
399      [{manager_net_if_module, snmpm_net_if_mt} | Config]);
400init_per_group(event_tests_mt = GroupName, Config) ->
401    ?LIB:init_group_top_dir(
402      GroupName,
403      [{manager_net_if_module, snmpm_net_if_mt} | Config]);
404init_per_group(ipv6_mt = GroupName, Config) ->
405    init_per_group_ipv6(GroupName,
406                        [{manager_net_if_module, snmpm_net_if_mt} | Config]);
407init_per_group(ipv6 = GroupName, Config) ->
408    init_per_group_ipv6(GroupName, Config);
409init_per_group(GroupName, Config) ->
410    ?LIB:init_group_top_dir(GroupName, Config).
411
412
413init_per_group_ipv6(GroupName, Config) ->
414    %% <OS-CONDITIONAL-SKIP>
415    OSSkipable = [{unix,
416                   [
417                    {darwin, fun(V) when (V > {9, 8, 0}) ->
418				     %% This version is OK: No Skip
419				     false;
420				(_) ->
421				     %% This version is *not* ok: Skip
422                                     %% We need a fully qualified hostname
423                                     %% to get a proper IPv6 address (in this
424                                     %% version), but its just to messy, so
425                                     %% instead we skip this **OLD** darwin...
426				     true
427                             end}
428                   ]
429                  }],
430    %% </OS-CONDITIONAL-SKIP>
431    case ?OS_BASED_SKIP(OSSkipable) of
432        true ->
433            {skip, "Host *may* not *properly* support IPV6"};
434        false ->
435            %% Even if this host supports IPv6 we don't use it unless its
436            %% one of the configures/supported IPv6 hosts...
437            case ?HAS_SUPPORT_IPV6() of
438                true ->
439                    ipv6_init(?LIB:init_group_top_dir(GroupName, Config));
440                false ->
441                    {skip, "Host does not support IPv6"}
442            end
443    end.
444
445
446end_per_group(_GroupName, Config) ->
447    %% Do we really need to do this?
448    lists:keydelete(snmp_group_top_dir, 1, Config).
449
450
451
452
453%%
454%% -----
455%%
456
457init_per_testcase(Case, Config) when is_list(Config) ->
458
459    ?IPRINT("init_per_testcase -> entry with"
460            "~n   Config: ~p"
461            "~n   Nodes:  ~p", [Config, erlang:nodes()]),
462
463    snmp_test_global_sys_monitor:reset_events(),
464
465    %% This version of the API, based on Addr and Port, has been deprecated
466    DeprecatedApiCases =
467	[
468	],
469    Result =
470	case lists:member(Case, DeprecatedApiCases) of
471	    true ->
472		{skip, "API no longer supported"};
473	    false ->
474		try init_per_testcase2(Case, Config)
475                catch
476                    C:{skip, _} = E:_ when ((C =:= throw) orelse
477                                            (C =:= exit)) ->
478                        E;
479                    exit:{suite_failed, {{Reason, _CS},_MFA}, Mod, Line}:_ ->
480                        {skip, {Reason, Mod, Line}};
481                    exit:{suite_failed, Reason, Mod, Line}:_ ->
482                        {skip, {Reason, Mod, Line}};
483                    C:E:_ when ((C =:= throw) orelse
484                                (C =:= exit)) ->
485                        {skip, {catched, C, E}}
486                end
487	end,
488    ?IPRINT("init_per_testcase end when"
489            "~n      Nodes:  ~p"
490            "~n      Result: ~p"
491            "~n~n", [erlang:nodes(), Result]),
492    Result.
493
494init_per_testcase2(Case, Config) ->
495    ?DBG("init_per_testcase2 -> "
496	 "~n   Case:   ~p"
497	 "~n   Config: ~p"
498	 "~n   Nodes:  ~p", [Case, Config, erlang:nodes()]),
499
500    CaseTopDir = snmp_test_lib:init_testcase_top_dir(Case, Config),
501
502    %% -- Manager dirs  --
503    MgrTopDir  = filename:join(CaseTopDir, "manager/"),
504    ?DBG("init_per_testcase2 -> try create manager top dir: ~n~p",
505	 [MgrTopDir]),
506    ?line ok   = file:make_dir(MgrTopDir),
507
508    MgrConfDir = filename:join(MgrTopDir,  "conf/"),
509    ?line ok   = file:make_dir(MgrConfDir),
510
511    MgrDbDir   = filename:join(MgrTopDir,  "db/"),
512    ?line ok   = file:make_dir(MgrDbDir),
513
514    MgrLogDir  = filename:join(MgrTopDir,  "log/"),
515    ?line ok   = file:make_dir(MgrLogDir),
516
517    %% -- Agent dirs --
518    AgTopDir  = filename:join(CaseTopDir, "agent/"),
519    ?line ok  = file:make_dir(AgTopDir),
520
521    AgConfDir = filename:join(AgTopDir,   "conf/"),
522    ?line ok  = file:make_dir(AgConfDir),
523
524    AgDbDir   = filename:join(AgTopDir,   "db/"),
525    ?line ok  = file:make_dir(AgDbDir),
526
527    AgLogDir  = filename:join(AgTopDir,   "log/"),
528    ?line ok  = file:make_dir(AgLogDir),
529
530    Family = proplists:get_value(ipfamily, Config, inet),
531
532    TO = case Case of
533             inform3 ->
534                 ?MINS(2);
535             InformSwarm when (InformSwarm =:= inform_swarm_cbp_def) orelse
536                              (InformSwarm =:= inform_swarm_cbp_temp) orelse
537                              (InformSwarm =:= inform_swarm_cbp_perm) ->
538                 case ?config(snmp_factor, Config) of
539                     N when is_integer(N) -> ?MINS(2*N);
540                     _                    -> ?MINS(2)
541                 end;
542             _ ->
543                 ?MINS(1)
544         end,
545    ?IPRINT("Set test case timetrap: ~p", [TO]),
546    ct:timetrap(TO),
547
548    Conf = [{ipfamily,                  Family},
549	    {ip,                        ?LOCALHOST(Family)},
550	    {case_top_dir,              CaseTopDir},
551	    {agent_dir,                 AgTopDir},
552	    {agent_conf_dir,            AgConfDir},
553	    {agent_db_dir,              AgDbDir},
554	    {agent_log_dir,             AgLogDir},
555	    {manager_agent_target_name, "agent01"},
556	    {manager_dir,               MgrTopDir},
557	    {manager_conf_dir,          MgrConfDir},
558	    {manager_db_dir,            MgrDbDir},
559	    {manager_log_dir,           MgrLogDir} | Config],
560    Conf2 = init_per_testcase3(Case, Conf),
561    ?DBG("init [~w] Nodes [2]: ~p", [Case, erlang:nodes()]),
562    Conf2.
563
564init_per_testcase3(Case, Config) ->
565    ApiCases02 =
566	[
567	 simple_sync_get2,
568	 simple_async_get2,
569	 simple_sync_get_next2,
570	 simple_async_get_next2,
571	 simple_sync_set2,
572	 simple_async_set2,
573	 simple_sync_get_bulk2,
574	 simple_async_get_bulk2,
575	 misc_async2,
576	 otp8395_1
577	],
578    ApiCases03 =
579	[
580	 simple_sync_get3,
581	 simple_async_get3,
582	 simple_sync_get_next3,
583	 simple_async_get_next3_cbp_def,
584	 simple_async_get_next3_cbp_temp,
585	 simple_async_get_next3_cbp_perm,
586	 simple_sync_set3,
587	 simple_async_set3_cbp_def,
588	 simple_async_set3_cbp_temp,
589	 simple_async_set3_cbp_perm,
590	 simple_sync_get_bulk3,
591         simple_async_get_bulk3_cbp_def,
592         simple_async_get_bulk3_cbp_temp,
593         simple_async_get_bulk3_cbp_perm
594	],
595    Cases =
596	[
597	 trap1,
598	 trap2,
599	 inform1,
600	 inform2,
601	 inform3,
602	 inform4,
603	 inform_swarm_cbp_def,
604         inform_swarm_cbp_temp,
605         inform_swarm_cbp_perm,
606	 report
607	] ++
608	ApiCases02 ++
609	ApiCases03,
610    case lists:member(Case, Cases) of
611	true ->
612	    NoAutoInformCases = [inform1, inform2, inform3,
613                                 inform_swarm_cbp_def,
614                                 inform_swarm_cbp_temp,
615                                 inform_swarm_cbp_perm],
616	    AutoInform = not lists:member(Case, NoAutoInformCases),
617	    Conf1 = if
618                        %% We turn off verbosity for the swarm cases
619                        %% (too much output).
620			(Case =:= inform_swarm_cbp_def) orelse
621                        (Case =:= inform_swarm_cbp_temp) orelse
622                        (Case =:= inform_swarm_cbp_perm) ->
623			    Verb = [{manager_config_verbosity,     silence},
624                                    {manager_note_store_verbosity, silence},
625                                    {manager_server_verbosity,     info},
626                                    {manager_net_if_verbosity,     info},
627                                    {agent_verbosity,              info},
628                                    {agent_net_if_verbosity,       info}],
629                            Verb ++ Config;
630			Case =:= otp8395_1 ->
631			    [{manager_atl_seqno, true} | Config];
632			true ->
633			    Config
634		    end,
635            Conf2 = if
636                        (Case =:= simple_async_get_next3_cbp_temp) orelse
637                        (Case =:= simple_async_set3_cbp_temp) orelse
638                        (Case =:= simple_async_get_bulk3_cbp_temp) orelse
639                        (Case =:= inform_swarm_cbp_temp) ->
640                            [{manager_server_cbproxy, temporary} | Conf1];
641                        (Case =:= simple_async_get_next3_cbp_perm) orelse
642                        (Case =:= simple_async_set3_cbp_perm) orelse
643                        (Case =:= simple_async_get_bulk3_cbp_perm) orelse
644                        (Case =:= inform_swarm_cbp_perm) ->
645                            [{manager_server_cbproxy, permanent} | Conf1];
646                        true ->
647                            Conf1
648                    end,
649            %% We don't need to try catch this (init_agent)
650            %% since we have a try catch "higher up"...
651	    Conf3 = init_agent(Conf2),
652	    Conf4 = try init_manager(AutoInform, Conf3)
653                    catch AC:AE:_ ->
654                            %% Ouch we need to clean up:
655                            %% The init_agent starts an agent node!
656                            init_per_testcase_fail_agent_cleanup(Conf2),
657                            throw({skip, {manager_init_failed, AC, AE}})
658                    end,
659	    Conf5 = try init_mgr_user(Conf4)
660                    catch MC:ME:_ ->
661                            %% Ouch we need to clean up:
662                            %% The init_agent starts an agent node!
663                            %% The init_magager starts an manager node!
664                            init_per_testcase_fail_manager_cleanup(Conf3),
665                            init_per_testcase_fail_agent_cleanup(Conf3),
666                            throw({skip, {manager_user_init_failed, MC, ME}})
667                    end,
668	    case lists:member(Case, ApiCases02 ++ ApiCases03) of
669		true ->
670		    init_mgr_user_data2(Conf5);
671		false ->
672		    init_mgr_user_data1(Conf5)
673	    end;
674	false ->
675	    Config
676    end.
677
678init_per_testcase_fail_manager_cleanup(Conf) ->
679    (catch fin_manager(Conf)).
680
681init_per_testcase_fail_agent_cleanup(Conf) ->
682    (catch fin_agent(Conf)).
683
684end_per_testcase(Case, Config) when is_list(Config) ->
685    ?IPRINT("end_per_testcase -> entry with"
686            "~n   Config:        ~p"
687            "~n   Nodes:         ~p",
688            [Config, erlang:nodes()]),
689
690    ?IPRINT("system events during test: "
691            "~n   ~p", [snmp_test_global_sys_monitor:events()]),
692
693    Conf1  = Config,
694    Conf2  = end_per_testcase2(Case, Conf1),
695
696    ?IPRINT("end_per_testcase -> done with"
697            "~n   Condif: ~p"
698            "~n   Nodes:  ~p", [Conf2, erlang:nodes()]),
699
700    Conf2.
701
702end_per_testcase2(Case, Config) ->
703    ApiCases02 =
704	[
705	 simple_sync_get2,
706	 simple_async_get2,
707	 simple_sync_get_next2,
708	 simple_async_get_next2,
709	 simple_sync_set2,
710	 simple_async_set2,
711	 simple_sync_get_bulk2,
712	 simple_async_get_bulk2,
713	 misc_async2,
714	 otp8395_1
715	],
716    ApiCases03 =
717	[
718	 simple_sync_get3,
719	 simple_async_get3,
720	 simple_sync_get_next3,
721	 simple_async_get_next3_cbp_def,
722	 simple_async_get_next3_cbp_temp,
723	 simple_async_get_next3_cbp_perm,
724	 simple_sync_set3,
725	 simple_async_set3_cbp_def,
726	 simple_async_set3_cbp_temp,
727	 simple_async_set3_cbp_perm,
728	 simple_sync_get_bulk3,
729         simple_async_get_bulk3_cbp_def,
730         simple_async_get_bulk3_cbp_temp,
731         simple_async_get_bulk3_cbp_perm
732	],
733    Cases =
734	[
735	 trap1,
736	 trap2,
737	 inform1,
738	 inform2,
739	 inform3,
740	 inform4,
741         inform_swarm_cbp_def,
742         inform_swarm_cbp_temp,
743         inform_swarm_cbp_perm,
744	 report
745	] ++
746	ApiCases02 ++
747	ApiCases03,
748    case lists:member(Case, Cases) of
749	true ->
750	    Conf1 = case lists:member(Case, ApiCases02 ++ ApiCases03) of
751			true ->
752			    fin_mgr_user_data2(Config);
753			false ->
754			    fin_mgr_user_data1(Config)
755		    end,
756	    Conf2 = fin_mgr_user(Conf1),
757	    Conf3 = fin_manager(Conf2),
758	    fin_agent(Conf3);
759	false ->
760	    Config
761    end.
762
763
764%%======================================================================
765%% Test case definitions
766%%======================================================================
767
768
769%%======================================================================
770%% Test functions
771%%======================================================================
772
773simple_start_and_stop1(suite) -> [];
774simple_start_and_stop1(Config) when is_list(Config) ->
775    ?TC_TRY(simple_start_and_stop1,
776            fun() -> do_simple_start_and_stop1(Config) end).
777
778do_simple_start_and_stop1(Config) ->
779    ?IPRINT("starting with Config: "
780            "~n      ~p", [Config]),
781    ConfDir = ?config(manager_conf_dir, Config),
782    DbDir   = ?config(manager_db_dir, Config),
783
784    write_manager_conf(ConfDir),
785
786    Opts = [{server, [{verbosity, trace}]},
787	    {net_if, [{verbosity, trace}]},
788	    {note_store, [{verbosity, trace}]},
789	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
790
791    ?IPRINT("try starting manager"),
792    ok = snmpm:start_link(Opts),
793
794    ?SLEEP(1000),
795
796    ?IPRINT("manager started, now try to stop"),
797    ok = snmpm:stop(),
798
799    ?SLEEP(1000),
800
801    ok.
802
803
804%%======================================================================
805
806simple_start_and_stop2(suite) -> [];
807simple_start_and_stop2(Config) when is_list(Config) ->
808    Pre  = fun() ->
809                   ManagerNode = start_manager_node(),
810                   [ManagerNode]
811           end,
812    Case = fun(State) -> do_simple_start_and_stop2(State, Config) end,
813    Post = fun([ManagerNode]) -> stop_node(ManagerNode) end,
814    ?TC_TRY(simple_start_and_stop2, Pre, Case, Post).
815
816do_simple_start_and_stop2([ManagerNode], Config) ->
817    ?IPRINT("starting with Config: "
818            "~n      ~p"
819            "~n", [Config]),
820
821    ConfDir = ?config(manager_conf_dir, Config),
822    DbDir   = ?config(manager_db_dir, Config),
823
824    write_manager_conf(ConfDir),
825
826    Opts = [{server, [{verbosity, trace}]},
827	    {net_if, [{verbosity, trace}]},
828	    {note_store, [{verbosity, trace}]},
829	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
830
831
832    ?IPRINT("try load snmp application"),
833    ?line ok = load_snmp(ManagerNode),
834
835    ?IPRINT("try set manager env for the snmp application"),
836    ?line ok = set_mgr_env(ManagerNode, Opts),
837
838    ?IPRINT("try starting snmp application (with only manager)"),
839    ?line ok = start_snmp(ManagerNode),
840
841    ?IPRINT("started"),
842
843    ?SLEEP(1000),
844
845    ?IPRINT("try stopping snmp application (with only manager)"),
846    ?line ok = stop_snmp(ManagerNode),
847
848    ?SLEEP(1000),
849    ?IPRINT("end"),
850
851    ok.
852
853
854%%======================================================================
855
856simple_start_and_stop3(suite) -> [];
857simple_start_and_stop3(Config) when is_list(Config) ->
858    ?TC_TRY(simple_start_and_stop3,
859            fun() -> do_simple_start_and_stop3(Config) end).
860
861do_simple_start_and_stop3(Config) ->
862    ?IPRINT("starting with Config: "
863            "~n      ~p", [Config]),
864
865    ConfDir = ?config(manager_conf_dir, Config),
866    DbDir   = ?config(manager_db_dir, Config),
867
868    write_manager_conf(ConfDir),
869
870    Opts = [{server,     [{verbosity, trace}]},
871	    {net_if,     [{verbosity, trace}, {options, [{extra_sock_opts, ['this-should-not-work']}]}]},
872	    {note_store, [{verbosity, trace}]},
873	    {config,     [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
874
875    ?IPRINT("try starting manager"),
876    try snmpm:start_link(Opts) of
877        ok ->
878            (catch snmpm:stop()),
879            ?FAIL('unexpected-success')
880    catch
881        _:_:_ ->
882            ?IPRINT("expected start failure"),
883            ok
884    end,
885
886    ?SLEEP(1000),
887    ?IPRINT("end"),
888
889    ok.
890
891
892%%======================================================================
893
894simple_start_and_monitor_crash1(suite) -> [];
895simple_start_and_monitor_crash1(Config) when is_list(Config) ->
896    ?TC_TRY(simple_start_and_monitor_crash1,
897            fun() -> do_simple_start_and_monitor_crash1(Config) end).
898
899do_simple_start_and_monitor_crash1(Config) ->
900    ?IPRINT("starting with Config: "
901            "~n      ~p", [Config]),
902
903    ConfDir = ?config(manager_conf_dir, Config),
904    DbDir   = ?config(manager_db_dir, Config),
905
906    write_manager_conf(ConfDir),
907
908    Opts = [{server, [{verbosity, trace}]},
909	    {net_if, [{verbosity, trace}]},
910	    {note_store, [{verbosity, trace}]},
911	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
912
913    ?IPRINT("try starting manager"),
914    ok = snmpm:start(Opts),
915
916    ?SLEEP(1000),
917
918    ?IPRINT("create the monitor"),
919    Ref = snmpm:monitor(),
920
921    ?IPRINT("make sure it has not already crashed..."),
922    receive
923	{'DOWN', Ref, process, Obj1, Reason1} ->
924	    ?FAIL({unexpected_down, Obj1, Reason1})
925    after 1000 ->
926	    ok
927    end,
928
929    ?IPRINT("stop the manager"),
930    ok = snmpm:stop(),
931
932    ?IPRINT("await the down-message"),
933    receive
934	{'DOWN', Ref, process, Obj2, Reason2} ->
935	    ?IPRINT("received expected down-message: "
936                    "~n   Obj2:    ~p"
937                    "~n   Reason2: ~p",
938                    [Obj2, Reason2]),
939	    ok
940    after 1000 ->
941            %% The manager is an entire process tree and we can't
942            %% wait for all of them. Instead, we assume that if
943            %% we deal with the top supervisor, all the other procs
944            %% will also follow...
945            ?ENSURE_NOT_RUNNING(snmpm_supervisor,
946                                fun() -> snmpm:stop() end,
947                                1000),
948	    ?FAIL(timeout)
949    end,
950    ?IPRINT("end"),
951
952    ok.
953
954
955%%======================================================================
956
957simple_start_and_monitor_crash2(suite) -> [];
958simple_start_and_monitor_crash2(Config) when is_list(Config) ->
959    Cond = fun() -> case os:type() of
960			{unix, netbsd} ->
961			    {skip, "Unstable on NetBSD"};
962			_ ->
963			    ok
964		    end
965	   end,
966    Pre  = fun()  -> undefined end,
967    Case = fun(_) -> do_simple_start_and_monitor_crash2(Config) end,
968    Post = fun(_) -> ok end,
969    ?TC_TRY(simple_start_and_monitor_crash2,
970	    Cond, Pre, Case, Post).
971
972do_simple_start_and_monitor_crash2(Config) ->
973    ?IPRINT("starting with Config: "
974            "~n      ~p", [Config]),
975
976    ConfDir = ?config(manager_conf_dir, Config),
977    DbDir   = ?config(manager_db_dir, Config),
978
979    write_manager_conf(ConfDir),
980
981    Opts = [{restart_type, permanent},
982	    {server, [{verbosity, trace}]},
983	    {net_if, [{verbosity, trace}]},
984	    {note_store, [{verbosity, trace}]},
985	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
986
987    ?IPRINT("try starting manager"),
988    ok = snmpm:start(Opts),
989
990    ?SLEEP(1000),
991
992    ?IPRINT("create the monitor"),
993    Ref = snmpm:monitor(),
994
995    ?IPRINT("make sure it has not already crashed..."),
996    receive
997	{'DOWN', Ref, process, Obj1, Reason1} ->
998	    ?FAIL({unexpected_down, Obj1, Reason1})
999    after 1000 ->
1000	    ok
1001    end,
1002
1003    ?IPRINT("crash the manager"),
1004    simulate_crash(),
1005
1006    ?IPRINT("await the down-message"),
1007    receive
1008	{'DOWN', Ref, process, Obj2, Reason2} ->
1009	    ?IPRINT("received expected down-message: "
1010                    "~n   Obj2:    ~p"
1011                    "~n   Reason2: ~p",
1012                    [Obj2, Reason2]),
1013	    ok
1014    after 1000 ->
1015	    ?FAIL(timeout)
1016    end,
1017
1018    ok.
1019
1020
1021%% The server supervisor allow 5 restarts in 500 msec.
1022server_pid() ->
1023    whereis(snmpm_server).
1024
1025-define(MAX_KILLS, 6).
1026
1027simulate_crash() ->
1028    simulate_crash(0, server_pid()).
1029
1030simulate_crash(?MAX_KILLS, _) ->
1031    ?SLEEP(1000),
1032    case server_pid() of
1033	P when is_pid(P) ->
1034	    exit({error, {still_alive, P}});
1035	_ ->
1036	    ok
1037    end;
1038simulate_crash(NumKills, Pid) when (NumKills < ?MAX_KILLS) and is_pid(Pid) ->
1039    ?IPRINT("similate_crash -> ~w, ~p", [NumKills, Pid]),
1040    Ref = erlang:monitor(process, Pid),
1041    exit(Pid, kill),
1042    receive
1043	{'DOWN', Ref, process, _Object, _Info} ->
1044	    ?IPRINT("received expected 'DOWN' message"),
1045	    simulate_crash(NumKills + 1, server_pid())
1046    after 1000 ->
1047	    case server_pid() of
1048		P when is_pid(P) ->
1049                    ?EPRINT("received expected 'DOWN' message"),
1050		    exit({error, {no_down_from_server, P}});
1051		_ ->
1052		    ok
1053	    end
1054    end;
1055simulate_crash(NumKills, _) ->
1056    ?SLEEP(10),
1057    simulate_crash(NumKills, server_pid()).
1058
1059
1060%%======================================================================
1061
1062notify_started01(suite) -> [];
1063notify_started01(Config) when is_list(Config) ->
1064    ?TC_TRY(notify_started01,
1065            fun() -> do_notify_started01(Config) end).
1066
1067do_notify_started01(Config) ->
1068    ?IPRINT("starting with Config: "
1069            "~n      ~p", [Config]),
1070
1071    ConfDir = ?config(manager_conf_dir, Config),
1072    DbDir   = ?config(manager_db_dir, Config),
1073
1074    write_manager_conf(ConfDir),
1075
1076    Opts = [{server, [{verbosity, log}]},
1077	    {net_if, [{verbosity, silence}]},
1078	    {note_store, [{verbosity, silence}]},
1079	    {config, [{verbosity, log}, {dir, ConfDir}, {db_dir, DbDir}]}],
1080
1081    ?IPRINT("request start notification (1)"),
1082    Pid1 = snmpm:notify_started(10000),
1083    receive
1084	{snmpm_start_timeout, Pid1} ->
1085	    ?IPRINT("received expected start timeout"),
1086	    ok;
1087	Any1 ->
1088	    ?FAIL({unexpected_message, Any1})
1089    after 15000 ->
1090	    ?FAIL({unexpected_timeout, Pid1})
1091    end,
1092
1093    ?IPRINT("request start notification (2)"),
1094    Pid2 = snmpm:notify_started(10000),
1095
1096    ?IPRINT("start the snmpm starter"),
1097    Pid = snmpm_starter(Opts, 5000),
1098
1099    ?IPRINT("await the start notification"),
1100    Ref =
1101	receive
1102	    {snmpm_started, Pid2} ->
1103		?IPRINT("received started message -> create the monitor"),
1104		snmpm:monitor();
1105	    Any2 ->
1106		?FAIL({unexpected_message, Any2})
1107	after 15000 ->
1108		?FAIL({unexpected_timeout, Pid2})
1109	end,
1110
1111    ?IPRINT("[~p] make sure it has not already crashed...", [Ref]),
1112    receive
1113	{'DOWN', Ref, process, Obj1, Reason1} ->
1114	    ?FAIL({unexpected_down, Obj1, Reason1})
1115    after 1000 ->
1116	    ok
1117    end,
1118
1119    ?IPRINT("stop the manager"),
1120    Pid ! {stop, self()}, %ok = snmpm:stop(),
1121
1122    ?IPRINT("await the down-message"),
1123    receive
1124	{'DOWN', Ref, process, Obj2, Reason2} ->
1125	    ?IPRINT("received expected down-message: "
1126                    "~n   Obj2:    ~p"
1127                    "~n   Reason2: ~p",
1128                    [Obj2, Reason2]),
1129	    ok
1130    after 5000 ->
1131	    ?FAIL(down_timeout)
1132    end,
1133
1134    ?IPRINT("end"),
1135    ok.
1136
1137
1138snmpm_starter(Opts, To) ->
1139    Parent = self(),
1140    spawn(
1141      fun() ->
1142	      ?SLEEP(To),
1143	      ok = snmpm:start(Opts),
1144	      receive
1145		  {stop, Parent} ->
1146		      snmpm:stop()
1147	      end
1148      end).
1149
1150
1151%%======================================================================
1152
1153notify_started02(suite) -> [];
1154notify_started02(Config) when is_list(Config) ->
1155    ?TC_TRY(notify_started02,
1156            fun() -> notify_started02_cond(Config) end,
1157            fun() -> do_notify_started02(Config) end).
1158
1159notify_started02_cond(Config) ->
1160    LinuxVersionVerify =
1161	fun() ->
1162		case os:cmd("uname -m") of
1163		    "i686" ++ _ ->
1164			case os:version() of
1165			    {2, 6, Rev} when Rev >= 16 ->
1166				false;
1167			    {2, Min, _} when Min > 6 ->
1168				false;
1169			    {Maj, _, _} when Maj > 2 ->
1170				false;
1171			    _ ->
1172				true
1173			end;
1174		    _ ->
1175			false
1176		end
1177	end,
1178    Skippable = [{unix, [{linux, LinuxVersionVerify}]}],
1179    Condition = fun() -> ?OS_BASED_SKIP(Skippable) end,
1180    ?NON_PC_TC_MAYBE_SKIP(Config, Condition).
1181
1182do_notify_started02(Config) ->
1183    ?IPRINT("starting with Config: "
1184            "~n      ~p", [Config]),
1185
1186    ConfDir = ?config(manager_conf_dir, Config),
1187    DbDir   = ?config(manager_db_dir, Config),
1188
1189    write_manager_conf(ConfDir),
1190
1191    Opts = [{server,     [{verbosity, log}]},
1192	    {net_if,     [{verbosity, silence}]},
1193	    {note_store, [{verbosity, silence}]},
1194	    {config,     [{verbosity, debug}, {dir, ConfDir}, {db_dir, DbDir}]}],
1195
1196    ?IPRINT("start snmpm client process"),
1197    NumIterations = 5,
1198    Pid1 = ns02_client_start(NumIterations),
1199
1200    ?IPRINT("start snmpm ctrl (starter) process"),
1201    Pid2 = ns02_ctrl_start(Opts, NumIterations),
1202
1203    %% On a reasonably fast machine, one iteration takes approx 4 seconds.
1204    %% We measure the first iteration, and then we wait for the remaining
1205    %% ones (4 in this case).
1206    ApproxStartTime =
1207        case ns02_client_await_approx_runtime(Pid1) of
1208            {ok, T} ->
1209                T;
1210            {error, Reason} ->
1211                %% Attempt cleanup just in case
1212                exit(Pid1, kill),
1213                exit(Pid2, kill),
1214                ?FAIL(Reason);
1215            {skip, Reason} ->
1216                %% Attempt cleanup just in case
1217                exit(Pid1, kill),
1218                exit(Pid2, kill),
1219                ?SKIP(Reason)
1220        end,
1221
1222    ?IPRINT("await snmpm client process exit (max ~p+10000 msec)",
1223            [ApproxStartTime]),
1224    receive
1225        %% We take this opportunity to check if we got a skip from
1226        %% the ctrl process.
1227	{'EXIT', Pid2, {skip, SkipReason1}} ->
1228	    ?SKIP(SkipReason1);
1229	{'EXIT', Pid1, normal} ->
1230	    ok;
1231	{'EXIT', Pid1, {suite_failed, Reason1}} ->
1232	    ?FAIL({client, Reason1});
1233	{'EXIT', Pid1, Reason1} ->
1234	    ?FAIL({client, Reason1})
1235    after ApproxStartTime + 10000 ->
1236            exit(Pid1, kill),
1237            exit(Pid2, kill),
1238	    ?FAIL(timeout)
1239    end,
1240
1241    ?IPRINT("await snmpm starter process exit"),
1242    receive
1243	{'EXIT', Pid2, normal} ->
1244	    ok;
1245	{'EXIT', Pid2, {skip, SkipReason2}} ->
1246            %% In case of a race
1247	    ?SKIP(SkipReason2);
1248	{'EXIT', Pid2, Reason2} ->
1249	    ?FAIL({ctrl, Reason2})
1250    after 5000 ->
1251            exit(Pid2, kill),
1252	    ?FAIL(timeout)
1253    end,
1254
1255    ?IPRINT("end"),
1256    ok.
1257
1258
1259ns02_client_start(N) ->
1260    Self = self(),
1261    spawn_link(fun() -> ns02_client(Self, N) end).
1262
1263ns02_client_await_approx_runtime(Pid) ->
1264    receive
1265        {?MODULE, client_time, Time} ->
1266            {ok, Time};
1267        {'EXIT', Pid, Reason} ->
1268            ?EPRINT("client (~p) failed: "
1269                    "~n      ~p", [Pid, Reason]),
1270            {error, Reason}
1271
1272    after 30000 ->
1273            %% Either something is *really* wrong or this machine
1274            %% is dog slow. Either way, this is a skip-reason...
1275            {skip, approx_runtime_timeout}
1276    end.
1277
1278
1279ns02_client(Parent, N) when is_pid(Parent) ->
1280    put(tname, ns02_client),
1281    ?IPRINT("starting"),
1282    ns02_client_loop(Parent,
1283                     dummy, snmpm:notify_started(?NS_TIMEOUT),
1284                     snmp_misc:now(ms), undefined,
1285                     N).
1286
1287ns02_client_loop(_Parent, _Ref, _Pid, _Begin, _End, 0) ->
1288    %% ?IPRINT("loop -> done"),
1289    exit(normal);
1290ns02_client_loop(Parent, Ref, Pid, Begin, End, N)
1291  when is_pid(Parent) andalso is_integer(Begin) andalso is_integer(End) ->
1292    %% ?IPRINT("loop -> [~w] inform parent: ~w, ~w => ~w", [N, Begin, End, End-Begin]),
1293    Parent ! {?MODULE, client_time, N*(End-Begin)},
1294    ns02_client_loop(undefined, Ref, Pid, snmp_misc:now(ms), undefined, N);
1295ns02_client_loop(Parent, Ref, Pid, Begin, End, N)
1296  when is_integer(Begin) andalso is_integer(End) ->
1297    %% ?IPRINT("loop -> [~w] entry when"
1298    %%   "~n      Ref:   ~p"
1299    %%   "~n      Pid:   ~p"
1300    %%   "~n      Begin: ~p"
1301    %%   "~n      End:   ~p", [N, Ref, Pid, Begin, End]),
1302    ns02_client_loop(Parent, Ref, Pid, snmp_misc:now(ms), undefined, N);
1303ns02_client_loop(Parent, Ref, Pid, Begin, End, N) ->
1304    %% ?IPRINT("loop(await message) -> [~w] entry when"
1305    %%   "~n      Ref:   ~p"
1306    %%   "~n      Pid:   ~p"
1307    %%   "~n      Begin: ~p"
1308    %%   "~n      End:   ~p", [N, Ref, Pid, Begin, End]),
1309    receive
1310	{snmpm_started, Pid} ->
1311	    ?IPRINT("received expected started message (~w)", [N]),
1312	    ns02_client_loop(Parent,
1313                             snmpm:monitor(), dummy,
1314                             Begin, End,
1315                             N);
1316	{snmpm_start_timeout, Pid} ->
1317	    ?EPRINT("unexpected timeout"),
1318	    ?FAIL({unexpected_start_timeout, Pid});
1319	{'DOWN', Ref, process, Obj, Reason} ->
1320	    ?IPRINT("received expected DOWN message (~w) with"
1321                    "~n   Obj:    ~p"
1322                    "~n   Reason: ~p", [N, Obj, Reason]),
1323	    ns02_client_loop(Parent,
1324                             dummy, snmpm:notify_started(?NS_TIMEOUT),
1325                             Begin, snmp_misc:now(ms),
1326                             N-1)
1327    end.
1328
1329ns02_ctrl_start(Opts, N) ->
1330    spawn_link(fun() -> ns02_ctrl(Opts, N) end).
1331
1332ns02_ctrl(Opts, N) ->
1333    put(tname, ns02_ctrl),
1334    ?IPRINT("starting"),
1335    ns02_ctrl_loop(Opts, N).
1336
1337
1338%% We have seen that some times it takes unreasonably long time to
1339%% start the manager (it got "stuck" in snmpm_config). But since
1340%% we did not have enough verbosity, we do not know how far it got.
1341%% So, we try to monitor each start attempt. We allow 5 sec (just
1342%% to give slow boxes a chance).
1343ns02_ctrl_loop(_Opts, 0) ->
1344    ?IPRINT("done"),
1345    exit(normal);
1346ns02_ctrl_loop(Opts, N) ->
1347    ?IPRINT("entry when N: ~p", [N]),
1348    ?SLEEP(2000),
1349    ?IPRINT("start manager"),
1350    TS1 = erlang:system_time(millisecond),
1351    {StarterPid, StarterMRef} =
1352        erlang:spawn_monitor(fun() -> exit(snmpm:start(Opts)) end),
1353    receive
1354        {'DOWN', StarterMRef, process, StarterPid, ok} ->
1355            TS2 = erlang:system_time(millisecond),
1356            ?IPRINT("manager started: ~w ms", [TS2-TS1]),
1357            ok
1358    after 5000 ->
1359            ?EPRINT("manager (~p) start timeout - kill", [StarterPid]),
1360            exit(StarterPid, kill),
1361            exit({skip, start_timeout})
1362    end,
1363    ?SLEEP(2000),
1364    ?IPRINT("stop manager"),
1365    ?SLEEP(100), % Give the verbosity to take effect...
1366    TS3 = erlang:system_time(millisecond),
1367    case snmpm:stop(5000) of
1368        ok ->
1369            TS4 = erlang:system_time(millisecond),
1370            ?IPRINT("manager stopped: ~p ms", [TS4-TS3]),
1371            ok;
1372        {error, timeout} ->
1373            ?EPRINT("manager stop timeout - kill (cleanup) and skip"),
1374            exit(whereis(snmpm_supervisor), kill),
1375            exit({skip, stop_timeout})
1376    end,
1377    ns02_ctrl_loop(Opts, N-1).
1378
1379
1380
1381%%======================================================================
1382
1383info(suite) -> [];
1384info(Config) when is_list(Config) ->
1385    Pre = fun() ->
1386                  ConfDir = ?config(manager_conf_dir, Config),
1387                  DbDir   = ?config(manager_db_dir, Config),
1388
1389                  write_manager_conf(ConfDir),
1390
1391                  Opts = [{server, [{verbosity, trace}]},
1392                          {net_if, [{verbosity, trace}]},
1393                          {note_store, [{verbosity, trace}]},
1394                          {config, [{verbosity, trace},
1395                                    {dir,       ConfDir},
1396                                    {db_dir,    DbDir}]}],
1397                  ?IPRINT("try starting manager"),
1398                  ok = snmpm:start(Opts),
1399                  ?SLEEP(1000),
1400                  ok
1401          end,
1402    Case = fun(_) -> do_info(Config) end,
1403    Post = fun(_) ->
1404                   ?IPRINT("info verified, now try to stop"),
1405                   snmpm:stop(),
1406                   ?SLEEP(1000),
1407                   ok
1408           end,
1409    ?TC_TRY(info, Pre, Case, Post).
1410
1411
1412do_info(Config) ->
1413    ?IPRINT("starting with Config: "
1414            "~n      ~p", [Config]),
1415
1416    ?IPRINT("get info"),
1417    Info = snmpm:info(),
1418    ?IPRINT("got info, now verify: "
1419            "~n   ~p", [Info]),
1420    ok = verify_info( Info ),
1421
1422    ?IPRINT("end"),
1423    ok.
1424
1425verify_info(Info) when is_list(Info) ->
1426    Keys = [{server,     [process_memory, db_memory]},
1427	    {config,     [process_memory, db_memory]},
1428	    {net_if,     [process_memory, port_info]},
1429	    {note_store, [process_memory, db_memory]},
1430	    stats_counters],
1431    verify_info(Keys, Info);
1432verify_info(BadInfo) ->
1433    {error, {bad_info, BadInfo}}.
1434
1435verify_info([], _) ->
1436    ok;
1437verify_info([Key|Keys], Info) when is_atom(Key) ->
1438    case lists:keymember(Key, 1, Info) of
1439	true ->
1440	    verify_info(Keys, Info);
1441	false ->
1442	    {error, {missing_info, {Key, Info}}}
1443    end;
1444verify_info([{Key, SubKeys}|Keys], Info) ->
1445    case lists:keysearch(Key, 1, Info) of
1446	{value, {Key, SubInfo}} ->
1447	    case verify_info(SubKeys, SubInfo) of
1448		ok ->
1449		    verify_info(Keys, Info);
1450		{error, {missing_info, {SubKey, _}}} ->
1451		    {error, {missing_subinfo, {Key, SubKey, Info}}}
1452	    end;
1453	false ->
1454	    {error, {missing_info, {Key, Info}}}
1455    end.
1456
1457
1458%%======================================================================
1459
1460%% USM privacy fails with AES in OTP 22.2.3. Test to prevent
1461%% regression in future releases.
1462%%
1463usm_priv_aes(suite) -> [];
1464usm_priv_aes(Config) when is_list(Config) ->
1465    Pre = fun() ->
1466                  ConfDir = ?config(manager_conf_dir, Config),
1467                  DbDir   = ?config(manager_db_dir, Config),
1468
1469                  write_manager_conf(ConfDir),
1470
1471                  Opts = [{server,     [{verbosity, trace}]},
1472                          {net_if,     [{verbosity, trace}]},
1473                          {note_store, [{verbosity, trace}]},
1474                          {config,     [{verbosity, trace},
1475                                        {dir,       ConfDir},
1476                                        {db_dir,    DbDir}]}],
1477
1478                  io:format("[~s] try starting manager", [?FTS()]),
1479                  ok = snmpm:start(Opts),
1480                  ?SLEEP(1000), % Give it time to settle
1481                  ok
1482          end,
1483    Case = fun(_) -> do_usm_priv_aes(Config) end,
1484    Post = fun(_) ->
1485                   io:format("[~s] try stop manager", [?FTS()]),
1486                   ok = snmpm:stop(),
1487                   ?SLEEP(1000), % Give it time to settle
1488                   ok
1489           end,
1490    ?TC_TRY(usm_priv_aes, Pre, Case, Post).
1491
1492do_usm_priv_aes(Config) ->
1493    io:format("[~s] starting with Config: "
1494              "~n   ~p", [?FTS(), Config]),
1495
1496    io:format("[~s] generate AES-encrypted message", [?FTS()]),
1497
1498    EngineID = [128,0,0,0,6],
1499    SecName  = "v3_user",
1500    AuthPass = "authpass",
1501    AuthKey  =
1502      snmp:passwd2localized_key(sha, AuthPass, EngineID),
1503    PrivPass = "privpass",
1504    PrivKey  =
1505      snmp:passwd2localized_key(md5, PrivPass, EngineID),
1506
1507    Credentials =
1508      [ {auth,     usmHMACSHAAuthProtocol},
1509        {auth_key, AuthKey},
1510        {priv,     usmAesCfb128Protocol},
1511        {priv_key, PrivKey}
1512      ],
1513
1514    AgentConfig =
1515      [ {engine_id, EngineID},
1516        {address,   {192,0,2,1}},
1517        {version,   v3},
1518        {sec_model, usm},
1519        {sec_level, authPriv},
1520        {sec_name,  SecName}
1521      ],
1522
1523    snmpm:register_user(SecName, snmpm_user_default, nil),
1524    snmpm:register_usm_user(EngineID, SecName, Credentials),
1525    snmpm:register_agent(SecName, "v3_agent", AgentConfig),
1526
1527    PduType   = 'get-request',
1528    ScopedPDU =
1529      { scopedPdu,
1530        "",        % CtxEngineID
1531        "",        % Context
1532        { pdu,
1533          PduType,
1534          0,       % RequestID
1535          noError, % ErrorStatus
1536          0,       % ErrorIndex
1537          [ {varbind, [1,3,6,1,2,1,1,5,0], 'OCTET STRING', [], 0}
1538          ]
1539        }
1540      },
1541
1542    MsgSecurityParameters =
1543      { usmSecurityParameters,
1544        _MsgAuthoritativeEngineID    = EngineID,
1545        _MsgAuthoritativeEngineBoots = 1,
1546        _MsgAuthoritativeEngineTime  = 0,
1547        _MsgUserName                 = SecName,
1548        _MsgAuthenticationParameters = AuthKey,
1549        _MsgPrivacyParameters        = PrivKey
1550      },
1551
1552    {ok, MsgMaxSize} =
1553      snmpm_config:get_engine_max_message_size(),
1554
1555    Message =
1556      { message,
1557        _Version = 'version-3',
1558        { v3_hdr,
1559          _MsgID = 1,
1560          MsgMaxSize,
1561          _MsgFlags = snmp_misc:mk_msg_flags(PduType, 2),
1562          _MsgSecurityModel = 3,  % SEC_USM
1563          MsgSecurityParameters,
1564          0
1565        },
1566        Data = snmp_pdus:enc_scoped_pdu(ScopedPDU)
1567      },
1568
1569    {_, CredVals} = lists:unzip(Credentials),
1570
1571    SecLevel = 2,
1572
1573    Msg =
1574      snmpm_usm:generate_outgoing_msg(
1575        Message,
1576        EngineID,
1577        SecName,
1578        list_to_tuple([SecName|CredVals]),
1579        SecLevel
1580      ),
1581
1582    io:format("[~s] got AES-encrypted message, now decrypt: "
1583              "~n   ~p", [?FTS(), Msg]),
1584
1585    {message, _Version, Hdr, NextData} =
1586      snmp_pdus:dec_message_only(Msg),
1587
1588    { v3_hdr,
1589      _MsgID,
1590      _MsgMaxSize,
1591      _MsgFlags,
1592      _SecModel,
1593      SecParams,
1594      _Hdr_size
1595    } = Hdr,
1596
1597    { ok,
1598      { _MsgAuthEngineID,
1599        _SecName,
1600        ScopedPDUBytes,
1601        _CachedSecData
1602      }
1603    } =
1604      snmpm_usm:process_incoming_msg(
1605        Msg,
1606        NextData,
1607        SecParams,
1608        SecLevel
1609      ),
1610
1611    Data = ScopedPDUBytes,
1612
1613    io:format("[~s] Message decrypted", [?FTS()]),
1614    ok.
1615
1616
1617%%======================================================================
1618
1619register_user1(suite) -> [];
1620register_user1(Config) when is_list(Config) ->
1621    Pre  = fun() ->
1622                   ManagerNode = start_manager_node(),
1623                   [ManagerNode]
1624           end,
1625    Case = fun(State) -> do_register_user1(State, Config) end,
1626    Post = fun([ManagerNode]) -> stop_node(ManagerNode) end,
1627    ?TC_TRY(register_user1, Pre, Case, Post).
1628
1629do_register_user1([ManagerNode], Config) ->
1630    ?IPRINT("starting with Config: "
1631            "~n   ~p"
1632            "~n", [Config]),
1633
1634    ConfDir = ?config(manager_conf_dir, Config),
1635    DbDir   = ?config(manager_db_dir, Config),
1636
1637    write_manager_conf(ConfDir),
1638
1639    Opts = [{server,     [{verbosity, trace}]},
1640	    {net_if,     [{verbosity, trace}]},
1641	    {note_store, [{verbosity, trace}]},
1642	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
1643
1644
1645    ?IPRINT("load snmp application"),
1646    ?line ok = load_snmp(ManagerNode),
1647
1648    ?IPRINT("set manager env for the snmp application"),
1649    ?line ok = set_mgr_env(ManagerNode, Opts),
1650
1651    ?IPRINT("starting snmp application (with only manager)"),
1652    ?line ok = start_snmp(ManagerNode),
1653
1654    ?IPRINT("started"),
1655
1656    ?SLEEP(1000),
1657
1658    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1659
1660    ?IPRINT("try register user(s)"),
1661    ?line ok = mgr_register_user(ManagerNode, calvin, snmpm_user_default,
1662				 [self(), "various misc info"]),
1663
1664    Users1 = mgr_which_users(ManagerNode),
1665    ?IPRINT("users: ~p~n", [Users1]),
1666    ?line ok = verify_users(Users1, [calvin]),
1667    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1668
1669    ?line ok = mgr_register_user(ManagerNode, hobbe, snmpm_user_default,
1670				 {"misc info", self()}),
1671
1672    Users2 = mgr_which_users(ManagerNode),
1673    ?IPRINT("users: ~p~n", [Users2]),
1674    ?line ok = verify_users(Users2, [calvin, hobbe]),
1675    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1676
1677    ?IPRINT("try unregister user(s)"),
1678    ?line ok = mgr_unregister_user(ManagerNode, calvin),
1679
1680    Users3 = mgr_which_users(ManagerNode),
1681    ?IPRINT("users: ~p~n", [Users3]),
1682    ?line ok = verify_users(Users3, [hobbe]),
1683    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1684
1685    ?line ok = mgr_unregister_user(ManagerNode, hobbe),
1686
1687    Users4 = mgr_which_users(ManagerNode),
1688    ?IPRINT("users: ~p~n", [Users4]),
1689    ?line ok = verify_users(Users4, []),
1690    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1691
1692    ?SLEEP(1000),
1693
1694    ?IPRINT("stop snmp application (with only manager)"),
1695    ?line ok = stop_snmp(ManagerNode),
1696
1697    ?SLEEP(1000),
1698
1699    ok.
1700
1701verify_users([], []) ->
1702    ok;
1703verify_users(ActualUsers, []) ->
1704    {error, {unexpected_users, ActualUsers}};
1705verify_users(ActualUsers0, [User|RegUsers]) ->
1706    case lists:delete(User, ActualUsers0) of
1707	ActualUsers0 ->
1708	    {error, {not_registered, User}};
1709	ActualUsers ->
1710	    verify_users(ActualUsers, RegUsers)
1711    end.
1712
1713
1714%%======================================================================
1715
1716register_agent_old(doc) ->
1717    ["Test registration of agents with the OLD interface functions"];
1718register_agent_old(suite) ->
1719    [];
1720register_agent_old(Config) when is_list(Config) ->
1721    Pre  = fun() ->
1722                   ManagerNode = start_manager_node(),
1723                   [ManagerNode]
1724           end,
1725    Case = fun(State) -> do_register_agent_old(State, Config) end,
1726    Post = fun([ManagerNode]) -> stop_node(ManagerNode) end,
1727    ?TC_TRY(register_agent_old, Pre, Case, Post).
1728
1729do_register_agent_old([ManagerNode], Config) ->
1730    ?IPRINT("starting with Config: "
1731            "~n      ~p"
1732            "~n", [Config]),
1733
1734    ConfDir = ?config(manager_conf_dir, Config),
1735    DbDir   = ?config(manager_db_dir, Config),
1736
1737    write_manager_conf(ConfDir),
1738
1739    Opts = [{server,     [{verbosity, trace}]},
1740	    {net_if,     [{verbosity, trace}]},
1741	    {note_store, [{verbosity, trace}]},
1742	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
1743
1744
1745    ?IPRINT("load snmp application"),
1746    ?line ok = load_snmp(ManagerNode),
1747
1748    ?IPRINT("set manager env for the snmp application"),
1749    ?line ok = set_mgr_env(ManagerNode, Opts),
1750
1751    ?IPRINT("starting snmp application (with only manager)"),
1752    ?line ok = start_snmp(ManagerNode),
1753
1754    ?IPRINT("started"),
1755
1756    ?SLEEP(1000),
1757
1758    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1759
1760    ?IPRINT("register user(s) user_alfa & user_beta"),
1761    ?line ok = mgr_register_user(ManagerNode, user_alfa, snmpm_user_default, []),
1762    ?line ok = mgr_register_user(ManagerNode, user_beta, snmpm_user_default, []),
1763    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1764
1765    ?IPRINT("register agent(s)"),
1766    ?line ok = mgr_register_agent(ManagerNode, user_alfa, 5000, []),
1767    ?line ok = mgr_register_agent(ManagerNode, user_alfa, 5001, []),
1768    ?line ok = mgr_register_agent(ManagerNode, user_beta, 5002, []),
1769    ?line ok = mgr_register_agent(ManagerNode, user_beta, 5003, []),
1770
1771    ?IPRINT("verify all agent(s): expect 4"),
1772    case mgr_which_agents(ManagerNode) of
1773	Agents1 when length(Agents1) =:= 4 ->
1774	    ?IPRINT("all agents: ~p~n", [Agents1]),
1775	    ok;
1776	Agents1 ->
1777	    ?FAIL({agent_registration_failure, Agents1})
1778    end,
1779
1780    ?IPRINT("verify user_alfa agent(s)"),
1781    case mgr_which_agents(ManagerNode, user_alfa) of
1782	Agents2 when length(Agents2) =:= 2 ->
1783	    ?IPRINT("calvin agents: ~p", [Agents2]),
1784	    ok;
1785	Agents2 ->
1786	    ?FAIL({agent_registration_failure, Agents2})
1787    end,
1788
1789    ?IPRINT("verify user_beta agent(s)"),
1790    case mgr_which_agents(ManagerNode, user_beta) of
1791	Agents3 when length(Agents3) =:= 2 ->
1792	    ?IPRINT("hobbe agents: ~p", [Agents3]),
1793	    ok;
1794	Agents3 ->
1795	    ?FAIL({agent_registration_failure, Agents3})
1796    end,
1797
1798    ?IPRINT("manager info: "
1799            "~n      ~p", [mgr_info(ManagerNode)]),
1800
1801    ?IPRINT("unregister user user_alfa"),
1802    ?line ok = mgr_unregister_user(ManagerNode, user_alfa),
1803
1804    ?IPRINT("verify all agent(s): expect 2"),
1805    case mgr_which_agents(ManagerNode) of
1806	Agents4 when length(Agents4) =:= 2 ->
1807	    ?IPRINT("all agents: ~p", [Agents4]),
1808	    ok;
1809	Agents4 ->
1810	    ?FAIL({agent_unregistration_failure, Agents4})
1811    end,
1812    ?IPRINT("manager info: "
1813            "~n      ~p~n", [mgr_info(ManagerNode)]),
1814
1815    ?IPRINT("unregister user_beta agents"),
1816    ?line ok = mgr_unregister_agent(ManagerNode, user_beta, 5002),
1817    ?line ok = mgr_unregister_agent(ManagerNode, user_beta, 5003),
1818
1819    ?IPRINT("verify all agent(s): expect 0"),
1820    case mgr_which_agents(ManagerNode) of
1821	[] ->
1822	    ok;
1823	Agents5 ->
1824	    ?IPRINT("all agents: ~p~n", [Agents5]),
1825	    ?FAIL({agent_unregistration_failure, Agents5})
1826    end,
1827
1828    ?IPRINT("manager info: "
1829            "~n      ~p", [mgr_info(ManagerNode)]),
1830
1831    ?IPRINT("unregister user hobbe"),
1832    ?line ok = mgr_unregister_user(ManagerNode, user_beta),
1833
1834    ?IPRINT("manager info: "
1835            "~n      ~p", [mgr_info(ManagerNode)]),
1836
1837    ?SLEEP(1000),
1838
1839    ?IPRINT("stop snmp application (with only manager)"),
1840    ?line ok = stop_snmp(ManagerNode),
1841
1842    ?SLEEP(1000),
1843    ?IPRINT("end"),
1844
1845    ok.
1846
1847
1848%%======================================================================
1849
1850register_agent2(doc) ->
1851    ["Test registration of agents with the NEW interface functions"];
1852register_agent2(suite) ->
1853    [];
1854register_agent2(Config) when is_list(Config) ->
1855    Pre  = fun() ->
1856                   ManagerNode = start_manager_node(),
1857                   [ManagerNode]
1858           end,
1859    Case = fun(State) -> do_register_agent2(State, Config) end,
1860    Post = fun([ManagerNode]) -> stop_node(ManagerNode) end,
1861    ?TC_TRY(register_agent2, Pre, Case, Post).
1862
1863do_register_agent2([ManagerNode], Config) ->
1864    ?IPRINT("starting with Config: "
1865            "~n      ~p", [Config]),
1866
1867    ConfDir   = ?config(manager_conf_dir, Config),
1868    DbDir     = ?config(manager_db_dir, Config),
1869    LocalHost = snmp_test_lib:localhost(),
1870
1871    write_manager_conf(ConfDir),
1872
1873    Opts = [{server,     [{verbosity, trace}]},
1874	    {net_if,     [{verbosity, trace}]},
1875	    {note_store, [{verbosity, trace}]},
1876	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
1877
1878    ?IPRINT("load snmp application"),
1879    ?line ok = load_snmp(ManagerNode),
1880
1881    ?IPRINT("set manager env for the snmp application"),
1882    ?line ok = set_mgr_env(ManagerNode, Opts),
1883
1884    ?IPRINT("starting snmp application (with only manager)"),
1885    ?line ok = start_snmp(ManagerNode),
1886
1887    ?IPRINT("started"),
1888
1889    ?SLEEP(1000),
1890
1891    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1892
1893    ?IPRINT("register user(s) user_alfa & user_beta"),
1894    ?line ok = mgr_register_user(ManagerNode, user_alfa, snmpm_user_default, []),
1895    ?line ok = mgr_register_user(ManagerNode, user_beta, snmpm_user_default, []),
1896    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1897
1898    ?IPRINT("register agent(s)"),
1899    TargetName1 = "agent1",
1900    ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName1,
1901				  [{address,   LocalHost},
1902				   {port,      5001},
1903				   {engine_id, "agentEngineId-1"}]),
1904    TargetName2 = "agent2",
1905    ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName2,
1906				  [{address,   LocalHost},
1907				   {port,      5002},
1908				   {engine_id, "agentEngineId-2"}]),
1909    TargetName3 = "agent3",
1910    ?line ok = mgr_register_agent(ManagerNode, user_beta, TargetName3,
1911				  [{address,   LocalHost},
1912				   {port,      5003},
1913				   {engine_id, "agentEngineId-3"}]),
1914    TargetName4 = "agent4",
1915    ?line ok = mgr_register_agent(ManagerNode, user_beta, TargetName4,
1916				  [{address,   LocalHost},
1917				   {port,      5004},
1918				   {engine_id, "agentEngineId-4"}]),
1919
1920    ?IPRINT("verify all agent(s): expect 4"),
1921    case mgr_which_agents(ManagerNode) of
1922	Agents1 when length(Agents1) =:= 4 ->
1923	    ?IPRINT("all agents: ~p~n", [Agents1]),
1924	    ok;
1925	Agents1 ->
1926	    ?FAIL({agent_registration_failure, Agents1})
1927    end,
1928
1929    ?IPRINT("verify user_alfa agent(s)"),
1930    case mgr_which_agents(ManagerNode, user_alfa) of
1931	Agents2 when length(Agents2) =:= 2 ->
1932	    ?IPRINT("calvin agents: ~p~n", [Agents2]),
1933	    ok;
1934	Agents2 ->
1935	    ?FAIL({agent_registration_failure, Agents2})
1936    end,
1937
1938    ?IPRINT("verify user_beta agent(s)"),
1939    case mgr_which_agents(ManagerNode, user_beta) of
1940	Agents3 when length(Agents3) =:= 2 ->
1941	    ?IPRINT("hobbe agents: ~p~n", [Agents3]),
1942	    ok;
1943	Agents3 ->
1944	    ?FAIL({agent_registration_failure, Agents3})
1945    end,
1946
1947    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1948
1949    ?IPRINT("unregister user user_alfa"),
1950    ?line ok = mgr_unregister_user(ManagerNode, user_alfa),
1951
1952    ?IPRINT("verify all agent(s): expect 2"),
1953    case mgr_which_agents(ManagerNode) of
1954	Agents4 when length(Agents4) =:= 2 ->
1955	    ?IPRINT("all agents: ~p~n", [Agents4]),
1956	    ok;
1957	Agents4 ->
1958	    ?FAIL({agent_unregistration_failure, Agents4})
1959    end,
1960    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1961
1962    ?IPRINT("unregister user_beta agents"),
1963    ?line ok = mgr_unregister_agent(ManagerNode, user_beta, TargetName3),
1964    ?line ok = mgr_unregister_agent(ManagerNode, user_beta, TargetName4),
1965
1966    ?IPRINT("verify all agent(s): expect 0"),
1967    case mgr_which_agents(ManagerNode) of
1968	[] ->
1969	    ok;
1970	Agents5 ->
1971	    ?IPRINT("all agents: ~p~n", [Agents5]),
1972	    ?FAIL({agent_unregistration_failure, Agents5})
1973    end,
1974
1975    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1976
1977    ?IPRINT("unregister user user_beta"),
1978    ?line ok = mgr_unregister_user(ManagerNode, user_beta),
1979
1980    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
1981
1982    ?SLEEP(1000),
1983
1984    ?IPRINT("stop snmp application (with only manager)"),
1985    ?line ok = stop_snmp(ManagerNode),
1986
1987    ?SLEEP(1000),
1988
1989    ok.
1990
1991
1992%%======================================================================
1993
1994register_agent3(doc) ->
1995    ["Test registration of agents with the NEW interface functions "
1996     "and specifying transport domain"];
1997register_agent3(suite) ->
1998    [];
1999register_agent3(Config) when is_list(Config) ->
2000    Pre  = fun() ->
2001                   ManagerNode = start_manager_node(),
2002                   [ManagerNode]
2003           end,
2004    Case = fun(State) -> do_register_agent3(State, Config) end,
2005    Post = fun([ManagerNode]) -> stop_node(ManagerNode) end,
2006    ?TC_TRY(register_agent3, Pre, Case, Post).
2007
2008do_register_agent3([ManagerNode], Config) ->
2009    ?IPRINT("starting with Config: "
2010            "~n      ~p", [Config]),
2011
2012    ConfDir   = ?config(manager_conf_dir, Config),
2013    DbDir     = ?config(manager_db_dir, Config),
2014    LocalHost = snmp_test_lib:localhost(),
2015
2016
2017    write_manager_conf(ConfDir),
2018
2019    Opts = [{server,     [{verbosity, trace}]},
2020	    {net_if,     [{verbosity, trace}]},
2021	    {note_store, [{verbosity, trace}]},
2022	    {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],
2023
2024
2025    ?IPRINT("load snmp application"),
2026    ?line ok = load_snmp(ManagerNode),
2027
2028    ?IPRINT("set manager env for the snmp application"),
2029    ?line ok = set_mgr_env(ManagerNode, Opts),
2030
2031    ?IPRINT("starting snmp application (with only manager)"),
2032    ?line ok = start_snmp(ManagerNode),
2033
2034    ?IPRINT("started"),
2035
2036    ?SLEEP(1000),
2037
2038    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
2039
2040    ?IPRINT("register user(s) user_alfa & user_beta"),
2041    ?line ok = mgr_register_user(ManagerNode, user_alfa, snmpm_user_default, []),
2042    ?line ok = mgr_register_user(ManagerNode, user_beta, snmpm_user_default, []),
2043    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
2044
2045    ?IPRINT("register agent(s)"),
2046    TargetName1 = "agent2",
2047    ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName1,
2048				  [{tdomain,   transportDomainUdpIpv4},
2049				   {address,   LocalHost},
2050				   {port,      5001},
2051				   {engine_id, "agentEngineId-1"}]),
2052    TargetName2 = "agent3",
2053    ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName2,
2054				  [{tdomain,   transportDomainUdpIpv6},
2055				   {address,   {0,0,0,0,0,0,0,1}},
2056				   {port,      5002},
2057				   {engine_id, "agentEngineId-2"}]),
2058    TargetName3 = "agent4",
2059    ?line {error, {unsupported_domain, _} = Reason4} =
2060	mgr_register_agent(ManagerNode, user_beta, TargetName3,
2061			   [{tdomain,   transportDomainTcpIpv4},
2062			    {address,   LocalHost},
2063			    {port,      5003},
2064			    {engine_id, "agentEngineId-3"}]),
2065    ?IPRINT("Expected registration failure: ~p", [Reason4]),
2066    TargetName4 = "agent5",
2067    ?line {error, {unknown_domain, _} = Reason5} =
2068	mgr_register_agent(ManagerNode, user_beta, TargetName4,
2069			   [{tdomain,   transportDomainUdpIpv4_bad},
2070			    {address,   LocalHost},
2071			    {port,      5004},
2072			    {engine_id, "agentEngineId-4"}]),
2073    ?IPRINT("Expected registration failure: ~p", [Reason5]),
2074
2075    ?IPRINT("verify all agent(s): expect 2"),
2076    case mgr_which_agents(ManagerNode) of
2077	Agents1 when length(Agents1) =:= 2 ->
2078	    ?IPRINT("all agents: ~p~n", [Agents1]),
2079	    ok;
2080	Agents1 ->
2081	    ?FAIL({agent_registration_failure, Agents1})
2082    end,
2083
2084    ?IPRINT("verify user_alfa agent(s)"),
2085    case mgr_which_agents(ManagerNode, user_alfa) of
2086	Agents2 when length(Agents2) =:= 2 ->
2087	    ?IPRINT("calvin agents: ~p~n", [Agents2]),
2088	    ok;
2089	Agents2 ->
2090	    ?FAIL({agent_registration_failure, Agents2})
2091    end,
2092
2093    ?IPRINT("verify user_beta agent(s)"),
2094    case mgr_which_agents(ManagerNode, user_beta) of
2095	Agents3 when length(Agents3) =:= 0 ->
2096	    ?IPRINT("hobbe agents: ~p~n", [Agents3]),
2097	    ok;
2098	Agents3 ->
2099	    ?FAIL({agent_registration_failure, Agents3})
2100    end,
2101
2102    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
2103
2104    ?IPRINT("unregister user user_alfa"),
2105    ?line ok = mgr_unregister_user(ManagerNode, user_alfa),
2106
2107    ?IPRINT("verify all agent(s): expect 0"),
2108    case mgr_which_agents(ManagerNode) of
2109	Agents4 when length(Agents4) =:= 0 ->
2110	    ?IPRINT("all agents: ~p~n", [Agents4]),
2111	    ok;
2112	Agents4 ->
2113	    ?FAIL({agent_unregistration_failure, Agents4})
2114    end,
2115    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
2116
2117    ?IPRINT("verify all agent(s): expect 0"),
2118    case mgr_which_agents(ManagerNode) of
2119	[] ->
2120	    ok;
2121	Agents5 ->
2122	    ?EPRINT("all agents: ~p~n", [Agents5]),
2123	    ?FAIL({agent_unregistration_failure, Agents5})
2124    end,
2125
2126    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
2127
2128    ?IPRINT("unregister user user_beta"),
2129    ?line ok = mgr_unregister_user(ManagerNode, user_beta),
2130
2131    ?IPRINT("manager info: ~p~n", [mgr_info(ManagerNode)]),
2132
2133    ?SLEEP(1000),
2134
2135    ?IPRINT("stop snmp application (with only manager)"),
2136    ?line ok = stop_snmp(ManagerNode),
2137
2138    ?SLEEP(1000),
2139
2140    ok.
2141
2142
2143%%======================================================================
2144
2145simple_sync_get2(doc) ->
2146    ["Simple sync get-request - Version 2 API (TargetName)"];
2147simple_sync_get2(suite) -> [];
2148simple_sync_get2(Config) when is_list(Config) ->
2149    ?TC_TRY(simple_sync_get2,
2150            fun() -> do_simple_sync_get2(Config) end).
2151
2152do_simple_sync_get2(Config) ->
2153    ?IPRINT("starting with Config: "
2154            "~n      ~p", [Config]),
2155    Get = fun(Node, TargetName, Oids) ->
2156		  mgr_user_sync_get(Node, TargetName, Oids)
2157	  end,
2158    PostVerify = fun() -> ok end,
2159    Res = do_simple_sync_get2(Config, Get, PostVerify),
2160    display_log(Config),
2161    Res.
2162
2163do_simple_sync_get2(Config, Get, PostVerify) ->
2164    ?IPRINT("starting with Config: "
2165            "~n      ~p", [Config]),
2166
2167    Node       = ?config(manager_node, Config),
2168    TargetName = ?config(manager_agent_target_name, Config),
2169
2170    ?IPRINT("issue get-request without loading the mib"),
2171    Oids1 = [?sysObjectID_instance, ?sysDescr_instance, ?sysUpTime_instance],
2172    ?line ok = do_simple_sync_get2(Node, TargetName, Oids1, Get, PostVerify),
2173
2174    ?IPRINT("issue get-request after first loading the mibs"),
2175    ?line ok = mgr_user_load_mib(Node, std_mib()),
2176    Oids2 = [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
2177    ?line ok = do_simple_sync_get2(Node, TargetName, Oids2, Get, PostVerify),
2178    ok.
2179
2180do_simple_sync_get2(Node, TargetName, Oids, Get, PostVerify)
2181  when is_function(Get, 3) andalso is_function(PostVerify, 0) ->
2182    ?line {ok, Reply, _Rem} = Get(Node, TargetName, Oids),
2183
2184    ?DBG("~n   Reply: ~p"
2185	 "~n   Rem:   ~w", [Reply, _Rem]),
2186
2187    %% verify that the operation actually worked:
2188    %% The order should be the same, so no need to search
2189    ?line ok = case Reply of
2190		   {noError, 0, [#varbind{oid   = ?sysObjectID_instance,
2191					  value = SysObjectID},
2192				 #varbind{oid   = ?sysDescr_instance,
2193					  value = SysDescr},
2194				 #varbind{oid   = ?sysUpTime_instance,
2195					  value = SysUpTime}]} ->
2196		       ?IPRINT("expected result from get: "
2197                               "~n   SysObjectID: ~p"
2198                               "~n   SysDescr:    ~s"
2199                               "~n   SysUpTime:   ~w",
2200                               [SysObjectID, SysDescr, SysUpTime]),
2201		       PostVerify();
2202		   {noError, 0, Vbs} ->
2203		       ?EPRINT("unexpected varbinds: "
2204                               "~n      ~p", [Vbs]),
2205		       {error, {unexpected_vbs, Vbs}};
2206		   Else ->
2207		       ?EPRINT("unexpected reply: "
2208                               "~n      ~p", [Else]),
2209		       {error, {unexpected_response, Else}}
2210	       end,
2211    ok.
2212
2213
2214%%======================================================================
2215
2216simple_sync_get3(doc) ->
2217    ["Simple sync get-request - Version 3 API (TargetName and send-opts)"];
2218simple_sync_get3(suite) -> [];
2219simple_sync_get3(Config) when is_list(Config) ->
2220    ?TC_TRY(simple_sync_get3,
2221            fun() -> do_simple_sync_get3(Config) end).
2222
2223do_simple_sync_get3(Config) ->
2224    ?IPRINT("starting with Config: "
2225            "~n      ~p", [Config]),
2226    Self  = self(),
2227    Msg   = simple_sync_get3,
2228    Fun   = fun() -> Self ! Msg end,
2229    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
2230    SendOpts =
2231	[
2232	 {extra, Extra}
2233	],
2234    Get = fun(Node, TargetName, Oids) ->
2235		  mgr_user_sync_get2(Node, TargetName, Oids, SendOpts)
2236	  end,
2237    PostVerify =
2238	fun() ->
2239		receive
2240		    Msg ->
2241			ok
2242		end
2243	end,
2244    Res = do_simple_sync_get2(Config, Get, PostVerify),
2245    display_log(Config),
2246    Res.
2247
2248
2249
2250
2251%%======================================================================
2252
2253sag_verify({noError, 0, _Vbs}, any) ->
2254    ?IPRINT("verified [any]"),
2255    ok;
2256sag_verify({noError, 0, Vbs}, Exp) ->
2257    ?DBG("verified first stage ok: "
2258	 "~n   Vbs: ~p"
2259	 "~n   Exp: ~p", [Vbs, Exp]),
2260    sag_verify_vbs(Vbs, Exp);
2261sag_verify(Error, _) ->
2262    {error, {unexpected_response, Error}}.
2263
2264sag_verify_vbs([], []) ->
2265    ?DBG("verified second stage ok", []),
2266    ok;
2267sag_verify_vbs(Vbs, []) ->
2268    {error, {unexpected_vbs, Vbs}};
2269sag_verify_vbs([], Exp) ->
2270    {error, {expected_vbs, Exp}};
2271sag_verify_vbs([#varbind{oid = Oid}|Vbs], [any|Exp]) ->
2272    ?IPRINT("verified [any] oid ~w", [Oid]),
2273    sag_verify_vbs(Vbs, Exp);
2274sag_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [Oid|Exp]) ->
2275    ?IPRINT("verified oid ~w [~p]", [Oid, Value]),
2276    sag_verify_vbs(Vbs, Exp);
2277sag_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [{Oid,Value}|Exp]) ->
2278    ?IPRINT("verified oid ~w and ~p", [Oid, Value]),
2279    sag_verify_vbs(Vbs, Exp);
2280sag_verify_vbs([Vb|_], [E|_]) ->
2281    {error, {unexpected_vb, Vb, E}}.
2282
2283
2284%%======================================================================
2285
2286simple_async_get2(doc) ->
2287    ["Simple (async) get-request - Version 2 API (TargetName)"];
2288simple_async_get2(suite) -> [];
2289simple_async_get2(Config) when is_list(Config) ->
2290    ?TC_TRY(simple_async_get2,
2291            fun() -> do_simple_async_get2(Config) end).
2292
2293do_simple_async_get2(Config) ->
2294    ?IPRINT("starting with Config: "
2295            "~n      ~p", [Config]),
2296    MgrNode    = ?config(manager_node, Config),
2297    AgentNode  = ?config(agent_node, Config),
2298    TargetName = ?config(manager_agent_target_name, Config),
2299    Get        = fun(Oids) -> async_g_exec2(MgrNode, TargetName, Oids) end,
2300    PostVerify = fun(Res) -> Res end,
2301    do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify),
2302    display_log(Config),
2303    ok.
2304
2305do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify) ->
2306    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
2307    Test2Mib = test2_mib(Config),
2308    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
2309    ?line ok = agent_load_mib(AgentNode, Test2Mib),
2310    do_simple_async_sync_get2(fun() -> mgr_info(MgrNode) end,
2311			      fun() -> agent_info(AgentNode) end,
2312			      Get, PostVerify).
2313
2314do_simple_async_sync_get2(MgrInfo, AgentInfo, Get, PostVerify)
2315  when is_function(MgrInfo, 0) andalso
2316       is_function(AgentInfo, 0) andalso
2317       is_function(Get, 1) andalso
2318       is_function(PostVerify, 1) ->
2319    Requests =
2320	[
2321	 { 1,
2322	   [?sysObjectID_instance],
2323	   Get,
2324	   fun(X) ->
2325		   PostVerify(sag_verify(X, [?sysObjectID_instance])) end},
2326	 { 2,
2327	   [?sysDescr_instance, ?sysUpTime_instance],
2328	   Get,
2329	   fun(X) ->
2330		   PostVerify(sag_verify(X, [?sysObjectID_instance,
2331					     ?sysUpTime_instance]))
2332	   end},
2333	 { 3,
2334	   [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
2335	   Get,
2336	   fun(X) ->
2337		   PostVerify(sag_verify(X, [?sysObjectID_instance,
2338					     ?sysDescr_instance,
2339					     ?sysUpTime_instance]))
2340
2341	   end},
2342	 { 4,
2343	   [?sysObjectID_instance,
2344	    ?sysDescr_instance,
2345	    ?sysUpTime_instance],
2346	   Get,
2347	   fun(X) ->
2348		   PostVerify(sag_verify(X, [?sysObjectID_instance,
2349					     ?sysDescr_instance,
2350					     ?sysUpTime_instance]))
2351	   end}
2352	],
2353
2354    ?IPRINT("manager info when starting test: "
2355            "~n      ~p", [MgrInfo()]),
2356    ?IPRINT("agent info when starting test: "
2357            "~n      ~p",   [AgentInfo()]),
2358
2359    ?line ok = async_exec(Requests, []),
2360
2361    ?IPRINT("manager info when ending test: "
2362            "~n      ~p", [MgrInfo()]),
2363    ?IPRINT("agent info when ending test: "
2364            "~n      ~p",   [AgentInfo()]),
2365
2366    ok.
2367
2368async_g_exec2(Node, TargetName, Oids) ->
2369    mgr_user_async_get(Node, TargetName, Oids).
2370
2371
2372%%======================================================================
2373
2374simple_async_get3(doc) ->
2375    ["Simple (async) get-request - Version 3 API (TargetName and send-opts)"];
2376simple_async_get3(suite) -> [];
2377simple_async_get3(Config) when is_list(Config) ->
2378    ?TC_TRY(simple_async_get3,
2379            fun() -> do_simple_async_get3(Config) end).
2380
2381do_simple_async_get3(Config) ->
2382    ?IPRINT("starting with Config: "
2383            "~n      ~p", [Config]),
2384    MgrNode    = ?config(manager_node, Config),
2385    AgentNode  = ?config(agent_node, Config),
2386    TargetName = ?config(manager_agent_target_name, Config),
2387    Self  = self(),
2388    Msg   = simple_async_get3,
2389    Fun   = fun() -> Self ! Msg end,
2390    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
2391    SendOpts =
2392	[
2393	 {extra, Extra}
2394	],
2395    Get = fun(Oids) -> async_g_exec3(MgrNode, TargetName, Oids, SendOpts) end,
2396    PostVerify = fun(ok)    -> receive Msg -> ok end;
2397		    (Error) -> Error
2398		 end,
2399    Res = do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify),
2400    display_log(Config),
2401    Res.
2402
2403async_g_exec3(Node, TargetName, Oids, SendOpts) ->
2404    mgr_user_async_get2(Node, TargetName, Oids, SendOpts).
2405
2406
2407%%======================================================================
2408
2409verify_ssgn_reply1({noError, 0, _Vbs}, any) ->
2410    ok;
2411verify_ssgn_reply1({noError, 0, Vbs}, Expected) ->
2412    check_ssgn_vbs(Vbs, Expected);
2413verify_ssgn_reply1(R, _) ->
2414    {error, {unexpected_reply, R}}.
2415
2416verify_ssgn_reply2({ErrStatus, ErrIdx, _Vbs}, {ErrStatus, ErrIdx, any}) ->
2417    ok;
2418verify_ssgn_reply2({ErrStatus, ErrIdx, Vbs}, {ErrStatus, ErrIdx, Expected}) ->
2419    check_ssgn_vbs(Vbs, Expected);
2420verify_ssgn_reply2(R, _) ->
2421    {error, {unexpected_reply, R}}.
2422
2423check_ssgn_vbs([], []) ->
2424    ok;
2425check_ssgn_vbs(Unexpected, []) ->
2426    {error, {unexpected_vbs, Unexpected}};
2427check_ssgn_vbs([], Expected) ->
2428    {error, {expected_vbs, Expected}};
2429check_ssgn_vbs([#varbind{value = endOfMibView}|R],
2430	       [endOfMibView|Expected]) ->
2431    check_ssgn_vbs(R, Expected);
2432check_ssgn_vbs([#varbind{oid = Oid}|R], [Oid|Expected]) ->
2433    check_ssgn_vbs(R, Expected);
2434check_ssgn_vbs([#varbind{oid = Oid, value = Value}|R],
2435	       [{Oid, Value}|Expected]) ->
2436    check_ssgn_vbs(R, Expected);
2437check_ssgn_vbs([Vb|_], [E|_]) ->
2438    {error, {unexpected_vb, Vb, E}}.
2439
2440
2441%%======================================================================
2442
2443simple_sync_get_next2(doc) ->
2444    ["Simple (sync) get_next-request - Version 2 API (TargetName)"];
2445simple_sync_get_next2(suite) -> [];
2446simple_sync_get_next2(Config) when is_list(Config) ->
2447    ?TC_TRY(simple_sync_get_next2,
2448            fun() -> do_simple_sync_get_next2(Config) end).
2449
2450do_simple_sync_get_next2(Config) ->
2451    ?IPRINT("starting with Config: "
2452            "~n      ~p", [Config]),
2453
2454    GetNext = fun(Node, TargetName, Oids) ->
2455		      mgr_user_sync_get_next(Node, TargetName, Oids)
2456	      end,
2457    PostVerify = fun(Res) -> Res end,
2458    Res = do_simple_sync_get_next2(Config, GetNext, PostVerify),
2459    display_log(Config),
2460    Res.
2461
2462
2463do_simple_sync_get_next2(Config, GetNext, PostVerify)
2464  when is_function(GetNext, 3) andalso is_function(PostVerify, 1) ->
2465
2466    MgrNode    = ?config(manager_node, Config),
2467    AgentNode  = ?config(agent_node, Config),
2468    TargetName = ?config(manager_agent_target_name, Config),
2469
2470    %% -- 1 --
2471    Oids01 = [[1,3,7,1]],
2472    VF01   = fun(X) -> verify_ssgn_reply1(X, [{[1,3,7,1],endOfMibView}]) end,
2473    ?line ok = do_simple_get_next(1,
2474				  MgrNode, TargetName, Oids01, VF01,
2475				  GetNext, PostVerify),
2476
2477    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
2478
2479    %% -- 2 --
2480    Oids02 = [[sysDescr], [1,3,7,1]],
2481    VF02   = fun(X) ->
2482		     verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView])
2483	     end,
2484    ?line ok = do_simple_get_next(2,
2485				  MgrNode, TargetName, Oids02, VF02,
2486				  GetNext, PostVerify),
2487
2488    Test2Mib = test2_mib(Config),
2489    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
2490    ?line ok = agent_load_mib(AgentNode, Test2Mib),
2491
2492    %% -- 3 --
2493    ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),
2494    Oids03 = [[TCnt2, 1]],
2495    VF03   = fun(X) ->
2496		     verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}])
2497	     end,
2498    ?line ok = do_simple_get_next(3,
2499				  MgrNode, TargetName, Oids03, VF03,
2500				  GetNext, PostVerify),
2501
2502    %% -- 4 --
2503    Oids04 = [[TCnt2, 2]],
2504    VF04   = fun(X) ->
2505		     verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}])
2506	     end,
2507    ?line ok = do_simple_get_next(4,
2508				  MgrNode, TargetName, Oids04, VF04,
2509				  GetNext, PostVerify),
2510
2511    %% -- 5 --
2512    ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),
2513    Oids05 = [TGenErr1],
2514    VF05   = fun(X) ->
2515		     verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]})
2516	     end,
2517    ?line ok = do_simple_get_next(5,
2518				  MgrNode, TargetName, Oids05, VF05,
2519				  GetNext, PostVerify),
2520
2521    %% -- 6 --
2522    ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),
2523    Oids06 = [TGenErr2],
2524    VF06   = fun(X) ->
2525		     verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]})
2526	     end,
2527    ?line ok = do_simple_get_next(6,
2528				  MgrNode, TargetName, Oids06, VF06,
2529				  GetNext, PostVerify),
2530
2531    %% -- 7 --
2532    ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),
2533    Oids07 = [[sysDescr], TGenErr3],
2534    VF07   = fun(X) ->
2535		     verify_ssgn_reply2(X, {genErr, 2,
2536					   [?sysDescr, TGenErr3]})
2537	     end,
2538    ?line ok = do_simple_get_next(7,
2539				  MgrNode, TargetName, Oids07, VF07,
2540				  GetNext, PostVerify),
2541
2542    %% -- 8 --
2543    ?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),
2544    Oids08 = [TTooBig],
2545    VF08   = fun(X) ->
2546		     verify_ssgn_reply2(X, {tooBig, 0, []})
2547	     end,
2548    ?line ok = do_simple_get_next(8,
2549				  MgrNode, TargetName, Oids08, VF08,
2550				  GetNext, PostVerify),
2551    ok.
2552
2553
2554do_simple_get_next(N, Node, TargetName, Oids, Verify, GetNext, PostVerify) ->
2555    ?IPRINT("issue get-next command ~w", [N]),
2556    case GetNext(Node, TargetName, Oids) of
2557	{ok, Reply, _Rem} ->
2558	    ?DBG("get-next ok:"
2559		 "~n   Reply: ~p"
2560		 "~n   Rem:   ~w", [Reply, _Rem]),
2561	    PostVerify(Verify(Reply));
2562
2563	Error ->
2564	    {error, {unexpected_reply, Error}}
2565    end.
2566
2567
2568%%======================================================================
2569
2570simple_sync_get_next3(doc) ->
2571    ["Simple (sync) get_next-request - "
2572     "Version 3 API (TargetName with send-opts)"];
2573simple_sync_get_next3(suite) -> [];
2574simple_sync_get_next3(Config) when is_list(Config) ->
2575    process_flag(trap_exit, true),
2576    put(tname, ssgn3),
2577    ?IPRINT("starting with Config: "
2578            "~n      ~p", [Config]),
2579    Self  = self(),
2580    Msg   = simple_sync_get_next3,
2581    Fun   = fun() -> Self ! Msg end,
2582    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
2583    SendOpts =
2584	[
2585	 {extra, Extra}
2586	],
2587    GetNext = fun(Node, TargetName, Oids) ->
2588		      mgr_user_sync_get_next2(Node, TargetName, Oids, SendOpts)
2589	      end,
2590    PostVerify = fun(ok)    -> receive Msg -> ok end;
2591		    (Error) -> Error
2592		 end,
2593    do_simple_sync_get_next2(Config, GetNext, PostVerify),
2594    display_log(Config),
2595    ok.
2596
2597
2598%%======================================================================
2599
2600simple_async_get_next2(doc) ->
2601    ["Simple (async) get_next-request - Version 2 API (TargetName)"];
2602simple_async_get_next2(suite) -> [];
2603simple_async_get_next2(Config) when is_list(Config) ->
2604    ?TC_TRY(simple_async_get_next2,
2605            fun() -> do_simple_async_get_next2(Config) end).
2606
2607do_simple_async_get_next2(Config) ->
2608    ?IPRINT("starting with Config: "
2609            "~n      ~p", [Config]),
2610
2611    MgrNode    = ?config(manager_node, Config),
2612    AgentNode  = ?config(agent_node, Config),
2613    TargetName = ?config(manager_agent_target_name, Config),
2614
2615    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
2616    Test2Mib = test2_mib(Config),
2617    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
2618    ?line ok = agent_load_mib(AgentNode, Test2Mib),
2619    GetNext = fun(Oids) ->
2620		      async_gn_exec2(MgrNode, TargetName, Oids)
2621	      end,
2622    PostVerify = fun(Res) -> Res end,
2623    Res = do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify),
2624    display_log(Config),
2625    Res.
2626
2627do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify)
2628  when is_function(GetNext, 1) andalso is_function(PostVerify, 1) ->
2629    ?line {ok, [TCnt2|_]}    = mgr_user_name_to_oid(MgrNode, tCnt2),
2630    ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),
2631    ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),
2632    ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),
2633    ?line {ok, [TTooBig|_]}  = mgr_user_name_to_oid(MgrNode, tTooBig),
2634
2635    Requests =
2636	[
2637	 {1,
2638	  [[1,3,7,1]],
2639	  GetNext,
2640	  fun(X) ->
2641		  PostVerify(
2642		    verify_ssgn_reply1(X, [{[1,3,7,1], endOfMibView}]))
2643
2644	  end},
2645	 {2,
2646	  [[sysDescr], [1,3,7,1]],
2647	  GetNext,
2648	  fun(X) ->
2649		  PostVerify(
2650		    verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView]))
2651	  end},
2652	 {3,
2653	  [[TCnt2, 1]],
2654	  GetNext,
2655	  fun(X) ->
2656		  PostVerify(
2657		    verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}]))
2658	  end},
2659	 {4,
2660	  [[TCnt2, 2]],
2661	  GetNext,
2662	  fun(X) ->
2663		  PostVerify(
2664		    verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}]))
2665	  end},
2666	 {5,
2667	  [TGenErr1],
2668	  GetNext,
2669	  fun(X) ->
2670		  PostVerify(
2671		    verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}))
2672	  end},
2673	 {6,
2674	  [TGenErr2],
2675	  GetNext,
2676	  fun(X) ->
2677		  PostVerify(
2678		    verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}))
2679	  end},
2680	 {7,
2681	  [[sysDescr], TGenErr3],
2682	  GetNext,
2683	  fun(X) ->
2684		  PostVerify(
2685		    verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]}))
2686	  end},
2687	 {8,
2688	  [TTooBig],
2689	  GetNext,
2690	  fun(X) ->
2691		  PostVerify(
2692		    verify_ssgn_reply2(X, {tooBig, 0, []}))
2693	  end}
2694	],
2695
2696    ?IPRINT("manager info when starting test: "
2697            "~n      ~p", [mgr_info(MgrNode)]),
2698    ?IPRINT("agent info when starting test: "
2699            "~n      ~p", [agent_info(AgentNode)]),
2700
2701    ?line ok = async_exec(Requests, []),
2702
2703    ?IPRINT("manager info when ending test: "
2704            "~n      ~p", [mgr_info(MgrNode)]),
2705    ?IPRINT("agent info when ending test: "
2706            "~n      ~p", [agent_info(AgentNode)]),
2707
2708    ok.
2709
2710
2711async_gn_exec2(Node, TargetName, Oids) ->
2712    mgr_user_async_get_next(Node, TargetName, Oids).
2713
2714
2715%%======================================================================
2716
2717simple_async_get_next3_cbp_def(doc) ->
2718    ["Simple (async) get_next-request - "
2719     "Version 3 API (TargetName with send-opts)"];
2720simple_async_get_next3_cbp_def(suite) -> [];
2721simple_async_get_next3_cbp_def(Config) when is_list(Config) ->
2722    simple_async_get_next3(ssgn2_cbp_def, Config).
2723
2724simple_async_get_next3_cbp_temp(doc) ->
2725    ["Simple (async) get_next-request - "
2726     "Version 3 API (TargetName with send-opts)"];
2727simple_async_get_next3_cbp_temp(suite) -> [];
2728simple_async_get_next3_cbp_temp(Config) when is_list(Config) ->
2729    simple_async_get_next3(ssgn2_cbp_temp, Config).
2730
2731simple_async_get_next3_cbp_perm(doc) ->
2732    ["Simple (async) get_next-request - "
2733     "Version 3 API (TargetName with send-opts)"];
2734simple_async_get_next3_cbp_perm(suite) -> [];
2735simple_async_get_next3_cbp_perm(Config) when is_list(Config) ->
2736    simple_async_get_next3(ssgn2_cbp_perm, Config).
2737
2738simple_async_get_next3(Case, Config) when is_list(Config) ->
2739    ?TC_TRY(Case,
2740            fun() -> do_simple_async_get_next3(Config) end).
2741
2742do_simple_async_get_next3(Config) ->
2743    %% process_flag(trap_exit, true),
2744    ?IPRINT("starting with Config: "
2745            "~n      ~p", [Config]),
2746
2747    MgrNode    = ?config(manager_node, Config),
2748    AgentNode  = ?config(agent_node, Config),
2749    TargetName = ?config(manager_agent_target_name, Config),
2750
2751    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
2752    Test2Mib = test2_mib(Config),
2753    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
2754    ?line ok = agent_load_mib(AgentNode, Test2Mib),
2755
2756    Self  = self(),
2757    Msg   = simple_async_get_next3,
2758    Fun   = fun() -> Self ! Msg end,
2759    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
2760    SendOpts =
2761	[
2762	 {extra, Extra}
2763	],
2764
2765    GetNext = fun(Oids) ->
2766		      async_gn_exec3(MgrNode, TargetName, Oids, SendOpts)
2767	      end,
2768    PostVerify = fun(ok)    -> receive Msg -> ok end;
2769		    (Error) -> Error
2770		 end,
2771
2772    Res = do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify),
2773    display_log(Config),
2774    Res.
2775
2776async_gn_exec3(Node, TargetName, Oids, SendOpts) ->
2777    mgr_user_async_get_next2(Node, TargetName, Oids, SendOpts).
2778
2779
2780%%======================================================================
2781
2782value_of_vavs(VAVs) ->
2783    value_of_vavs(VAVs, []).
2784
2785value_of_vavs([], Acc) ->
2786    lists:reverse(Acc);
2787value_of_vavs([{_Oid, _Type, Val}|VAVs], Acc) ->
2788    value_of_vavs(VAVs, [Val|Acc]);
2789value_of_vavs([{_Oid, Val}|VAVs], Acc) ->
2790    value_of_vavs(VAVs, [Val|Acc]).
2791
2792
2793%%======================================================================
2794
2795simple_sync_set2(doc) ->
2796    ["Simple (sync) set-request - Version 2 API (TargetName)"];
2797simple_sync_set2(suite) -> [];
2798simple_sync_set2(Config) when is_list(Config) ->
2799    ?TC_TRY(simple_sync_set2,
2800            fun() -> do_simple_sync_set2(Config) end).
2801
2802do_simple_sync_set2(Config) ->
2803    ?IPRINT("starting with Config: "
2804            "~n      ~p", [Config]),
2805
2806    Set = fun(Node, TargetName, VAVs) ->
2807		  mgr_user_sync_set(Node, TargetName, VAVs)
2808	  end,
2809    PostVerify = fun() -> ok end,
2810
2811    Res = do_simple_sync_set2(Config, Set, PostVerify),
2812    display_log(Config),
2813    Res.
2814
2815do_simple_sync_set2(Config, Set, PostVerify)
2816  when is_function(Set, 3) andalso is_function(PostVerify, 0) ->
2817
2818    Node       = ?config(manager_node, Config),
2819    TargetName = ?config(manager_agent_target_name, Config),
2820
2821    ?IPRINT("issue set-request without loading the mib"),
2822    Val11 = "Arne Anka",
2823    Val12 = "Stockholm",
2824    VAVs1 = [
2825	     {?sysName_instance,     s, Val11},
2826	     {?sysLocation_instance, s, Val12}
2827	    ],
2828    ?line ok = do_simple_set2(Node, TargetName, VAVs1, Set, PostVerify),
2829
2830    ?IPRINT("issue set-request after first loading the mibs"),
2831    ?line ok = mgr_user_load_mib(Node, std_mib()),
2832    Val21 = "Sune Anka",
2833    Val22 = "Gothenburg",
2834    VAVs2 = [
2835	     {[sysName, 0],     Val21},
2836	     {[sysLocation, 0], Val22}
2837	    ],
2838    ?line ok = do_simple_set2(Node, TargetName, VAVs2, Set, PostVerify),
2839    ok.
2840
2841do_simple_set2(Node, TargetName, VAVs, Set, PostVerify) ->
2842    [SysName, SysLoc] = value_of_vavs(VAVs),
2843    ?line {ok, Reply, _Rem} = Set(Node, TargetName, VAVs),
2844
2845    ?DBG("~n   Reply: ~p"
2846	 "~n   Rem:   ~w", [Reply, _Rem]),
2847
2848    %% verify that the operation actually worked:
2849    %% The order should be the same, so no need to search
2850    %% The value we get should be exactly the same as we sent
2851    ?line ok = case Reply of
2852		   {noError, 0, [#varbind{oid   = ?sysName_instance,
2853					  value = SysName},
2854				 #varbind{oid   = ?sysLocation_instance,
2855					  value = SysLoc}]} ->
2856		       PostVerify();
2857		   {noError, 0, Vbs} ->
2858		       {error, {unexpected_vbs, Vbs}};
2859		   Else ->
2860		       ?EPRINT("unexpected reply: "
2861                               "~n      ~p", [Else]),
2862		       {error, {unexpected_response, Else}}
2863	       end,
2864    ok.
2865
2866
2867%%======================================================================
2868
2869simple_sync_set3(doc) ->
2870    ["Simple (sync) set-request - Version 3 API (TargetName with send-opts)"];
2871simple_sync_set3(suite) -> [];
2872simple_sync_set3(Config) when is_list(Config) ->
2873    ?TC_TRY(simple_sync_set3,
2874            fun() -> do_simple_sync_set3(Config) end).
2875
2876do_simple_sync_set3(Config) ->
2877    ?IPRINT("starting with Config: "
2878            "~n      ~p", [Config]),
2879
2880    Self  = self(),
2881    Msg   = simple_sync_set3,
2882    Fun   = fun() -> Self ! Msg end,
2883    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
2884    SendOpts =
2885	[
2886	 {extra, Extra}
2887	],
2888
2889    Set = fun(Node, TargetName, VAVs) ->
2890		  mgr_user_sync_set2(Node, TargetName, VAVs, SendOpts)
2891	  end,
2892    PostVerify = fun() -> receive Msg -> ok end end,
2893
2894    Res = do_simple_sync_set2(Config, Set, PostVerify),
2895    display_log(Config),
2896    Res.
2897
2898
2899%%======================================================================
2900
2901sas_verify({noError, 0, _Vbs}, any) ->
2902    ?IPRINT("verified [any]"),
2903    ok;
2904sas_verify({noError, 0, Vbs}, Expected) ->
2905    ?DBG("verified stage 1: "
2906	 "~n   Vbs: ~p"
2907	 "~n   Exp: ~p", [Vbs, Expected]),
2908    sas_verify_vbs(Vbs, Expected);
2909sas_verify(Error, _) ->
2910    {error, {unexpected_reply, Error}}.
2911
2912sas_verify_vbs([], []) ->
2913    ok;
2914sas_verify_vbs(Vbs, []) ->
2915    {error, {unexpected_vbs, Vbs}};
2916sas_verify_vbs([], Exp) ->
2917    {error, {expected_vbs, Exp}};
2918sas_verify_vbs([#varbind{oid = Oid}|Vbs], [any|Exp]) ->
2919    ?IPRINT("verified [any] oid ~w", [Oid]),
2920    sas_verify_vbs(Vbs, Exp);
2921sas_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [Oid|Exp]) ->
2922    ?IPRINT("verified oid ~w [~p]", [Oid, Value]),
2923    sas_verify_vbs(Vbs, Exp);
2924sas_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [{Oid,Value}|Exp]) ->
2925    ?IPRINT("verified oid ~w and ~p", [Oid, Value]),
2926    sas_verify_vbs(Vbs, Exp);
2927sas_verify_vbs([Vb|_], [E|_]) ->
2928    {error, {unexpected_vb, Vb, E}}.
2929
2930
2931%%======================================================================
2932
2933simple_async_set2(doc) ->
2934    ["Simple (async) set-request - Version 2 API (TargetName)"];
2935simple_async_set2(suite) -> [];
2936simple_async_set2(Config) when is_list(Config) ->
2937    ?TC_TRY(simple_async_set2,
2938            fun() -> do_simple_async_set2(Config) end).
2939
2940do_simple_async_set2(Config) ->
2941    ?IPRINT("starting with Config: "
2942            "~n      ~p"
2943            "~n", [Config]),
2944
2945    MgrNode    = ?config(manager_node, Config),
2946    AgentNode  = ?config(agent_node, Config),
2947    TargetName = ?config(manager_agent_target_name, Config),
2948
2949    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
2950    Test2Mib = test2_mib(Config),
2951    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
2952    ?line ok = agent_load_mib(AgentNode, Test2Mib),
2953
2954    Set =
2955	fun(Oids) ->
2956		async_s_exec2(MgrNode, TargetName, Oids)
2957	end,
2958    PostVerify = fun(Res) -> Res end,
2959
2960    Res = do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify),
2961    display_log(Config),
2962    Res.
2963
2964do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify) ->
2965    Requests =
2966	[
2967	 {1,
2968	  [{?sysName_instance, s, "Arne Anka"}],
2969	  Set,
2970	  fun(X) ->
2971		  PostVerify(sas_verify(X, [?sysName_instance]))
2972	  end},
2973	 {2,
2974	  [{?sysLocation_instance, s, "Stockholm"},
2975	   {?sysName_instance,     s, "Arne Anka"}],
2976	  Set,
2977	  fun(X) ->
2978		  PostVerify(sas_verify(X,
2979					[?sysLocation_instance,
2980					 ?sysName_instance]))
2981	  end},
2982	 {3,
2983	  [{[sysName, 0],     "Gothenburg"},
2984	   {[sysLocation, 0], "Sune Anka"}],
2985	  Set,
2986	  fun(X) ->
2987		  PostVerify(sas_verify(X,
2988					[?sysName_instance,
2989					 ?sysLocation_instance]))
2990	  end}
2991	],
2992
2993    ?IPRINT("manager info when starting test: "
2994            "~n      ~p", [mgr_info(MgrNode)]),
2995    ?IPRINT("agent info when starting test: "
2996            "~n      ~p", [agent_info(AgentNode)]),
2997
2998    ?line ok = async_exec(Requests, []),
2999
3000    ?IPRINT("manager info when ending test: "
3001            "~n      ~p", [mgr_info(MgrNode)]),
3002    ?IPRINT("agent info when ending test: "
3003            "~n      ~p", [agent_info(AgentNode)]),
3004
3005    ok.
3006
3007
3008async_s_exec2(Node, TargetName, VAVs) ->
3009    mgr_user_async_set(Node, TargetName, VAVs).
3010
3011
3012%%======================================================================
3013
3014simple_async_set3_cbp_def(doc) ->
3015    ["Simple (async) set-request - Version 3 API (TargetName with send-opts)"];
3016simple_async_set3_cbp_def(suite) -> [];
3017simple_async_set3_cbp_def(Config) when is_list(Config) ->
3018    simple_async_set3(sas3_cbp_def, Config).
3019
3020simple_async_set3_cbp_temp(doc) ->
3021    ["Simple (async) set-request - Version 3 API (TargetName with send-opts)"];
3022simple_async_set3_cbp_temp(suite) -> [];
3023simple_async_set3_cbp_temp(Config) when is_list(Config) ->
3024    simple_async_set3(sas3_cbp_temp, Config).
3025
3026simple_async_set3_cbp_perm(doc) ->
3027    ["Simple (async) set-request - Version 3 API (TargetName with send-opts)"];
3028simple_async_set3_cbp_perm(suite) -> [];
3029simple_async_set3_cbp_perm(Config) when is_list(Config) ->
3030    simple_async_set3(sas3_cbp_perm, Config).
3031
3032simple_async_set3(Case, Config) ->
3033    ?TC_TRY(Case,
3034            fun() -> do_simple_async_set3(Config) end).
3035
3036do_simple_async_set3(Config) ->
3037    ?IPRINT("starting with Config: "
3038            "~n      ~p~n", [Config]),
3039
3040    MgrNode    = ?config(manager_node, Config),
3041    AgentNode  = ?config(agent_node, Config),
3042    TargetName = ?config(manager_agent_target_name, Config),
3043
3044    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
3045    Test2Mib = test2_mib(Config),
3046    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
3047    ?line ok = agent_load_mib(AgentNode, Test2Mib),
3048
3049    Self  = self(),
3050    Msg   = simple_async_set3,
3051    Fun   = fun() -> Self ! Msg end,
3052    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
3053    SendOpts =
3054	[
3055	 {extra, Extra}
3056	],
3057
3058    Set =
3059	fun(Oids) ->
3060		async_s_exec3(MgrNode, TargetName, Oids, SendOpts)
3061	end,
3062    PostVerify = fun(ok)  -> receive Msg -> ok end;
3063		    (Res) -> Res
3064		 end,
3065
3066    Res = do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify),
3067    display_log(Config),
3068    Res.
3069
3070async_s_exec3(Node, TargetName, VAVs, SendOpts) ->
3071    mgr_user_async_set2(Node, TargetName, VAVs, SendOpts).
3072
3073
3074%%======================================================================
3075
3076fl(L) ->
3077    lists:flatten(L).
3078
3079verify_ssgb_reply1({noError, 0, []}) ->
3080    ok;
3081verify_ssgb_reply1(X) ->
3082    {error, {unexpected_reply, X}}.
3083
3084verify_ssgb_reply2({noError, 0, Vbs}, ExpectedVbs) ->
3085    check_ssgb_vbs(Vbs, ExpectedVbs);
3086verify_ssgb_reply2(Error, _) ->
3087    {error, {unexpected_reply, Error}}.
3088
3089verify_ssgb_reply3({genErr, 3, Vbs}, ExpectedVbs) ->
3090    check_ssgb_vbs(Vbs, ExpectedVbs);
3091verify_ssgb_reply3(Unexpected, _) ->
3092    {error, {unexpected_reply, Unexpected}}.
3093
3094check_ssgb_vbs([], []) ->
3095    ok;
3096check_ssgb_vbs(Unexpected, []) ->
3097    {error, {unexpected_vbs, Unexpected}};
3098check_ssgb_vbs([], Expected) ->
3099    {error, {expected_vbs, Expected}};
3100check_ssgb_vbs([#varbind{value = endOfMibView}|R],
3101	       [endOfMibView|Expected]) ->
3102    check_ssgb_vbs(R, Expected);
3103check_ssgb_vbs([#varbind{oid = Oid}|R], [Oid|Expected]) ->
3104    check_ssgb_vbs(R, Expected);
3105check_ssgb_vbs([#varbind{oid = Oid, value = Value}|R],
3106	       [{Oid, Value}|Expected]) ->
3107    check_ssgb_vbs(R, Expected);
3108check_ssgb_vbs([R|_], [E|_]) ->
3109    {error, {unexpected_vb, R, E}}.
3110
3111%%======================================================================
3112
3113simple_sync_get_bulk2(doc) ->
3114    ["Simple (sync) get_bulk-request - Version 2 API (TargetName)"];
3115simple_sync_get_bulk2(suite) -> [];
3116simple_sync_get_bulk2(Config) when is_list(Config) ->
3117    ?TC_TRY(simple_sync_get_bulk2,
3118            fun() -> do_simple_sync_get_bulk2(Config) end).
3119
3120do_simple_sync_get_bulk2(Config) ->
3121    ?IPRINT("starting with Config: "
3122            "~n      ~p~n", [Config]),
3123
3124    MgrNode    = ?config(manager_node, Config),
3125    AgentNode  = ?config(agent_node, Config),
3126    TargetName = ?config(manager_agent_target_name, Config),
3127
3128    GetBulk =
3129	fun(NonRep, MaxRep, Oids) ->
3130		mgr_user_sync_get_bulk(MgrNode, TargetName,
3131				       NonRep, MaxRep, Oids)
3132	end,
3133    PostVerify = fun(Res) -> Res end,
3134
3135    Res = do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify),
3136    display_log(Config),
3137    Res.
3138
3139do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify) ->
3140    %% -- 1 --
3141    ?line ok = do_simple_get_bulk2(1,
3142				   1,  1, [],
3143				   fun verify_ssgb_reply1/1,
3144				   GetBulk, PostVerify),
3145
3146    %% -- 2 --
3147    ?line ok = do_simple_get_bulk2(2,
3148				   -1,  1, [],
3149				   fun verify_ssgb_reply1/1,
3150				   GetBulk, PostVerify),
3151
3152    %% -- 3 --
3153    ?line ok = do_simple_get_bulk2(3,
3154				   -1, -1, [],
3155				   fun verify_ssgb_reply1/1,
3156				   GetBulk, PostVerify),
3157
3158    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
3159    %% -- 4 --
3160    VF04 = fun(X) ->
3161		   verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView])
3162	   end,
3163    ?line ok = do_simple_get_bulk2(4,
3164				   2, 0, [[sysDescr],[1,3,7,1]], VF04,
3165				   GetBulk, PostVerify),
3166
3167    %% -- 5 --
3168    ?line ok = do_simple_get_bulk2(5,
3169				   1, 2, [[sysDescr],[1,3,7,1]], VF04,
3170				   GetBulk, PostVerify),
3171
3172    %% -- 6 --
3173    VF06 = fun(X) ->
3174		   verify_ssgb_reply2(X,
3175				      [?sysDescr_instance,    endOfMibView,
3176				       ?sysObjectID_instance, endOfMibView])
3177	   end,
3178    ?line ok = do_simple_get_bulk2(6,
3179				   0, 2, [[sysDescr],[1,3,7,1]], VF06,
3180				   GetBulk, PostVerify),
3181
3182    %% -- 7 --
3183    VF07 = fun(X) ->
3184		   verify_ssgb_reply2(X,
3185				      [?sysDescr_instance,    endOfMibView,
3186				       ?sysDescr_instance,    endOfMibView,
3187				       ?sysObjectID_instance, endOfMibView])
3188	   end,
3189    ?line ok = do_simple_get_bulk2(7,
3190				   2, 2,
3191				   [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]],
3192				   VF07,
3193				   GetBulk, PostVerify),
3194
3195    Test2Mib = test2_mib(Config),
3196    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
3197    ?line ok = agent_load_mib(AgentNode, Test2Mib),
3198
3199    %% -- 8 --
3200    VF08 = fun(X) ->
3201		   verify_ssgb_reply2(X,
3202				      [?sysDescr_instance,
3203				       ?sysDescr_instance])
3204	   end,
3205    ?line ok = do_simple_get_bulk2(8,
3206				   1, 2,
3207				   [[sysDescr],[sysDescr],[tTooBig]],
3208				   VF08,
3209				   GetBulk, PostVerify),
3210
3211    %% -- 9 --
3212    ?line ok = do_simple_get_bulk2(9,
3213				   1, 12,
3214				   [[tDescr2], [sysDescr]],
3215				   fun verify_ssgb_reply1/1,
3216				   GetBulk, PostVerify),
3217
3218    %% -- 10 --
3219    VF10 = fun(X) ->
3220		   verify_ssgb_reply3(X,
3221				      [{?sysDescr,    'NULL'},
3222				       {?sysObjectID, 'NULL'},
3223				       {?tGenErr1,    'NULL'},
3224				       {?sysDescr,    'NULL'}])
3225	   end,
3226    ?line ok = do_simple_get_bulk2(10,
3227				   2, 2,
3228				   [[sysDescr],
3229				    [sysObjectID],
3230				    [tGenErr1],
3231				    [sysDescr]],
3232				   VF10,
3233				   GetBulk, PostVerify),
3234
3235    %% -- 11 --
3236    ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),
3237    ?IPRINT("TCnt2: ~p", [TCnt2]),
3238    VF11 = fun(X) ->
3239		   verify_ssgb_reply2(X,
3240				      [{fl([TCnt2,2]), 100},
3241				       {fl([TCnt2,2]), endOfMibView}])
3242	   end,
3243    ?line ok = do_simple_get_bulk2(11,
3244				   0, 2,
3245				   [[TCnt2, 1]], VF11,
3246				   GetBulk, PostVerify),
3247
3248    ok.
3249
3250do_simple_get_bulk2(N,
3251		    NonRep, MaxRep, Oids,
3252		    Verify, GetBulk, PostVerify)
3253  when is_function(Verify, 1) andalso
3254       is_function(GetBulk, 3) andalso
3255       is_function(PostVerify) ->
3256    ?IPRINT("issue get-bulk command ~w", [N]),
3257    case GetBulk(NonRep, MaxRep, Oids) of
3258	{ok, Reply, _Rem} ->
3259	    ?DBG("get-bulk ok:"
3260		 "~n   Reply: ~p"
3261		 "~n   Rem:   ~w", [Reply, _Rem]),
3262	    PostVerify(Verify(Reply));
3263
3264	Error ->
3265	    {error, {unexpected_reply, Error}}
3266    end.
3267
3268
3269%%======================================================================
3270
3271simple_sync_get_bulk3(doc) ->
3272    ["Simple (sync) get_bulk-request - "
3273     "Version 3 API (TargetName with send-opts)"];
3274simple_sync_get_bulk3(suite) -> [];
3275simple_sync_get_bulk3(Config) when is_list(Config) ->
3276    ?TC_TRY(simple_sync_get_bulk3,
3277            fun() -> do_simple_sync_get_bulk3(Config) end).
3278
3279do_simple_sync_get_bulk3(Config) ->
3280    ?IPRINT("starting with Config: "
3281            "~n      ~p~n", [Config]),
3282
3283    MgrNode    = ?config(manager_node, Config),
3284    AgentNode  = ?config(agent_node, Config),
3285    TargetName = ?config(manager_agent_target_name, Config),
3286
3287    Self  = self(),
3288    Msg   = simple_async_set3,
3289    Fun   = fun() -> Self ! Msg end,
3290    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
3291    SendOpts =
3292	[
3293	 {extra, Extra}
3294	],
3295
3296    GetBulk =
3297	fun(NonRep, MaxRep, Oids) ->
3298		mgr_user_sync_get_bulk2(MgrNode, TargetName,
3299					NonRep, MaxRep, Oids, SendOpts)
3300	end,
3301    PostVerify = fun(ok) -> receive Msg -> ok end;
3302		    (Res) -> Res
3303		 end,
3304
3305    Res = do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify),
3306    display_log(Config),
3307    Res.
3308
3309
3310%%======================================================================
3311
3312simple_async_get_bulk2(doc) ->
3313    ["Simple (async) get_bulk-request - Version 2 API (TargetName)"];
3314simple_async_get_bulk2(suite) -> [];
3315simple_async_get_bulk2(Config) when is_list(Config) ->
3316    ?TC_TRY(simple_async_get_bulk2,
3317            fun() -> do_simple_async_get_bulk2(Config) end).
3318
3319do_simple_async_get_bulk2(Config) ->
3320    ?IPRINT("starting with Config: "
3321            "~p      ~n", [Config]),
3322
3323    MgrNode    = ?config(manager_node, Config),
3324    AgentNode  = ?config(agent_node, Config),
3325    TargetName = ?config(manager_agent_target_name, Config),
3326
3327    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
3328    Test2Mib = test2_mib(Config),
3329    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
3330    ?line ok = agent_load_mib(AgentNode, Test2Mib),
3331
3332    GetBulk =
3333	fun(Data) ->
3334		async_gb_exec2(MgrNode, TargetName, Data)
3335	end,
3336    PostVerify = fun(Res) -> Res end,
3337
3338    Res = do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify),
3339    display_log(Config),
3340    Res.
3341
3342do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify) ->
3343    %% We re-use the verification functions from the ssgb test-case
3344    VF04 = fun(X) ->
3345		   PostVerify(
3346		     verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]))
3347	   end,
3348    VF06 = fun(X) ->
3349		   PostVerify(
3350		     verify_ssgb_reply2(X,
3351					[?sysDescr_instance,    endOfMibView,
3352					 ?sysObjectID_instance, endOfMibView]))
3353	   end,
3354    VF07 = fun(X) ->
3355		   PostVerify(
3356		     verify_ssgb_reply2(X,
3357					[?sysDescr_instance,    endOfMibView,
3358					 ?sysDescr_instance,    endOfMibView,
3359					 ?sysObjectID_instance, endOfMibView]))
3360	   end,
3361    VF08 = fun(X) ->
3362		   PostVerify(
3363		     verify_ssgb_reply2(X,
3364					[?sysDescr_instance,
3365					 ?sysDescr_instance]))
3366	   end,
3367    VF10 = fun(X) ->
3368		   PostVerify(
3369		     verify_ssgb_reply3(X,
3370					[{?sysDescr,    'NULL'},
3371					 {?sysObjectID, 'NULL'},
3372					 {?tGenErr1,    'NULL'},
3373					 {?sysDescr,    'NULL'}]))
3374	   end,
3375    ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),
3376    VF11 = fun(X) ->
3377		   PostVerify(
3378		     verify_ssgb_reply2(X,
3379					[{fl([TCnt2,2]), 100},
3380					 {fl([TCnt2,2]), endOfMibView}]))
3381	   end,
3382    Requests = [
3383		{ 1,
3384		  {1,  1, []},
3385		  GetBulk,
3386		  fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
3387		{ 2,
3388		  {-1,  1, []},
3389		  GetBulk,
3390		  fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
3391		{ 3,
3392		  {-1, -1, []},
3393		  GetBulk,
3394		  fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
3395		{ 4,
3396		  {2,  0, [[sysDescr],[1,3,7,1]]},
3397		  GetBulk,
3398		  VF04},
3399		{ 5,
3400		  {1,  2, [[sysDescr],[1,3,7,1]]},
3401		  GetBulk,
3402		  VF04},
3403		{ 6,
3404		  {0,  2, [[sysDescr],[1,3,7,1]]},
3405		  GetBulk,
3406		  VF06},
3407		{ 7,
3408		  {2,  2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]},
3409		  GetBulk,
3410		  VF07},
3411		{ 8,
3412		  {1,  2, [[sysDescr],[sysDescr],[tTooBig]]},
3413		  GetBulk,
3414		  VF08},
3415		{ 9,
3416		  {1, 12, [[tDescr2], [sysDescr]]},
3417		  GetBulk,
3418		  fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
3419		{10,
3420		 {2,  2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]},
3421		 GetBulk,
3422		 VF10},
3423		{11,
3424		 {0,  2, [[TCnt2, 1]]},
3425		 GetBulk,
3426		 VF11},
3427		{12,
3428		 {2,  0, [[sysDescr],[1,3,7,1]]},
3429		 GetBulk,
3430		 VF04},
3431		{13,
3432		 {1, 12, [[tDescr2], [sysDescr]]},
3433		 GetBulk,
3434		 fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
3435		{14,
3436		 {2,  2, [[sysDescr],[sysObjectID],[tGenErr1],[sysDescr]]},
3437		 GetBulk,
3438		 VF10},
3439		{15,
3440		 {0,  2, [[TCnt2, 1]]},
3441		 GetBulk,
3442		 VF11},
3443		{16,
3444		 {2,  2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]},
3445		 GetBulk,
3446		 VF07},
3447		{17,
3448		 {2,  2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]},
3449		 GetBulk,
3450		 VF10}
3451	       ],
3452
3453    ?IPRINT("manager info when starting test: "
3454            "~n      ~p", [mgr_info(MgrNode)]),
3455    ?IPRINT("agent info when starting test: "
3456            "~n      ~p", [agent_info(AgentNode)]),
3457
3458    ?line ok = async_exec(Requests, []),
3459
3460    ?IPRINT("manager info when ending test: "
3461            "~n      ~p", [mgr_info(MgrNode)]),
3462    ?IPRINT("agent info when ending test: "
3463            "~n      ~p", [agent_info(AgentNode)]),
3464
3465    ok.
3466
3467
3468async_gb_exec2(Node, TargetName, {NR, MR, Oids}) ->
3469    mgr_user_async_get_bulk(Node, TargetName, NR, MR, Oids).
3470
3471
3472%%======================================================================
3473
3474simple_async_get_bulk3_cbp_def(doc) ->
3475    ["Simple (async) get_bulk-request - "
3476     "Version 3 API (TargetName with send-opts)"];
3477simple_async_get_bulk3_cbp_def(suite) -> [];
3478simple_async_get_bulk3_cbp_def(Config) when is_list(Config) ->
3479    simple_async_get_bulk3(sagb3_cbp_def, Config).
3480
3481simple_async_get_bulk3(Case, Config) ->
3482    ?TC_TRY(Case,
3483            fun() -> do_simple_async_get_bulk3(Config) end).
3484
3485do_simple_async_get_bulk3(Config) ->
3486    process_flag(trap_exit, true),
3487    ?IPRINT("starting with Config: "
3488            "~n      ~p~n", [Config]),
3489
3490    MgrNode    = ?config(manager_node, Config),
3491    AgentNode  = ?config(agent_node, Config),
3492    TargetName = ?config(manager_agent_target_name, Config),
3493
3494    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
3495    Test2Mib = test2_mib(Config),
3496    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
3497    ?line ok = agent_load_mib(AgentNode, Test2Mib),
3498
3499    Self  = self(),
3500    Msg   = simple_async_get_bulk3,
3501    Fun   = fun() -> Self ! Msg end,
3502    Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
3503    SendOpts =
3504	[
3505	 {extra, Extra}
3506	],
3507
3508    GetBulk =
3509	fun(Data) ->
3510		async_gb_exec3(MgrNode, TargetName, Data, SendOpts)
3511	end,
3512    PostVerify = fun(ok)  -> receive Msg -> ok end;
3513		    (Res) -> Res
3514		 end,
3515
3516    Res = do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify),
3517    display_log(Config),
3518    Res.
3519
3520async_gb_exec3(Node, TargetName, {NR, MR, Oids}, SendOpts) ->
3521    mgr_user_async_get_bulk2(Node, TargetName, NR, MR, Oids, SendOpts).
3522
3523
3524%%======================================================================
3525
3526simple_async_get_bulk3_cbp_temp(doc) ->
3527    ["Simple (async) get_bulk-request - "
3528     "Version 3 API (TargetName with send-opts)"];
3529simple_async_get_bulk3_cbp_temp(suite) -> [];
3530simple_async_get_bulk3_cbp_temp(Config) when is_list(Config) ->
3531    simple_async_get_bulk3(sagb3_cbp_temp, Config).
3532
3533
3534%%======================================================================
3535
3536simple_async_get_bulk3_cbp_perm(doc) ->
3537    ["Simple (async) get_bulk-request - "
3538     "Version 3 API (TargetName with send-opts)"];
3539simple_async_get_bulk3_cbp_perm(suite) -> [];
3540simple_async_get_bulk3_cbp_perm(Config) when is_list(Config) ->
3541    simple_async_get_bulk3(sagb3_cbp_perm, Config).
3542
3543
3544%%======================================================================
3545
3546misc_async2(doc) ->
3547    ["Misc (async) request(s) - Version 2 API (TargetName)"];
3548misc_async2(suite) -> [];
3549misc_async2(Config) when is_list(Config) ->
3550    ?TC_TRY(misc_async2,
3551            fun() -> do_misc_async2(Config) end).
3552
3553do_misc_async2(Config) ->
3554    ?IPRINT("starting with Config: "
3555            "~n      ~p"
3556            "~n", [Config]),
3557
3558    MgrNode   = ?config(manager_node, Config),
3559    AgentNode = ?config(agent_node, Config),
3560    TargetName = ?config(manager_agent_target_name, Config),
3561
3562    ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
3563    Test2Mib = test2_mib(Config),
3564    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
3565    ?line ok = agent_load_mib(AgentNode, Test2Mib),
3566
3567    ExecG = fun(Data) ->
3568		    async_g_exec2(MgrNode, TargetName, Data)
3569	    end,
3570
3571    ExecGN = fun(Data) ->
3572		     async_gn_exec2(MgrNode, TargetName, Data)
3573	     end,
3574
3575    ExecS = fun(Data) ->
3576		    async_s_exec2(MgrNode, TargetName, Data)
3577	    end,
3578
3579    ExecGB = fun(Data) ->
3580		     async_gb_exec2(MgrNode, TargetName, Data)
3581	     end,
3582
3583    ?line {ok, [TCnt2|_]}    = mgr_user_name_to_oid(MgrNode, tCnt2),
3584    ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),
3585    ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),
3586    ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),
3587    ?line {ok, [TTooBig|_]}  = mgr_user_name_to_oid(MgrNode, tTooBig),
3588
3589    Requests =
3590	[
3591	 { 1,
3592	   [?sysObjectID_instance],
3593	   ExecG,
3594	   fun(X) ->
3595		   sag_verify(X, [?sysObjectID_instance])
3596	   end
3597	  },
3598	 { 2,
3599	   {1,  1, []},
3600	   ExecGB,
3601	   fun verify_ssgb_reply1/1},
3602	 { 3,
3603	   {-1,  1, []},
3604	   ExecGB,
3605	   fun verify_ssgb_reply1/1},
3606	 { 4,
3607	   [{?sysLocation_instance, s, "Stockholm"},
3608	    {?sysName_instance,     s, "Arne Anka"}],
3609	   ExecS,
3610	   fun(X) ->
3611		   sas_verify(X, [?sysLocation_instance, ?sysName_instance])
3612	   end},
3613	 { 5,
3614	   [[sysDescr], [1,3,7,1]],
3615	   ExecGN,
3616	   fun(X) ->
3617		   verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView])
3618	   end},
3619	 { 6,
3620	   [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
3621	   ExecG,
3622	   fun(X) ->
3623		   sag_verify(X, [?sysObjectID_instance,
3624				  ?sysDescr_instance,
3625				  ?sysUpTime_instance])
3626	   end},
3627	 { 7,
3628	  [TGenErr2],
3629	   ExecGN,
3630	   fun(X) ->
3631		   verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]})
3632	   end},
3633	 { 8,
3634	   {2,  0, [[sysDescr],[1,3,7,1]]},
3635	   ExecGB,
3636	   fun(X) ->
3637		   verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView])
3638	   end},
3639	 { 9,
3640	   {1,  2, [[sysDescr],[1,3,7,1]]},
3641	   ExecGB,
3642	   fun(X) ->
3643		   verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView])
3644	   end},
3645	 {10,
3646	  [TGenErr1],
3647	  ExecGN,
3648	  fun(X) ->
3649		  verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]})
3650	  end},
3651	 {11,
3652	  {0,  2, [[sysDescr],[1,3,7,1]]},
3653	  ExecGB,
3654	  fun(X) ->
3655		  verify_ssgb_reply2(X,
3656				     [?sysDescr_instance,    endOfMibView,
3657				      ?sysObjectID_instance, endOfMibView])
3658	  end},
3659	 {12,
3660	  [{[sysName, 0],     "Gothenburg"},
3661	   {[sysLocation, 0], "Sune Anka"}],
3662	  ExecS,
3663	  fun(X) ->
3664		  sas_verify(X, [?sysName_instance, ?sysLocation_instance])
3665	  end},
3666	 {13,
3667	  {2,  2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]},
3668	  ExecGB,
3669	  fun(X) ->
3670		  verify_ssgb_reply2(X,
3671				     [?sysDescr_instance,    endOfMibView,
3672				      ?sysDescr_instance,    endOfMibView,
3673				      ?sysObjectID_instance, endOfMibView])
3674	  end},
3675	 {14,
3676	  {1,  2, [[sysDescr],[sysDescr],[tTooBig]]},
3677	  ExecGB,
3678	  fun(X) ->
3679		  verify_ssgb_reply2(X,
3680				     [?sysDescr_instance,
3681				      ?sysDescr_instance])
3682	  end},
3683	 {15,
3684	  {1, 12, [[tDescr2], [sysDescr]]},
3685	  ExecGB,
3686	  fun verify_ssgb_reply1/1},
3687	 {16,
3688	  {2,  2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]},
3689	  ExecGB,
3690	  fun(X) ->
3691		  verify_ssgb_reply3(X,
3692				     [{?sysDescr,    'NULL'},
3693				      {?sysObjectID, 'NULL'},
3694				      {?tGenErr1,    'NULL'},
3695				      {?sysDescr,    'NULL'}])
3696	  end},
3697	 {17,
3698	  [[sysDescr], TGenErr3],
3699	  ExecGN,
3700	  fun(X) ->
3701		  verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]})
3702	  end},
3703	 {18,
3704	  {0,  2, [[TCnt2, 1]]},
3705	  ExecGB,
3706	  fun(X) ->
3707		  verify_ssgb_reply2(X,
3708				     [{fl([TCnt2,2]), 100},
3709				      {fl([TCnt2,2]), endOfMibView}])
3710	  end},
3711	 {19,
3712	  [TTooBig],
3713	  ExecGN,
3714	  fun(X) ->
3715		  verify_ssgn_reply2(X, {tooBig, 0, []})
3716	  end},
3717	 {20,
3718	  [TTooBig],
3719	  ExecGN,
3720	  fun(X) ->
3721		  verify_ssgn_reply2(X, {tooBig, 0, []})
3722	  end}
3723	],
3724
3725    ?IPRINT("manager info when starting test: "
3726            "~n      ~p", [mgr_info(MgrNode)]),
3727    ?IPRINT("agent info when starting test: "
3728            "~n      ~p", [agent_info(AgentNode)]),
3729
3730    ?line ok = async_exec(Requests, []),
3731
3732    ?IPRINT("manager info when ending test: "
3733            "~n      ~p", [mgr_info(MgrNode)]),
3734    ?IPRINT("agent info when ending test: "
3735            "~n      ~p", [agent_info(AgentNode)]),
3736
3737    display_log(Config),
3738    ok.
3739
3740
3741%%======================================================================
3742
3743discovery(suite) -> [];
3744discovery(Config) when is_list(Config) ->
3745    ?SKIP(not_yet_implemented).
3746
3747
3748%%======================================================================
3749%%
3750%% Utility functions for cases trap1 and trap2
3751%%
3752
3753collect_traps(N) ->
3754    collect_traps(N, []).
3755
3756collect_traps(0, TrapInfo) ->
3757    TrapInfo;
3758collect_traps(N, Acc) ->
3759    receive
3760	{async_event, _From, {trap, TrapInfo}} ->
3761	    ?IPRINT("collect_traps -> received trap: "
3762                    "~n      ~p", [TrapInfo]),
3763	    collect_traps(N-1, [TrapInfo|Acc])
3764    after 10000 ->
3765	    ?WPRINT("collect_traps -> still awaiting ~w trap(s) - giving up", [N]),
3766	    Acc
3767    end.
3768
3769verify_traps([], []) ->
3770    ?IPRINT("verify_traps -> done"),
3771    ok;
3772verify_traps([], Verifiers) ->
3773    ?IPRINT("verify_traps -> done when ~w verifiers remain", [length(Verifiers)]),
3774    {error, {failed_verify, [Id || {Id, _} <- Verifiers]}};
3775verify_traps([Trap|Traps], Verifiers0) ->
3776    ?IPRINT("verify_traps -> entry"),
3777    case verify_trap(Trap, Verifiers0) of
3778	{ok, Id} ->
3779	    ?IPRINT("verify_traps -> trap verified: ~p", [Id]),
3780	    Verifiers = lists:keydelete(Id, 1, Verifiers0),
3781	    verify_traps(Traps, Verifiers);
3782	error ->
3783	    ?EPRINT("verify_traps -> failed verifying trap: "
3784                    "~n      ~p", [Trap]),
3785	    {error, {failed_verifying_trap, Trap}}
3786    end.
3787
3788verify_trap(Trap, []) ->
3789    ?EPRINT("verify_trap -> could not verify trap:"
3790            "~n   Trap: ~p", [Trap]),
3791    error;
3792verify_trap(Trap, [{Id, Verifier}|Verifiers]) ->
3793    ?IPRINT("verify_trap -> entry with"
3794            "~n   Id:   ~p"
3795            "~n   Trap: ~p", [Id, Trap]),
3796    case Verifier(Trap) of
3797	ok ->
3798	    ?IPRINT("verify_trap -> verified"),
3799	    {ok, Id};
3800	{error, _} ->
3801	    ?NPRINT("verify_trap -> not verified"),
3802	    verify_trap(Trap, Verifiers)
3803    end.
3804
3805
3806%%======================================================================
3807
3808trap1(suite) -> [];
3809trap1(Config) when is_list(Config) ->
3810    ?TC_TRY(trap1,
3811            fun() -> do_trap1(Config) end).
3812
3813do_trap1(Config) ->
3814    ?IPRINT("starting with Config: "
3815            "~n      ~p"
3816            "~n", [Config]),
3817
3818    MgrNode   = ?config(manager_node, Config),
3819    AgentNode = ?config(agent_node, Config),
3820
3821    ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),
3822    Test2Mib      = test2_mib(Config),
3823    TestTrapMib   = test_trap_mib(Config),
3824    TestTrapv2Mib = test_trap_v2_mib(Config),
3825    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
3826    ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),
3827    ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),
3828    ?line ok = agent_load_mib(AgentNode,  Test2Mib),
3829    ?line ok = agent_load_mib(AgentNode,  TestTrapMib),
3830    ?line ok = agent_load_mib(AgentNode,  TestTrapv2Mib),
3831
3832    %% Version 1 trap verification function:
3833    VerifyTrap_v1 =
3834	fun(Ent, Gen, Spec, ExpVBs, Trap) ->
3835		case Trap of
3836		    {Ent, Gen, Spec, _Timestamp, VBs} ->
3837			?IPRINT("trap info as expected"),
3838			case (catch validate_vbs(MgrNode,
3839						 ExpVBs, VBs)) of
3840			    ok ->
3841				?IPRINT("valid trap"),
3842				ok;
3843			    Error ->
3844				?EPRINT("invalid trap: "
3845                                        "~n      ~p", [Error]),
3846				Error
3847			end;
3848		    {Enteprise, Generic, Spec, Timestamp, VBs} ->
3849		       ?EPRINT("unepxected v1 trap info:"
3850                               "~n   Enteprise: ~p"
3851                               "~n   Generic:   ~p"
3852                               "~n   Spec:      ~p"
3853                               "~n   Timestamp: ~p"
3854                               "~n   VBs:       ~p",
3855                               [Enteprise, Generic, Spec, Timestamp, VBs]),
3856			ExpTrap = {Ent, Gen, Spec, ignore, ExpVBs},
3857			Reason = {unexpected_trap, {ExpTrap, Trap}},
3858			{error, Reason};
3859		    {Err, Idx, VBs} ->
3860			?EPRINT("unexpected trap info: "
3861                                "~n   Err: ~p"
3862                                "~n   Idx: ~p"
3863                                "~n   VBs: ~p", [Err, Idx, VBs]),
3864			Reason = {unexpected_status, {Err, Idx, VBs}},
3865			{error, Reason}
3866		end
3867	end,
3868
3869    %% Version 2 trap verification function:
3870    VerifyTrap_v2 =
3871	fun(ExpVBs, Trap) ->
3872		case Trap of
3873		    {noError, 0, VBs0} ->
3874			?IPRINT("trap info as expected: "
3875                                "~n      ~p", [VBs0]),
3876			%% The first two are a timestamp and oid
3877			[_,_|VBs] = VBs0,
3878			case (catch validate_vbs(MgrNode,
3879						 ExpVBs, VBs)) of
3880			    ok ->
3881				?IPRINT("valid trap"),
3882				ok;
3883			    Error ->
3884				?EPRINT("invalid trap: "
3885                                        "~n      ~p", [Error]),
3886				Error
3887			end;
3888		    {Err, Idx, VBs} ->
3889			?EPRINT("unexpected error status: "
3890                                "~n   Err: ~p"
3891                                "~n   Idx: ~p"
3892                                "~n   VBs: ~p", [Err, Idx, VBs]),
3893			Reason = {unexpected_status, {Err, Idx, VBs}},
3894			{error, Reason}
3895		end
3896	end,
3897
3898
3899    %% -- command 1 --
3900    %% Collect various info about the manager and the agent
3901    Cmd1 =
3902	fun() ->
3903		?IPRINT("manager info: "
3904                        "~n      ~p", [mgr_info(MgrNode)]),
3905		?IPRINT("agent info: "
3906                        "~n      ~p", [agent_info(AgentNode)]),
3907		ok
3908	end,
3909
3910    %% -- command 2 --
3911    %% Make the agent send trap(s) (both a v1 and a v2 trap)
3912    Cmd2 =
3913	fun() ->
3914		VBs = [{ifIndex,       [1], 1},
3915		       {ifAdminStatus, [1], 1},
3916		       {ifOperStatus,  [1], 2}],
3917		agent_send_trap(AgentNode, linkUp, "standard trap", VBs),
3918		ok
3919	end,
3920
3921    %% -- command 3 --
3922    %% Version 1 trap verify function
3923    Cmd3_VerifyTrap_v1 =
3924	fun(Trap) ->
3925		Ent    = [1,2,3],
3926		Gen    = 3,
3927		Spec   = 0,
3928		ExpVBs = [{[ifIndex,       1], 1},
3929			  {[ifAdminStatus, 1], 1},
3930			  {[ifOperStatus,  1], 2}],
3931		VerifyTrap_v1(Ent, Gen, Spec, ExpVBs, Trap)
3932	end,
3933
3934    %% Version 2 trap verify function
3935    Cmd3_VerifyTrap_v2 =
3936	fun(Trap) ->
3937		ExpVBs = [{[ifIndex,       1], 1},
3938			  {[ifAdminStatus, 1], 1},
3939			  {[ifOperStatus,  1], 2}],
3940		VerifyTrap_v2(ExpVBs, Trap)
3941	end,
3942
3943    %% Verify the two traps. The order of them is unknown
3944    Cmd3 =
3945	fun() ->
3946		Verifiers = [{"v1 trap verifier", Cmd3_VerifyTrap_v1},
3947			     {"v2 trap verifier", Cmd3_VerifyTrap_v2}],
3948		verify_traps(collect_traps(2), Verifiers)
3949	end,
3950
3951    Cmd4 = fun() -> ?SLEEP(1000), ok end,
3952
3953    Commands =
3954	[
3955	 {1, "Manager and agent info at start of test", Cmd1},
3956	 {2, "Send trap from agent", Cmd2},
3957	 {3, "Await trap(s) to manager", Cmd3},
3958	 {4, "Sleep some time (1 sec)", Cmd4},
3959	 {5, "Manager and agent info after test completion", Cmd1}
3960	],
3961
3962    Res = command_handler(Commands),
3963    display_log(Config),
3964    Res.
3965
3966
3967%%======================================================================
3968
3969trap2(suite) -> [];
3970trap2(Config) when is_list(Config) ->
3971    ?TC_TRY(trap2,
3972            fun() -> do_trap2(Config) end).
3973
3974do_trap2(Config) ->
3975    ?IPRINT("starting with Config: "
3976            "~n      ~p"
3977            "~n", [Config]),
3978
3979    MgrNode   = ?config(manager_node, Config),
3980    AgentNode = ?config(agent_node, Config),
3981
3982    ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),
3983    Test2Mib      = test2_mib(Config),
3984    TestTrapMib   = test_trap_mib(Config),
3985    TestTrapv2Mib = test_trap_v2_mib(Config),
3986    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
3987    ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),
3988    ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),
3989    ?line ok = agent_load_mib(AgentNode,  Test2Mib),
3990    ?line ok = agent_load_mib(AgentNode,  TestTrapMib),
3991    ?line ok = agent_load_mib(AgentNode,  TestTrapv2Mib),
3992
3993    %% Version 1 trap verification function:
3994    VerifyTrap_v1 =
3995	fun(Ent, Gen, Spec, ExpVBs, Trap) ->
3996		case Trap of
3997		    {Ent, Gen, Spec, _Timestamp, VBs} ->
3998			?IPRINT("trap info as expected"),
3999			case (catch validate_vbs(MgrNode,
4000						 ExpVBs, VBs)) of
4001			    ok ->
4002				?IPRINT("valid trap"),
4003				ok;
4004			    Error ->
4005				?EPRINT("invalid trap: ~n   Error: ~p", [Error]),
4006				Error
4007			end;
4008		    {Enteprise, Generic, Spec, Timestamp, VBs} ->
4009			?EPRINT("unepxected v1 trap info:"
4010                                "~n   Enteprise: ~p"
4011                                "~n   Generic:   ~p"
4012                                "~n   Spec:      ~p"
4013                                "~n   Timestamp: ~p"
4014                                "~n   VBs:       ~p",
4015                                [Enteprise, Generic, Spec, Timestamp, VBs]),
4016			ExpTrap = {Ent, Gen, Spec, ignore, ExpVBs},
4017			Reason = {unexpected_trap, {ExpTrap, Trap}},
4018			{error, Reason};
4019		    {Err, Idx, VBs} ->
4020			?EPRINT("unexpected trap info: "
4021                                "~n   Err: ~p"
4022                                "~n   Idx: ~p"
4023                                "~n   VBs: ~p", [Err, Idx, VBs]),
4024			Reason = {unexpected_status, {Err, Idx, VBs}},
4025			{error, Reason}
4026		end
4027	end,
4028
4029    %% Version 2 trap verification function:
4030    VerifyTrap_v2 =
4031	fun(ExpVBs, Trap) ->
4032		case Trap of
4033		    {noError, 0, VBs0} ->
4034			?IPRINT("trap info as expected: ~n~p", [VBs0]),
4035			%% The first two are a timestamp and oid
4036			[_,_|VBs] = VBs0,
4037			case (catch validate_vbs(MgrNode,
4038						 ExpVBs, VBs)) of
4039			    ok ->
4040				?IPRINT("valid trap"),
4041				ok;
4042			    Error ->
4043				?EPRINT("invalid trap: "
4044                                        "~n      ~p", [Error]),
4045				Error
4046			end;
4047		    {Err, Idx, VBs} ->
4048			?EPRINT("unexpected error status: "
4049                                "~n   Err: ~p"
4050                                "~n   Idx: ~p"
4051                                "~n   VBs: ~p", [Err, Idx, VBs]),
4052			Reason = {unexpected_status, {Err, Idx, VBs}},
4053			{error, Reason}
4054		end
4055	end,
4056
4057    %% -- command 1 --
4058    %% Collect various info about the manager and the agent
4059    Cmd1 =
4060	fun() ->
4061		?IPRINT("manager info: "
4062                        "~n      ~p", [mgr_info(MgrNode)]),
4063		?IPRINT("agent info: "
4064                        "~n      ~p",   [agent_info(AgentNode)]),
4065		ok
4066	end,
4067
4068    %% -- command 2 --
4069    %% Make the agent send trap(s) (both a v1 and a v2 trap)
4070    Cmd2 =
4071	fun() ->
4072		VBs = [{sysContact, "pelle"}],
4073		agent_send_trap(AgentNode, testTrap1, "standard trap", VBs),
4074		ok
4075	end,
4076
4077    %% -- command 3 --
4078    %% Version 1 trap verify function
4079    Cmd3_VerifyTrap_v1 =
4080	fun(Trap) ->
4081		Ent    = [1,2,3],
4082		Gen    = 1,
4083		Spec   = 0,
4084		ExpVBs = [{[system, [4,0]], "pelle"}],
4085		VerifyTrap_v1(Ent, Gen, Spec, ExpVBs, Trap)
4086	end,
4087
4088    %% Version 2 trap verify function
4089    Cmd3_VerifyTrap_v2 =
4090	fun(Trap) ->
4091		ExpVBs = [{[system, [4,0]], "pelle"},
4092			  {[snmpTrapEnterprise,0], any}],
4093		VerifyTrap_v2(ExpVBs, Trap)
4094	end,
4095
4096    %% Verify the two traps. The order of them is unknown
4097    Cmd3 =
4098	fun() ->
4099		Verifiers = [{"v1 trap verifier", Cmd3_VerifyTrap_v1},
4100			     {"v2 trap verifier", Cmd3_VerifyTrap_v2}],
4101		verify_traps(collect_traps(2), Verifiers)
4102	end,
4103
4104    %% -- command 4 --
4105    %% Make the agent send another set of trap(s) (both a v1 and a v2 trap)
4106    Cmd4 =
4107	fun() ->
4108		VBs = [{ifIndex,       [1], 1},
4109		       {ifAdminStatus, [1], 1},
4110		       {ifOperStatus,  [1], 2}],
4111		agent_send_trap(AgentNode, linkUp, "standard trap", VBs),
4112		ok
4113	end,
4114
4115
4116    %% -- command 5 --
4117    %% Expected varbinds
4118    ExpVBs5 = [{[ifIndex,       1], 1},
4119	       {[ifAdminStatus, 1], 1},
4120	       {[ifOperStatus,  1], 2}],
4121
4122
4123    %% Version 1 trap verify function
4124    Cmd5_VerifyTrap_v1 =
4125	fun(Trap) ->
4126		Ent    = [1,2,3],
4127		Gen    = 3,
4128		Spec   = 0,
4129		VerifyTrap_v1(Ent, Gen, Spec, ExpVBs5, Trap)
4130	end,
4131
4132    %% Version 2 trap verify function
4133    Cmd5_VerifyTrap_v2 =
4134	fun(Trap) ->
4135		VerifyTrap_v2(ExpVBs5, Trap)
4136	end,
4137
4138    %% Verify the two traps. The order of them is unknown
4139    Cmd5 =
4140	fun() ->
4141		Verifiers = [{"v1 trap verifier", Cmd5_VerifyTrap_v1},
4142			     {"v2 trap verifier", Cmd5_VerifyTrap_v2}],
4143		verify_traps(collect_traps(2), Verifiers)
4144	end,
4145
4146    %% -- command 6 --
4147    %% Some sleep before we are done
4148    Cmd6 = fun() -> ?SLEEP(1000), ok end,
4149
4150    Commands =
4151	[
4152	 {1, "Manager and agent info at start of test", Cmd1},
4153	 {2, "Send first trap(s) from agent", Cmd2},
4154	 {3, "Await the trap(s) from agent", Cmd3},
4155	 {4, "Send second trap(s) from agent", Cmd4},
4156	 {5, "Await the trap(s) from the agent", Cmd5},
4157	 {6, "Sleep some time (1 sec)", Cmd6},
4158	 {7, "Manager and agent info after test completion", Cmd1}
4159	],
4160
4161    Res = command_handler(Commands),
4162    display_log(Config),
4163    Res.
4164
4165
4166%%======================================================================
4167
4168inform1(suite) -> [];
4169inform1(Config) when is_list(Config) ->
4170    ?TC_TRY(inform1,
4171            fun() -> do_inform1(Config) end).
4172
4173do_inform1(Config) ->
4174    ?IPRINT("starting with Config: "
4175            "~n      ~p"
4176            "~n", [Config]),
4177
4178    MgrNode   = ?config(manager_node, Config),
4179    AgentNode = ?config(agent_node, Config),
4180
4181    ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),
4182    Test2Mib      = test2_mib(Config),
4183    TestTrapMib   = test_trap_mib(Config),
4184    TestTrapv2Mib = test_trap_v2_mib(Config),
4185    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
4186    ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),
4187    ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),
4188    ?line ok = agent_load_mib(AgentNode,  Test2Mib),
4189    ?line ok = agent_load_mib(AgentNode,  TestTrapMib),
4190    ?line ok = agent_load_mib(AgentNode,  TestTrapv2Mib),
4191
4192
4193    Cmd1 =
4194	fun() ->
4195		?IPRINT("manager info: "
4196                        "~n      ~p", [mgr_info(MgrNode)]),
4197		?IPRINT("manager system info: "
4198                        "~n      ~p", [mgr_sys_info(MgrNode)]),
4199		?IPRINT("agent info: "
4200                        "~n      ~p", [agent_info(AgentNode)]),
4201		ok
4202	end,
4203
4204    Cmd2 =
4205	fun() ->
4206		agent_send_notif(AgentNode, testTrapv22, "standard inform"),
4207		ok
4208	end,
4209
4210    Cmd3 =
4211	fun() ->
4212		receive
4213		    {async_event, From, {inform, Pid, Inform}} ->
4214			?IPRINT("received inform"),
4215			case Inform of
4216			    {noError, 0, VBs} when is_list(VBs) ->
4217				case (catch validate_testTrapv22_vbs(MgrNode,
4218								     VBs)) of
4219				    ok ->
4220					?IPRINT("valid inform"),
4221					Pid ! {handle_inform_no_response,
4222					       From},
4223					ok;
4224				    Error ->
4225					?EPRINT("invalid inform: "
4226                                                "~n      ~p", [Error]),
4227					Error
4228				end;
4229			    {Err, Idx, VBs} ->
4230				?EPRINT("unexpected error status: "
4231                                        "~n   Err: ~p"
4232                                        "~n   Idx: ~p"
4233                                        "~n   VBs: ~p", [Err, Idx, VBs]),
4234				Reason = {unexpected_status, {Err, Idx, VBs}},
4235				{error, Reason}
4236			end
4237		after 10000 ->
4238			receive
4239			    Any ->
4240				{error, {timeout_crap, Any}}
4241			after 1000 ->
4242				{error, timeout}
4243			end
4244		end
4245	end,
4246
4247    Cmd4 =
4248	fun() ->
4249		receive
4250		    {async_event, From, {inform, Pid, Inform}} ->
4251			?IPRINT("received inform"),
4252			case Inform of
4253			    {noError, 0, VBs} when is_list(VBs) ->
4254				case (catch validate_testTrapv22_vbs(MgrNode,
4255								     VBs)) of
4256				    ok ->
4257                                        ?IPRINT("valid inform"),
4258					Pid ! {handle_inform_response, From},
4259					ok;
4260				    Error ->
4261					?EPRINT("invalid inform: "
4262                                                "~n      ~p", [Error]),
4263					Error
4264				end;
4265			    {Err, Idx, VBs} ->
4266				?EPRINT("unexpected error status: "
4267                                        "~n   Err: ~p"
4268                                        "~n   Idx: ~p"
4269                                        "~n   VBs: ~p", [Err, Idx, VBs]),
4270				Reason = {unexpected_status, {Err, Idx, VBs}},
4271				{error, Reason}
4272			end
4273		after 20000 ->
4274			receive
4275			    Any ->
4276				{error, {timeout_crap, Any}}
4277			after 1000 ->
4278				{error, timeout}
4279			end
4280		end
4281	end,
4282
4283    Cmd5 = fun() -> ?SLEEP(5000), ok end,
4284
4285    Commands =
4286	[
4287	 {1, "Manager and agent info at start of test", Cmd1},
4288	 {2, "Send notifcation [no receiver] from agent", Cmd2},
4289	 {3, "Await first inform to manager - do not reply", Cmd3},
4290	 {4, "Await second inform to manager - reply", Cmd4},
4291	 {5, "Sleep some time (5 sec)", Cmd5},
4292	 {6, "Manager and agent info after test completion", Cmd1}
4293	],
4294
4295    Res = command_handler(Commands),
4296    display_log(Config),
4297    Res.
4298
4299
4300%%======================================================================
4301
4302inform2(suite) -> [];
4303inform2(Config) when is_list(Config) ->
4304    ?TC_TRY(inform2,
4305            fun() -> do_inform2(Config) end).
4306
4307do_inform2(Config) ->
4308    ?IPRINT("starting with Config: "
4309            "~n      ~p"
4310            "~n", [Config]),
4311
4312    MgrNode   = ?config(manager_node, Config),
4313    AgentNode = ?config(agent_node, Config),
4314    %% Addr = ?config(ip, Config),
4315    %% Port = ?AGENT_PORT,
4316
4317    ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),
4318    Test2Mib      = test2_mib(Config),
4319    TestTrapMib   = test_trap_mib(Config),
4320    TestTrapv2Mib = test_trap_v2_mib(Config),
4321    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
4322    ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),
4323    ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),
4324    ?line ok = agent_load_mib(AgentNode,  Test2Mib),
4325    ?line ok = agent_load_mib(AgentNode,  TestTrapMib),
4326    ?line ok = agent_load_mib(AgentNode,  TestTrapv2Mib),
4327
4328    Cmd1 =
4329	fun() ->
4330		?IPRINT("manager info: "
4331                        "~n    ~p", [mgr_info(MgrNode)]),
4332		?IPRINT("agent info: "
4333                        "~n    ~p", [agent_info(AgentNode)]),
4334		ok
4335	end,
4336
4337    Cmd2 =
4338	fun() ->
4339		agent_send_notif(AgentNode,
4340				 testTrapv22,
4341				 {inform2_tag1, self()},
4342				 "standard inform",
4343				[]),
4344		ok
4345	end,
4346
4347    Cmd3 =
4348	fun() ->
4349		receive
4350		    {snmp_targets, inform2_tag1, Addrs} ->
4351			?IPRINT("sent inform to ~p", [Addrs]),
4352			ok
4353		after 10000 ->
4354			receive
4355			    Any ->
4356				{error, {timeout_crap, Any}}
4357			after 1000 ->
4358				{error, timeout}
4359			end
4360		end
4361	end,
4362
4363    Cmd4 =
4364	fun() ->
4365		receive
4366		    {async_event, From, {inform, Pid, Inform}} ->
4367			?IPRINT("received inform"),
4368			case Inform of
4369			    {noError, 0, VBs} when is_list(VBs) ->
4370				case (catch validate_testTrapv22_vbs(MgrNode,
4371								     VBs)) of
4372				    ok ->
4373					?IPRINT("valid inform"),
4374					Pid ! {handle_inform_no_response,
4375					       From},
4376					ok;
4377				    Error ->
4378					?IPRINT("invalid inform: "
4379                                                "~n      ~p", [Error]),
4380					Error
4381				end;
4382			    {Err, Idx, VBs} ->
4383				?EPRINT("unexpected error status: "
4384                                        "~n   Err: ~p"
4385                                        "~n   Idx: ~p"
4386                                        "~n   VBs: ~p", [Err, Idx, VBs]),
4387				Reason = {unexpected_status, {Err, Idx, VBs}},
4388				{error, Reason}
4389			end
4390		after 10000 ->
4391			receive
4392			    Any ->
4393				{error, {timeout_crap, Any}}
4394			after 1000 ->
4395				{error, timeout}
4396			end
4397		end
4398	end,
4399
4400    Cmd5 =
4401	fun() ->
4402		receive
4403		    {async_event, From, {inform, Pid, Inform}} ->
4404			?IPRINT("received inform"),
4405			case Inform of
4406			    {noError, 0, VBs} when is_list(VBs) ->
4407				case (catch validate_testTrapv22_vbs(MgrNode,
4408								     VBs)) of
4409				    ok ->
4410					?IPRINT("valid inform"),
4411					Pid ! {handle_inform_response, From},
4412					ok;
4413				    Error ->
4414					?EPRINT("invalid inform: "
4415                                                "~n      ~p", [Error]),
4416					Error
4417				end;
4418			    {Err, Idx, VBs} ->
4419				?EPRINT("unexpected error status: "
4420                                        "~n   Err: ~p"
4421                                        "~n   Idx: ~p"
4422                                        "~n   VBs: ~p", [Err, Idx, VBs]),
4423				Reason = {unexpected_status, {Err, Idx, VBs}},
4424				{error, Reason}
4425			end
4426		after 20000 ->
4427			receive
4428			    Any ->
4429				{error, {timeout_crap, Any}}
4430			after 1000 ->
4431				{error, timeout}
4432			end
4433		end
4434	end,
4435
4436    Cmd6 =
4437	fun() ->
4438		receive
4439		    {snmp_notification, inform2_tag1, {got_response, Addr}} ->
4440			?IPRINT("received expected \"got response\" notification "
4441                                "from: "
4442                                "~n      ~p", [Addr]),
4443			ok;
4444		    {snmp_notification, inform2_tag1, {no_response, Addr}} ->
4445			?EPRINT("Received unexpected \"no response\" "
4446                                "notification from: "
4447                                "~n      ~p", [Addr]),
4448			{error, no_response}
4449		after 10000 ->
4450			receive
4451			    Any ->
4452				{error, {timeout_crap, Any}}
4453			after 1000 ->
4454				{error, timeout}
4455			end
4456		end
4457	end,
4458
4459    Cmd7 = fun() -> ?SLEEP(5000), ok end,
4460
4461    Commands =
4462	[
4463	 {1, "Manager and agent info at start of test", Cmd1},
4464	 {2, "Send notifcation [no receiver] from agent", Cmd2},
4465	 {3, "Await inform-sent acknowledge from agent", Cmd3},
4466	 {4, "Await first inform to manager - do not reply", Cmd4},
4467	 {5, "Await second inform to manager - reply", Cmd5},
4468	 {6, "await inform-acknowledge from agent", Cmd6},
4469	 {7, "Sleep some time (5 sec)", Cmd7},
4470	 {8, "Manager and agent info after test completion", Cmd1}
4471	],
4472
4473    Res = command_handler(Commands),
4474    display_log(Config),
4475    Res.
4476
4477
4478%%======================================================================
4479
4480inform3(suite) -> [];
4481inform3(Config) when is_list(Config) ->
4482    ?TC_TRY(inform3,
4483            fun() -> do_inform3(Config) end).
4484
4485do_inform3(Config) ->
4486    ?IPRINT("starting with Config: "
4487            "~n      ~p~n", [Config]),
4488
4489    MgrNode   = ?config(manager_node, Config),
4490    AgentNode = ?config(agent_node, Config),
4491
4492    ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),
4493    Test2Mib      = test2_mib(Config),
4494    TestTrapMib   = test_trap_mib(Config),
4495    TestTrapv2Mib = test_trap_v2_mib(Config),
4496    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
4497    ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),
4498    ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),
4499    ?line ok = agent_load_mib(AgentNode,  Test2Mib),
4500    ?line ok = agent_load_mib(AgentNode,  TestTrapMib),
4501    ?line ok = agent_load_mib(AgentNode,  TestTrapv2Mib),
4502
4503    Cmd1 =
4504	fun() ->
4505		?IPRINT("manager info: "
4506                        "~n      ~p", [mgr_info(MgrNode)]),
4507		?IPRINT("agent info: "
4508                        "~n      ~p", [agent_info(AgentNode)]),
4509		ok
4510	end,
4511
4512    Cmd2 =
4513	fun() ->
4514		agent_send_notif(AgentNode,
4515				 testTrapv22,
4516				 {inform3_tag1, self()},
4517				 "standard inform",
4518				 []),
4519		ok
4520	end,
4521
4522    Cmd3 =
4523	fun() ->
4524		receive
4525		    {snmp_targets, inform3_tag1, [_Addr]} ->
4526			?IPRINT("received inform-sent ack"),
4527			ok
4528		after 10000 ->
4529			receive
4530			    Crap ->
4531				{error, {timeout_crap, Crap}}
4532			after 0 ->
4533				{error, timeout}
4534			end
4535		end
4536	end,
4537
4538    Cmd4 =
4539	fun() ->
4540		receive
4541		    {async_event, From, {inform, Pid, Inform}} ->
4542			?IPRINT("received inform"),
4543			case Inform of
4544			    {noError, 0, VBs} when is_list(VBs) ->
4545				case (catch validate_testTrapv22_vbs(MgrNode,
4546								     VBs)) of
4547				    ok ->
4548					?IPRINT("valid inform"),
4549					Pid ! {handle_inform_no_response, From},
4550					ok;
4551				    Error ->
4552					?EPRINT("invalid inform: "
4553                                                "~n      ~p", [Error]),
4554					Error
4555				end;
4556			    {Err, Idx, VBs} ->
4557				?EPRINT("unexpected error status: "
4558                                        "~n   Err: ~p"
4559                                        "~n   Idx: ~p"
4560                                        "~n   VBs: ~p", [Err, Idx, VBs]),
4561				Reason = {unexpected_status, {Err, Idx, VBs}},
4562				{error, Reason}
4563			end
4564		after 50000 ->
4565			receive
4566			    Any ->
4567				{error, {timeout_crap, Any}}
4568			after 0 ->
4569				{error, timeout}
4570			end
4571		end
4572	end,
4573
4574    Cmd7 =
4575	fun() ->
4576		receive
4577		    {snmp_notification, inform3_tag1, {no_response, Addr}} ->
4578			?IPRINT("received expected \"no response\" notification "
4579                                "from: "
4580                                "~n   ~p", [Addr]),
4581			ok;
4582		    {snmp_notification, inform3_tag1, {got_response, Addr}} ->
4583			?EPRINT("Received unexpected \"got response\" "
4584                                "notification from: "
4585                                "~n   ~p",
4586                                [Addr]),
4587			{error, {got_response, Addr}}
4588		after 120000 ->
4589			receive
4590			    Crap ->
4591				{error, {timeout_crap, Crap}}
4592			after 0 ->
4593				{error, timeout}
4594			end
4595		end
4596	end,
4597
4598    Cmd8 = fun() -> ?SLEEP(1000), ok end,
4599
4600    Commands =
4601	[
4602	 {1, "Manager and agent info at start of test", Cmd1},
4603	 {2, "Send notifcation from agent", Cmd2},
4604	 {3, "await inform-sent acknowledge from agent", Cmd3},
4605	 {4, "Await first inform to manager - do not reply", Cmd4},
4606	 {5, "Await first inform to manager - do not reply", Cmd4},
4607	 {6, "Await first inform to manager - do not reply", Cmd4},
4608	 {7, "await inform-acknowledge from agent", Cmd7},
4609	 {8, "Sleep some time (1 sec)", Cmd8},
4610	 {9, "Manager and agent info after test completion", Cmd1}
4611	],
4612
4613    Res = command_handler(Commands),
4614    display_log(Config),
4615    Res.
4616
4617
4618%%======================================================================
4619
4620inform4(suite) -> [];
4621inform4(Config) when is_list(Config) ->
4622    ?TC_TRY(inform4,
4623            fun() -> do_inform4(Config) end).
4624
4625do_inform4(Config) ->
4626    ?IPRINT("starting with Config: "
4627            "~n      ~p~n", [Config]),
4628
4629    MgrNode   = ?config(manager_node, Config),
4630    AgentNode = ?config(agent_node, Config),
4631
4632    ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),
4633    Test2Mib      = test2_mib(Config),
4634    TestTrapMib   = test_trap_mib(Config),
4635    TestTrapv2Mib = test_trap_v2_mib(Config),
4636    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
4637    ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),
4638    ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),
4639    ?line ok = agent_load_mib(AgentNode,  Test2Mib),
4640    ?line ok = agent_load_mib(AgentNode,  TestTrapMib),
4641    ?line ok = agent_load_mib(AgentNode,  TestTrapv2Mib),
4642
4643    Cmd1 =
4644	fun() ->
4645		?IPRINT("manager info: "
4646                        "~n      ~p", [mgr_info(MgrNode)]),
4647		?IPRINT("agent info: "
4648                        "~n      ~p", [agent_info(AgentNode)]),
4649		ok
4650	end,
4651
4652    Cmd2 =
4653	fun() ->
4654		agent_send_notif(AgentNode, testTrapv22, "standard inform"),
4655		ok
4656	end,
4657
4658    Cmd3 =
4659	fun() ->
4660		receive
4661		    {async_event, From, {inform, Pid, Inform}} ->
4662			?IPRINT("received inform"),
4663			case Inform of
4664			    {noError, 0, VBs} when is_list(VBs) ->
4665				case (catch validate_testTrapv22_vbs(MgrNode,
4666								     VBs)) of
4667				    ok ->
4668					?IPRINT("valid inform"),
4669					%% Actually, as we have
4670					%% configured the manager in
4671					%% this test case (irb = auto)
4672					%% it has already responded
4673					Pid ! {handle_inform_response, From},
4674					ok;
4675				    Error ->
4676					?EPRINT("invalid inform: "
4677                                                "~n      ~p", [Error]),
4678					Error
4679				end;
4680			    {Err, Idx, VBs} ->
4681				?EPRINT("unexpected error status: "
4682                                        "~n   Err: ~p"
4683                                        "~n   Idx: ~p"
4684                                        "~n   VBs: ~p", [Err, Idx, VBs]),
4685				Reason = {unexpected_status, {Err, Idx, VBs}},
4686				{error, Reason}
4687			end
4688		after 20000 ->
4689			receive
4690			    Any ->
4691				{error, {crap, Any}}
4692			after 1000 ->
4693				{error, timeout}
4694			end
4695		end
4696	end,
4697
4698    %% This is the a result of erroneous configuration.
4699%%     Cmd4 =
4700%% 	fun() ->
4701%% 		receive
4702%% 		    {async_event, _ReqId, {error, Reason}} ->
4703%% 			?IPRINT("received error"),
4704%% 			case Reason of
4705%% 			    {failed_processing_message,
4706%% 			     {securityError, usmStatsUnknownEngineIDs}} ->
4707%% 				?IPRINT("expected error"),
4708%% 				ok;
4709%% 			    _ ->
4710%% 				p("unexpected error: "
4711%% 				  "~n   Reason: ~p", [Reason]),
4712%% 				{error, {unexpected_error, Reason}}
4713%% 			end
4714%% 		after 20000 ->
4715%% 			receive
4716%% 			    Any ->
4717%% 				{error, {crap, Any}}
4718%% 			after 1000 ->
4719%% 				{error, timeout}
4720%% 			end
4721%% 		end
4722%% 	end,
4723
4724    Cmd5 = fun() -> ?SLEEP(1000), ok end,
4725
4726    Commands =
4727	[
4728	 {1, "Manager and agent info at start of test", Cmd1},
4729	 {2, "Send notifcation [no receiver] from agent", Cmd2},
4730	 {3, "Await inform to manager", Cmd3},
4731%% 	 {4, "Await error info (because of erroneous config)", Cmd4},
4732	 {5, "Sleep some time (1 sec)", Cmd5},
4733	 {6, "Manager and agent info after test completion", Cmd1}
4734	],
4735
4736    Res = command_handler(Commands),
4737    display_log(Config),
4738    Res.
4739
4740
4741%%======================================================================
4742%%
4743%% Test: ts:run(snmp, snmp_manager_test, inform_swarm_cbp_def, [batch]).
4744
4745inform_swarm_cbp_def(suite) -> [];
4746inform_swarm_cbp_def(Config) when is_list(Config) ->
4747    inform_swarm(is_cbp_def, Config).
4748
4749inform_swarm_cbp_temp(suite) -> [];
4750inform_swarm_cbp_temp(Config) when is_list(Config) ->
4751    inform_swarm(is_cbp_temp, Config).
4752
4753inform_swarm_cbp_perm(suite) -> [];
4754inform_swarm_cbp_perm(Config) when is_list(Config) ->
4755    inform_swarm(is_cbp_perm, Config).
4756
4757inform_swarm(Case, Config) ->
4758    ?TC_TRY(Case,
4759            fun() -> do_inform_swarm(Config) end).
4760
4761do_inform_swarm(Config) ->
4762    %% process_flag(trap_exit, true),
4763    ?IPRINT("starting with Config: "
4764            "~p      ~n", [Config]),
4765
4766    MgrNode   = ?config(manager_node, Config),
4767    AgentNode = ?config(agent_node, Config),
4768
4769    ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),
4770    Test2Mib      = test2_mib(Config),
4771    TestTrapMib   = test_trap_mib(Config),
4772    TestTrapv2Mib = test_trap_v2_mib(Config),
4773    ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
4774    ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),
4775    ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),
4776    ?line ok = agent_load_mib(AgentNode,  Test2Mib),
4777    ?line ok = agent_load_mib(AgentNode,  TestTrapMib),
4778    ?line ok = agent_load_mib(AgentNode,  TestTrapv2Mib),
4779    NumInforms = 2000,
4780
4781    Collector = self(),
4782
4783    Generator =
4784	erlang:spawn(
4785	  fun() ->
4786		  receive
4787		      {Collector, start} ->
4788			  ok
4789		  end,
4790		  Seqs = lists:seq(1, NumInforms),
4791		  lists:foreach(
4792		    fun(N) ->
4793			    ?IPRINT("send notification ~w", [N]),
4794			    agent_send_notif(AgentNode,
4795					     testTrapv22,
4796					     {{inform2_tag1, N}, Collector},
4797					     "standard inform",
4798					     []),
4799			    %% Sleep some [(N div 10)*100 ms]
4800			    %% every tenth notification
4801			    if
4802                                N rem 100 == 0 ->
4803                                    Sleep = 1000,
4804				    ?IPRINT("sleep ~w [~w]", [Sleep, N]),
4805                                    ?SLEEP(Sleep);
4806				N rem 10 == 0 ->
4807                                    Sleep = 100,
4808				    ?IPRINT("sleep ~w [~w]", [Sleep, N]),
4809				    ?SLEEP(Sleep);
4810				true ->
4811				    ok
4812			    end
4813		    end,
4814		    Seqs),
4815		  ok
4816	  end),
4817
4818    Cmd1 =
4819	fun() ->
4820		?IPRINT("manager info: "
4821                        "~n      ~p", [mgr_info(MgrNode)]),
4822		?IPRINT("agent info: "
4823                        "~n      ~p", [agent_info(AgentNode)]),
4824		ok
4825	end,
4826
4827    Cmd2 = fun() -> Generator ! {Collector, start}, ok end,
4828
4829    Cmd3 =
4830	fun() ->
4831		inform_swarm_collector(NumInforms)
4832	end,
4833
4834
4835    Cmd4 = fun() -> ?SLEEP(1000), ok end,
4836
4837    Commands =
4838	[
4839	 {1, "Manager and agent info at start of test", Cmd1},
4840	 {2, "Send notifcation(s) from agent", Cmd2},
4841	 {3, "Await send-ack(s)/inform(s)/response(s)", Cmd3},
4842	 {4, "Sleep some time (1 sec)", Cmd4},
4843	 {5, "Manager and agent info after test completion", Cmd1}
4844	],
4845
4846    Res = command_handler(Commands),
4847    display_log(Config),
4848    Res.
4849
4850
4851inform_swarm_collector(N) ->
4852    inform_swarm_collector(N, 0, 0, 0, ?SECS(60)).
4853
4854%% Note that we need to deal with re-transmissions!
4855%% That is, the agent did not receive the ack in time,
4856%% and therefor did a re-transmit. This means that we
4857%% expect to receive more inform's then we actually
4858%% sent. So for success we assume:
4859%%
4860%%     SentAckCnt =  N
4861%%     RespCnt    =  N
4862%%     RecvCnt    >= N
4863%%
4864inform_swarm_collector(N, SentAckCnt, RecvCnt, RespCnt, _)
4865  when ((N == SentAckCnt) and
4866	(N == RespCnt)    and
4867	(N =< RecvCnt)) ->
4868    ?IPRINT("inform_swarm_collector -> done when"
4869            "~n      N:          ~w"
4870            "~n      SentAckCnt: ~w"
4871            "~n      RecvCnt:    ~w"
4872            "~n      RespCnt:    ~w", [N, SentAckCnt, RecvCnt, RespCnt]),
4873    ok;
4874inform_swarm_collector(N, SentAckCnt, RecvCnt, RespCnt, Timeout) ->
4875    %% ?IPRINT("inform_swarm_collector -> entry with"
4876    %%         "~n      N:          ~w"
4877    %%         "~n      SentAckCnt: ~w"
4878    %%         "~n      RecvCnt:    ~w"
4879    %%         "~n      RespCnt:    ~w", [N, SentAckCnt, RecvCnt, RespCnt]),
4880    receive
4881	{snmp_targets, {inform2_tag1, Id}, [_Addr]} ->
4882	    ?IPRINT("received inform-sent acknowledgement for ~w", [Id]),
4883	    inform_swarm_collector(N, SentAckCnt+1, RecvCnt, RespCnt,
4884				   Timeout);
4885
4886	%% The manager has received the actual inform
4887	{async_event, From, {inform, Pid, Inform}} ->
4888	    ?IPRINT("received inform"),
4889	    case Inform of
4890		{noError, 0, VBs} when is_list(VBs) ->
4891		    Pid ! {handle_inform_response, From},
4892		    inform_swarm_collector(N, SentAckCnt, RecvCnt+1, RespCnt,
4893					   Timeout);
4894		{Err, Idx, VBs} ->
4895		    ?EPRINT("Unexpected error status: "
4896                            "~n   Err: ~p"
4897                            "~n   Idx: ~p"
4898                            "~n   VBs: ~p", [Err, Idx, VBs]),
4899		    Reason = {unexpected_status, {Err, Idx, VBs}},
4900		    {error, Reason}
4901	    end;
4902
4903	%% The agent has received ack from the manager
4904	{snmp_notification, {inform2_tag1, Id}, {got_response, Addr}} ->
4905	    ?IPRINT("received expected \"got response\" for ~w "
4906                    "notification from: "
4907                    "~n      ~p", [Id, Addr]),
4908	    inform_swarm_collector(N, SentAckCnt, RecvCnt, RespCnt+1,
4909				   Timeout);
4910
4911	%% The agent did not received ack from the manager in time
4912	{snmp_notification, inform2_tag1, {no_response, Addr}} ->
4913	    ?EPRINT("Received expected \"no response\" notification "
4914                    "from: "
4915                    "~n      ~p", [Addr]),
4916	    Reason = {no_response, Addr, {N, SentAckCnt, RecvCnt, RespCnt}},
4917	    {error, Reason}
4918
4919    after Timeout ->
4920	    %% Give up when we have been dead in the water for Timeout ms
4921            ?EPRINT("timeout when"
4922                    "~n   N:          ~p"
4923                    "~n   SentAckCnt: ~p"
4924                    "~n   RecvCnt:    ~p"
4925                    "~n   RespCnt:    ~p",
4926                    [N, SentAckCnt, RecvCnt, RespCnt]),
4927	    {error, {timeout, N, SentAckCnt, RecvCnt, RespCnt}}
4928    end.
4929
4930
4931%%======================================================================
4932
4933report(suite) -> [];
4934report(Config) when is_list(Config) ->
4935    ?SKIP(not_yet_implemented).
4936
4937
4938
4939%%======================================================================
4940
4941otp8015_1(doc) -> ["OTP-8015:1 - testing the new api-function."];
4942otp8015_1(suite) -> [];
4943otp8015_1(Config) when is_list(Config) ->
4944    Pre = fun() ->
4945                  ConfDir = ?config(manager_conf_dir, Config),
4946                  DbDir   = ?config(manager_db_dir, Config),
4947
4948                  write_manager_conf(ConfDir),
4949
4950                  Opts = [{server,     [{verbosity, trace}]},
4951                          {net_if,     [{verbosity, trace}]},
4952                          {note_store, [{verbosity, trace}]},
4953                          {config,     [{verbosity, trace},
4954                                        {dir,       ConfDir},
4955                                        {db_dir,    DbDir}]}],
4956
4957                  ?IPRINT("starting manager"),
4958                  ok = snmpm:start_link(Opts),
4959
4960                  ?SLEEP(1000),
4961                  ok
4962          end,
4963    Case = fun(_) -> do_otp8015_1(Config) end,
4964    Post = fun(_) ->
4965                   ?IPRINT("stop manager"),
4966                   ok = snmpm:stop(),
4967                   ?SLEEP(1000),
4968                   ok
4969           end,
4970    ?TC_TRY(otp8015_1, Pre, Case, Post).
4971
4972do_otp8015_1(Config) ->
4973    ?IPRINT("starting with Config: "
4974           "~n      ~p"
4975           "~n", [Config]),
4976
4977    snmpm:load_mib(std_mib()),
4978    snmpm:load_mib(test_trap_mib(Config)),
4979
4980    ?IPRINT("manager started, now sleep some"),
4981
4982    ?SLEEP(1000),
4983
4984    ?IPRINT("loaded mibs: ~p", [snmpm:which_mibs()]),
4985
4986    ?IPRINT("get some type(s) from the mibs"),
4987    {ok, 'Counter32'} = snmpm:oid_to_type(?snmpOutTraps),
4988    {ok, [IfIndex]}   = snmpm:name_to_oid(ifIndex),
4989    {ok, 'INTEGER'}   = snmpm:oid_to_type(IfIndex),
4990
4991    ?IPRINT("end"),
4992    ok.
4993
4994
4995%%======================================================================
4996
4997otp8395_1(doc) -> ["OTP-8395:1 - simple get with ATL sequence numbering."];
4998otp8395_1(suite) -> [];
4999otp8395_1(Config) when is_list(Config) ->
5000    ?TC_TRY(otp8395_1,
5001            fun() -> do_otp8395_1(Config) end).
5002
5003do_otp8395_1(Config) ->
5004    do_simple_sync_get2(Config).
5005
5006
5007%%======================================================================
5008%% async snmp utility functions
5009%%======================================================================
5010
5011async_exec([], Acc) ->
5012    ?IPRINT("all async request's sent => now await responses"),
5013    async_verify(async_collector(Acc, []));
5014async_exec([{Id, Data, Exec, Ver}|Reqs], Acc) ->
5015    ?IPRINT("issue async request ~w", [Id]),
5016    ?line {ok, ReqId} = Exec(Data),
5017    async_exec(Reqs, [{ReqId, Id, Ver}|Acc]).
5018
5019async_collector([], Acc) ->
5020    ?IPRINT("received replies for all requests - now sort"),
5021    lists:keysort(1, Acc);
5022async_collector(Expected, Acc) ->
5023    receive
5024	{async_event, ReqId, Reply} ->
5025	    ?IPRINT("received async event with request-id ~w", [ReqId]),
5026	    case lists:keysearch(ReqId, 1, Expected) of
5027		{value, {_, Id, Ver}} ->
5028		    ?IPRINT("event was for request ~w", [Id]),
5029		    Expected2 = lists:keydelete(ReqId, 1, Expected),
5030		    async_collector(Expected2, [{Id, Ver, Reply}|Acc]);
5031		false ->
5032		    % Duplicate reply?
5033                    ?EPRINT("unexpected async event: "
5034                            "~n      ReqId: ~p"
5035                            "~n      Reply: ~p", [ReqId, Reply]),
5036		    ?FAIL({unexpected_async_event, ReqId, Reply})
5037	    end
5038    after 10000 ->
5039	    ?FAIL({timeout, {Expected, Acc}})
5040    end.
5041
5042async_verify([]) ->
5043    ok;
5044async_verify([{Id, Verify, Reply}|Replies]) ->
5045    ?IPRINT("verify reply ~w", [Id]),
5046    Verify(Reply),
5047    async_verify(Replies).
5048
5049
5050
5051%%======================================================================
5052%% Internal functions
5053%%======================================================================
5054
5055
5056%% -- Verify varbinds --
5057
5058validate_vbs(Node, ExpVBs, VBs) ->
5059    validate_vbs(purify_oids(Node, ExpVBs), VBs).
5060
5061validate_testTrapv22_vbs(Node, VBs) ->
5062    ExpVBs = [{[sysUpTime, 0], any},
5063	      {[snmpTrapOID, 0], ?system ++ [0,1]}],
5064    validate_vbs(purify_oids(Node, ExpVBs), VBs).
5065
5066validate_vbs([], []) ->
5067    ok;
5068validate_vbs(Exp, []) ->
5069    {error, {expected_vbs, Exp}};
5070validate_vbs([], VBs) ->
5071    {error, {unexpected_vbs, VBs}};
5072validate_vbs([any|Exp], [_|VBs]) ->
5073    validate_vbs(Exp, VBs);
5074validate_vbs([{_, any}|Exp], [#varbind{}|VBs]) ->
5075    validate_vbs(Exp, VBs);
5076validate_vbs([{Oid, Val}|Exp], [#varbind{oid = Oid, value = Val}|VBs]) ->
5077    validate_vbs(Exp, VBs);
5078validate_vbs([{Oid, Val1}|_], [#varbind{oid = Oid, value = Val2}|_]) ->
5079    {error, {unexpected_vb_value, Oid, Val1, Val2}};
5080validate_vbs([{Oid1, _}|_], [#varbind{oid = Oid2}|_]) ->
5081    {error, {unexpected_vb_oid, Oid1, Oid2}}.
5082
5083purify_oids(_, []) ->
5084    [];
5085purify_oids(Node, [{Oid, Val}|Oids]) ->
5086    [{purify_oid(Node, Oid), Val}| purify_oids(Node, Oids)].
5087
5088purify_oid(Node, Oid) ->
5089    case mgr_user_purify_oid(Node, Oid) of
5090	Oid2 when is_list(Oid2) ->
5091	    Oid2;
5092	{error, _} = Error ->
5093	    throw(Error)
5094    end.
5095
5096
5097%% -- Test case command handler (executor) ---
5098
5099command_handler([]) ->
5100    ok;
5101command_handler([{No, Desc, Cmd}|Cmds]) ->
5102    ?IPRINT("command_handler -> command ~w: "
5103            "~n   ~s", [No, Desc]),
5104    case (catch Cmd()) of
5105	ok ->
5106            ?IPRINT("command_handler -> ~w: ok", [No]),
5107            command_handler(Cmds);
5108        {error, Reason} ->
5109            ?EPRINT("Command_handler -> ~w error: "
5110                    "~n      ~p", [No, Reason]),
5111            ?line ?FAIL({command_failed, No, Reason});
5112        Error ->
5113            ?EPRINT("Command_handler -> ~w unexpected: "
5114                    "~n      ~p", [No, Error]),
5115            ?line ?FAIL({unexpected_command_result, No, Error})
5116    end.
5117
5118
5119%% -- Misc manager functions --
5120
5121init_manager(AutoInform, Config) ->
5122
5123    ?IPRINT("init_manager -> entry with"
5124            "~n   AutoInform: ~p"
5125            "~n   Config:     ~p", [AutoInform, Config]),
5126
5127    %% --
5128    %% Start node
5129    %%
5130
5131    ?line Node = start_manager_node(),
5132
5133    %% The point with this (try catch block) is to be
5134    %% able to do some cleanup in case we fail to
5135    %% start some of the apps. That is, if we fail to
5136    %% start the apps (mnesia, crypto and snmp agent)
5137    %% we stop the (agent) node!
5138
5139    try
5140	begin
5141
5142	    %% --
5143	    %% Start and initiate crypto on manager node
5144	    %%
5145
5146	    ?line ok = init_crypto(Node),
5147
5148	    %%
5149	    %% Write manager config
5150	    %%
5151
5152	    ?line ok = write_manager_config(Config),
5153
5154	    IRB  = case AutoInform of
5155		       true ->
5156			   auto;
5157		       _ ->
5158			   user
5159		   end,
5160	    Conf = [{manager_node, Node}, {irb, IRB} | Config],
5161	    Vsns = [v1,v2,v3],
5162	    start_manager(Node, Vsns, Conf)
5163	end
5164    catch
5165	C:{suite_failed, Reason, _M, _L} = E:S when (C =:= exit) ->
5166	    ?EPRINT("Failure during manager start (suite-failed):"
5167                    "~n      Reason:      ~p"
5168                    "~n      StackTrace:  ~p", [Reason, S]),
5169	    %% And now, *try* to cleanup
5170	    (catch stop_node(Node)),
5171	    erlang:raise(C, E, S);
5172	C:E:S ->
5173	    ?EPRINT("Failure during manager start: "
5174                    "~n      Error Class: ~p"
5175                    "~n      Error:       ~p"
5176                    "~n      StackTrace:  ~p", [C, E, S]),
5177	    %% And now, *try* to cleanup
5178	    (catch stop_node(Node)),
5179	    ?FAIL({failed_starting_manager, C, E, S})
5180    end.
5181
5182fin_manager(Config) ->
5183    Node = ?config(manager_node, Config),
5184    StopMgrRes    = stop_manager(Node),
5185    StopCryptoRes = fin_crypto(Node),
5186    StopNode      = stop_node(Node),
5187    ?IPRINT("fin_manager -> stop apps and (mgr node ~p) node results: "
5188            "~n      SNMP Mgr: ~p"
5189            "~n      Crypto:   ~p"
5190            "~n      Node:     ~p",
5191            [Node, StopMgrRes, StopCryptoRes, StopNode]),
5192    Config.
5193
5194
5195%% -- Misc agent functions --
5196
5197init_agent(Config) ->
5198    ?IPRINT("init_agent -> entry with"
5199            "~n   Config: ~p", [Config]),
5200
5201    %% --
5202    %% Retrieve some dir's
5203    %%
5204    Dir    = ?config(agent_dir, Config),
5205    MibDir = ?config(mib_dir,  Config),
5206
5207    %% --
5208    %% Start node
5209    %%
5210
5211    ?line Node = start_agent_node(),
5212
5213    %% The point with this (try catch block) is to be
5214    %% able to do some cleanup in case we fail to
5215    %% start some of the apps. That is, if we fail to
5216    %% start the apps (mnesia, crypto and snmp agent)
5217    %% we stop the (agent) node!
5218
5219    try
5220	begin
5221
5222	    %% --
5223	    %% Start and initiate mnesia on agent node
5224	    %%
5225
5226	    ?line ok = init_mnesia(Node, Dir, ?config(mnesia_debug, Config)),
5227
5228
5229	    %% --
5230	    %% Start and initiate crypto on agent node
5231	    %%
5232
5233	    ?line ok = init_crypto(Node),
5234
5235
5236	    %%
5237	    %% Write agent config
5238	    %%
5239
5240	    Vsns = [v1,v2],
5241	    ?line ok = write_agent_config(Vsns, Config),
5242
5243	    Conf = [{agent_node, Node},
5244		    {mib_dir,    MibDir} | Config],
5245
5246	    %%
5247	    %% Start the agent
5248	    %%
5249
5250	    start_agent(Node, Vsns, Conf)
5251	end
5252    catch
5253	C:{suite_failed, Reason, _M, _L} = E:S when (C =:= exit) ->
5254	    ?EPRINT("Failure during agent start (suite-failed):"
5255                    "~n   Reason:     ~p"
5256                    "~n   StackTrace: ~p", [Reason, S]),
5257	    %% And now, *try* to cleanup
5258	    (catch stop_node(Node)),
5259	    erlang:raise(C, E, S);
5260	C:E:S ->
5261	    ?EPRINT("Failure during agent start: "
5262                    "~n   Error Class: ~p"
5263                    "~n   Error:       ~p"
5264                    "~n   StackTrace:  ~p", [C, E, S]),
5265	    %% And now, *try* to cleanup
5266	    (catch stop_node(Node)),
5267	    ?FAIL({failed_starting_agent, C, E, S})
5268    end.
5269
5270
5271fin_agent(Config) ->
5272    Node          = ?config(agent_node, Config),
5273    StopAgentRes  = stop_agent(Node),
5274    StopCryptoRes = fin_crypto(Node),
5275    StopMnesiaRes = fin_mnesia(Node),
5276    StopNode      = stop_node(Node),
5277    ?IPRINT("fin_agent -> stop apps and (agent node ~p) node results: "
5278            "~n   SNMP Agent: ~p"
5279            "~n   Crypto:     ~p"
5280            "~n   Mnesia:     ~p"
5281            "~n   Node:       ~p",
5282            [Node, StopAgentRes, StopCryptoRes, StopMnesiaRes, StopNode]),
5283    Config.
5284
5285init_mnesia(Node, Dir, MnesiaDebug)
5286  when ((MnesiaDebug =/= none) andalso
5287	(MnesiaDebug =/= debug) andalso (MnesiaDebug =/= trace)) ->
5288    init_mnesia(Node, Dir, ?DEFAULT_MNESIA_DEBUG);
5289init_mnesia(Node, Dir, MnesiaDebug) ->
5290    ?DBG("init_mnesia -> load application mnesia", []),
5291    ?line ok = load_mnesia(Node),
5292
5293    ?DBG("init_mnesia -> application mnesia: set_env dir: ~n~p",[Dir]),
5294    ?line ok = set_mnesia_env(Node, dir, filename:join(Dir, "mnesia")),
5295
5296    %% Just in case, only set (known to be) valid values for debug
5297    if
5298	((MnesiaDebug =:= debug) orelse (MnesiaDebug =:= trace)) ->
5299	    ?DBG("init_mnesia -> application mnesia: set_env debug: ~w",
5300		 [MnesiaDebug]),
5301	    ?line ok = set_mnesia_env(Node, debug, MnesiaDebug);
5302	true ->
5303	    ok
5304    end,
5305
5306    ?DBG("init_mnesia -> create mnesia schema",[]),
5307    ?line case create_schema(Node) of
5308	      ok ->
5309		  ok;
5310	      {error, {Node, {already_exists, Node}}} ->
5311		  ?line ok = delete_schema(Node),
5312		  ?line ok = create_schema(Node);
5313	      Error ->
5314		  ?FAIL({failed_creating_mnesia_schema, Error})
5315	  end,
5316
5317    ?DBG("init_mnesia -> start application mnesia",[]),
5318    ?line ok = start_mnesia(Node),
5319
5320    ?DBG("init_mnesia -> create tables",[]),
5321    ?line ok = create_tables(Node),
5322    ok.
5323
5324fin_mnesia(Node) ->
5325    ?line ok = delete_tables(Node),
5326    ?line ok = stop_mnesia(Node),
5327    ok.
5328
5329
5330init_crypto(Node) ->
5331    ?line ok = load_crypto(Node),
5332    ?line ok = start_crypto(Node),
5333    ok.
5334
5335fin_crypto(Node) ->
5336    ?line ok = stop_crypto(Node),
5337    ok.
5338
5339
5340%% -- Misc application wrapper functions --
5341
5342load_app(Node, App) ->
5343    VerifySuccess = fun(ok) ->
5344			    ok;
5345		       ({error, {already_loaded, LoadedApp}}) when (LoadedApp =:= App) ->
5346			    ok;
5347		       ({error, Reason}) ->
5348			    ?EPRINT("failed loading app ~w on ~p: "
5349                                    "~n      ~p", [App, Node, Reason]),
5350			    ?FAIL({failed_load, Node, App, Reason})
5351		    end,
5352    do_load_app(Node, App, VerifySuccess).
5353
5354do_load_app(Node, App, VerifySuccess)
5355  when (Node =:= node()) andalso is_atom(App) ->
5356    %% Local app
5357    exec(fun() -> application:load(App) end, VerifySuccess);
5358do_load_app(Node, App, VerifySuccess) ->
5359    %% Remote app
5360    exec(fun() -> rcall(Node, application, load, [App]) end, VerifySuccess).
5361
5362
5363start_app(Node, App) ->
5364    VerifySuccess = fun(ok) ->
5365			    ok;
5366		       ({error, {already_started, LoadedApp}}) when (LoadedApp =:= App) ->
5367			    ok;
5368		       ({error, Reason}) ->
5369			    ?EPRINT("failed starting app ~w on ~p: "
5370                                    "~n   Reason: ~p", [App, Node, Reason]),
5371			    ?FAIL({failed_start, Node, App, Reason})
5372		    end,
5373    start_app(Node, App, VerifySuccess).
5374
5375start_app(Node, App, VerifySuccess)
5376  when (Node =:= node()) andalso is_atom(App) ->
5377    exec(fun() -> application:start(App) end, VerifySuccess);
5378start_app(Node, App, VerifySuccess) ->
5379    exec(fun() -> rcall(Node, application, start, [App]) end, VerifySuccess).
5380
5381
5382stop_app(Node, App) ->
5383    VerifySuccess = fun(ok) ->
5384			    ok;
5385		       ({error, {not_started, LoadedApp}}) when (LoadedApp =:= App) ->
5386			    ok;
5387		       ({error, Reason}) ->
5388			    ?EPRINT("failed stopping app ~w on ~p: "
5389                                    "~n      ~p", [App, Node, Reason]),
5390			    ?FAIL({failed_stop, Node, App, Reason})
5391		    end,
5392    stop_app(Node, App, VerifySuccess).
5393
5394stop_app(Node, App, VerifySuccess)
5395  when (Node =:= node()) andalso is_atom(App)  ->
5396    exec(fun() -> application:stop(App) end, VerifySuccess);
5397stop_app(Node, App, VerifySuccess) when is_atom(App) ->
5398    exec(fun() -> rcall(Node, application, stop, [App]) end, VerifySuccess).
5399
5400
5401set_app_env(Node, App, Key, Val) ->
5402    VerifySuccess = fun(ok) ->
5403			    ok;
5404		       ({error, Reason}) ->
5405			    ?EPRINT("failed setting app ~w env on ~p"
5406                                    "~n      Key:    ~p"
5407                                    "~n      Val:    ~p"
5408                                    "~n      Reason: ~p",
5409                                    [App, Node, Key, Val, Reason]),
5410			    ?FAIL({failed_set_app_env,
5411				   Node, App, Key, Val, Reason})
5412		    end,
5413    set_app_env(Node, App, Key, Val, VerifySuccess).
5414
5415set_app_env(Node, App, Key, Val, VerifySuccess)
5416  when (Node =:= node()) andalso is_atom(App) ->
5417    exec(fun() -> application:set_env(App, Key, Val) end, VerifySuccess);
5418set_app_env(Node, App, Key, Val, VerifySuccess) when is_atom(App) ->
5419    exec(fun() -> rcall(Node, application, set_env, [App, Key, Val]) end,
5420	 VerifySuccess).
5421
5422
5423exec(Cmd, VerifySuccess) ->
5424    VerifySuccess(Cmd()).
5425
5426
5427%% -- Misc snmp wrapper functions --
5428
5429load_snmp(Node)                 -> load_app(Node, snmp).
5430start_snmp(Node)                -> start_app(Node, snmp).
5431stop_snmp(Node)                 -> stop_app(Node, snmp).
5432set_agent_env(Node, Env)        -> set_snmp_env(Node, agent, Env).
5433set_mgr_env(Node, Env)          -> set_snmp_env(Node, manager, Env).
5434set_snmp_env(Node, Entity, Env) -> set_app_env(Node, snmp, Entity, Env).
5435
5436mgr_info(Node) ->
5437    rcall(Node, snmpm, info, []).
5438
5439mgr_sys_info(Node) ->
5440    rcall(Node, snmpm_config, system_info, []).
5441
5442%% mgr_register_user(Node, Id, Data) ->
5443%%     mgr_register_user(Node, Id, ?MODULE, Data).
5444
5445mgr_register_user(Node, Id, Mod, Data) when is_atom(Mod) ->
5446    rcall(Node, snmpm, register_user, [Id, Mod, Data]).
5447
5448mgr_unregister_user(Node, Id) ->
5449    rcall(Node, snmpm, unregister_user, [Id]).
5450
5451mgr_which_users(Node) ->
5452    rcall(Node, snmpm, which_users, []).
5453
5454%% mgr_register_agent(Node, Id) ->
5455%%     mgr_register_agent(Node, Id, []).
5456
5457%% mgr_register_agent(Node, Id, Conf) when is_list(Conf) ->
5458%%     mgr_register_agent(Node, Id, 5000, Conf).
5459
5460mgr_register_agent(Node, Id, Port, Conf)
5461  when is_integer(Port) andalso is_list(Conf) ->
5462    Localhost = snmp_test_lib:localhost(),
5463    mgr_register_agent(Node, Id, Localhost, Port, Conf);
5464mgr_register_agent(Node, Id, TargetName, Config)
5465  when is_list(TargetName) andalso is_list(Config) ->
5466    rcall(Node, snmpm, register_agent, [Id, TargetName, Config]).
5467
5468mgr_register_agent(Node, Id, Addr, Port, Conf)
5469  when is_integer(Port) andalso is_list(Conf) ->
5470    rcall(Node, snmpm, register_agent, [Id, Addr, Port, Conf]).
5471
5472%% mgr_unregister_agent(Node, Id) ->
5473%%     mgr_unregister_agent(Node, Id, 4000).
5474
5475mgr_unregister_agent(Node, Id, Port) when is_integer(Port) ->
5476    Localhost = snmp_test_lib:localhost(),
5477    rcall(Node, snmpm, unregister_agent, [Id, Localhost, Port]);
5478mgr_unregister_agent(Node, Id, TargetName) when is_list(TargetName) ->
5479    rcall(Node, snmpm, unregister_agent, [Id, TargetName]).
5480
5481mgr_which_agents(Node) ->
5482    rcall(Node, snmpm, which_agents, []).
5483
5484mgr_which_agents(Node, Id) ->
5485    rcall(Node, snmpm, which_agents, [Id]).
5486
5487
5488%% -- Misc crypto wrapper functions --
5489
5490load_crypto(Node)  -> load_app(Node,  crypto).
5491start_crypto(Node) -> start_app(Node, crypto).
5492stop_crypto(Node)  -> stop_app(Node,  crypto).
5493
5494
5495%% -- Misc mnesia wrapper functions --
5496
5497load_mnesia(Node)              -> load_app(Node,    mnesia).
5498start_mnesia(Node)             -> start_app(Node,   mnesia).
5499stop_mnesia(Node)              -> stop_app(Node,    mnesia).
5500set_mnesia_env(Node, Key, Val) -> set_app_env(Node, mnesia, Key, Val).
5501
5502create_schema(Node) ->
5503    rcall(Node, mnesia, create_schema, [[Node]]).
5504
5505delete_schema(Node) ->
5506    rcall(Node, mnesia, delete_schema, [[Node]]).
5507
5508create_table(Node, Table) ->
5509    rcall(Node, mnesia, create_table, [Table]).
5510
5511delete_table(Node, Table) ->
5512    rcall(Node, mnesia, delete_table, [Table]).
5513
5514create_tables(Node) ->
5515    Tab1 = [{name,       friendsTable2},
5516	    {ram_copies, [Node]},
5517	    {snmp,       [{key, integer}]},
5518	    {attributes, [a1,a2,a3]}],
5519    Tab2 = [{name,       kompissTable2},
5520	    {ram_copies, [Node]},
5521	    {snmp,       [{key, integer}]},
5522	    {attributes, [a1,a2,a3]}],
5523    Tab3 = [{name,       snmp_variables},
5524	    {attributes, [a1,a2]}],
5525    Tabs = [Tab1, Tab2, Tab3],
5526    create_tables(Node, Tabs).
5527
5528create_tables(_Node, []) ->
5529    ok;
5530create_tables(Node, [Tab|Tabs]) ->
5531    case create_table(Node, Tab) of
5532	{atomic, ok} ->
5533	    create_tables(Node, Tabs);
5534	Error ->
5535	    ?FAIL({failed_creating_table, Node, Tab, Error})
5536    end.
5537
5538delete_tables(Node) ->
5539    Tabs = [friendsTable2, kompissTable2, snmp_variables],
5540    delete_tables(Node, Tabs).
5541
5542%% delete_mib_storage_tables(Node) ->
5543%%     Tabs = [snmpa_mib_data, snmpa_mib_tree, snmpa_symbolic_store],
5544%%     delete_tables(Node, Tabs).
5545
5546delete_tables(Node, Tabs) ->
5547    lists:foreach(fun(Tab) -> delete_table(Node, Tab) end, Tabs).
5548
5549
5550%% -- Misc manager user wrapper functions --
5551
5552init_mgr_user(Conf) ->
5553    ?DBG("init_mgr_user -> entry with"
5554	 "~n   Conf: ~p", [Conf]),
5555
5556    Node   = ?config(manager_node, Conf),
5557    %% UserId = ?config(user_id, Conf),
5558
5559    ?line {ok, User} = mgr_user_start(Node),
5560    ?DBG("start_mgr_user -> User: ~p", [User]),
5561    link(User),
5562
5563    [{user_pid, User} | Conf].
5564
5565fin_mgr_user(Conf) ->
5566    User = ?config(user_pid, Conf),
5567    unlink(User),
5568    Node = ?config(manager_node, Conf),
5569    ?line ok = mgr_user_stop(Node),
5570    Conf.
5571
5572init_mgr_user_data1(Conf) ->
5573    Node = ?config(manager_node, Conf),
5574    TargetName = ?config(manager_agent_target_name, Conf),
5575    IpFamily   = ?config(ipfamily, Conf),
5576    Ip         = ?config(ip, Conf),
5577    Port       = ?AGENT_PORT,
5578    ?line ok =
5579	case IpFamily of
5580	    inet ->
5581		mgr_user_register_agent(
5582		  Node, TargetName,
5583		  [{address,   Ip},
5584		   {port,      Port},
5585		   {engine_id, "agentEngine"}]);
5586	    inet6 ->
5587		mgr_user_register_agent(
5588		  Node, TargetName,
5589		  [{tdomain,   transportDomainUdpIpv6},
5590		   {taddress,  {Ip, Port}},
5591		   {engine_id, "agentEngine"}])
5592	end,
5593    _Agents = mgr_user_which_own_agents(Node),
5594    ?DBG("Own agents: ~p", [_Agents]),
5595
5596    ?line {ok, _DefAgentConf} = mgr_user_agent_info(Node, TargetName, all),
5597    ?DBG("Default agent config: ~n~p", [_DefAgentConf]),
5598
5599    ?line ok = mgr_user_update_agent_info(Node, TargetName,
5600					  community, "all-rights"),
5601    ?line ok = mgr_user_update_agent_info(Node, TargetName,
5602					  sec_name, "all-rights"),
5603    ?line ok = mgr_user_update_agent_info(Node, TargetName,
5604					  engine_id, "agentEngine"),
5605    ?line ok = mgr_user_update_agent_info(Node, TargetName,
5606					  max_message_size, 1024),
5607
5608    ?line {ok, _AgentConf} = mgr_user_agent_info(Node, TargetName, all),
5609    ?DBG("Updated agent config: ~n~p", [_AgentConf]),
5610    Conf.
5611
5612init_mgr_user_data2(Conf) ->
5613    ?DBG("init_mgr_user_data2 -> entry with"
5614	 "~n   Conf: ~p", [Conf]),
5615    Node       = ?config(manager_node, Conf),
5616    TargetName = ?config(manager_agent_target_name, Conf),
5617    IpFamily   = ?config(ipfamily, Conf),
5618    Ip         = ?config(ip, Conf),
5619    Port       = ?AGENT_PORT,
5620    ?line ok =
5621	case IpFamily of
5622	    inet ->
5623		mgr_user_register_agent(
5624		  Node, TargetName,
5625		  [{address,   Ip},
5626		   {port,      Port},
5627		   {engine_id, "agentEngine"}]);
5628	    inet6 ->
5629		mgr_user_register_agent(
5630		  Node, TargetName,
5631		  [{tdomain,   transportDomainUdpIpv6},
5632		   {taddress,  {Ip, Port}},
5633		   {engine_id, "agentEngine"}])
5634	end,
5635    _Agents = mgr_user_which_own_agents(Node),
5636    ?DBG("Own agents: ~p", [_Agents]),
5637
5638    ?line {ok, _DefAgentConf} = mgr_user_agent_info(Node, TargetName, all),
5639    ?DBG("Default agent config: ~n~p", [_DefAgentConf]),
5640
5641    ?line ok = mgr_user_update_agent_info(Node, TargetName,
5642					  community, "all-rights"),
5643    ?line ok = mgr_user_update_agent_info(Node, TargetName,
5644					  sec_name, "all-rights"),
5645    ?line ok = mgr_user_update_agent_info(Node, TargetName,
5646					  max_message_size, 1024),
5647
5648    ?line {ok, _AgentConf} = mgr_user_agent_info(Node, TargetName, all),
5649    ?DBG("Updated agent config: ~n~p", [_AgentConf]),
5650    Conf.
5651
5652fin_mgr_user_data1(Conf) ->
5653    Node = ?config(manager_node, Conf),
5654    TargetName = ?config(manager_agent_target_name, Conf),
5655    mgr_user_unregister_agent(Node, TargetName),
5656    mgr_user_which_own_agents(Node),
5657    Conf.
5658
5659fin_mgr_user_data2(Conf) ->
5660    Node = ?config(manager_node, Conf),
5661    TargetName = ?config(manager_agent_target_name, Conf),
5662    mgr_user_unregister_agent(Node, TargetName),
5663    mgr_user_which_own_agents(Node),
5664    Conf.
5665
5666mgr_user_start(Node) ->
5667    mgr_user_start(Node, snmp_manager_test_user).
5668mgr_user_start(Node, Id) ->
5669    rcall(Node, snmp_manager_user, start, [self(), Id]).
5670
5671mgr_user_stop(Node) ->
5672    rcall(Node, snmp_manager_user, stop, []).
5673
5674%% mgr_user_register_agent(Node) ->
5675%%     mgr_user_register_agent(Node, ?LOCALHOST(), ?AGENT_PORT, []).
5676%% mgr_user_register_agent(Node, TargetName) when is_list(TargetName) ->
5677%%     mgr_user_register_agent(Node, TargetName, []);
5678%% mgr_user_register_agent(Node, Addr) ->
5679%%     mgr_user_register_agent(Node, Addr, ?AGENT_PORT, []).
5680mgr_user_register_agent(Node, TargetName, Conf)
5681  when is_list(TargetName) andalso is_list(Conf) ->
5682    rcall(Node, snmp_manager_user, register_agent, [TargetName, Conf]).
5683
5684%% mgr_user_unregister_agent(Node) ->
5685%%     mgr_user_unregister_agent(Node, ?LOCALHOST(), ?AGENT_PORT).
5686mgr_user_unregister_agent(Node, TargetName) when is_list(TargetName) ->
5687    rcall(Node, snmp_manager_user, unregister_agent, [TargetName]).
5688
5689mgr_user_agent_info(Node, TargetName, Item)
5690  when is_list(TargetName) andalso is_atom(Item) ->
5691    rcall(Node, snmp_manager_user, agent_info, [TargetName, Item]).
5692
5693%% mgr_user_update_agent_info(Node, Item, Val) when atom(Item) ->
5694%%     mgr_user_update_agent_info(Node, ?LOCALHOST(), ?AGENT_PORT, Item, Val).
5695mgr_user_update_agent_info(Node, TargetName, Item, Val)
5696  when is_list(TargetName) andalso is_atom(Item) ->
5697    rcall(Node, snmp_manager_user, update_agent_info, [TargetName, Item, Val]).
5698
5699%% mgr_user_which_all_agents(Node) ->
5700%%     rcall(Node, snmp_manager_user, which_all_agents, []).
5701
5702mgr_user_which_own_agents(Node) ->
5703    rcall(Node, snmp_manager_user, which_own_agents, []).
5704
5705mgr_user_load_mib(Node, Mib) ->
5706    rcall(Node, snmp_manager_user, load_mib, [Mib]).
5707
5708%% mgr_user_sync_get(Node, Oids) ->
5709%%     mgr_user_sync_get(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).
5710mgr_user_sync_get(Node, TargetName, Oids) when is_list(TargetName) ->
5711    rcall(Node, snmp_manager_user, sync_get, [TargetName, Oids]).
5712
5713mgr_user_sync_get2(Node, TargetName, Oids, SendOpts) when is_list(TargetName) ->
5714    rcall(Node, snmp_manager_user, sync_get2, [TargetName, Oids, SendOpts]).
5715
5716%% mgr_user_async_get(Node, Oids) ->
5717%%     mgr_user_async_get(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).
5718mgr_user_async_get(Node, TargetName, Oids) when is_list(TargetName) ->
5719    rcall(Node, snmp_manager_user, async_get, [TargetName, Oids]).
5720
5721mgr_user_async_get2(Node, TargetName, Oids, SendOpts)
5722  when is_list(TargetName) ->
5723    rcall(Node, snmp_manager_user, async_get2, [TargetName, Oids, SendOpts]).
5724
5725%% mgr_user_sync_get_next(Node, Oids) ->
5726%%     mgr_user_sync_get_next(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).
5727mgr_user_sync_get_next(Node, TargetName, Oids) when is_list(TargetName) ->
5728    rcall(Node, snmp_manager_user, sync_get_next, [TargetName, Oids]).
5729
5730mgr_user_sync_get_next2(Node, TargetName, Oids, SendOpts)
5731  when is_list(TargetName) ->
5732    rcall(Node, snmp_manager_user, sync_get_next2, [TargetName, Oids, SendOpts]).
5733
5734%% mgr_user_async_get_next(Node, Oids) ->
5735%%     mgr_user_async_get_next(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).
5736mgr_user_async_get_next(Node, TargetName, Oids) when is_list(TargetName) ->
5737    rcall(Node, snmp_manager_user, async_get_next, [TargetName, Oids]).
5738
5739mgr_user_async_get_next2(Node, TargetName, Oids, SendOpts)
5740  when is_list(TargetName) ->
5741    rcall(Node, snmp_manager_user, async_get_next2, [TargetName, Oids, SendOpts]).
5742
5743%% mgr_user_sync_set(Node, VAV) ->
5744%%     mgr_user_sync_set(Node, ?LOCALHOST(), ?AGENT_PORT, VAV).
5745mgr_user_sync_set(Node, TargetName, VAV) when is_list(TargetName) ->
5746    rcall(Node, snmp_manager_user, sync_set, [TargetName, VAV]).
5747
5748mgr_user_sync_set2(Node, TargetName, VAV, SendOpts) when is_list(TargetName) ->
5749    rcall(Node, snmp_manager_user, sync_set2, [TargetName, VAV, SendOpts]).
5750
5751%% mgr_user_async_set(Node, VAV) ->
5752%%     mgr_user_async_set(Node, ?LOCALHOST(), ?AGENT_PORT, VAV).
5753mgr_user_async_set(Node, TargetName, VAV) when is_list(TargetName) ->
5754    rcall(Node, snmp_manager_user, async_set, [TargetName, VAV]).
5755
5756mgr_user_async_set2(Node, TargetName, VAV, SendOpts) when is_list(TargetName) ->
5757    rcall(Node, snmp_manager_user, async_set2, [TargetName, VAV, SendOpts]).
5758
5759%% mgr_user_sync_get_bulk(Node, NonRep, MaxRep, Oids) ->
5760%%     mgr_user_sync_get_bulk(Node, ?LOCALHOST(), ?AGENT_PORT,
5761%% 			   NonRep, MaxRep, Oids).
5762mgr_user_sync_get_bulk(Node, TargetName, NonRep, MaxRep, Oids)
5763  when is_list(TargetName) ->
5764    rcall(Node, snmp_manager_user, sync_get_bulk,
5765	  [TargetName, NonRep, MaxRep, Oids]).
5766
5767mgr_user_sync_get_bulk2(Node, TargetName, NonRep, MaxRep, Oids, SendOpts)
5768  when is_list(TargetName) ->
5769    rcall(Node, snmp_manager_user, sync_get_bulk2,
5770	  [TargetName, NonRep, MaxRep, Oids, SendOpts]).
5771
5772%% mgr_user_async_get_bulk(Node, NonRep, MaxRep, Oids) ->
5773%%     mgr_user_async_get_bulk(Node, ?LOCALHOST(), ?AGENT_PORT,
5774%% 			   NonRep, MaxRep, Oids).
5775mgr_user_async_get_bulk(Node, TargetName, NonRep, MaxRep, Oids)
5776  when is_list(TargetName) ->
5777    rcall(Node, snmp_manager_user, async_get_bulk,
5778	  [TargetName, NonRep, MaxRep, Oids]).
5779
5780mgr_user_async_get_bulk2(Node, TargetName, NonRep, MaxRep, Oids, SendOpts)
5781  when is_list(TargetName) ->
5782    rcall(Node, snmp_manager_user, async_get_bulk2,
5783	  [TargetName, NonRep, MaxRep, Oids, SendOpts]).
5784
5785mgr_user_purify_oid(Node, Oid) ->
5786    rcall(Node, snmp_manager_user, purify_oid, [Oid]).
5787
5788mgr_user_name_to_oid(Node, Name) ->
5789    rcall(Node, snmp_manager_user, name_to_oid, [Name]).
5790
5791
5792%% -- Misc manager wrapper functions --
5793
5794start_manager(Node, Vsns, Config) ->
5795    start_manager(Node, Vsns, Config, []).
5796start_manager(Node, Vsns, Conf0, _Opts) ->
5797
5798    ?DBG("start_manager -> entry with"
5799	 "~n   Node:   ~p"
5800	 "~n   Vsns:   ~p"
5801	 "~n   Conf0:  ~p"
5802	 "~n   Opts:   ~p", [Node, Vsns, Conf0, _Opts]),
5803
5804    AtlDir  = ?config(manager_log_dir,  Conf0),
5805    ConfDir = ?config(manager_conf_dir, Conf0),
5806    DbDir   = ?config(manager_db_dir,   Conf0),
5807    IRB     = ?config(irb,              Conf0),
5808
5809    ConfigVerbosity    = get_opt(manager_config_verbosity,     Conf0, trace),
5810    NoteStoreVerbosity = get_opt(manager_note_store_verbosity, Conf0, log),
5811    NetIfVerbosity     = get_opt(manager_net_if_verbosity,     Conf0, trace),
5812
5813    AtlSeqNo           = get_opt(manager_atl_seqno,            Conf0, false),
5814
5815    ServerVerbosity    = get_opt(manager_server_verbosity,     Conf0, trace),
5816    CBP                = get_opt(manager_server_cbproxy,       Conf0, temporary),
5817    NIS                = get_opt(manager_server_nis,           Conf0, none),
5818
5819    NetIfConf =
5820	case get_opt(manager_net_if_module, Conf0, no_module) of
5821	    no_module ->
5822		[{verbosity, NetIfVerbosity}];
5823	    NetIfModule ->
5824		[{module,    NetIfModule},
5825		 {verbosity, NetIfVerbosity}]
5826	end,
5827
5828    Env = [{versions,                     Vsns},
5829	   {inform_request_behaviour,     IRB},
5830	   {audit_trail_log, [{type,      read_write},
5831			      {dir,       AtlDir},
5832			      {size,      {10240, 10}},
5833			      {repair,    true},
5834			      {seqno,     AtlSeqNo}]},
5835	   {config,          [{dir,       ConfDir},
5836			      {db_dir,    DbDir},
5837			      {verbosity, ConfigVerbosity}]},
5838	   {note_store,      [{verbosity, NoteStoreVerbosity}]},
5839	   {server,          [{verbosity, ServerVerbosity},
5840                              {cbproxy,   CBP},
5841                              {netif_sup, NIS}]},
5842	   {net_if,          NetIfConf}],
5843    ?line ok = set_mgr_env(Node, Env),
5844
5845    ?line ok = try start_snmp(Node) of
5846		   ok ->
5847		       ok;
5848		   {error, Reason} ->
5849		       ?FAIL({failed_start_manager, Reason})
5850	       catch
5851		   exit:{suite_failed, {failed_start, _, _, Reason}, _M, _L}:_ ->
5852		       ?FAIL({failed_start_manager, Reason});
5853                   C:E:S ->
5854                       erlang:raise(C, E, S)
5855	       end,
5856    Conf0.
5857
5858stop_manager(Node) ->
5859    stop_snmp(Node).
5860
5861
5862%% -- Misc agent wrapper functions --
5863
5864start_agent(Node, Vsns, Config) ->
5865    start_agent(Node, Vsns, Config, []).
5866start_agent(Node, Vsns, Conf0, _Opts) ->
5867    ?DBG("start_agent -> entry with"
5868	 "~n   Node:   ~p"
5869	 "~n   Vsns:   ~p"
5870	 "~n   Conf0:  ~p"
5871	 "~n   Opts:   ~p", [Node, Vsns, Conf0, _Opts]),
5872
5873    AtlDir  = ?config(agent_log_dir,  Conf0),
5874    ConfDir = ?config(agent_conf_dir, Conf0),
5875    DbDir   = ?config(agent_db_dir,   Conf0),
5876
5877    MAV  = get_opt(agent_verbosity,                Conf0, trace),
5878    CV   = get_opt(agent_config_verbosity,         Conf0, info),
5879    LDBV = get_opt(agent_local_db_verbosity,       Conf0, info),
5880    MSV  = get_opt(agent_mib_server_verbosity,     Conf0, info),
5881    NSV  = get_opt(agent_note_store_verbosity,     Conf0, info),
5882    SSV  = get_opt(agent_symbolic_store_verbosity, Conf0, info),
5883    NIV  = get_opt(agent_net_if_verbosity,         Conf0, log),
5884
5885    Env = [{versions,        Vsns},
5886	   {type,            master},
5887	   {agent_verbosity, MAV},
5888	   {audit_trail_log, [{type,   read_write},
5889			      {dir,    AtlDir},
5890			      {size,   {10240, 10}},
5891			      {repair, true}]},
5892	   {config,          [{dir,        ConfDir},
5893			      {force_load, false},
5894			      {verbosity,  CV}]},
5895	   {db_dir,          DbDir},
5896	   {local_db,        [{repair,    true},
5897			      {auto_save, 10000},
5898			      {verbosity, LDBV}]},
5899	   {mib_server,      [{verbosity, MSV}]},
5900	   {note_store,      [{verbosity, NSV}]},
5901	   {stymbolic_store, [{verbosity, SSV}]},
5902	   {net_if,          [{verbosity, NIV},
5903                              %% On some linux "they" add a 127.0.1.1 or somthing
5904                              %% similar, so if we don't specify bind_to
5905                              %% we don't know which address will be selected
5906                              %% (which will cause problems for some test cases).
5907                              {options, [{bind_to, true}]}]},
5908	   {multi_threaded,  true}],
5909    ?line ok = set_agent_env(Node, Env),
5910
5911    ?line try start_snmp(Node) of
5912	      ok ->
5913		  ok;
5914	      {error, Reason} ->
5915		  ?FAIL({failed_start_agent, Reason})
5916	  catch
5917	      exit:{suite_failed, {failed_start, _, _, Reason}, _M, _L}:_ ->
5918		  ?FAIL({failed_start_agent, Reason});
5919              C:E:S ->
5920		  erlang:raise(C, E, S)
5921	  end,
5922    Conf0.
5923
5924stop_agent(Node) ->
5925    stop_snmp(Node).
5926
5927agent_load_mib(Node, Mib) ->
5928    rcall(Node, snmpa, load_mibs, [[Mib]]).
5929%% agent_unload_mib(Node, Mib) ->
5930%%     rcall(Node, snmpa, unload_mibs, [[Mib]]).
5931
5932%% agent_send_trap(Node, Trap, Community) ->
5933%%     Args = [snmp_master_agent, Trap, Community],
5934%%     rcall(Node, snmpa, send_trap, Args).
5935
5936agent_send_trap(Node, Trap, Community, VBs) ->
5937    Args = [snmp_master_agent, Trap, Community, VBs],
5938    rcall(Node, snmpa, send_trap, Args).
5939
5940agent_send_notif(Node, Trap, Name) ->
5941    agent_send_notif(Node, Trap, Name, []).
5942
5943agent_send_notif(Node, Trap, Name, VBs) ->
5944    agent_send_notif(Node, Trap, no_receiver, Name, VBs).
5945
5946agent_send_notif(Node, Trap, Recv, Name, VBs) ->
5947    Args = [snmp_master_agent, Trap, Recv, Name, VBs],
5948    rcall(Node, snmpa, send_notification, Args).
5949
5950agent_info(Node) ->
5951    rcall(Node, snmpa, info, []).
5952
5953%% agent_which_mibs(Node) ->
5954%%     rcall(Node, snmpa, which_mibs, []).
5955
5956
5957%% -- Misc node operation wrapper functions --
5958
5959start_agent_node() ->
5960    start_node(snmp_agent).
5961
5962start_manager_node() ->
5963    start_node(snmp_manager).
5964
5965start_node(Name) ->
5966    start_node(Name, true).
5967start_node(Name, Retry) ->
5968    Pa   = filename:dirname(code:which(?MODULE)),
5969    Args = case init:get_argument('CC_TEST') of
5970               {ok, [[]]} ->
5971                   " -pa /clearcase/otp/libraries/snmp/ebin ";
5972               {ok, [[Path]]} ->
5973                   " -pa " ++ Path;
5974               error ->
5975                      ""
5976              end,
5977    A = Args ++ " -pa " ++ Pa ++
5978        " -s " ++ atom_to_list(snmp_test_sys_monitor) ++ " start" ++
5979        " -s global sync",
5980    try ?START_NODE(Name, A) of
5981	{ok, Node} ->
5982            global:sync(),
5983	    Node;
5984	{error, timeout} ->
5985            ?EPRINT("Failed starting node ~p: timeout", [Name]),
5986	    ?line ?FAIL({error_starting_node, Name, timeout});
5987	{error, {already_running, Node}} when (Retry =:= true) ->
5988            %% Ouch
5989            %% Either we previously failed to (properly) stop the node
5990            %% or it was a failed start, that reported failure (for instance
5991            %% timeout) but actually succeeded. Regardless, we don't know
5992            %% the state of this node, so (try) stop it and then (re-) try
5993            %% start again.
5994            ?WPRINT("Failed starting node ~p: Already Running - try stop", [Node]),
5995            case ?STOP_NODE(Node) of
5996                true ->
5997                    ?IPRINT("Successfully stopped old node ~p", [Node]),
5998                    start_node(Name, false);
5999                false ->
6000                    ?EPRINT("Failed stop old node ~p", [Node]),
6001                    ?line ?FAIL({error_starting_node, Node, Retry, already_running})
6002            end;
6003	{error, {already_running, Node}} ->
6004            ?EPRINT("Failed starting node ~p: Already Running", [Node]),
6005            ?line ?FAIL({error_starting_node, Node, Retry, already_running});
6006	{error, Reason} ->
6007            ?EPRINT("Failed starting node ~p: ~p", [Name, Reason]),
6008	    ?line ?FAIL({error_starting_node, Name, Reason})
6009    catch
6010        exit:{suite_failed, Reason} ->
6011            ?EPRINT("(suite) Failed starting node ~p: ~p", [Name, Reason]),
6012            ?line ?FAIL({failed_starting_node, Name, Reason})
6013    end.
6014
6015
6016stop_node(Node) ->
6017    case ?STOP_NODE(Node) of
6018        true ->
6019            ok;
6020        false ->
6021            ?line ?FAIL({failed_stop_node, Node})
6022    end.
6023
6024
6025
6026%% -- Misc config wrapper functions --
6027
6028write_manager_config(Config) ->
6029    Dir  = ?config(manager_conf_dir, Config),
6030    Ip = tuple_to_list(?config(ip, Config)),
6031    {Addr, Port} =
6032	case ?config(ipfamily, Config) of
6033	    inet ->
6034		{Ip, ?MGR_PORT};
6035	    inet6 ->
6036		{transportDomainUdpIpv6, {Ip, ?MGR_PORT}}
6037	end,
6038    snmp_config:write_manager_snmp_files(
6039      Dir, Addr, Port, ?MGR_MMS, ?MGR_ENGINE_ID, [], [], []).
6040
6041write_manager_conf(Dir) ->
6042    Port = "5000",
6043    MMS  = "484",
6044    EngineID = "\"mgrEngine\"",
6045    Str = lists:flatten(
6046            io_lib:format("%% Minimum manager config file\n"
6047                          "{port,             ~s}.\n"
6048                          "{max_message_size, ~s}.\n"
6049                          "{engine_id,        ~s}.\n",
6050                          [Port, MMS, EngineID])),
6051    write_manager_conf(Dir, Str).
6052
6053%% write_manager_conf(Dir, IP, Port, MMS, EngineID) ->
6054%%     Str = lists:flatten(
6055%%             io_lib:format("{address,          ~s}.\n"
6056%%                           "{port,             ~s}.\n"
6057%%                           "{max_message_size, ~s}.\n"
6058%%                           "{engine_id,        ~s}.\n",
6059%%                           [IP, Port, MMS, EngineID])),
6060%%     write_manager_conf(Dir, Str).
6061
6062write_manager_conf(Dir, Str) ->
6063    write_conf_file(Dir, "manager.conf", Str).
6064
6065
6066write_agent_config(Vsns, Conf) ->
6067    Dir = ?config(agent_conf_dir, Conf),
6068    ?line Ip  = tuple_to_list(?config(ip, Conf)),
6069    ?line Domain =
6070	case ?config(ipfamily, Conf) of
6071	    inet ->
6072		snmpUDPDomain;
6073	    inet6 ->
6074		transportDomainUdpIpv6
6075	end,
6076    ?line ok = write_agent_config_files(Dir, Vsns, Domain, Ip),
6077    ?line ok = update_agent_usm(Vsns, Dir),
6078    ?line ok = update_agent_community(Vsns, Dir),
6079    ?line ok = update_agent_vacm(Vsns, Dir),
6080    ?line ok = write_agent_target_addr_conf(Dir, Domain, Ip, Vsns),
6081    ?line ok = write_agent_target_params_conf(Dir, Vsns),
6082    ?line ok = write_agent_notify_conf(Dir),
6083    ok.
6084
6085write_agent_config_files(Dir, Vsns, Domain, Ip) ->
6086    snmp_config:write_agent_snmp_files(
6087      Dir, Vsns, Domain, {Ip, ?MGR_PORT}, {Ip, ?AGENT_PORT}, "mgr-test",
6088      trap, none, "", ?AGENT_ENGINE_ID, ?AGENT_MMS).
6089
6090update_agent_usm(Vsns, Dir) ->
6091    case lists:member(v3, Vsns) of
6092        true ->
6093            Conf = [{"agentEngine", "all-rights", "all-rights", zeroDotZero,
6094                     usmNoAuthProtocol, "", "",
6095                     usmNoPrivProtocol, "", "", "", "", ""},
6096
6097                    {"agentEngine", "no-rights", "no-rights", zeroDotZero,
6098                     usmNoAuthProtocol, "", "",
6099                     usmNoPrivProtocol, "", "", "", "", ""},
6100
6101                    {"agentEngine", "authMD5", "authMD5", zeroDotZero,
6102                     usmHMACMD5AuthProtocol, "", "",
6103                     usmNoPrivProtocol, "", "", "", "passwd_md5xxxxxx", ""},
6104
6105                    {"agentEngine", "authSHA", "authSHA", zeroDotZero,
6106                     usmHMACSHAAuthProtocol, "", "",
6107                     usmNoPrivProtocol, "", "", "",
6108                     "passwd_shaxxxxxxxxxx", ""},
6109
6110                    {"agentEngine", "privDES", "privDES", zeroDotZero,
6111                     usmHMACSHAAuthProtocol, "", "",
6112                     usmDESPrivProtocol, "", "", "",
6113                     "passwd_shaxxxxxxxxxx", "passwd_desxxxxxx"},
6114
6115                    {"mgrEngine", "all-rights", "all-rights", zeroDotZero,
6116                     usmNoAuthProtocol, "", "",
6117                     usmNoPrivProtocol, "", "", "", "", ""},
6118
6119                    {"mgrEngine", "no-rights", "no-rights", zeroDotZero,
6120                     usmNoAuthProtocol, "", "",
6121                     usmNoPrivProtocol, "", "", "", "", ""},
6122
6123                    {"mgrEngine", "authMD5", "authMD5", zeroDotZero,
6124                     usmHMACMD5AuthProtocol, "", "",
6125                     usmNoPrivProtocol, "", "", "", "passwd_md5xxxxxx", ""},
6126
6127                    {"mgrEngine", "authSHA", "authSHA", zeroDotZero,
6128                     usmHMACSHAAuthProtocol, "", "",
6129                     usmNoPrivProtocol, "", "", "",
6130                     "passwd_shaxxxxxxxxxx", ""},
6131
6132                    {"mgrEngine", "privDES", "privDES", zeroDotZero,
6133                     usmHMACSHAAuthProtocol, "", "",
6134                     usmDESPrivProtocol, "", "", "",
6135                     "passwd_shaxxxxxxxxxx", "passwd_desxxxxxx"}],
6136            snmp_config:update_agent_usm_config(Dir, Conf);
6137        false ->
6138            ok
6139    end.
6140
6141update_agent_community([v3], _Dir) ->
6142    ok;
6143update_agent_community(_, Dir) ->
6144    Conf = [{"no-rights", "no-rights", "no-rights", "", ""}],
6145    snmp_config:update_agent_community_config(Dir, Conf).
6146
6147update_agent_vacm(_Vsns, Dir) ->
6148    Conf = [{vacmSecurityToGroup, usm, "authMD5", "initial"},
6149            {vacmSecurityToGroup, usm, "authSHA", "initial"},
6150            {vacmSecurityToGroup, usm, "privDES", "initial"},
6151            {vacmSecurityToGroup, usm, "newUser", "initial"},
6152            {vacmViewTreeFamily, "internet", ?tDescr_instance,
6153             excluded, null}],
6154    snmp_config:update_agent_vacm_config(Dir, Conf).
6155
6156write_agent_target_addr_conf(Dir, Domain, Ip, Vsns) ->
6157    snmp_config:write_agent_snmp_target_addr_conf(
6158      Dir, Domain, {Ip, ?MGR_PORT}, 300, 3, Vsns).
6159
6160write_agent_target_params_conf(Dir, Vsns) ->
6161    F = fun(v1) -> {"target_v1", v1,  v1,  "all-rights", noAuthNoPriv};
6162           (v2) -> {"target_v2", v2c, v2c, "all-rights", noAuthNoPriv};
6163           (v3) -> {"target_v3", v3,  usm, "all-rights", noAuthNoPriv}
6164        end,
6165    Conf = [F(Vsn) || Vsn <- Vsns],
6166    snmp_config:write_agent_target_params_config(Dir, "", Conf).
6167
6168write_agent_notify_conf(Dir) ->
6169    Conf = [{"standard trap",   "std_trap",   trap},
6170            {"standard inform", "std_inform", inform}],
6171    snmp_config:write_agent_notify_config(Dir, "", Conf).
6172
6173
6174write_conf_file(Dir, File, Str) ->
6175    ?line {ok, Fd} = file:open(filename:join(Dir, File), write),
6176    ?line ok = io:format(Fd, "~s", [Str]),
6177    file:close(Fd).
6178
6179
6180%% ------
6181
6182display_log(Config) ->
6183    case lists:keysearch(manager_log_dir, 1, Config) of
6184	{value, {_, Dir}} ->
6185	    case lists:keysearch(manager_node, 1, Config) of
6186		{value, {_, Node}} ->
6187		    LogDir  = Dir,
6188		    Mibs    = [],
6189		    OutFile = j(LogDir, "snmpm_log.txt"),
6190		    ?IPRINT("~n"
6191                            "========================="
6192                            "  < Audit Trail Log >  "
6193                            "========================="
6194                            "~n"),
6195		    rcall(Node, snmpm, log_to_txt, [LogDir, Mibs, OutFile]),
6196		    rcall(Node, snmpm, log_to_io, [LogDir, Mibs]),
6197		    ?IPRINT("~n"
6198                            "========================="
6199                            " < / Audit Trail Log > "
6200                            "========================="
6201                            "~n");
6202		false ->
6203		    ?IPRINT("display_log -> no manager node found"),
6204		    ok
6205	    end;
6206	false ->
6207	    ?IPRINT("display_log -> no manager log dir found"),
6208	    ok
6209    end.
6210
6211
6212%% ------
6213
6214test2_mib(Config) ->
6215    j(test_mib_dir(Config), "Test2.bin").
6216
6217test_trap_mib(Config) ->
6218    j(test_mib_dir(Config), "TestTrap.bin").
6219
6220test_trap_v2_mib(Config) ->
6221    j(test_mib_dir(Config), "TestTrapv2.bin").
6222
6223std_mib() ->
6224    j(mib_dir(), "STANDARD-MIB.bin").
6225
6226snmpv2_mib() ->
6227    j(mib_dir(), "SNMPv2-MIB.bin").
6228
6229test_mib_dir(Config) ->
6230    ?config(mib_dir, Config).
6231
6232mib_dir() ->
6233    j(code:priv_dir(snmp), "mibs").
6234
6235j(A, B) ->
6236    filename:join(A, B).
6237
6238
6239%% ------
6240
6241get_opt(Key, Opts, Def) ->
6242    snmp_misc:get_option(Key, Opts, Def).
6243
6244
6245%% ------
6246
6247rcall(Node, Mod, Func, Args) ->
6248    case rpc:call(Node, Mod, Func, Args) of
6249	{badrpc, nodedown} ->
6250	    ?FAIL({rpc_failure, Node});
6251	Else ->
6252	    Else
6253    end.
6254
6255
6256%% ------
6257
6258ipv6_init(Config) when is_list(Config) ->
6259    [{ipfamily, inet6} | Config].
6260