aboutsummaryrefslogtreecommitdiffstats
path: root/lib/diameter/src/base/diameter_lib.erl
blob: 58b9a298128086cb2073307ffd771bef19a0d429 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2010-2016. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%

-module(diameter_lib).
-compile({no_auto_import, [now/0]}).

-export([info_report/2,
         error_report/2,
         warning_report/2,
         now/0,
         timestamp/0,
         timestamp/1,
         now_diff/1,
         micro_diff/1,
         micro_diff/2,
         time/1,
         eval/1,
         eval_name/1,
         get_stacktrace/0,
         ipaddr/1,
         spawn_opts/2,
         wait/1,
         fold_n/3,
         for_n/2,
         log/4]).

%% ---------------------------------------------------------------------------
%% # get_stacktrace/0
%% ---------------------------------------------------------------------------

%% Return a stacktrace with a leading, potentially large, argument
%% list replaced by an arity. Trace on stacktrace/0 to see the
%% original.

get_stacktrace() ->
    stacktrace(erlang:get_stacktrace()).

stacktrace([{M,F,A,L} | T]) when is_list(A) ->
    [{M, F, length(A), L} | T];
stacktrace(L) ->
    L.

%% ---------------------------------------------------------------------------
%% # info_report/2
%% ---------------------------------------------------------------------------

-spec info_report(Reason :: term(), T :: term())
   -> true.

info_report(Reason, T) ->
    report(fun error_logger:info_report/1, Reason, T),
    true.

%% ---------------------------------------------------------------------------
%% # error_report/2
%% # warning_report/2
%% ---------------------------------------------------------------------------

-spec error_report(Reason :: term(), T :: term())
   -> false.

error_report(Reason, T) ->
    report(fun error_logger:error_report/1, Reason, T).

-spec warning_report(Reason :: term(), T :: term())
   -> false.

warning_report(Reason, T) ->
    report(fun error_logger:warning_report/1, Reason, T).

report(Fun, Reason, T) ->
    Fun(io_lib:format("diameter: ~" ++ fmt(Reason) ++ "~n    ~p~n",
                      [Reason, T])),
    false.

fmt(T) ->
    if is_list(T) ->
            "s";
       true ->
            "p"
    end.

%% ---------------------------------------------------------------------------
%% # now/0
%% ---------------------------------------------------------------------------

-spec now()
   -> integer().

now() ->
    erlang:monotonic_time().

%% ---------------------------------------------------------------------------
%% # timestamp/0
%% ---------------------------------------------------------------------------

-spec timestamp()
   -> erlang:timestamp().

timestamp() ->
    timestamp(now()).

%% ---------------------------------------------------------------------------
%% # timestamp/1
%% ---------------------------------------------------------------------------

-spec timestamp(integer())
   -> erlang:timestamp().

timestamp(MonoT) ->  %% monotonic time
    MicroSecs = monotonic_to_microseconds(MonoT + erlang:time_offset()),
    Secs = MicroSecs div 1000000,
    {Secs div 1000000, Secs rem 1000000, MicroSecs rem 1000000}.

monotonic_to_microseconds(MonoT) ->
    erlang:convert_time_unit(MonoT, native, micro_seconds).

%% ---------------------------------------------------------------------------
%% # now_diff/1
%% ---------------------------------------------------------------------------

-spec now_diff(T0 :: integer())
   -> {Hours, Mins, Secs, MicroSecs}
 when Hours :: non_neg_integer(),
      Mins  :: 0..59,
      Secs  :: 0..59,
      MicroSecs :: 0..999999.

%% Return time difference as an {H, M, S, MicroS} tuple instead of as
%% integer microseconds.

now_diff(T0) ->
    time(micro_diff(T0)).

%% ---------------------------------------------------------------------------
%% # micro_diff/1
%% ---------------------------------------------------------------------------

-spec micro_diff(T0 :: integer())
   -> MicroSecs
 when MicroSecs :: non_neg_integer().

micro_diff(T0) ->  %% monotonic time
    monotonic_to_microseconds(erlang:monotonic_time() - T0).

%% ---------------------------------------------------------------------------
%% # micro_diff/2
%% ---------------------------------------------------------------------------

-spec micro_diff(T1 :: integer(), T0 :: integer())
   -> MicroSecs
 when MicroSecs :: non_neg_integer().

micro_diff(T1, T0) ->  %% monotonic time
    monotonic_to_microseconds(T1 - T0).

%% ---------------------------------------------------------------------------
%% # time/1
%%
%% Return an elapsed time as an {H, M, S, MicroS} tuple.
%% ---------------------------------------------------------------------------

-spec time(Diff :: non_neg_integer())
   -> {Hours, Mins, Secs, MicroSecs}
 when Hours :: non_neg_integer(),
      Mins  :: 0..59,
      Secs  :: 0..59,
      MicroSecs :: 0..999999.

time(Micro) ->  %% elapsed time
    Seconds = Micro div 1000000,
    H = Seconds div 3600,
    M = (Seconds rem 3600) div 60,
    S = Seconds rem 60,
    {H, M, S, Micro rem 1000000}.

%% ---------------------------------------------------------------------------
%% # eval/1
%%
%% Evaluate a function in various forms.
%% ---------------------------------------------------------------------------

-type f() :: {module(), atom(), list()}
           | nonempty_maybe_improper_list(fun(), list())
           | fun().

-spec eval(Fun)
   -> term()
 when Fun :: f()
           | {f()}
           | nonempty_maybe_improper_list(f(), list()).

eval({M,F,A}) ->
    apply(M,F,A);

eval([{M,F,A} | X]) ->
    apply(M, F, X ++ A);

eval([[F|X] | A]) ->
    eval([F | A ++ X]);

eval([F|A]) ->
    apply(F,A);

eval({F}) ->
    eval(F);

eval(F) ->
    F().

%% ---------------------------------------------------------------------------
%% eval_name/1
%% ---------------------------------------------------------------------------

eval_name({M,F,A}) ->
    {M, F, length(A)};

eval_name([{M,F,A} | X]) ->
    {M, F, length(A) + length(X)};

eval_name([[F|A] | X]) ->
    eval_name([F | X ++ A]);

eval_name([F|_]) ->
    F;

eval_name({F}) ->
    eval_name(F);

eval_name(F) ->
    F.

%% ---------------------------------------------------------------------------
%% # ipaddr/1
%%
%% Parse an IP address.
%% ---------------------------------------------------------------------------

-spec ipaddr([byte()] | tuple())
   -> inet:ip_address()
    | none().

%% Don't convert lists of integers since a length 8 list like
%% [$1,$0,$.,$0,$.,$0,$.,$1] is ambiguous: is it "10.0.0.1" or
%% "49:48:46:48:46:48:46:49"?
%%
%% RFC 2373 defines the format parsed for v6 addresses.

%% Be brutal.
ipaddr(Addr) ->
    try
        ip(Addr)
    catch
        error: _ ->
            erlang:error({invalid_address, erlang:get_stacktrace()})
    end.

%% Already a tuple: ensure non-negative integers of the right size.
ip(T)
  when size(T) == 4;
       size(T) == 8 ->
    Bs = 2*size(T),
    [] = lists:filter(fun(N) when 0 =< N -> 0 < N bsr Bs end,
                      tuple_to_list(T)),
    T;

%% Or not: convert from '.'/':'-separated decimal/hex.
ip(Addr) ->
    {ok, A} = inet_parse:address(Addr),  %% documented in inet(3)
    A.

%% ---------------------------------------------------------------------------
%% # spawn_opts/2
%% ---------------------------------------------------------------------------

-spec spawn_opts(server|worker, list())
   -> list().

spawn_opts(server, Opts) ->
    opts(75000, Opts);
spawn_opts(worker, Opts) ->
    opts(5000, Opts).

%% These setting are historical rather than useful. In particular, the
%% server setting can bloat many processes unnecessarily. Let them be
%% disabled with -diameter min_heap_size false.

opts(Def, Opts) ->
    Key = min_heap_size,
    case getenv(Key, Def) of
        N when is_integer(N), 0 =< N ->
            [{Key, N} | lists:keydelete(Key, 1, Opts)];
        _ ->
            Opts
    end.

%% getenv/1

getenv(Key, Def) ->
    case application:get_env(Key) of
        {ok, T} ->
            T;
        undefined ->
            Def
    end.

%% ---------------------------------------------------------------------------
%% # wait/1
%% ---------------------------------------------------------------------------

-spec wait([pid() | reference()])
   -> ok.

wait(L) ->
    lists:foreach(fun down/1, L).

down(Pid)
  when is_pid(Pid) ->
    down(monitor(process, Pid));

down(MRef)
  when is_reference(MRef) ->
    receive {'DOWN', MRef, process, _, _} = T -> T end.

%% ---------------------------------------------------------------------------
%% # fold_n/3
%% ---------------------------------------------------------------------------

-spec fold_n(F, Acc0, N)
   -> term()
 when F    :: fun((non_neg_integer(), term()) -> term()),
      Acc0 :: term(),
      N    :: non_neg_integer().

fold_n(F, Acc, N)
  when is_integer(N), 0 < N ->
    fold_n(F, F(N, Acc), N-1);

fold_n(_, Acc, _) ->
    Acc.

%% ---------------------------------------------------------------------------
%% # for_n/2
%% ---------------------------------------------------------------------------

-spec for_n(F, N)
   -> non_neg_integer()
 when F :: fun((non_neg_integer()) -> term()),
      N :: non_neg_integer().

for_n(F, N) ->
    fold_n(fun(M,A) -> F(M), A+1 end, 0, N).

%% ---------------------------------------------------------------------------
%% # log/4
%%
%% Called to have something to trace on for happenings of interest.
%% ---------------------------------------------------------------------------

log(_Slogan, _Mod, _Line, _Details) ->
    ok.