aboutsummaryrefslogtreecommitdiff
path: root/src/shaper.erl
blob: 811315f0f3f553ba9cfcdc13585aef53222b23cc (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
%%%----------------------------------------------------------------------
%%% File    : shaper.erl
%%% Author  : Alexey Shchepin <alexey@sevcom.net>
%%% Purpose : Functions to control connections traffic
%%% Created :  9 Feb 2003 by Alexey Shchepin <alexey@sevcom.net>
%%% Id      : $Id$
%%%----------------------------------------------------------------------

-module(shaper).
-author('alexey@sevcom.net').
-vsn('$Revision$ ').

-export([new/1, new1/1, update/2]).

-record(maxrate, {maxrate, lastrate, lasttime}).


new(Name) ->
    Data = case ejabberd_config:get_global_option({shaper, Name}) of
	       undefined ->
		   none;
	       D ->
		   D
	   end,
    new1(Data).


new1(none) ->
    none;
new1({maxrate, MaxRate}) ->
    #maxrate{maxrate = MaxRate,
	     lastrate = 0,
	     lasttime = now_to_usec(now())}.


update(none, Size) ->
    none;
update(#maxrate{} = State, Size) ->
    MinInterv = 1000 * Size /
	(2 * State#maxrate.maxrate - State#maxrate.lastrate),
    Interv = (now_to_usec(now()) - State#maxrate.lasttime) / 1000,
    %io:format("State: ~p, Size=~p~nM=~p, I=~p~n",
    %          [State, Size, MinInterv, Interv]),
    if
	MinInterv > Interv ->
	    timer:sleep(1 + trunc(MinInterv - Interv));
	true ->
	    ok
    end,
    Now = now_to_usec(now()),
    State#maxrate{
      lastrate = (State#maxrate.lastrate +
		  1000000 * Size / (Now - State#maxrate.lasttime))/2,
      lasttime = Now}.


now_to_usec({MSec, Sec, USec}) ->
    (MSec*1000000 + Sec)*1000000 + USec.